text
stringlengths 3
1.05M
|
---|
import express from "express";
import compression from "compression";
import helmet from "helmet";
import favicon from "serve-favicon";
import logger from "morgan";
import dotenv from "dotenv";
import renderPage from "./renderPage";
var https = require('https')
// Load environment variables from .env file
dotenv.config();
const app = express();
// MongoClient.connect(process.env.MONGODB_URL).then(client => {
// const db = client.db(process.env.MONGODB_NAME);
// configurePassport(db);
var certOptions = {
key: fs.readFileSync(path.resolve('build/cert/server.key')),
cert: fs.readFileSync(path.resolve('build/cert/server.crt'))
};
app.use(helmet());
app.use(logger("tiny"));
app.use(compression());
app.use(favicon("build/public/favicons/favicon.ico"));
app.use(express.json());
app.use(express.urlencoded({extended: true}));
// aggressive cache static assets (1 year)
app.use("/static", express.static("dist/public", {maxAge: "1y"}));
// Persist session in mongoDB
// app.use(
// session({
// store: new MongoStore({ db }),
// secret: process.env.SESSION_SECRET,
// resave: false,
// saveUninitialized: false
// })
// );
app.use(passport.initialize());
app.use(passport.session());
// app.use("/auth", auth);
// app.use("/api", api(db));
// app.use(fetchBoardData(db));
app.use(fetchBoardData());
app.get("*", renderPage);
const port = process.env.PORT || "1337";
/* eslint-disable no-console */
var server = https.createServer(certOptions, app).listen(port, () => {
});
|
/**
* GitHub v3 REST API
* GitHub's v3 REST API.
*
* The version of the OpenAPI document: 0.0.5
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
/**
* The InlineObject30 model module.
* @module model/InlineObject30
* @version 0.0.5
*/
class InlineObject30 {
/**
* Constructs a new <code>InlineObject30</code>.
* @alias module:model/InlineObject30
*/
constructor() {
InlineObject30.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>InlineObject30</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/InlineObject30} obj Optional instance to populate.
* @return {module:model/InlineObject30} The populated <code>InlineObject30</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineObject30();
if (data.hasOwnProperty('body')) {
obj['body'] = ApiClient.convertToType(data['body'], 'String');
}
if (data.hasOwnProperty('title')) {
obj['title'] = ApiClient.convertToType(data['title'], 'String');
}
}
return obj;
}
}
/**
* The discussion post's body text.
* @member {String} body
*/
InlineObject30.prototype['body'] = undefined;
/**
* The discussion post's title.
* @member {String} title
*/
InlineObject30.prototype['title'] = undefined;
export default InlineObject30;
|
import React from 'react'
import bg from "./bg.jpg"
const Home = () => {
return (
<div>
{
!localStorage.getItem("jtoken") ?
window.location.href = "/login" : null
}
<div
style={{
backgroundImage: `linear-gradient( rgba(0,0,0,.5), rgba(0,0,0,.1) ),url(${bg})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
width: '100vw',
height: '100vh'
}}
>
</div>
</div >
)
}
export default Home
|
define("maq-metadata-dojo/dojox/mobile/TabBarButtonHelper", [
"dojo/query"
], function(query) {
var TabBarButtonHelper = function() {};
TabBarButtonHelper.prototype = {
create: function(widget, srcElement){
// Fix for #705.
// The TabBarButton widget's startup logic registers an onclick
// handler on one of its interior DOM nodes if there is a
// "moveTo" property that has a reference to a view.
// This built-in onclick handler will launch an animated
// transition to make that view visible. This is good for runtime execution,
// but we don't want this onclick handler to execute in the page editor.
// So, register a "click" handler in the capture phase (happens before default bubble phase)
// that calls stopPropagation(), which prevents the TabBarButton's onclick logic from getting invoked.
// This allows event to bubble up to ancestor widgets, and therefore
// will be caught by Maqetta and will cause a selection action to occur.
var dijitWidget = widget.dijitWidget;
if(dijitWidget){
var domNode = dijitWidget.domNode;
var mblTabBarButtonAnchorNode = query('.mblTabBarButtonAnchor',domNode)[0];
if(mblTabBarButtonAnchorNode){
mblTabBarButtonAnchorNode.addEventListener("click",function(e){
e.stopPropagation();
}, true);
}
}
}
};
return TabBarButtonHelper;
}); |
/* Copyright (C) YOOtheme GmbH, http://www.gnu.org/licenses/gpl.html GNU/GPL */
!function(e){var t=function(){};e.extend(t.prototype,{name:"autosuggest",options:{prefill:"",allowDuplicates:true,inputName:"term[]",resultsHighlight:true,addButtonText:"Add"},initialize:function(t,i){this.options=e.extend({},this.options,i);var s=this;this.input=t;e.extend(e.expr[":"],{focus:function(e){return e==document.activeElement}});t.addClass("as-input").wrap('<ul class="as-selections">').wrap('<li class="as-original">').autocomplete(e.extend({select:function(e,t){s.addItem(t.item);t.item.value=t.item.label=""}},this.options)).bind("blur",function(e){s.selections_holder.addClass("blur").find("li.as-selection-item").removeClass("selected")}).bind("focus",function(){s.selections_holder.removeClass("blur")}).bind("keydown",function(i){switch(i.which){case 8:if(t.val()==""){i.preventDefault();li=e("li.as-selection-item:last");li.is(".selected")?s.removeItem(li):s.selectItem(li)}break;case 9:case 188:i.preventDefault();s.addItem(t.val());break}});this.selections_holder=t.closest("ul.as-selections").bind("click",function(){if(t.not(":focus")){t.focus()}});this.original=this.selections_holder.find("li.as-original");e('<li class="add-tag-button" >').insertAfter(this.original).text(this.options.addButtonText).bind("click",function(){e.each(t.val().split(","),function(e,t){s.addItem(t)})});if(typeof this.options.prefill=="string"){e.each(this.options.prefill.split(","),function(e,t){s.addItem(t)})}else{s.addItem(this.options.prefill)}t.is(":focus")?t.focus():t.blur();this.selections_holder.delegate("a.as-close","click",function(){s.removeItem(e(this).parent())}).delegate("li.as-selection-item","click",function(){s.selectItem(this)})},addItem:function(t){if(typeof t=="string")t={label:t.trim(),value:t.trim()};if(t.value!=""&&(this.options.allowDuplicates||!this.itemExists(t))){var i=e('<li class="as-selection-item">').text(t.label).data("item",t).insertBefore(this.original);e('<a class="as-close">×</a>').appendTo(i);e('<input type="hidden" class="as-value">').attr("name",this.options.inputName).val(t.value).appendTo(i)}this.input.val("");this.input.trigger("addItem",i)},removeItem:function(e){e.remove()},itemExists:function(t){var i=false;this.selections_holder.find("li.as-selection-item").each(function(){if(e(this).data("item")&&e(this).data("item").value.toLowerCase()==t.value.toLowerCase()){i=true;return}});return i},selectItem:function(t){e("li.as-selection-item",this.selections_holder).not(t).removeClass("selected");e(t).addClass("selected");if(this.input.not(":focus"))this.input.focus()}});e.fn[t.prototype.name]=function(){var i=arguments;var s=i[0]?i[0]:null;return this.each(function(){var a=e(this);if(t.prototype[s]&&a.data(t.prototype.name)&&s!="initialize"){a.data(t.prototype.name)[s].apply(a.data(t.prototype.name),Array.prototype.slice.call(i,1))}else if(!s||e.isPlainObject(s)){var n=new t;if(t.prototype["initialize"]){n.initialize.apply(n,e.merge([a],i))}a.data(t.prototype.name,n)}else{e.error("Method "+s+" does not exist on jQuery."+t.name)}})}}(jQuery); |
import mohawk
from django.conf import settings
from django.urls import reverse
from django.test import override_settings
from rest_framework import status
from urllib import parse
from api.cases.enums import CaseTypeEnum
from api.cases.models import CaseType
from api.core.requests import get_hawk_sender
from api.licences.enums import LicenceStatus
from api.open_general_licences.tests.factories import OpenGeneralLicenceFactory, OpenGeneralLicenceCaseFactory
from api.organisations.tests.factories import SiteFactory
from api.staticdata.statuses.enums import CaseStatusEnum
from api.staticdata.statuses.libraries.get_case_status import get_case_status_by_status
from test_helpers.clients import DataTestClient
class InternalListTests(DataTestClient):
def setUp(self):
super().setUp()
case_type = CaseType.objects.get(id=CaseTypeEnum.OGTCL.id)
self.ogl_1 = OpenGeneralLicenceFactory(name="b", case_type=case_type)
self.ogl_2 = OpenGeneralLicenceFactory(name="c", case_type=case_type)
self.url = reverse("open_general_licences:list")
self.gov_user.role = self.super_user_role
self.gov_user.save()
def test_get_list_back(self):
response = self.client.get(self.url, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()["results"]
self.assertEqual(str(self.ogl_1.id), response_data[0]["id"])
self.assertEqual(str(self.ogl_2.id), response_data[1]["id"])
def test_get_list_back_alphabetical(self):
self.ogl_2.name = "a"
self.ogl_2.save()
response = self.client.get(self.url, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
response_data = response.json()["results"]
self.assertEqual(str(self.ogl_2.id), response_data[0]["id"])
self.assertEqual(str(self.ogl_1.id), response_data[1]["id"])
def test_fail_without_permission(self):
self.gov_user.role = self.default_role
self.gov_user.save()
response = self.client.get(self.url, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
class ExporterListTests(DataTestClient):
def setUp(self):
super().setUp()
case_type = CaseType.objects.get(id=CaseTypeEnum.OGTCL.id)
self.open_general_licence = OpenGeneralLicenceFactory(name="b", case_type=case_type)
self.url = reverse("open_general_licences:list")
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
self.site = SiteFactory(organisation=self.organisation)
self.open_general_licence_case = OpenGeneralLicenceCaseFactory(
open_general_licence=self.open_general_licence,
site=self.organisation.primary_site,
organisation=self.organisation,
)
self.open_general_licence_case_2 = OpenGeneralLicenceCaseFactory(
open_general_licence=self.open_general_licence, site=self.site, organisation=self.organisation,
)
def test_exporter_view_licences_success(self):
response = self.client.get(self.url, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
self.assertEqual(len(response.json()["results"][0]["registrations"]), 2)
registration = response.json()["results"][0]["registrations"][0]
self.assertEqual(registration["reference_code"], self.open_general_licence_case.reference_code)
self.assertEqual(registration["site"]["id"], str(self.organisation.primary_site.id))
self.assertEqual(registration["site"]["name"], self.organisation.primary_site.name)
self.assertEqual(
registration["site"]["address"]["address_line_1"], self.organisation.primary_site.address.address_line_1
)
self.assertEqual(
registration["site"]["address"]["address_line_2"], self.organisation.primary_site.address.address_line_2
)
self.assertEqual(registration["site"]["address"]["city"], self.organisation.primary_site.address.city)
self.assertEqual(
registration["site"]["address"]["country"]["name"], self.organisation.primary_site.address.country.name
)
self.assertEqual(registration["site"]["address"]["postcode"], self.organisation.primary_site.address.postcode)
self.assertEqual(registration["site"]["address"]["region"], self.organisation.primary_site.address.region)
self.assertEqual(
registration["site"]["records_located_at"]["name"],
self.organisation.primary_site.site_records_located_at.name,
)
self.assertEqual(registration["status"]["key"], LicenceStatus.ISSUED)
self.assertEqual(registration["submitted_at"], self.open_general_licence_case.submitted_at)
def test_exporter_view_site_licences_success(self):
response = self.client.get(
self.url + "?site=" + str(self.organisation.primary_site.id), **self.exporter_headers
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
self.assertEqual(len(response.json()["results"][0]["registrations"]), 2)
def test_exporter_view_active_licences_success(self):
self.open_general_licence_case_2.status = get_case_status_by_status(CaseStatusEnum.DRAFT)
self.open_general_licence_case_2.save()
response = self.client.get(self.url + "?active_only=True", **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
self.assertEqual(len(response.json()["results"][0]["registrations"]), 1)
def test_exporter_view_registered_licences_success(self):
response = self.client.get(self.url + "?registered=True", **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
self.assertEqual(len(response.json()["results"][0]["registrations"]), 2)
|
import React, { Component } from 'react';
import microsoft from '../../images/microsoft.png';
import uss from '../../images/uss.png';
import pageload from '../../images/pageload.png';
import mediastream from '../../images/mediastream.png';
import frontendmasters from '../../images/frontendmasters.png';
import codeschool from '../../images/codeschool.png';
import balsamiq from '../../images/balsamiq.png';
import edge from '../../images/edge.png';
import GitHub from '../../images/GitHub.png';
import Community from './community';
import style from './style.css';
export default class Sponsors extends Component {
constructor (props) {
super(props);
this.state = {};
}
render () {
return (
<section id="first" className="main special">
<header className="major">
<h2>Platinum Sponsors</h2>
</header>
<div className={style.body}>
<a className={style.imageLinks} href="http://www.microsoft.com">
<img src={microsoft} alt="microsoft" className={[style.images, style.big].join(' ')} />
</a>
<a className={style.imageLinks} href="http://www.mediastre.am">
<img src={mediastream} alt="mediastream" className={[style.images, style.big].join(' ')} />
</a>
</div>
<br />
<header className="major">
<h2>Gold Sponsors</h2>
</header>
<div className={style.body}>
<a className={style.imageLinks} href="http://www.uss.cl">
<img src={uss} alt="universidad san sebastian" className={style.images} />
</a>
</div>
<header className="major">
<h2>Silver Sponsors</h2>
</header>
<div className={style.body}>
<a className={style.imageLinks} href="http://edgecowork.com/">
<img src={edge} alt="Edge Cowork" className={style.images} />
</a>
<a className={style.imageLinks} href="http://www.frontendmasters.com">
<img src={frontendmasters} alt="frontend masters" className={style.images} />
</a>
<a className={style.imageLinks} href="http://www.github.com">
<img src={GitHub} alt="github" className={style.images} />
</a>
<a className={style.imageLinks} href="http://www.codeschool.com">
<img src={codeschool} alt="codeschool" className={style.images} />
</a>
<a className={style.imageLinks} href="https://balsamiq.com/products/mockups/">
<img src={balsamiq} alt="balsamiq" className={style.images} />
</a>
<a className={style.imageLinks} href="http://www.pageload.io">
<img src={pageload} alt="pageload" className={style.images} />
</a>
</div>
<br />
<Community />
<footer className="major">
<p>
¿Nos falta alguien? ¿Quieres apoyarnos? ¿Te gustaría estar entre nuestros sponsors?
</p>
<ul className="actions">
<li>
<a href="mailto:[email protected]" className="button">Envíanos un mensaje</a>
</li>
</ul>
</footer>
</section>
);
}
}
/*
<section id="first" className="main special">
<header className="major">
<h2>Nuestros Sponsors</h2>
</header>
<ul className="features">
<li>
<span className="icon major style1 fa-code" />
<h3>Ipsum consequat</h3>
<p>Sed lorem amet ipsum dolor et amet nullam consequat a feugiat consequat tempus veroeros sed consequat.</p>
</li>
<li>
<span className="icon major style3 fa-copy" />
<h3>Amed sed feugiat</h3>
<p>Sed lorem amet ipsum dolor et amet nullam consequat a feugiat consequat tempus veroeros sed consequat.</p>
</li>
<li>
<span className="icon major style5 fa-diamond" />
<h3>Dolor nullam</h3>
<p>Sed lorem amet ipsum dolor et amet nullam consequat a feugiat consequat tempus veroeros sed consequat.</p>
</li>
</ul>
<footer className="major">
<ul className="actions">
<li>
<a href="generic.html" className="button">Learn More</a>
</li>
</ul>
</footer>
</section>
*/
|
require('dotenv').config();
const jwt = require('jsonwebtoken');
const privateKey = process.env.PK;
module.exports = async (req, res, next) => {
const token = req.get('Authorization');
if (!token) {
req.isAuth = false;
return next();
}
let decodedToken;
try {
decodedToken = await jwt.verify(token, privateKey);
} catch (err) {
req.isAuth = false;
return next();
}
if (!decodedToken) {
req.isAuth = false;
return next();
}
req.isAuth = true;
req.roleId = decodedToken.roleId;
req.userId = decodedToken.subject;
return next();
};
|
var M1 = eval("module M { } M");
var M2 = eval("module M { } M");
assertEq(M1 === M2, false);
|
// @flow
import DOM from '../../util/dom';
import { bezier, bindAll } from '../../util/util';
import window from '../../util/window';
import browser from '../../util/browser';
import { Event } from '../../util/evented';
import assert from 'assert';
import type Map from '../map';
import type Point from '@mapbox/point-geometry';
import type {TaskID} from '../../util/task_queue';
const inertiaLinearity = 0.25,
inertiaEasing = bezier(0, 0, inertiaLinearity, 1),
inertiaMaxSpeed = 180, // deg/s
inertiaDeceleration = 720; // deg/s^2
/**
* The `DragRotateHandler` allows the user to rotate the map by clicking and
* dragging the cursor while holding the right mouse button or `ctrl` key.
*/
class DragRotateHandler {
_map: Map;
_el: HTMLElement;
_state: 'disabled' | 'enabled' | 'pending' | 'active';
_button: 'right' | 'left';
_eventButton: number;
_bearingSnap: number;
_pitchWithRotate: boolean;
_startPos: Point;
_prevPos: Point;
_lastPos: Point;
_startTime: number;
_lastMoveEvent: MouseEvent;
_inertia: Array<[number, number]>;
_center: Point;
_frameId: ?TaskID;
/**
* @param {Map} map The Mapbox GL JS map to add the handler to.
* @param {Object} [options]
* @param {number} [options.bearingSnap] The threshold, measured in degrees, that determines when the map's
* bearing will snap to north.
* @param {bool} [options.pitchWithRotate=true] Control the map pitch in addition to the bearing
* @private
*/
constructor(map: Map, options: {
button?: 'right' | 'left',
element?: HTMLElement,
bearingSnap?: number,
pitchWithRotate?: boolean
}) {
this._map = map;
this._el = options.element || map.getCanvasContainer();
this._state = 'disabled';
this._button = options.button || 'right';
this._bearingSnap = options.bearingSnap || 0;
this._pitchWithRotate = options.pitchWithRotate !== false;
bindAll([
'onMouseDown',
'_onMouseMove',
'_onMouseUp',
'_onBlur',
'_onDragFrame'
], this);
}
/**
* Returns a Boolean indicating whether the "drag to rotate" interaction is enabled.
*
* @returns {boolean} `true` if the "drag to rotate" interaction is enabled.
*/
isEnabled() {
return this._state !== 'disabled';
}
/**
* Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used.
*
* @returns {boolean} `true` if the "drag to rotate" interaction is active.
*/
isActive() {
return this._state === 'active';
}
/**
* Enables the "drag to rotate" interaction.
*
* @example
* map.dragRotate.enable();
*/
enable() {
if (this.isEnabled()) return;
this._state = 'enabled';
}
/**
* Disables the "drag to rotate" interaction.
*
* @example
* map.dragRotate.disable();
*/
disable() {
if (!this.isEnabled()) return;
switch (this._state) {
case 'active':
this._state = 'disabled';
this._unbind();
this._deactivate();
this._fireEvent('rotateend');
if (this._pitchWithRotate) {
this._fireEvent('pitchend');
}
this._fireEvent('moveend');
break;
case 'pending':
this._state = 'disabled';
this._unbind();
break;
default:
this._state = 'disabled';
break;
}
}
onMouseDown(e: MouseEvent) {
if (this._state !== 'enabled') return;
const touchEvent = e.type === 'touchstart';
if (touchEvent) {
this._startTime = Date.now();
} else {
if (this._button === 'right') {
this._eventButton = DOM.mouseButton(e);
if (this._eventButton !== (e.ctrlKey ? 0 : 2)) return;
} else {
if (e.ctrlKey || DOM.mouseButton(e) !== 0) return;
this._eventButton = 0;
}
}
DOM.disableDrag();
// Bind window-level event listeners for move and up/end events. In the absence of
// the pointer capture API, which is not supported by all necessary platforms,
// window-level event listeners give us the best shot at capturing events that
// fall outside the map canvas element. Use `{capture: true}` for the move event
// to prevent map move events from being fired during a drag.
if (touchEvent) {
window.document.addEventListener('touchmove', this._onMouseMove, { capture: true });
window.document.addEventListener('touchend', this._onMouseUp);
} else {
window.document.addEventListener('mousemove', this._onMouseMove, { capture: true });
window.document.addEventListener('mouseup', this._onMouseUp);
}
// Deactivate when the window loses focus. Otherwise if a mouseup occurs when the window
// isn't in focus, dragging will continue even though the mouse is no longer pressed.
window.addEventListener('blur', this._onBlur);
this._state = 'pending';
this._inertia = [[browser.now(), this._map.getBearing()]];
this._startPos = this._prevPos = this._lastPos = DOM.mousePos(this._el, e);
this._center = this._map.transform.centerPoint; // Center of rotation
e.preventDefault();
}
_onMouseMove(e: MouseEvent) {
const pos = DOM.mousePos(this._el, e);
if (this._lastPos.equals(pos)) {
return;
}
this._lastMoveEvent = e;
this._lastPos = pos;
if (this._state === 'pending') {
this._state = 'active';
this._fireEvent('rotatestart', e);
this._fireEvent('movestart', e);
if (this._pitchWithRotate) {
this._fireEvent('pitchstart', e);
}
}
if (!this._frameId) {
this._frameId = this._map._requestRenderFrame(this._onDragFrame);
}
}
_onDragFrame() {
this._frameId = null;
const e = this._lastMoveEvent;
if (!e) return;
const tr = this._map.transform;
const p1 = this._prevPos,
p2 = this._lastPos,
bearingDiff = (p1.x - p2.x) * 0.8,
pitchDiff = (p1.y - p2.y) * -0.5,
bearing = tr.bearing - bearingDiff,
pitch = tr.pitch - pitchDiff,
inertia = this._inertia,
last = inertia[inertia.length - 1];
this._drainInertiaBuffer();
inertia.push([browser.now(), this._map._normalizeBearing(bearing, last[1])]);
tr.bearing = bearing;
if (this._pitchWithRotate) {
this._fireEvent('pitch', e);
tr.pitch = pitch;
}
this._fireEvent('rotate', e);
this._fireEvent('move', e);
delete this._lastMoveEvent;
this._prevPos = this._lastPos;
}
_onMouseUp(e: MouseEvent) {
const touchEvent = e.type === 'touchend';
if (touchEvent && (this._startPos === this._lastPos) && (Date.now() - this._startTime) < 300) {
this._el.click();
}
if (DOM.mouseButton(e) !== this._eventButton) return;
switch (this._state) {
case 'active':
this._state = 'enabled';
DOM.suppressClick();
this._unbind();
this._deactivate();
this._inertialRotate(e);
break;
case 'pending':
this._state = 'enabled';
this._unbind();
break;
default:
assert(false);
break;
}
}
_onBlur(e: FocusEvent) {
switch (this._state) {
case 'active':
this._state = 'enabled';
this._unbind();
this._deactivate();
this._fireEvent('rotateend', e);
if (this._pitchWithRotate) {
this._fireEvent('pitchend', e);
}
this._fireEvent('moveend', e);
break;
case 'pending':
this._state = 'enabled';
this._unbind();
break;
default:
assert(false);
break;
}
}
_unbind() {
window.document.removeEventListener('mousemove', this._onMouseMove, { capture: true });
window.document.removeEventListener('mouseup', this._onMouseUp);
window.document.removeEventListener('touchmove', this._onMouseMove, { capture: true });
window.document.removeEventListener('touchend', this._onMouseUp);
window.removeEventListener('blur', this._onBlur);
DOM.enableDrag();
}
_deactivate() {
if (this._frameId) {
this._map._cancelRenderFrame(this._frameId);
this._frameId = null;
}
delete this._lastMoveEvent;
delete this._startPos;
delete this._prevPos;
delete this._lastPos;
}
_inertialRotate(e: MouseEvent) {
this._fireEvent('rotateend', e);
this._drainInertiaBuffer();
const map = this._map,
mapBearing = map.getBearing(),
inertia = this._inertia;
const finish = () => {
if (Math.abs(mapBearing) < this._bearingSnap) {
map.resetNorth({noMoveStart: true}, { originalEvent: e });
} else {
this._fireEvent('moveend', e);
}
if (this._pitchWithRotate) this._fireEvent('pitchend', e);
};
if (inertia.length < 2) {
finish();
return;
}
const first = inertia[0],
last = inertia[inertia.length - 1],
previous = inertia[inertia.length - 2];
let bearing = map._normalizeBearing(mapBearing, previous[1]);
const flingDiff = last[1] - first[1],
sign = flingDiff < 0 ? -1 : 1,
flingDuration = (last[0] - first[0]) / 1000;
if (flingDiff === 0 || flingDuration === 0) {
finish();
return;
}
let speed = Math.abs(flingDiff * (inertiaLinearity / flingDuration)); // deg/s
if (speed > inertiaMaxSpeed) {
speed = inertiaMaxSpeed;
}
const duration = speed / (inertiaDeceleration * inertiaLinearity),
offset = sign * speed * (duration / 2);
bearing += offset;
if (Math.abs(map._normalizeBearing(bearing, 0)) < this._bearingSnap) {
bearing = map._normalizeBearing(0, bearing);
}
map.rotateTo(bearing, {
duration: duration * 1000,
easing: inertiaEasing,
noMoveStart: true
}, { originalEvent: e });
}
_fireEvent(type: string, e: *) {
return this._map.fire(new Event(type, e ? { originalEvent: e } : {}));
}
_drainInertiaBuffer() {
const inertia = this._inertia,
now = browser.now(),
cutoff = 160; //msec
while (inertia.length > 0 && now - inertia[0][0] > cutoff)
inertia.shift();
}
}
export default DragRotateHandler;
|
export { default as EffectiveOriginExt } from "./EffectiveOriginExt.js"
export { default as EffectivePosExt } from "./EffectivePosExt.js"
|
"""Test for the MNE BIDS updating of BIDS datasets."""
# Authors: Adam Li <[email protected]>
#
# License: BSD-3-Clause
import json
import os.path as op
from pathlib import Path
import pytest
import numpy as np
import mne
from mne.io.constants import FIFF
from mne.datasets import testing
from mne.utils import requires_nibabel
from mne_bids import (BIDSPath, write_raw_bids,
write_meg_calibration, write_meg_crosstalk,
get_anat_landmarks, update_sidecar_json, write_anat,
update_anat_landmarks)
from mne_bids.path import _mkdir_p
from mne_bids.utils import _write_json
subject_id = '01'
session_id = '01'
run = '01'
acq = None
task = 'testing'
bids_path = BIDSPath(
subject=subject_id, session=session_id, run=run, acquisition=acq,
task=task)
@pytest.fixture(scope='session')
def _get_bids_test_dir(tmp_path_factory):
"""Return path to a written test BIDS dir."""
bids_root = str(tmp_path_factory.mktemp('mnebids_utils_test_bids_ds'))
data_path = testing.data_path()
raw_fname = op.join(data_path, 'MEG', 'sample',
'sample_audvis_trunc_raw.fif')
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2, 'Visual/Left': 3,
'Visual/Right': 4, 'Smiley': 5, 'Button': 32}
events_fname = op.join(data_path, 'MEG', 'sample',
'sample_audvis_trunc_raw-eve.fif')
cal_fname = op.join(data_path, 'SSS', 'sss_cal_mgh.dat')
crosstalk_fname = op.join(data_path, 'SSS', 'ct_sparse.fif')
raw = mne.io.read_raw_fif(raw_fname)
raw.info['line_freq'] = 60
# Drop unknown events.
events = mne.read_events(events_fname)
events = events[events[:, 2] != 0]
bids_path.update(root=bids_root)
# Write multiple runs for test_purposes
for run_idx in [run, '02']:
name = bids_path.copy().update(run=run_idx)
write_raw_bids(raw, name, events_data=events,
event_id=event_id, overwrite=True)
write_meg_calibration(cal_fname, bids_path=bids_path)
write_meg_crosstalk(crosstalk_fname, bids_path=bids_path)
return bids_root
@pytest.fixture(scope='session')
def _get_sidecar_json_update_file(_get_bids_test_dir):
"""Return path to a sidecar JSON updating file."""
bids_root = _get_bids_test_dir
sample_scripts = op.join(bids_root, 'sourcedata')
sidecar_fpath = op.join(sample_scripts, 'sidecarjson_update.json')
_mkdir_p(sample_scripts)
update_json = {
'InstitutionName': 'mne-bids',
'InstitutionAddress': 'Internet',
'MEGChannelCount': 300,
'MEGREFChannelCount': 6,
'SEEGChannelCount': 0,
}
_write_json(sidecar_fpath, update_json, overwrite=True)
return sidecar_fpath
@pytest.mark.usefixtures('_get_bids_test_dir', '_bids_validate',
'_get_sidecar_json_update_file')
def test_update_sidecar_jsons(_get_bids_test_dir, _bids_validate,
_get_sidecar_json_update_file):
"""Test updating sidecar JSON files."""
bids_path = BIDSPath(
subject=subject_id, session=session_id, run=run, acquisition=acq,
task=task, suffix='meg', root=_get_bids_test_dir)
# expected key, original value, and expected value after update
# Fields that are not `None` already are expected to exist
# in this sidecar file. Fields that are `None` will get
# written with the sidecar json value when update is called.
expected_checks = [('InstitutionName', None, 'mne-bids'),
('InstitutionAddress', None, 'Internet'),
('MEGChannelCount', 306, 300),
('MEGREFChannelCount', 0, 6),
('ECGChannelCount', 0, 0),
('SEEGChannelCount', None, 0)]
# get the sidecar json
sidecar_path = bids_path.copy().update(extension='.json')
sidecar_fpath = sidecar_path.fpath
with open(sidecar_fpath, 'r', encoding='utf-8') as fin:
sidecar_json = json.load(fin)
for key, val, _ in expected_checks:
assert sidecar_json.get(key) == val
_bids_validate(bids_path.root)
# update sidecars
update_sidecar_json(sidecar_path, _get_sidecar_json_update_file)
with open(sidecar_fpath, 'r', encoding='utf-8') as fin:
sidecar_json = json.load(fin)
for key, _, val in expected_checks:
assert sidecar_json.get(key) == val
_bids_validate(bids_path.root)
# should result in error if you don't explicitly say
# its a json file
with pytest.raises(RuntimeError, match='Only works for ".json"'):
update_sidecar_json(sidecar_path.copy().update(
extension=None), _get_sidecar_json_update_file)
# error should raise if the file path doesn't exist
error_bids_path = sidecar_path.copy().update(subject='02')
with pytest.raises(RuntimeError, match='Sidecar file '
'does not exist.'):
update_sidecar_json(
error_bids_path, _get_sidecar_json_update_file)
@requires_nibabel()
def test_update_anat_landmarks(tmp_path):
"""Test updating the anatomical landmarks of an MRI scan."""
data_path = Path(testing.data_path())
raw_path = data_path / 'MEG' / 'sample' / 'sample_audvis_trunc_raw.fif'
trans_path = Path(str(raw_path).replace('_raw.fif', '-trans.fif'))
t1_path = data_path / 'subjects' / 'sample' / 'mri' / 'T1.mgz'
fs_subject = 'sample'
fs_subjects_dir = data_path / 'subjects'
bids_root = tmp_path
bids_path_mri = BIDSPath(subject=subject_id, session=session_id,
acquisition=acq, root=bids_root, datatype='anat',
suffix='T1w')
# First, write the MRI scan to BIDS, including the anatomical landmarks
info = mne.io.read_info(raw_path)
trans = mne.read_trans(trans_path)
landmarks = get_anat_landmarks(
image=t1_path, info=info, trans=trans, fs_subject=fs_subject,
fs_subjects_dir=fs_subjects_dir
)
bids_path_mri = write_anat(image=t1_path, bids_path=bids_path_mri,
landmarks=landmarks, deface=False)
bids_path_mri_json = bids_path_mri.copy().update(extension='.json')
# Modify the landmarks
# Move the nasion a bit
landmarks_new = landmarks.copy()
landmarks_new.dig[1]['r'] *= 0.9
update_anat_landmarks(bids_path=bids_path_mri, landmarks=landmarks_new)
with bids_path_mri_json.fpath.open(encoding='utf-8') as f:
mri_json = json.load(f)
assert np.allclose(
landmarks_new.dig[1]['r'],
mri_json['AnatomicalLandmarkCoordinates']['NAS']
)
# Remove JSON sidecar; updating the anatomical landmarks should re-create
# the file
bids_path_mri_json.fpath.unlink()
update_anat_landmarks(bids_path=bids_path_mri, landmarks=landmarks_new)
with bids_path_mri_json.fpath.open(encoding='utf-8') as f:
mri_json = json.load(f)
assert np.allclose(
landmarks_new.dig[1]['r'],
mri_json['AnatomicalLandmarkCoordinates']['NAS']
)
# Check without extension provided
bids_path_mri_no_ext = bids_path_mri.copy().update(extension=None)
update_anat_landmarks(bids_path=bids_path_mri_no_ext,
landmarks=landmarks_new)
# Check without datatytpe provided
bids_path_mri_no_datatype = bids_path_mri.copy().update(datatype=None)
update_anat_landmarks(bids_path=bids_path_mri_no_datatype,
landmarks=landmarks)
# Check handling of invalid input
bids_path_invalid = bids_path_mri.copy().update(datatype='meg')
with pytest.raises(ValueError, match='Can only operate on "anat"'):
update_anat_landmarks(bids_path=bids_path_invalid, landmarks=landmarks)
bids_path_invalid = bids_path_mri.copy().update(suffix=None)
with pytest.raises(ValueError, match='lease specify the "suffix"'):
update_anat_landmarks(bids_path=bids_path_invalid, landmarks=landmarks)
bids_path_invalid = bids_path_mri.copy().update(suffix='meg')
with pytest.raises(ValueError,
match='Can only operate on "T1w" and "FLASH"'):
update_anat_landmarks(bids_path=bids_path_invalid, landmarks=landmarks)
bids_path_invalid = bids_path_mri.copy().update(subject='invalid')
with pytest.raises(ValueError, match='Could not find an MRI scan'):
update_anat_landmarks(bids_path=bids_path_invalid, landmarks=landmarks)
# Unsupported coordinate frame
landmarks_invalid = landmarks.copy()
for digpoint in landmarks_invalid.dig:
digpoint['coord_frame'] = FIFF.FIFFV_MNE_COORD_RAS
with pytest.raises(ValueError, match='must be specified in MRI voxel'):
update_anat_landmarks(bids_path=bids_path_mri,
landmarks=landmarks_invalid)
# Missing cardinal point
landmarks_invalid = landmarks.copy()
del landmarks_invalid.dig[0]
with pytest.raises(ValueError,
match='did not contain all required cardinal points'):
update_anat_landmarks(bids_path=bids_path_mri,
landmarks=landmarks_invalid)
|
/*
* This file is part of the nivo project.
*
* Copyright 2016-present, Raphaël Benitte.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import React, { useRef, useEffect } from 'react'
import { withContainer, useDimensions, useTheme } from '@nivo/core'
import { useInheritedColor } from '@nivo/colors'
import { NetworkCanvasPropTypes, NetworkCanvasDefaultProps } from './props'
import { useNetwork, useNodeColor, useLinkThickness } from './hooks'
const NetworkCanvas = props => {
const {
width,
height,
margin: partialMargin,
pixelRatio,
nodes: rawNodes,
links: rawLinks,
linkDistance,
repulsivity,
distanceMin,
distanceMax,
iterations,
layers,
nodeColor,
nodeBorderWidth,
nodeBorderColor,
linkThickness,
linkColor,
isInteractive,
} = props
const canvasEl = useRef(null)
const { margin, innerWidth, innerHeight, outerWidth, outerHeight } = useDimensions(
width,
height,
partialMargin
)
const [nodes, links] = useNetwork({
nodes: rawNodes,
links: rawLinks,
linkDistance,
repulsivity,
distanceMin,
distanceMax,
iterations,
center: [innerWidth / 2, innerHeight / 2],
})
const theme = useTheme()
const getNodeColor = useNodeColor(nodeColor)
const getBorderColor = useInheritedColor(nodeBorderColor, theme)
const getLinkThickness = useLinkThickness(linkThickness)
const getLinkColor = useInheritedColor(linkColor, theme)
useEffect(() => {
canvasEl.current.width = outerWidth * pixelRatio
canvasEl.current.height = outerHeight * pixelRatio
const ctx = canvasEl.current.getContext('2d')
ctx.scale(pixelRatio, pixelRatio)
ctx.fillStyle = theme.background
ctx.fillRect(0, 0, outerWidth, outerHeight)
ctx.translate(margin.left, margin.top)
layers.forEach(layer => {
if (layer === 'links') {
links.forEach(link => {
ctx.strokeStyle = getLinkColor(link)
ctx.lineWidth = getLinkThickness(link)
ctx.beginPath()
ctx.moveTo(link.source.x, link.source.y)
ctx.lineTo(link.target.x, link.target.y)
ctx.stroke()
})
} else if (layer === 'nodes') {
nodes.forEach(node => {
ctx.fillStyle = getNodeColor(node)
ctx.beginPath()
ctx.arc(node.x, node.y, node.radius, 0, 2 * Math.PI)
ctx.fill()
if (nodeBorderWidth > 0) {
ctx.strokeStyle = getBorderColor(node)
ctx.lineWidth = nodeBorderWidth
ctx.stroke()
}
})
} else if (typeof layer === 'function') {
layer(ctx, {
...props,
nodes,
links,
})
}
})
}, [
canvasEl,
outerWidth,
outerHeight,
layers,
theme,
nodes,
links,
getNodeColor,
nodeBorderWidth,
getBorderColor,
getLinkThickness,
getLinkColor,
])
return (
<canvas
ref={canvasEl}
width={outerWidth * pixelRatio}
height={outerHeight * pixelRatio}
style={{
width: outerWidth,
height: outerHeight,
cursor: isInteractive ? 'auto' : 'normal',
}}
/>
)
}
NetworkCanvas.propTypes = NetworkCanvasPropTypes
NetworkCanvas.defaultProps = NetworkCanvasDefaultProps
export default withContainer(NetworkCanvas)
|
# ##
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. 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.
# ##
# -*- coding: utf-8 -*-
""" Fwpkg Command for rdmc """
import os
import json
import shutil
import zipfile
import tempfile
import ctypes
from ctypes import c_char_p, c_int, c_bool
from redfish.hpilo.risblobstore2 import BlobStore2
from ilorest.rdmc_helper import IncompatibleiLOVersionError, ReturnCodes, Encryption, \
InvalidCommandLineErrorOPTS, InvalidCommandLineError,\
InvalidFileInputError, UploadError, TaskQueueError, FirmwareUpdateError
def _get_comp_type(payload):
""" Get's the component type and returns it
:param payload: json payload of .fwpkg file
:type payload: dict.
:returns: returns the type of component. Either A,B,C, or D.
:rtype: string
"""
ctype = ''
if "Uefi" in payload['UpdatableBy'] and "RuntimeAgent" in payload['UpdatableBy']:
ctype = 'D'
else:
for device in payload['Devices']['Device']:
for image in device['FirmwareImages']:
if 'DirectFlashOk' not in list(image.keys()):
raise InvalidFileInputError("Cannot flash this firmware.")
if image['DirectFlashOk']:
ctype = 'A'
if image['ResetRequired']:
ctype = 'B'
break
elif image['UefiFlashable']:
ctype = 'C'
break
else:
ctype = 'D'
return ctype
class FwpkgCommand():
""" Fwpkg command class """
def __init__(self):
self.ident = {
'name':'flashfwpkg',
'usage': None,
'description':'Run to upload and flash '
'components from fwpkg files.\n\n\tUpload component and flashes it or sets a task'
'queue to flash.\n\texample: flashfwpkg component.fwpkg.\n\n\t'
'Skip extra checks before adding taskqueue. (Useful when adding '
'many flashfwpkg taskqueue items in sequence.)\n\texample: flashfwpkg '
'component.fwpkg --ignorechecks',
'summary':'Flashes fwpkg components using the iLO repository.',
'aliases': ['fwpkg'],
'auxcommands': ['UploadComponentCommand', 'UpdateTaskQueueCommand',
'FirmwareUpdateCommand', 'FwpkgCommand']
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
""" Main fwpkg worker function
:param line: string of arguments passed in
:type line: str.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, _) = self.rdmc.rdmc_parse_arglist(self, line)
if not line or line[0] == "help":
self.parser.print_help()
return ReturnCodes.SUCCESS
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
# self.rdmc.ui.printer(self.ident['usage'])
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
self.fwpkgvalidation(options)
if self.rdmc.app.typepath.defs.isgen9:
raise IncompatibleiLOVersionError(
'iLO Repository commands are only available on iLO 5.')
if self.rdmc.app.getiloversion() <= 5.120 and options.fwpkg.lower().startswith('iegen10'):
raise IncompatibleiLOVersionError('Please upgrade to iLO 5 1.20 or '
'greater to ensure correct flash of this firmware.')
tempdir = ''
if not options.fwpkg.endswith('.fwpkg'):
InvalidFileInputError("Invalid file type. Please make sure the file "
"provided is a valid .fwpkg file type.")
try:
components, tempdir, comptype = self.preparefwpkg(self, options.fwpkg)
if comptype == 'D':
raise InvalidFileInputError("Unable to flash this fwpkg file.")
elif comptype == 'C':
try:
self.taskqueuecheck()
except TaskQueueError as excp:
if options.ignore:
self.rdmc.ui.warn(str(excp)+'\n')
else:
raise excp
self.applyfwpkg(options, tempdir, components, comptype)
if comptype == 'A':
message = "Firmware has successfully been flashed.\n"
if 'ilo' in options.fwpkg.lower():
message += "iLO will reboot to complete flashing. Session will be"\
" terminated.\n"
elif comptype == 'B':
message = "Firmware has successfully been flashed and a reboot is required for "\
"this firmware to take effect.\n"
elif comptype == 'C':
message = "This firmware is set to flash on reboot.\n"
self.rdmc.ui.printer(message)
except (FirmwareUpdateError, UploadError) as excp:
raise excp
finally:
if tempdir:
shutil.rmtree(tempdir)
self.cmdbase.logout_routine(self, options)
#Return code
return ReturnCodes.SUCCESS
def taskqueuecheck(self):
""" Check taskqueue for potential issues before starting """
select = "ComputerSystem."
results = self.rdmc.app.select(selector=select, path_refresh=True)
try:
results = results[0]
except:
pass
powerstate = results.resp.dict['PowerState']
tasks = self.rdmc.app.getcollectionmembers(
'/redfish/v1/UpdateService/UpdateTaskQueue/')
for task in tasks:
if task['State'] == 'Exception':
raise TaskQueueError("Exception found in taskqueue which will "
"prevent firmware from flashing. Please run "
"iLOrest command: taskqueue --cleanqueue to clear"
" any errors before continuing.")
if task['UpdatableBy'] == 'Uefi' and not powerstate == 'Off' or \
task['Command'] == "Wait":
raise TaskQueueError("Taskqueue item found that will "
"prevent firmware from flashing immediately. Please "
"run iLOrest command: taskqueue --resetqueue to "
"reset the queue if you wish to flash immediately "
"or include --ignorechecks to add this firmware "
"into the task queue anyway.")
if tasks:
self.rdmc.ui.warn("Items are in the taskqueue that may delay the flash until they "
"are finished processing. Use the taskqueue command to monitor updates.\n")
@staticmethod
def preparefwpkg(self, pkgfile):
""" Prepare fwpkg file for flashing
:param pkgfile: Location of the .fwpkg file
:type pkgfile: string.
:returns: returns the files needed to flash, directory they are located
in, and type of file.
:rtype: string, string, string
"""
files = []
imagefiles = []
payloaddata = None
tempdir = tempfile.mkdtemp()
try:
zfile = zipfile.ZipFile(pkgfile)
zfile.extractall(tempdir)
zfile.close()
except Exception as excp:
raise InvalidFileInputError("Unable to unpack file. " + str(excp))
files = os.listdir(tempdir)
if 'payload.json' in files:
with open(os.path.join(tempdir, 'payload.json'), encoding='utf-8') as pfile:
data = pfile.read()
payloaddata = json.loads(data)
else:
raise InvalidFileInputError("Unable to find payload.json in fwpkg file.")
comptype = _get_comp_type(payloaddata)
if comptype == 'C':
imagefiles = [self.auxcommands['flashfwpkg'].type_c_change(tempdir, pkgfile)]
else:
results = self.rdmc.app.getprops(selector="UpdateService.",
props=['Oem/Hpe/Capabilities'])
for device in payloaddata['Devices']['Device']:
for firmwareimage in device['FirmwareImages']:
if firmwareimage['FileName'] not in imagefiles:
imagefiles.append(firmwareimage['FileName'])
if comptype in ['A','B'] and results and 'UpdateFWPKG' in results[0]['Oem']['Hpe']\
['Capabilities']:
dll = BlobStore2.gethprestchifhandle()
dll.isFwpkg20.argtypes = [c_char_p, c_int]
dll.isFwpkg20.restype = c_bool
with open(pkgfile, 'rb') as fwpkgfile:
fwpkgdata = fwpkgfile.read()
fwpkg_buffer = ctypes.create_string_buffer(fwpkgdata)
if dll.isFwpkg20(fwpkg_buffer, 2048):
imagefiles = [pkgfile]
tempdir = ''
return imagefiles, tempdir, comptype
def type_c_change(self, tdir, pkgloc):
""" Special changes for type C
:param tempdir: path to temp directory
:type tempdir: string.
:param components: components to upload
:type components: list.
:returns: The location of the type C file to upload
:rtype: string.
"""
shutil.copy(pkgloc, tdir)
fwpkgfile = os.path.split(pkgloc)[1]
zfile = fwpkgfile[:-6] + '.zip'
zipfileloc = os.path.join(tdir, zfile)
os.rename(os.path.join(tdir, fwpkgfile), zipfileloc)
return zipfileloc
def applyfwpkg(self, options, tempdir, components, comptype):
""" Apply the component to iLO
:param options: command line options
:type options: list.
:param tempdir: path to temp directory
:type tempdir: string.
:param components: components to upload
:type components: list.
:param comptype: type of component. Either A,B,C, or D.
:type comptype: str.
"""
for component in components:
taskqueuecommand = ' create %s ' % os.path.basename(component)
if options.tover:
taskqueuecommand = ' create %s --tpmover' % os.path.basename(component)
if component.endswith('.fwpkg') or component.endswith('.zip'):
uploadcommand = '--component %s' % component
else:
uploadcommand = '--component %s' % os.path.join(tempdir, component)
if options.forceupload:
uploadcommand += ' --forceupload'
if comptype in ['A', 'B']:
uploadcommand += ' --update_target --update_repository'
if options.update_srs:
uploadcommand += ' --update_srs'
self.rdmc.ui.printer("Uploading firmware: %s\n" % os.path.basename(component))
try:
ret = self.auxcommands['uploadcomp'].run(uploadcommand)
if ret != ReturnCodes.SUCCESS:
raise UploadError
except UploadError:
if comptype in ['A', 'B']:
select = self.rdmc.app.typepath.defs.hpilofirmwareupdatetype
results = self.rdmc.app.select(selector=select)
try:
results = results[0]
except:
pass
if results:
update_path = results.resp.request.path
error = self.rdmc.app.get_handler(update_path, silent=True)
self.auxcommands['firmwareupdate'].printerrmsg(error)
else:
raise FirmwareUpdateError("Error occurred while updating the firmware.")
else:
raise UploadError('Error uploading component.')
if comptype == 'C':
self.rdmc.ui.warn("Setting a taskqueue item to flash UEFI flashable firmware.\n")
self.auxcommands['taskqueue'].run(taskqueuecommand)
def fwpkgvalidation(self, options):
""" fwpkg validation function
:param options: command line options
:type options: list.
"""
self.rdmc.login_select_validation(self, options)
def definearguments(self, customparser):
""" Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
'fwpkg',
help="""fwpkg file path""",
metavar="[FWPKG]"
)
customparser.add_argument(
'--forceupload',
dest='forceupload',
action="store_true",
help='Add this flag to force upload firmware with the same name '\
'already on the repository.',
default=False
)
customparser.add_argument(
'--ignorechecks',
dest='ignore',
action="store_true",
help='Add this flag to ignore all checks to the taskqueue '\
'before attempting to process the .fwpkg file.',
default=False
)
customparser.add_argument(
'--tpmover',
dest='tover',
action="store_true",
help="If set then the TPMOverrideFlag is passed in on the "\
"associated flash operations",
default=False
)
customparser.add_argument(
'--update_srs',
dest='update_srs',
action="store_true",
help="Add this flag to update the System Recovery Set with the uploaded firmware. " \
"NOTE: This requires an account login with the system recovery set privilege.",
default=False
)
|
import handler from './libs/handler-lib';
import dynamoDb from './libs/dynamodb-lib';
export const main = handler(async (event, context) => {
const params = {
TableName: process.env.tableName,
KeyConditionExpression: 'score > 0',
};
const result = await dynamoDb.scan(params);
// Return the matching list of items in response body
return result.Items;
});
|
// 代入演算子
let i = 0;
// 算術演算
i = 10 + 3; // → 13
i = 10 - 3; // → 7
i = 10 * 3; // → 30
i = 10 / 3; // → 3.3333333333333335
i = 10 % 3; // → 1
i = 10 ** 3; // → 1000
// 代入+算術演算
console.log(i); // → 1000
i += 3; // → 1003
i -= 3; // → 1000
i *= 3; // → 3000
i /= 3; // → 1000
i %= 3; // → 1
// インクリメント、デクリメント
i = 1;
console.log(++i); // → 2;
i = 1;
console.log(i++); // → 1;
i = 1;
console.log(--i); // → 0;
i = 1;
console.log(i--); // → 1;
// ----------------------------------------------------------------------------
// 文字列の連結
i = 'abc' + 'def';
console.log(i); // → abcdef
// ----------------------------------------------------------------------------
// 論理演算
i = !true; // → false
i = 1 == 1; // → true
i = 1 != 1; // → false
i = 1 === 1; // → true
i = 1 !== 1; // → false
i = 1 > 1; // → false
i = 1 < 1; // → false
i = 1 >= 1; // → true
i = 1 <= 1; // → true
i = true && false; // → false
i = true || false; // → true
// ----------------------------------------------------------------------------
// ビット演算
i = ~2; // → -3
i = 1 & 2; // → 0
i = 1 | 2; // → 3
i = 1 ^ 2; // → 3
i = 100 << 2; // → 400
i = -100 << 2; // → -400
i = 100 >> 2; // → 25
i = -100 >> 2; // → -25
i = 100 >>> 2; // → 25
i = -100 >>> 2; // → 1073741799
// ----------------------------------------------------------------------------
// その他、比較的よく利用する演算子
console.log(+1); // → 1
console.log(+'1'); // → 1
console.log(-1); // → -1
console.log(-'-1'); // → 1
console.log(typeof 0); // → number
console.log([] instanceof Array); // → true
console.log(true ? '真' : '偽'); // → 真
i = {foo: 'foo', bar: 'bar'};
delete i.foo;
console.log(i); // → {bar: 'bar'}
|
const info = () => 'Welcome to Golb API.';
const findMany = async (
where,
{ skip, take, orderBy },
schemaContext,
collectionName
) => {
const collection = await schemaContext.findMany({
where,
skip,
take,
orderBy,
});
const count = await schemaContext.count({ where });
let res = {};
res[collectionName] = collection;
res.count = count;
return res;
};
// -------- Article ----------------------
const articles = async (parent, args, context) => {
const where = args.filter
? {
OR: [
{ title: { contains: args.filter } },
{ content: { contains: args.filter } },
],
}
: {};
return await findMany(where, args, context.prisma.article, 'articles');
};
const article = async (parent, args, context) =>
await context.prisma.article.findOne({ where: { id: args.id } });
// -------- User ----------------------
const users = async (parent, args, context) => {
const where = args.filter
? {
OR: [
{ name: { contains: args.filter } },
{ email: { contains: args.filter } },
],
}
: {};
return await findMany(where, args, context.prisma.user, 'users');
};
const user = async (parent, args, context) =>
await context.prisma.user.findOne({ where: { id: args.id } });
// -------- Comment ----------------------
const comments = async (parent, args, context) => {
const where = args.filter
? {
OR: [{ content: { contains: args.filter } }],
}
: {};
return await findMany(where, args, context.prisma.comment, 'comments');
};
const comment = async (parent, args, context) =>
await context.prisma.comment.findOne({ where: { id: args.id } });
// -------- Vote ----------------------
const votes = async (parent, args, context) => {
let where = {};
if (args.filter) {
if (args.filter.voteId) {
where = { id: { equals: +args.filter.voteId } };
}
if (args.filter.articleId) {
where = { article: { id: { equals: +args.filter.articleId } } };
}
if (args.filter.userId) {
where = { user: { id: { equals: +args.filter.userId } } };
}
}
return await findMany(where, args, context.prisma.vote, 'votes');
};
const vote = async (parent, args, context) =>
await context.prisma.vote.findOne({ where: { id: args.id } });
const Query = {
info,
articles,
article,
users,
user,
comments,
comment,
votes,
vote,
};
export default Query;
|
var table = $('.table').DataTable({
dom: 'Bfrtip',
responsive: true,
"aaSorting": [],
/* "columnDefs": [
{"orderable": false, "targets": 0}
],*/
/* "columnDefs": [
{
"targets": [ 1,2,3 ],
"visible": false,
"searchable": true
},
],*/
lengthChange: true,
buttons: [{
extend: 'copy',
exportOptions: {
columns: ':visible'
}
}, {
extend: 'excel',
exportOptions: {
columns: ':visible'
}
}, {
extend: 'pdf',
exportOptions: {
columns: ':visible'
}
}, {
extend: 'print',
exportOptions: {
columns: ':visible'
}
}, 'colvis']
});
table.buttons().container()
.appendTo('#example_wrapper .col-sm-6:eq(0)');
$("#data").on("click", "tbody tr", function () {
})
|
/**
* Auto-generated action file for "Vimeo" API.
*
* Generated at: 2019-05-07T14:44:41.143Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / vimeo-com-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: [email protected]
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: 'get_album_alt1'
* Endpoint Path: '/me/albums/{album_id}'
* Method: 'get'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"album_id"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"album_id": "album_id"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = undefined;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
securities['oauth2'] = {token: cfg['oauth2']};
let callParams = {
spec: spec,
operationId: 'get_album_alt1',
pathName: '/me/albums/{album_id}',
method: 'get',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
} |
macDetailCallback("00d00d000000/24",[{"d":"2000-09-08","t":"add","a":"CORPORATION\nONE MICROMEERITICS DRIVE\nNORCROSS GA 30093-1877\n","c":"UNITED STATES","o":"MICROMERITICS INSTRUMENT"},{"d":"2001-10-24","t":"change","a":"CORPORATION\nONE MICROMEERITICS DRIVE\nNORCROSS GA 30093-1877\n","c":"UNITED STATES","o":"MICROMERITICS INSTRUMENT"},{"d":"2015-08-27","t":"change","a":"CORPORATION NORCROSS GA US 30093-1877","c":"US","o":"MICROMERITICS INSTRUMENT"}]);
|
r"""Importing this file must **not** initialize CUDA context. test_distributed
relies on this assumption to properly run. This means that when this is imported
no CUDA calls shall be made, including torch.cuda.device_count(), etc.
torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported.
"""
import sys
import os
import platform
import re
import gc
import types
import math
from functools import partial
import inspect
import io
import copy
import operator
import argparse
import unittest
import warnings
import random
import contextlib
import shutil
import datetime
import pathlib
import socket
import subprocess
import time
from collections import OrderedDict
from collections.abc import Sequence
from contextlib import contextmanager, closing
from functools import wraps
from itertools import product
from copy import deepcopy
from numbers import Number
import tempfile
import json
from urllib.request import urlopen
import __main__ # type: ignore[import]
import errno
from typing import cast, Any, Dict, Iterable, Iterator, Optional, Union
import numpy as np
from torch.testing import floating_types_and, integral_types, complex_types
import expecttest
from .._core import \
(_compare_tensors_internal, _compare_scalars_internal, _compare_return_type)
import torch
import torch.cuda
from torch._utils_internal import get_writable_path
from torch._six import string_classes
import torch.backends.cudnn
import torch.backends.mkl
from enum import Enum
torch.backends.disable_global_flags()
FILE_SCHEMA = "file://"
if sys.platform == 'win32':
FILE_SCHEMA = "file:///"
# Environment variable `IN_CI` is set in `.jenkins/common.sh`.
IS_IN_CI = os.getenv('IN_CI') == '1'
IS_SANDCASTLE = os.getenv('SANDCASTLE') == '1' or os.getenv('TW_JOB_USER') == 'sandcastle'
IS_FBCODE = os.getenv('PYTORCH_TEST_FBCODE') == '1'
IS_REMOTE_GPU = os.getenv('PYTORCH_TEST_REMOTE_GPU') == '1'
class ProfilingMode(Enum):
LEGACY = 1
SIMPLE = 2
PROFILING = 3
def cppProfilingFlagsToProfilingMode():
old_prof_exec_state = torch._C._jit_set_profiling_executor(True)
old_prof_mode_state = torch._C._jit_set_profiling_mode(True)
torch._C._jit_set_profiling_executor(old_prof_exec_state)
torch._C._jit_set_profiling_mode(old_prof_mode_state)
if old_prof_exec_state:
if old_prof_mode_state:
return ProfilingMode.PROFILING
else:
return ProfilingMode.SIMPLE
else:
return ProfilingMode.LEGACY
@contextmanager
def enable_profiling_mode_for_profiling_tests():
if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
old_prof_exec_state = torch._C._jit_set_profiling_executor(True)
old_prof_mode_state = torch._C._jit_set_profiling_mode(True)
try:
yield
finally:
if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
torch._C._jit_set_profiling_executor(old_prof_exec_state)
torch._C._jit_set_profiling_mode(old_prof_mode_state)
@contextmanager
def enable_profiling_mode():
old_prof_exec_state = torch._C._jit_set_profiling_executor(True)
old_prof_mode_state = torch._C._jit_set_profiling_mode(True)
try:
yield
finally:
torch._C._jit_set_profiling_executor(old_prof_exec_state)
torch._C._jit_set_profiling_mode(old_prof_mode_state)
@contextmanager
def num_profiled_runs(num_runs):
old_num_runs = torch._C._jit_set_num_profiled_runs(num_runs)
try:
yield
finally:
torch._C._jit_set_num_profiled_runs(old_num_runs)
func_call = torch._C.ScriptFunction.__call__
meth_call = torch._C.ScriptMethod.__call__
def prof_callable(callable, *args, **kwargs):
if 'profile_and_replay' in kwargs:
del kwargs['profile_and_replay']
if GRAPH_EXECUTOR == ProfilingMode.PROFILING:
with enable_profiling_mode_for_profiling_tests():
callable(*args, **kwargs)
return callable(*args, **kwargs)
return callable(*args, **kwargs)
def prof_func_call(*args, **kwargs):
return prof_callable(func_call, *args, **kwargs)
def prof_meth_call(*args, **kwargs):
return prof_callable(meth_call, *args, **kwargs)
# TODO fix when https://github.com/python/mypy/issues/2427 is address
torch._C.ScriptFunction.__call__ = prof_func_call # type: ignore[assignment]
torch._C.ScriptMethod.__call__ = prof_meth_call # type: ignore[assignment]
def _get_test_report_path():
# allow users to override the test file location. We need this
# because the distributed tests run the same test file multiple
# times with different configurations.
override = os.environ.get('TEST_REPORT_SOURCE_OVERRIDE')
test_source = override if override is not None else 'python-unittest'
return os.path.join('test-reports', test_source)
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--subprocess', action='store_true',
help='whether to run each test in a subprocess')
parser.add_argument('--seed', type=int, default=1234)
parser.add_argument('--accept', action='store_true')
parser.add_argument('--jit_executor', type=str)
parser.add_argument('--repeat', type=int, default=1)
parser.add_argument('--test_bailouts', action='store_true')
parser.add_argument('--save-xml', nargs='?', type=str,
const=_get_test_report_path(),
default=_get_test_report_path() if IS_IN_CI else None)
parser.add_argument('--discover-tests', action='store_true')
parser.add_argument('--log-suffix', type=str, default="")
parser.add_argument('--run-parallel', type=int, default=1)
args, remaining = parser.parse_known_args()
if args.jit_executor == 'legacy':
GRAPH_EXECUTOR = ProfilingMode.LEGACY
elif args.jit_executor == 'profiling':
GRAPH_EXECUTOR = ProfilingMode.PROFILING
elif args.jit_executor == 'simple':
GRAPH_EXECUTOR = ProfilingMode.SIMPLE
else:
# infer flags based on the default settings
GRAPH_EXECUTOR = cppProfilingFlagsToProfilingMode()
LOG_SUFFIX = args.log_suffix
RUN_PARALLEL = args.run_parallel
TEST_BAILOUTS = args.test_bailouts
TEST_DISCOVER = args.discover_tests
TEST_IN_SUBPROCESS = args.subprocess
TEST_SAVE_XML = args.save_xml
REPEAT_COUNT = args.repeat
SEED = args.seed
if not expecttest.ACCEPT:
expecttest.ACCEPT = args.accept
UNITTEST_ARGS = [sys.argv[0]] + remaining
torch.manual_seed(SEED)
# CI Prefix path used only on CI environment
CI_TEST_PREFIX = str(pathlib.Path(os.getcwd()))
def wait_for_process(p):
try:
return p.wait()
except KeyboardInterrupt:
# Give `p` a chance to handle KeyboardInterrupt. Without this,
# `pytest` can't print errors it collected so far upon KeyboardInterrupt.
exit_status = p.wait(timeout=5)
if exit_status is not None:
return exit_status
else:
p.kill()
raise
except: # noqa: B001,E722, copied from python core library
p.kill()
raise
finally:
# Always call p.wait() to ensure exit
p.wait()
def shell(command, cwd=None, env=None):
sys.stdout.flush()
sys.stderr.flush()
# The following cool snippet is copied from Py3 core library subprocess.call
# only the with
# 1. `except KeyboardInterrupt` block added for SIGINT handling.
# 2. In Py2, subprocess.Popen doesn't return a context manager, so we do
# `p.wait()` in a `final` block for the code to be portable.
#
# https://github.com/python/cpython/blob/71b6c1af727fbe13525fb734568057d78cea33f3/Lib/subprocess.py#L309-L323
assert not isinstance(command, torch._six.string_classes), "Command to shell should be a list or tuple of tokens"
p = subprocess.Popen(command, universal_newlines=True, cwd=cwd, env=env)
return wait_for_process(p)
# Used to run the same test with different tensor types
def repeat_test_for_types(dtypes):
def repeat_helper(f):
@wraps(f)
def call_helper(self, *args):
for dtype in dtypes:
with TestCase.subTest(self, dtype=dtype):
f(self, *args, dtype=dtype)
return call_helper
return repeat_helper
def discover_test_cases_recursively(suite_or_case):
if isinstance(suite_or_case, unittest.TestCase):
return [suite_or_case]
rc = []
for element in suite_or_case:
rc.extend(discover_test_cases_recursively(element))
return rc
def get_test_names(test_cases):
return ['.'.join(case.id().split('.')[-2:]) for case in test_cases]
def chunk_list(lst, nchunks):
return [lst[i::nchunks] for i in range(nchunks)]
# sanitize filename e.g., distributed/pipeline/sync/skip/test_api.py -> distributed.pipeline.sync.skip.test_api
def sanitize_test_filename(filename):
# inspect.getfile returns absolute path in some CI jobs, converting it to relative path if needed
if filename.startswith(CI_TEST_PREFIX):
filename = filename[len(CI_TEST_PREFIX) + 1:]
strip_py = re.sub(r'.py$', '', filename)
return re.sub('/', r'.', strip_py)
def run_tests(argv=UNITTEST_ARGS):
if TEST_DISCOVER:
suite = unittest.TestLoader().loadTestsFromModule(__main__)
test_cases = discover_test_cases_recursively(suite)
for name in get_test_names(test_cases):
print(name)
elif TEST_IN_SUBPROCESS:
suite = unittest.TestLoader().loadTestsFromModule(__main__)
test_cases = discover_test_cases_recursively(suite)
failed_tests = []
for case in test_cases:
test_case_full_name = case.id().split('.', 1)[1]
exitcode = shell([sys.executable] + argv + [test_case_full_name])
if exitcode != 0:
failed_tests.append(test_case_full_name)
assert len(failed_tests) == 0, "{} unit test(s) failed:\n\t{}".format(
len(failed_tests), '\n\t'.join(failed_tests))
elif RUN_PARALLEL > 1:
suite = unittest.TestLoader().loadTestsFromModule(__main__)
test_cases = discover_test_cases_recursively(suite)
test_batches = chunk_list(get_test_names(test_cases), RUN_PARALLEL)
processes = []
for i in range(RUN_PARALLEL):
command = [sys.executable] + argv + ['--log-suffix=-shard-{}'.format(i + 1)] + test_batches[i]
processes.append(subprocess.Popen(command, universal_newlines=True))
failed = False
for p in processes:
failed |= wait_for_process(p) != 0
assert not failed, "Some test shards have failed"
elif TEST_SAVE_XML is not None:
# import here so that non-CI doesn't need xmlrunner installed
import xmlrunner # type: ignore[import]
test_filename = sanitize_test_filename(inspect.getfile(sys._getframe(1)))
test_report_path = TEST_SAVE_XML + LOG_SUFFIX
test_report_path = os.path.join(test_report_path, test_filename)
os.makedirs(test_report_path, exist_ok=True)
verbose = '--verbose' in argv or '-v' in argv
if verbose:
print('Test results will be stored in {}'.format(test_report_path))
unittest.main(argv=argv, testRunner=xmlrunner.XMLTestRunner(output=test_report_path, verbosity=2 if verbose else 1))
elif REPEAT_COUNT > 1:
for _ in range(REPEAT_COUNT):
if not unittest.main(exit=False, argv=argv).result.wasSuccessful():
sys.exit(-1)
else:
unittest.main(argv=argv)
IS_WINDOWS = sys.platform == "win32"
IS_MACOS = sys.platform == "darwin"
IS_PPC = platform.machine() == "ppc64le"
if IS_WINDOWS:
@contextmanager
def TemporaryFileName(*args, **kwargs):
# Ideally we would like to not have to manually delete the file, but NamedTemporaryFile
# opens the file, and it cannot be opened multiple times in Windows. To support Windows,
# close the file after creation and try to remove it manually
if 'delete' in kwargs:
if kwargs['delete'] is not False:
raise UserWarning("only TemporaryFileName with delete=False is supported on Windows.")
else:
kwargs['delete'] = False
f = tempfile.NamedTemporaryFile(*args, **kwargs)
try:
f.close()
yield f.name
finally:
os.unlink(f.name)
else:
@contextmanager # noqa: T484
def TemporaryFileName(*args, **kwargs):
with tempfile.NamedTemporaryFile(*args, **kwargs) as f:
yield f.name
if IS_WINDOWS:
@contextmanager
def TemporaryDirectoryName(suffix=None):
# On Windows the directory created by TemporaryDirectory is likely to be removed prematurely,
# so we first create the directory using mkdtemp and then remove it manually
try:
dir_name = tempfile.mkdtemp(suffix=suffix)
yield dir_name
finally:
shutil.rmtree(dir_name)
else:
@contextmanager # noqa: T484
def TemporaryDirectoryName(suffix=None):
with tempfile.TemporaryDirectory(suffix=suffix) as d:
yield d
IS_FILESYSTEM_UTF8_ENCODING = sys.getfilesystemencoding() == 'utf-8'
def _check_module_exists(name):
r"""Returns if a top-level module with :attr:`name` exists *without**
importing it. This is generally safer than try-catch block around a
`import X`. It avoids third party libraries breaking assumptions of some of
our tests, e.g., setting multiprocessing start method when imported
(see librosa/#747, torchvision/#544).
"""
import importlib.util
spec = importlib.util.find_spec(name)
return spec is not None
TEST_NUMPY = _check_module_exists('numpy')
TEST_SCIPY = _check_module_exists('scipy')
TEST_MKL = torch.backends.mkl.is_available()
TEST_NUMBA = _check_module_exists('numba')
TEST_DILL = _check_module_exists('dill')
TEST_LIBROSA = _check_module_exists('librosa')
# Python 2.7 doesn't have spawn
NO_MULTIPROCESSING_SPAWN = os.environ.get('NO_MULTIPROCESSING_SPAWN', '0') == '1'
TEST_WITH_ASAN = os.getenv('PYTORCH_TEST_WITH_ASAN', '0') == '1'
TEST_WITH_TSAN = os.getenv('PYTORCH_TEST_WITH_TSAN', '0') == '1'
TEST_WITH_UBSAN = os.getenv('PYTORCH_TEST_WITH_UBSAN', '0') == '1'
TEST_WITH_ROCM = os.getenv('PYTORCH_TEST_WITH_ROCM', '0') == '1'
# Enables tests that are slow to run (disabled by default)
TEST_WITH_SLOW = os.getenv('PYTORCH_TEST_WITH_SLOW', '0') == '1'
# Disables non-slow tests (these tests enabled by default)
# This is usually used in conjunction with TEST_WITH_SLOW to
# run *only* slow tests. (I could have done an enum, but
# it felt a little awkward.
TEST_SKIP_FAST = os.getenv('PYTORCH_TEST_SKIP_FAST', '0') == '1'
# Disables noarch tests; all but one CI configuration disables these. We don't
# disable them for local runs because you still want to run them
# (unlike slow tests!)
TEST_SKIP_NOARCH = os.getenv('PYTORCH_TEST_SKIP_NOARCH', '0') == '1'
# Determine whether to enable cuda memory leak check.
# CUDA mem leak check is expensive and thus we don't want to execute it on every
# test case / configuration.
# See: https://github.com/pytorch/pytorch/pull/59402#issuecomment-858811135
TEST_SKIP_CUDA_MEM_LEAK_CHECK = os.getenv('PYTORCH_TEST_SKIP_CUDA_MEM_LEAK_CHECK', '0') == '1'
# Disables tests for when on Github Actions
ON_GHA = os.getenv('GITHUB_ACTIONS', '0') == '1'
# Dict of NumPy dtype -> torch dtype (when the correspondence exists)
numpy_to_torch_dtype_dict = {
np.bool_ : torch.bool,
np.uint8 : torch.uint8,
np.int8 : torch.int8,
np.int16 : torch.int16,
np.int32 : torch.int32,
np.int64 : torch.int64,
np.float16 : torch.float16,
np.float32 : torch.float32,
np.float64 : torch.float64,
np.complex64 : torch.complex64,
np.complex128 : torch.complex128
}
if IS_WINDOWS:
# Size of `np.intc` is platform defined.
# It is returned by functions like `bitwise_not`.
# On Windows `int` is 32-bit
# https://docs.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-160
numpy_to_torch_dtype_dict[np.intc] = torch.int
# Dict of torch dtype -> NumPy dtype
torch_to_numpy_dtype_dict = {value : key for (key, value) in numpy_to_torch_dtype_dict.items()}
ALL_TENSORTYPES = [torch.float,
torch.double,
torch.half]
# bfloat16 bringup is currently only available on ROCm
# ALL_TENSORTYPES2 will eventually be unified with ALL_TENSORTYPES
# when bfloat16 bringup is complete on all platforms
if TEST_WITH_ROCM:
ALL_TENSORTYPES2 = [torch.float,
torch.double,
torch.half,
torch.bfloat16]
else:
ALL_TENSORTYPES2 = ALL_TENSORTYPES
def skipIfRocm(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if TEST_WITH_ROCM:
raise unittest.SkipTest("test doesn't currently work on the ROCm stack")
else:
fn(*args, **kwargs)
return wrapper
# Context manager for setting deterministic flag and automatically
# resetting it to its original value
class DeterministicGuard:
def __init__(self, deterministic):
self.deterministic = deterministic
def __enter__(self):
self.deterministic_restore = torch.are_deterministic_algorithms_enabled()
torch.use_deterministic_algorithms(self.deterministic)
def __exit__(self, exception_type, exception_value, traceback):
torch.use_deterministic_algorithms(self.deterministic_restore)
# This decorator can be used for API tests that call
# torch.use_deterministic_algorithms(). When the test is finished, it will
# restore the previous deterministic flag setting.
#
# If CUDA >= 10.2, this will set the environment variable
# CUBLAS_WORKSPACE_CONFIG=:4096:8 so that the error associated with that
# setting is not thrown during the test unless the test changes that variable
# on purpose. The previous CUBLAS_WORKSPACE_CONFIG setting will also be
# restored once the test is finished.
#
# Note that if a test requires CUDA to actually register the changed
# CUBLAS_WORKSPACE_CONFIG variable, a new subprocess must be created, because
# CUDA only checks the variable when the runtime initializes. Tests can be
# run inside a subprocess like so:
#
# import subprocess, sys, os
# script = '''
# # Test code should go here
# '''
# try:
# subprocess.check_output(
# [sys.executable, '-c', script],
# stderr=subprocess.STDOUT,
# cwd=os.path.dirname(os.path.realpath(__file__)),
# env=os.environ.copy())
# except subprocess.CalledProcessError as e:
# error_message = e.output.decode('utf-8')
# # Handle exceptions raised by the subprocess here
#
def wrapDeterministicFlagAPITest(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
with DeterministicGuard(torch.are_deterministic_algorithms_enabled()):
class CuBLASConfigGuard:
cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG'
def __enter__(self):
self.is_cuda10_2_or_higher = (
(torch.version.cuda is not None)
and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2]))
if self.is_cuda10_2_or_higher:
self.cublas_config_restore = os.environ.get(self.cublas_var_name)
os.environ[self.cublas_var_name] = ':4096:8'
def __exit__(self, exception_type, exception_value, traceback):
if self.is_cuda10_2_or_higher:
cur_cublas_config = os.environ.get(self.cublas_var_name)
if self.cublas_config_restore is None:
if cur_cublas_config is not None:
del os.environ[self.cublas_var_name]
else:
os.environ[self.cublas_var_name] = self.cublas_config_restore
with CuBLASConfigGuard():
fn(*args, **kwargs)
return wrapper
def skipIfCompiledWithoutNumpy(fn):
# Even if the numpy module is present, if `USE_NUMPY=0` is used during the
# build, numpy tests will fail
numpy_support = TEST_NUMPY
if numpy_support:
try:
# The numpy module is present, verify that PyTorch is compiled with
# numpy support
torch.from_numpy(np.array([2, 2]))
except RuntimeError:
numpy_support = False
@wraps(fn)
def wrapper(*args, **kwargs):
if not numpy_support:
raise unittest.SkipTest("PyTorch was compiled without numpy support")
else:
fn(*args, **kwargs)
return wrapper
def _test_function(fn, device):
def run_test_function(self):
return fn(self, device)
return run_test_function
def skipIfNoLapack(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not torch._C.has_lapack:
raise unittest.SkipTest('PyTorch compiled without Lapack')
else:
fn(*args, **kwargs)
return wrapper
def skipIfNotRegistered(op_name, message):
"""Wraps the decorator to hide the import of the `core`.
Args:
op_name: Check if this op is registered in `core._REGISTERED_OPERATORS`.
message: message to fail with.
Usage:
@skipIfNotRegistered('MyOp', 'MyOp is not linked!')
This will check if 'MyOp' is in the caffe2.python.core
"""
try:
from caffe2.python import core
skipper = unittest.skipIf(op_name not in core._REGISTERED_OPERATORS,
message)
except ImportError:
skipper = unittest.skip("Cannot import `caffe2.python.core`")
return skipper
def skipIfNoSciPy(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not TEST_SCIPY:
raise unittest.SkipTest("test require SciPy, but SciPy not found")
else:
fn(*args, **kwargs)
return wrapper
def skipIfOnGHA(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if ON_GHA:
raise unittest.SkipTest("Test disabled for GHA")
else:
fn(*args, **kwargs)
return wrapper
def slowTest(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not TEST_WITH_SLOW:
raise unittest.SkipTest("test is slow; run with PYTORCH_TEST_WITH_SLOW to enable test")
else:
fn(*args, **kwargs)
wrapper.__dict__['slow_test'] = True
return wrapper
# noarch tests are tests that should be only run on one CI configuration,
# because they don't exercise any interesting platform specific code
# and so if run once, indicate the test should pass everywhere.
# See https://github.com/pytorch/pytorch/issues/53743
def noarchTest(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if TEST_SKIP_NOARCH:
raise unittest.SkipTest("test is noarch: we are skipping noarch tests due to TEST_SKIP_NOARCH")
else:
fn(*args, **kwargs)
return wrapper
def slowAwareTest(fn):
fn.__dict__['slow_test'] = True
return fn
def skipCUDAMemoryLeakCheckIf(condition):
def dec(fn):
if getattr(fn, '_do_cuda_memory_leak_check', True): # if current True
fn._do_cuda_memory_leak_check = not condition
return fn
return dec
def skipCUDANonDefaultStreamIf(condition):
def dec(fn):
if getattr(fn, '_do_cuda_non_default_stream', True): # if current True
fn._do_cuda_non_default_stream = not condition
return fn
return dec
def suppress_warnings(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fn(*args, **kwargs)
return wrapper
def to_gpu(obj, type_map=None):
if type_map is None:
type_map = {}
if isinstance(obj, torch.Tensor):
assert obj.is_leaf
t = type_map.get(obj.dtype, obj.dtype)
with torch.no_grad():
res = obj.clone().to(dtype=t, device="cuda")
res.requires_grad = obj.requires_grad
return res
elif torch.is_storage(obj):
return obj.new().resize_(obj.size()).copy_(obj)
elif isinstance(obj, list):
return [to_gpu(o, type_map) for o in obj]
elif isinstance(obj, tuple):
return tuple(to_gpu(o, type_map) for o in obj)
else:
return deepcopy(obj)
def get_function_arglist(func):
return inspect.getfullargspec(func).args
def set_rng_seed(seed):
torch.manual_seed(seed)
random.seed(seed)
if TEST_NUMPY:
np.random.seed(seed)
@contextlib.contextmanager
def freeze_rng_state():
rng_state = torch.get_rng_state()
if torch.cuda.is_available():
cuda_rng_state = torch.cuda.get_rng_state()
yield
if torch.cuda.is_available():
torch.cuda.set_rng_state(cuda_rng_state)
torch.set_rng_state(rng_state)
@contextlib.contextmanager
def set_default_dtype(dtype):
saved_dtype = torch.get_default_dtype()
torch.set_default_dtype(dtype)
try:
yield
finally:
torch.set_default_dtype(saved_dtype)
def iter_indices(tensor):
if tensor.dim() == 0:
return range(0)
if tensor.dim() == 1:
return range(tensor.size(0))
return product(*(range(s) for s in tensor.size()))
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
def is_iterable_of_tensors(iterable, include_empty=False):
""" Returns True if iterable is an iterable of tensors and False o.w.
If the iterable is empty, the return value is :attr:`include_empty`
"""
# Tensor itself is iterable so we check this first
if isinstance(iterable, torch.Tensor):
return False
try:
if len(iterable) == 0:
return include_empty
for t in iter(iterable):
if not isinstance(t, torch.Tensor):
return False
except TypeError as te:
return False
return True
class CudaNonDefaultStream():
def __enter__(self):
# Before starting CUDA test save currently active streams on all
# CUDA devices and set new non default streams to all CUDA devices
# to ensure CUDA tests do not use default stream by mistake.
beforeDevice = torch.cuda.current_device()
self.beforeStreams = []
for d in range(torch.cuda.device_count()):
self.beforeStreams.append(torch.cuda.current_stream(d))
deviceStream = torch.cuda.Stream(device=d)
torch._C._cuda_setStream(deviceStream._cdata)
torch._C._cuda_setDevice(beforeDevice)
def __exit__(self, exec_type, exec_value, traceback):
# After completing CUDA test load previously active streams on all
# CUDA devices.
beforeDevice = torch.cuda.current_device()
for d in range(torch.cuda.device_count()):
torch._C._cuda_setStream(self.beforeStreams[d]._cdata)
torch._C._cuda_setDevice(beforeDevice)
class CudaMemoryLeakCheck():
def __init__(self, testcase, name=None):
self.name = testcase.id() if name is None else name
self.testcase = testcase
# initialize context & RNG to prevent false positive detections
# when the test is the first to initialize those
from torch.testing._internal.common_cuda import initialize_cuda_context_rng
initialize_cuda_context_rng()
@staticmethod
def get_cuda_memory_usage():
# we don't need CUDA synchronize because the statistics are not tracked at
# actual freeing, but at when marking the block as free.
num_devices = torch.cuda.device_count()
gc.collect()
return tuple(torch.cuda.memory_allocated(i) for i in range(num_devices))
def __enter__(self):
self.befores = self.get_cuda_memory_usage()
def __exit__(self, exec_type, exec_value, traceback):
# Don't check for leaks if an exception was thrown
if exec_type is not None:
return
afters = self.get_cuda_memory_usage()
for i, (before, after) in enumerate(zip(self.befores, afters)):
self.testcase.assertEqual(
before, after, msg='{} leaked {} bytes CUDA memory on device {}'.format(
self.name, after - before, i))
@contextmanager
def skip_exception_type(exc_type):
try:
yield
except exc_type as e:
raise unittest.SkipTest(f"not implemented: {e}") from e
# "min_satisfying_examples" setting has been deprecated in hypythesis
# 3.56.0 and removed in hypothesis 4.x
try:
import hypothesis
def settings(*args, **kwargs):
if 'min_satisfying_examples' in kwargs and hypothesis.version.__version_info__ >= (3, 56, 0):
kwargs.pop('min_satisfying_examples')
return hypothesis.settings(*args, **kwargs)
hypothesis.settings.register_profile(
"pytorch_ci",
settings(
derandomize=True,
suppress_health_check=[hypothesis.HealthCheck.too_slow],
database=None,
max_examples=50,
verbosity=hypothesis.Verbosity.normal))
hypothesis.settings.register_profile(
"dev",
settings(
suppress_health_check=[hypothesis.HealthCheck.too_slow],
database=None,
max_examples=10,
verbosity=hypothesis.Verbosity.normal))
hypothesis.settings.register_profile(
"debug",
settings(
suppress_health_check=[hypothesis.HealthCheck.too_slow],
database=None,
max_examples=1000,
verbosity=hypothesis.Verbosity.verbose))
hypothesis.settings.load_profile(
"pytorch_ci" if IS_IN_CI else os.getenv('PYTORCH_HYPOTHESIS_PROFILE', 'dev')
)
except ImportError:
print('Fail to import hypothesis in common_utils, tests are not derandomized')
FILE_CACHE_LIFESPAN_SECONDS = datetime.timedelta(hours=3).seconds
def fetch_and_cache(name: str, url: str):
"""
Some tests run in a different process so globals like `slow_test_dict` won't
always be filled even though the test file was already downloaded on this
machine, so cache it on disk
"""
path = os.path.join(tempfile.gettempdir(), name)
def is_cached_file_valid():
# Check if the file is new enough (say 1 hour for now). A real check
# could make a HEAD request and check/store the file's ETag
fname = pathlib.Path(path)
now = datetime.datetime.now()
mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
diff = now - mtime
return diff.total_seconds() < FILE_CACHE_LIFESPAN_SECONDS
if os.path.exists(path) and is_cached_file_valid():
# Another test process already downloaded the file, so don't re-do it
with open(path, "r") as f:
return json.load(f)
try:
contents = urlopen(url, timeout=1).read().decode('utf-8')
with open(path, "w") as f:
f.write(contents)
return json.loads(contents)
except Exception as e:
print(f'Could not download {url} because of error {e}.')
return {}
slow_tests_dict: Optional[Dict[str, float]] = None
def check_slow_test_from_stats(test):
global slow_tests_dict
if slow_tests_dict is None:
if not IS_SANDCASTLE and os.getenv("PYTORCH_RUN_DISABLED_TESTS", "0") != "1":
url = "https://raw.githubusercontent.com/pytorch/test-infra/master/stats/slow-tests.json"
slow_tests_dict = fetch_and_cache(".pytorch-slow-tests.json", url)
else:
slow_tests_dict = {}
test_suite = str(test.__class__).split('\'')[1]
test_name = f'{test._testMethodName} ({test_suite})'
if test_name in slow_tests_dict:
getattr(test, test._testMethodName).__dict__['slow_test'] = True
if not TEST_WITH_SLOW:
raise unittest.SkipTest("test is slow; run with PYTORCH_TEST_WITH_SLOW to enable test")
disabled_test_from_issues: Optional[Dict[str, Any]] = None
def check_disabled(test_name):
global disabled_test_from_issues
if disabled_test_from_issues is None:
_disabled_test_from_issues: Dict = {}
def read_and_process():
url = 'https://raw.githubusercontent.com/pytorch/test-infra/master/stats/disabled-tests.json'
contents = urlopen(url, timeout=1).read().decode('utf-8')
the_response = fetch_and_cache(".pytorch-disabled-tests", url)
for item in the_response['items']:
title = item['title']
key = 'DISABLED '
if title.startswith(key):
test_name = title[len(key):].strip()
_disabled_test_from_issues[test_name] = item['html_url']
if not IS_SANDCASTLE and os.getenv("PYTORCH_RUN_DISABLED_TESTS", "0") != "1":
try:
read_and_process()
disabled_test_from_issues = _disabled_test_from_issues
except Exception:
print("Couldn't download test skip set, leaving all tests enabled...")
disabled_test_from_issues = {}
if disabled_test_from_issues is not None:
if test_name in disabled_test_from_issues:
raise unittest.SkipTest(
"Test is disabled because an issue exists disabling it: {}".format(disabled_test_from_issues[test_name]) +
" To enable set the environment variable PYTORCH_RUN_DISABLED_TESTS=1")
# Acquires the comparison dtype, required since isclose
# requires both inputs have the same dtype, and isclose is not supported
# for some device x dtype combinations.
# NOTE: Remaps bfloat16 to float32 since neither the CPU or CUDA device types
# support needed bfloat16 comparison methods.
# NOTE: Remaps float16 to float32 on CPU since the CPU device type doesn't
# support needed float16 comparison methods.
# TODO: Update this once bfloat16 and float16 are better supported.
def get_comparison_dtype(a, b):
# TODO: update this when promote_types supports bfloat16 and/or
# isclose supports bfloat16.
a_dtype = torch.float32 if a.dtype is torch.bfloat16 else a.dtype
b_dtype = torch.float32 if b.dtype is torch.bfloat16 else b.dtype
compare_dtype = torch.promote_types(a_dtype, b_dtype)
# non-CUDA (CPU, for example) float16 -> float32
# TODO: update this when isclose is implemented for CPU float16
if (compare_dtype is torch.float16 and
(a.device != b.device or a.device.type != 'cuda' or
b.device.type != 'cuda')):
compare_dtype = torch.float32
return compare_dtype
# This implements a variant of assertRaises/assertRaisesRegex where we first test
# if the exception is NotImplementedError, and if so just skip the test instead
# of failing it.
#
# This is implemented by inheriting from the (private) implementation of
# assertRaises from unittest.case, and slightly tweaking it for this new
# behavior. The year is 2021: this private class hierarchy hasn't changed since
# 2010, seems low risk to inherit from.
class AssertRaisesContextIgnoreNotImplementedError(unittest.case._AssertRaisesContext):
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None and issubclass(exc_type, NotImplementedError):
self.test_case.skipTest(f"not_implemented: {exc_value}") # type: ignore[attr-defined]
return super().__exit__(exc_type, exc_value, tb)
@contextmanager
def set_warn_always_context(new_val: bool):
old_val = torch.is_warn_always_enabled()
torch.set_warn_always(new_val)
try:
yield
finally:
torch.set_warn_always(old_val)
class TestCase(expecttest.TestCase):
# NOTE: "precision" lets classes and generated tests set minimum
# atol values when comparing tensors. Used by @precisionOverride and @toleranceOverride, for
# example.
# NOTE: "rel_tol" lets classes and generated tests set minimum
# rtol values when comparing tensors. Used by @toleranceOverride, for example.
_precision: float = 0
_rel_tol: float = 0
# checker to early terminate test suite if unrecoverable failure occurs.
def _should_stop_test_suite(self):
if torch.cuda.is_initialized():
# CUDA device side error will cause subsequence test cases to fail.
# stop entire test suite if catches RuntimeError during torch.cuda.synchronize().
try:
torch.cuda.synchronize()
except RuntimeError as rte:
return True
return False
else:
return False
@property
def precision(self) -> float:
return self._precision
@precision.setter
def precision(self, prec: float) -> None:
self._precision = prec
@property
def rel_tol(self) -> float:
return self._rel_tol
@rel_tol.setter
def rel_tol(self, prec: float) -> None:
self._rel_tol = prec
_do_cuda_memory_leak_check = False
_do_cuda_non_default_stream = False
# When True, if a test case raises a NotImplementedError, instead of failing
# the test, skip it instead.
_ignore_not_implemented_error = False
def __init__(self, method_name='runTest'):
super().__init__(method_name)
test_method = getattr(self, method_name, None)
if test_method is not None:
# Wraps the tested method if we should do CUDA memory check.
if not TEST_SKIP_CUDA_MEM_LEAK_CHECK:
self._do_cuda_memory_leak_check &= getattr(test_method, '_do_cuda_memory_leak_check', True)
# FIXME: figure out the flaky -1024 anti-leaks on windows. See #8044
if self._do_cuda_memory_leak_check and not IS_WINDOWS:
self.wrap_with_cuda_policy(method_name, self.assertLeaksNoCudaTensors)
# Wraps the tested method if we should enforce non default CUDA stream.
self._do_cuda_non_default_stream &= getattr(test_method, '_do_cuda_non_default_stream', True)
if self._do_cuda_non_default_stream and not IS_WINDOWS:
self.wrap_with_cuda_policy(method_name, self.enforceNonDefaultStream)
if self._ignore_not_implemented_error:
self.wrap_with_policy(method_name, lambda: skip_exception_type(NotImplementedError))
def assertLeaksNoCudaTensors(self, name=None):
name = self.id() if name is None else name
return CudaMemoryLeakCheck(self, name)
def enforceNonDefaultStream(self):
return CudaNonDefaultStream()
def wrap_with_cuda_policy(self, method_name, policy):
test_method = getattr(self, method_name)
# the import below may initialize CUDA context, so we do it only if
# self._do_cuda_memory_leak_check or self._do_cuda_non_default_stream
# is True.
# TODO: sure looks like we unconditionally initialize the context here
# -- ezyang
from torch.testing._internal.common_cuda import TEST_CUDA
fullname = self.id().lower() # class_name.method_name
if TEST_CUDA and ('gpu' in fullname or 'cuda' in fullname):
setattr(self, method_name, self.wrap_method_with_policy(test_method, policy))
def wrap_with_policy(self, method_name, policy):
test_method = getattr(self, method_name)
setattr(self, method_name, self.wrap_method_with_policy(test_method, policy))
# A policy is a zero-argument function that returns a context manager.
# We don't take the context manager directly as it may be necessary to
# construct it once per test method
def wrap_method_with_policy(self, method, policy):
# Assumes that `method` is the tested function in `self`.
# NOTE: Python Exceptions (e.g., unittest.Skip) keeps objects in scope
# alive, so this cannot be done in setUp and tearDown because
# tearDown is run unconditionally no matter whether the test
# passes or not. For the same reason, we can't wrap the `method`
# call in try-finally and always do the check.
@wraps(method)
def wrapper(self, *args, **kwargs):
with policy():
method(*args, **kwargs)
return types.MethodType(wrapper, self)
def wrap_with_cuda_memory_check(self, method):
return self.wrap_method_with_policy(method, self.assertLeaksNoCudaTensors)
def run(self, result=None):
super().run(result=result)
# Early terminate test if necessary.
if self._should_stop_test_suite():
result.stop()
def setUp(self):
check_slow_test_from_stats(self)
if TEST_SKIP_FAST:
if not getattr(self, self._testMethodName).__dict__.get('slow_test', False):
raise unittest.SkipTest("test is fast; we disabled it with PYTORCH_TEST_SKIP_FAST")
check_disabled(str(self))
set_rng_seed(SEED)
@staticmethod
def _make_crow_indices(n_rows, n_cols, nnz,
*, device, dtype, random=True):
"""Return crow_indices of a CSR tensor with size (n_rows, n_cols) and
the number of specified elements nnz.
If random is True, the column counts of rows are in random
order. Otherwise, the column counts of rows are defined by the
used sampling method.
Sampling method
---------------
The used sampling method was introduced in
https://pearu.github.io/csr_sampling.html, and here we give
only an overall description of the method.
Notice that crow_indices can be defined as cumsum(counts)
where counts is a sequence of non-negative integers satisfying
the following conditions:
len(counts) == n_rows + 1
counts.max() <= n_cols
while counts[i + 1] is interpreted as the number of specified
elements in the i-th row.
The used sampling method aims at increasing the diversity of
CSR samples, that is, a CSR sample should contain (i) rows
that are all filled, (ii) rows with no elements at all, and
(iii) rows that are partially filled. At the same time and for
the given total number of specified elements (nnz), there
should be minimal preference to rows with a given number of
elements. To achieve this, the sampling method is built-up on
using a sawteeth model for counts. In the simplest case, we
would have
counts = arange(n_rows + 1) % (n_cols + 1)
that has equal number of all possible column counts per row.
This formula can be used only for specific input values of
n_rows, n_cols, and nnz. To generalize this model to any
combinations of inputs, the counts model above is extended
with an incomplete sawtooth, and the right and lower
rectangular parts that will guarantee that
counts.sum() == nnz
for any combination of n_rows, n_cols, and nnz. Basically,
we'll find a maximal window in (n_rows + 1, n_cols + 1)-grid
that is able to hold a sequence of sawteeth and so-called
final correction, while the external part of the window is
filled with counts to meet the nnz contraint exactly.
"""
assert 0 <= nnz <= n_rows * n_cols
def sawteeth(n, m):
# return the total number of counts in the sequence of
# sawteeth where n and m define a window in (n_rows+1,
# n_cols+1) rectangle where the sequence of sawteeth
# perfectly fit.
M = (n_cols - m) * (n_cols - m + 1) // 2
K = (n_rows - n) % (n_cols - m + 1)
return M * ((n_rows - n) // (n_cols - m + 1)) + K * (K - 1) // 2
# Different from the original method description, here counts
# has leading 0 required by crow_indices:
counts = torch.zeros(n_rows + 1, dtype=dtype, device=torch.device('cpu'))
n = m = 0
N = sawteeth(n, m)
if N and nnz >= max(N, n_cols):
# determine the width of the sawteeth window. We use bisection to solve
# N(n, 0) == 0 or nnz - n * n_cols < max(N(n, 0), n_cols)
# for n
n_left = n
n_right = n_rows - 1
N_right = sawteeth(n_right, m)
while n_right - n_left > 1:
n_middle = (n_left + n_right) // 2
N_middle = sawteeth(n_middle, m)
if N_middle == 0 or nnz - n_middle * n_cols < max(N_middle, n_cols):
n_right, N_right = n_middle, N_middle
else:
n_left = n_middle
n, N = n_right, N_right
# fill the right rectangle with counts:
assert n
counts[-n:].fill_(n_cols)
if N and nnz - n * n_cols >= max(N, n_rows - n):
# determine the height of the sawteeth window. We use bisection to solve
# N(n, m) == 0 or nnz - n * n_cols - m * (n_rows - n) < max(N(n, m), n_rows - n)
# for m.
m_left = m
m_right = n_cols - 1
N_right = sawteeth(n, m_right)
while m_right - m_left > 1:
m_middle = (m_left + m_right) // 2
N_middle = sawteeth(n, m_middle)
if N_middle == 0 or nnz - n * n_cols - m_middle * (n_rows - n) < max(N_middle, n_rows - n):
m_right, N_right = m_middle, N_middle
else:
m_left = m_middle
m, N = m_right, N_right
# fill the bottom rectangle with counts:
assert m
counts[1:n_rows - n + 1].fill_(m)
if N:
# fill the sawteeth window with counts
q, r = divmod(nnz - n * n_cols - m * (n_rows - n),
(n_cols - m) * (n_cols - m + 1) // 2)
p = 1 + q * (n_cols - m + 1)
if sys.version_info >= (3, 8):
k = math.isqrt(2 * r)
else:
# math.isqrt(x) is available starting from Python 3.8.
# Here we use int(math.sqrt(x)) as an approximation
# that appers to give exaxt result for all x values
# less than 2**35, at least, the upper limit of x is
# TBD.
k = int(math.sqrt(2 * r))
if k * (k + 1) > 2 * r:
k -= 1
corr = r - k * (k + 1) // 2
assert not ((p > 1) and (m > 0)) # full sawteeth are never on top of a bottom rectangle
# sequence of full sawteeth:
counts[1:p] = torch.arange(p - 1, dtype=dtype, device=counts.device) % (n_cols - m + 1)
# incomplete sawtooth:
counts[p:p + k + 1] += torch.arange(k + 1, dtype=dtype, device=counts.device)
else:
# given input does not support sawteeth
p = 1
corr = nnz - n * n_cols - m * (n_rows - n)
# correction that will guarantee counts.sum() == nnz:
counts[p] += corr
if random:
# randomize crow_indices by shuffling the sawteeth
# sequence:
perm = torch.randperm(n_rows, device=counts.device)
counts[1:] = counts[1:][perm]
# compute crow_indices:
crow_indices = counts
crow_indices.cumsum_(dim=0)
return crow_indices.to(device=device)
def genSparseCSRTensor(self, size, nnz, *, device, dtype, index_dtype):
sparse_dim = 2
assert all(size[d] > 0 for d in range(sparse_dim)) or nnz == 0, 'invalid arguments'
assert len(size) == sparse_dim
def random_sparse_csr(n_rows, n_cols, nnz):
crow_indices = self._make_crow_indices(n_rows, n_cols, nnz, device=device, dtype=index_dtype)
col_indices = torch.zeros(nnz, dtype=index_dtype, device=device)
for i in range(n_rows):
count = crow_indices[i + 1] - crow_indices[i]
col_indices[crow_indices[i]:crow_indices[i + 1]], _ = torch.sort(
torch.randperm(n_cols, dtype=index_dtype, device=device)[:count])
values = make_tensor([nnz], device=device, dtype=dtype, low=-1, high=1)
return values, crow_indices, col_indices
values, crow_indices, col_indices = random_sparse_csr(size[0], size[1], nnz)
return torch.sparse_csr_tensor(crow_indices,
col_indices,
values, size=size, dtype=dtype, device=device)
def genSparseTensor(self, size, sparse_dim, nnz, is_uncoalesced, device, dtype):
# Assert not given impossible combination, where the sparse dims have
# empty numel, but nnz > 0 makes the indices containing values.
assert all(size[d] > 0 for d in range(sparse_dim)) or nnz == 0, 'invalid arguments'
v_size = [nnz] + list(size[sparse_dim:])
v = make_tensor(v_size, device=device, dtype=dtype, low=-1, high=1)
i = torch.rand(sparse_dim, nnz, device=device)
i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i))
i = i.to(torch.long)
if is_uncoalesced:
v = torch.cat([v, torch.randn_like(v)], 0)
i = torch.cat([i, i], 1)
x = torch.sparse_coo_tensor(i, v, torch.Size(size), dtype=dtype, device=device)
if not is_uncoalesced:
x = x.coalesce()
else:
# FIXME: `x` is a sparse view of `v`. Currently rebase_history for
# sparse views is not implemented, so this workaround is
# needed for inplace operations done on `x`, e.g., copy_().
# Remove after implementing something equivalent to CopySlice
# for sparse views.
# NOTE: We do clone() after detach() here because we need to be able to change size/storage of x afterwards
x = x.detach().clone()
return x, x._indices().clone(), x._values().clone()
def safeToDense(self, t):
return t.coalesce().to_dense()
# Compares torch function with reference function for given sample input (object of SampleInput)
# Note: only values are compared, type comparison is not done here
def compare_with_reference(self, torch_fn, ref_fn, sample_input, **kwargs):
n_inp, n_args, n_kwargs = sample_input.numpy()
t_inp, t_args, t_kwargs = sample_input.input, sample_input.args, sample_input.kwargs
actual = torch_fn(t_inp, *t_args, **t_kwargs)
expected = ref_fn(n_inp, *n_args, **n_kwargs)
self.assertEqual(actual, expected, exact_device=False)
# Compares the given Torch and NumPy functions on the given tensor-like object.
# NOTE: both torch_fn and np_fn should be functions that take a single
# tensor (array). If the torch and/or NumPy function require additional
# arguments then wrap the function in a lambda or pass a partial function.
# TODO: add args/kwargs for passing to assertEqual (e.g. rtol, atol)
def compare_with_numpy(self, torch_fn, np_fn, tensor_like,
device=None, dtype=None, **kwargs):
assert TEST_NUMPY
if isinstance(tensor_like, torch.Tensor):
assert device is None
assert dtype is None
t_cpu = tensor_like.detach().cpu()
if t_cpu.dtype is torch.bfloat16:
t_cpu = t_cpu.float()
a = t_cpu.numpy()
t = tensor_like
else:
d = copy.copy(torch_to_numpy_dtype_dict)
d[torch.bfloat16] = np.float32
a = np.array(tensor_like, dtype=d[dtype])
t = torch.tensor(tensor_like, device=device, dtype=dtype)
np_result = np_fn(a)
torch_result = torch_fn(t).cpu()
# Converts arrays to tensors
if isinstance(np_result, np.ndarray):
try:
np_result = torch.from_numpy(np_result)
except Exception:
# NOTE: copying an array before conversion is necessary when,
# for example, the array has negative strides.
np_result = torch.from_numpy(np_result.copy())
if t.dtype is torch.bfloat16 and torch_result.dtype is torch.bfloat16 and np_result.dtype is torch.float:
torch_result = torch_result.to(torch.float)
self.assertEqual(np_result, torch_result, **kwargs)
# Some analysis of tolerance by logging tests from test_torch.py can be found
# in https://github.com/pytorch/pytorch/pull/32538.
# dtype name : (rtol, atol)
dtype_precisions = {
torch.float16 : (0.001, 1e-5),
torch.bfloat16 : (0.016, 1e-5),
torch.float32 : (1.3e-6, 1e-5),
torch.float64 : (1e-7, 1e-7),
torch.complex32 : (0.001, 1e-5),
torch.complex64 : (1.3e-6, 1e-5),
torch.complex128 : (1e-7, 1e-7),
}
# Returns the "default" rtol and atol for comparing scalars or
# tensors of the given dtypes.
def _getDefaultRtolAndAtol(self, dtype0, dtype1):
rtol = max(self.dtype_precisions.get(dtype0, (0, 0))[0],
self.dtype_precisions.get(dtype1, (0, 0))[0])
atol = max(self.dtype_precisions.get(dtype0, (0, 0))[1],
self.dtype_precisions.get(dtype1, (0, 0))[1])
return rtol, atol
# Checks if two dense tensors are equal(-ish), returning (True, None)
# when they are and (False, debug_msg) when they are not.
# If exact_dtype is true both tensors must have the same dtype.
# If exact_device is true both tensors must be on the same device.
# See the "Test Framework Tensor 'Equality'" note for more details.
# NOTE: tensors on different devices are moved to the CPU to be compared when
# exact_device is False.
# NOTE: this function checks the tensors' devices, sizes, and dtypes
# and acquires the appropriate device, dtype, rtol and atol to compare
# them with. It then calls _compare_tensors_internal.
def _compareTensors(self, a, b, *, rtol: Optional[float] = None, atol=None, equal_nan=True,
exact_dtype=True, exact_device=False) -> _compare_return_type:
assert (atol is None) == (rtol is None)
if not isinstance(a, torch.Tensor):
return (False, "argument a, {0}, to _compareTensors is not a tensor!".format(a))
if not isinstance(b, torch.Tensor):
return (False, "argument b, {0}, to _compareTensors is not a tensor!".format(b))
# Validates tensors are on the same device
if exact_device and a.device != b.device:
return (False, ("Attempted to compare equality of tensors on "
"different devices! Got devices {0} and "
"{1}.".format(a.device, b.device)))
# Compares tensors of different devices on the CPU
if a.device != b.device:
a = a.cpu()
b = b.cpu()
# Checks size matches
if a.size() != b.size():
return (False, ("Attempted to compare equality of tensors with "
"different sizes. Got sizes {0} and {1}.").format(a.size(), b.size()))
# Checks dtype (if exact_dtype)
if exact_dtype and a.dtype is not b.dtype:
return (False, ("Attempted to compare equality of tensors with "
"different dtypes. Got dtypes {0} and {1}.").format(a.dtype, b.dtype))
# Acquires rtol and atol
if rtol is None:
rtol, atol = self._getDefaultRtolAndAtol(a.dtype, b.dtype)
atol = max(atol, self.precision)
rtol = max(rtol, self.rel_tol)
# Converts to comparison dtype
dtype = get_comparison_dtype(a, b)
a = a.to(dtype)
b = b.to(dtype)
return _compare_tensors_internal(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
# Checks if two scalars are equal(-ish), returning (True, None)
# when they are and (False, debug_msg) when they are not.
# NOTE: this function just acquires rtol and atol
# before calling _compare_scalars_internal.
def _compareScalars(self, a, b, *,
rtol: Optional[float] = None, atol: Optional[float] = None, equal_nan=True) -> _compare_return_type:
# Acquires rtol and atol
assert (atol is None) == (rtol is None)
if rtol is None:
if isinstance(a, complex) or isinstance(b, complex):
rtol, atol = self._getDefaultRtolAndAtol(torch.complex64, torch.complex64)
elif isinstance(a, float) or isinstance(b, float):
rtol, atol = self._getDefaultRtolAndAtol(torch.float32, torch.float32)
else:
rtol, atol = 0, 0
rtol = cast(float, rtol)
atol = cast(float, atol)
assert atol is not None
atol = max(atol, self.precision)
rtol = max(rtol, self.rel_tol)
return _compare_scalars_internal(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
# Construct assert messages basd on internal debug message and user provided message.
def _get_assert_msg(self, msg, debug_msg=None):
if msg is None:
return debug_msg
else:
return f"\n{msg}" if debug_msg is None else f"{debug_msg}\n{msg}"
def assertEqualIgnoreType(self, *args, **kwargs) -> None:
# If you are seeing this function used, that means test is written wrongly
# and deserves detailed investigation
return self.assertEqual(*args, exact_dtype=False, **kwargs)
def _is_dict(self, obj):
return isinstance(obj, (dict, torch._C.ScriptDict)) # type: ignore[attr-defined]
# Compares x and y
# TODO: default exact_device to True
def assertEqual(self, x, y, msg: Optional[str] = None, *,
atol: Optional[float] = None, rtol: Optional[float] = None,
equal_nan=True, exact_dtype=True, exact_device=False) -> None:
assert (atol is None) == (rtol is None), "If one of atol or rtol is specified, then the other must be too"
debug_msg: Optional[str] = None
# Tensor x Number and Number x Tensor comparisons
if isinstance(x, torch.Tensor) and isinstance(y, Number):
self.assertEqual(x.item(), y, atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
elif isinstance(y, torch.Tensor) and isinstance(x, Number):
self.assertEqual(x, y.item(), atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
# Tensor x np.bool
elif isinstance(x, torch.Tensor) and isinstance(y, np.bool_):
self.assertEqual(x.item(), y, atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
elif isinstance(y, torch.Tensor) and isinstance(x, np.bool_):
self.assertEqual(x, y.item(), atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
# Tensor x Tensor
elif isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor):
debug_msg = ("Attempted to compare with different is_sparse settings: "
f"Expected: {x.is_sparse}; Actual: {y.is_sparse}.")
super().assertEqual(x.is_sparse, y.is_sparse, msg=self._get_assert_msg(msg=msg, debug_msg=debug_msg))
debug_msg = ("Attempted to compare with different is_quantized settings: "
f"Expected: {x.is_quantized}; Actual: {y.is_quantized}.")
super().assertEqual(x.is_quantized, y.is_quantized, msg=self._get_assert_msg(msg=msg, debug_msg=debug_msg))
if x.is_sparse:
if x.size() != y.size():
debug_msg_sparse = ("Attempted to compare equality of tensors with different sizes: "
f"Expected: {x.size()}; Actual: {y.size()}.")
super().assertTrue(False, msg=self._get_assert_msg(msg=msg, debug_msg=debug_msg_sparse))
x = x.coalesce()
y = y.coalesce()
indices_result, debug_msg_indices = self._compareTensors(x._indices(), y._indices(),
rtol=rtol, atol=atol,
equal_nan=equal_nan, exact_dtype=exact_dtype,
exact_device=exact_device)
if not indices_result:
assert debug_msg_indices is not None
debug_msg = "Sparse tensor indices failed to compare as equal! " + debug_msg_indices
super().assertTrue(indices_result, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
values_result, debug_msg_values = self._compareTensors(x._values(), y._values(),
rtol=rtol, atol=atol,
equal_nan=equal_nan, exact_dtype=exact_dtype,
exact_device=exact_device)
if not values_result:
assert debug_msg_values is not None
debug_msg = "Sparse tensor values failed to compare as equal! " + debug_msg_values
super().assertTrue(values_result, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
elif x.is_quantized and y.is_quantized:
self.assertEqual(x.qscheme(), y.qscheme(), atol=atol, rtol=rtol,
msg=msg, exact_dtype=exact_dtype,
exact_device=exact_device)
if x.qscheme() == torch.per_tensor_affine:
self.assertEqual(x.q_scale(), y.q_scale(), atol=atol, rtol=rtol,
msg=msg, exact_dtype=exact_dtype,
exact_device=exact_device)
self.assertEqual(x.q_zero_point(), y.q_zero_point(),
atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
elif x.qscheme() == torch.per_channel_affine:
self.assertEqual(x.q_per_channel_scales(), y.q_per_channel_scales(), atol=atol, rtol=rtol,
msg=msg, exact_dtype=exact_dtype,
exact_device=exact_device)
self.assertEqual(x.q_per_channel_zero_points(), y.q_per_channel_zero_points(),
atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
self.assertEqual(x.q_per_channel_axis(), y.q_per_channel_axis(),
atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
result, debug_msg_compare = self._compareTensors(x.int_repr().to(torch.int32),
y.int_repr().to(torch.int32),
atol=atol, rtol=rtol,
exact_dtype=exact_dtype,
exact_device=exact_device)
if not result:
assert debug_msg_compare is not None
debug_msg = "Quantized representations failed to compare as equal! " + debug_msg_compare
super().assertTrue(result, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
else:
result, debug_msg_generic = self._compareTensors(x, y, rtol=rtol, atol=atol,
equal_nan=equal_nan, exact_dtype=exact_dtype,
exact_device=exact_device)
if not result:
assert debug_msg_generic is not None
debug_msg = "Tensors failed to compare as equal!" + debug_msg_generic
super().assertTrue(result, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
elif isinstance(x, (np.ndarray, torch.Tensor)) or isinstance(y, (np.ndarray, torch.Tensor)):
def maybe_to_tensor(a: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
if not isinstance(a, np.ndarray):
return a
try:
return torch.from_numpy(a)
except TypeError:
# This happens if the dtype is non-numeric or not supported by torch
return a
def maybe_to_list(a: Any) -> Any:
if not isinstance(a, (np.ndarray, torch.Tensor)):
return a
return a.tolist()
x = maybe_to_tensor(x)
y = maybe_to_tensor(y)
if isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor):
self.assertEqual(
x, y, atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device
)
else:
# In case we can't convert the array to a tensor, we fall back to comparing x and y as iterables
self.assertEqual(
maybe_to_list(x),
maybe_to_list(y),
atol=atol,
rtol=rtol,
msg=msg,
exact_dtype=exact_dtype,
exact_device=exact_device
)
elif isinstance(x, string_classes) and isinstance(y, string_classes):
debug_msg = ("Attempted to compare [string] types: "
f"Expected: {repr(x)}; Actual: {repr(y)}.")
super().assertEqual(x, y, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
elif type(x) == set and type(y) == set:
debug_msg = ("Attempted to compare [set] types: "
f"Expected: {x}; Actual: {y}.")
super().assertEqual(x, y, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
elif self._is_dict(x) and self._is_dict(y):
if isinstance(x, OrderedDict) and isinstance(y, OrderedDict):
self.assertEqual(x.items(), y.items(), atol=atol, rtol=rtol,
msg=msg, exact_dtype=exact_dtype,
exact_device=exact_device)
else:
self.assertEqual(set(x.keys()), set(y.keys()), atol=atol, rtol=rtol,
msg=msg, exact_dtype=exact_dtype,
exact_device=exact_device)
key_list = list(x.keys())
self.assertEqual([x[k] for k in key_list],
[y[k] for k in key_list],
atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
elif isinstance(x, type) and isinstance(y, type):
# See TestTorch.test_assert_equal_generic_meta
debug_msg = ("Attempted to compare [type] types: "
f"Expected: {x}; Actual: {y}.")
super().assertEqual(x, y, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
elif is_iterable(x) and is_iterable(y):
debug_msg = ("Attempted to compare the lengths of [iterable] types: "
f"Expected: {len(x)}; Actual: {len(y)}.")
super().assertEqual(len(x), len(y), msg=self._get_assert_msg(msg, debug_msg=debug_msg))
for x_, y_ in zip(x, y):
self.assertEqual(x_, y_, atol=atol, rtol=rtol, msg=msg,
exact_dtype=exact_dtype, exact_device=exact_device)
elif isinstance(x, bool) and isinstance(y, bool):
super().assertTrue(x == y, msg=msg)
# Scalar x Scalar
elif isinstance(x, Number) and isinstance(y, Number):
result, debug_msg_scalars = self._compareScalars(x, y, rtol=rtol, atol=atol,
equal_nan=equal_nan)
if not result:
assert debug_msg_scalars is not None
debug_msg = "Scalars failed to compare as equal! " + debug_msg_scalars
super().assertTrue(result, msg=self._get_assert_msg(msg, debug_msg=debug_msg))
else:
super().assertEqual(x, y, msg=msg)
def assertNotEqual(self, x, y, msg: Optional[str] = None, *, # type: ignore[override]
atol: Optional[float] = None, rtol: Optional[float] = None, **kwargs) -> None:
with self.assertRaises(AssertionError, msg=msg):
self.assertEqual(x, y, msg, atol=atol, rtol=rtol, **kwargs)
def assertEqualTypeString(self, x, y) -> None:
# This API is used simulate deprecated x.type() == y.type()
self.assertEqual(x.device, y.device)
self.assertEqual(x.dtype, y.dtype)
self.assertEqual(x.is_sparse, y.is_sparse)
def assertObjectIn(self, obj: Any, iterable: Iterable[Any]) -> None:
for elem in iterable:
if id(obj) == id(elem):
return
raise AssertionError("object not found in iterable")
# Reimplemented to provide special behavior when
# _ignore_not_implemented_error is True
def assertRaises(self, expected_exception, *args, **kwargs):
if self._ignore_not_implemented_error:
context: Optional[AssertRaisesContextIgnoreNotImplementedError] = \
AssertRaisesContextIgnoreNotImplementedError(expected_exception, self) # type: ignore[call-arg]
try:
return context.handle('assertRaises', args, kwargs) # type: ignore[union-attr]
finally:
# see https://bugs.python.org/issue23890
context = None
else:
return super().assertRaises(expected_exception, *args, **kwargs)
# Reimplemented to provide special behavior when
# _ignore_not_implemented_error is True
def assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs):
if self._ignore_not_implemented_error:
context = AssertRaisesContextIgnoreNotImplementedError( # type: ignore[call-arg]
expected_exception, self, expected_regex)
return context.handle('assertRaisesRegex', args, kwargs) # type: ignore[attr-defined]
else:
return super().assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)
# TODO: Support context manager interface
# NB: The kwargs forwarding to callable robs the 'subname' parameter.
# If you need it, manually apply your callable in a lambda instead.
def assertExpectedRaises(self, exc_type, callable, *args, **kwargs):
subname = None
if 'subname' in kwargs:
subname = kwargs['subname']
del kwargs['subname']
try:
callable(*args, **kwargs)
except exc_type as e:
self.assertExpected(str(e), subname)
return
# Don't put this in the try block; the AssertionError will catch it
self.fail(msg="Did not raise when expected to")
def assertNotWarn(self, callable, msg=''):
r"""
Test if :attr:`callable` does not raise a warning.
"""
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always") # allow any warning to be raised
with set_warn_always_context(True):
callable()
self.assertTrue(len(ws) == 0, msg)
@contextmanager
def assertWarnsOnceRegex(self, category, regex=''):
"""Context manager for code that *must always* warn
This filters expected warnings from the test and fails if
the expected warning is not caught. It uses set_warn_always() to force
TORCH_WARN_ONCE to behave like TORCH_WARN
"""
pattern = re.compile(regex)
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always") # allow any warning to be raised
with set_warn_always_context(True):
yield
if len(ws) == 0:
self.fail('no warning caught')
self.assertTrue(any([type(w.message) is category for w in ws]))
self.assertTrue(
any([re.match(pattern, str(w.message)) for w in ws]),
f'{pattern}, {[w.message for w in ws if type(w.message) is category]}')
def assertExpected(self, s, subname=None):
r"""
Test that a string matches the recorded contents of a file
derived from the name of this test and subname. This file
is placed in the 'expect' directory in the same directory
as the test script. You can automatically update the recorded test
output using --accept.
If you call this multiple times in a single function, you must
give a unique subname each time.
"""
if not isinstance(s, str):
raise TypeError("assertExpected is strings only")
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
# NB: we take __file__ from the module that defined the test
# class, so we place the expect directory where the test script
# lives, NOT where test/common_utils.py lives. This doesn't matter in
# PyTorch where all test scripts are in the same directory as
# test/common_utils.py, but it matters in onnx-pytorch
module_id = self.__class__.__module__
munged_id = remove_prefix(self.id(), module_id + ".")
test_file = os.path.realpath(sys.modules[module_id].__file__)
expected_file = os.path.join(os.path.dirname(test_file),
"expect",
munged_id)
subname_output = ""
if subname:
expected_file += "-" + subname
subname_output = " ({})".format(subname)
expected_file += ".expect"
expected = None
def accept_output(update_type):
print("Accepting {} for {}{}:\n\n{}".format(update_type, munged_id, subname_output, s))
with open(expected_file, 'w') as f:
# Adjust for producer_version, leave s unmodified
s_tag = re.sub(r'(producer_version): "[0-9.]*"',
r'\1producer_version: "CURRENT_VERSION"', s)
f.write(s_tag)
try:
with open(expected_file) as f:
expected = f.read()
except IOError as e:
if e.errno != errno.ENOENT:
raise
elif expecttest.ACCEPT:
return accept_output("output")
else:
raise RuntimeError(
("I got this output for {}{}:\n\n{}\n\n"
"No expect file exists; to accept the current output, run:\n"
"python {} {} --accept").format(munged_id, subname_output, s, __main__.__file__, munged_id)) from None
# a hack for JIT tests
if IS_WINDOWS:
expected = re.sub(r'CppOp\[(.+?)\]', 'CppOp[]', expected)
s = re.sub(r'CppOp\[(.+?)\]', 'CppOp[]', s)
# Adjust for producer_version
expected = expected.replace(
'producer_version: "CURRENT_VERSION"',
'producer_version: "{}"'.format(torch.onnx.producer_version)
)
if expecttest.ACCEPT:
if expected != s:
return accept_output("updated output")
else:
if hasattr(self, "assertMultiLineEqual"):
# Python 2.7 only
# NB: Python considers lhs "old" and rhs "new".
self.assertMultiLineEqual(expected, s)
else:
self.assertEqual(s, expected)
def assertExpectedStripMangled(self, s, subname=None):
s = re.sub(r'__torch__[^ ]+', '', s)
self.assertExpected(s, subname)
def assertGreaterAlmostEqual(self, first, second, places=None, msg=None, delta=None):
"""Assert that ``first`` is greater than or almost equal to ``second``.
The equality of ``first`` and ``second`` is determined in a similar way to
the ``assertAlmostEqual`` function of the standard library.
"""
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
if first >= second:
return
diff = second - first
if delta is not None:
if diff <= delta:
return
standardMsg = f"{first} not greater than or equal to {second} within {delta} delta"
else:
if places is None:
places = 7
if round(diff, places) == 0:
return
standardMsg = f"{first} not greater than or equal to {second} within {places} places"
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
# run code in subprocess and capture exceptions.
@staticmethod
def run_process_no_exception(code, env=None):
import subprocess
popen = subprocess.Popen(
[sys.executable, '-c', code],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env)
(stdout, stderr) = popen.communicate()
return (stdout, stderr)
# returns captured stderr
@staticmethod
def runWithPytorchAPIUsageStderr(code):
env = os.environ.copy()
env["PYTORCH_API_USAGE_STDERR"] = "1"
# remove IN_CI flag since this is a wrapped test process.
# IN_CI flag should be set in the parent process only.
if "IN_CI" in env.keys():
del env["IN_CI"]
(stdout, stderr) = TestCase.run_process_no_exception(code, env=env)
return stderr.decode('ascii')
def download_file(url, binary=True):
from urllib.parse import urlsplit
from urllib import request, error
filename = os.path.basename(urlsplit(url)[2])
data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data'))
path = os.path.join(data_dir, filename)
if os.path.exists(path):
return path
try:
data = request.urlopen(url, timeout=15).read()
with open(path, 'wb' if binary else 'w') as f:
f.write(data)
return path
except error.URLError as e:
msg = "could not download test file '{}'".format(url)
warnings.warn(msg, RuntimeWarning)
raise unittest.SkipTest(msg) from e
def find_free_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 0))
_, port = sock.getsockname()
return port
# Errors that we can get in c10d initialization for which we should retry tests for.
ADDRESS_IN_USE = "Address already in use"
CONNECT_TIMEOUT = "connect() timed out."
def retry_on_connect_failures(func=None, connect_errors=(ADDRESS_IN_USE)):
"""Reruns a test if the test returns a RuntimeError and the exception
matches exactly with one of the strings in connect_errors."""
# This if block is executed when using this function as a decorator with arguments.
if func is None:
return partial(retry_on_connect_failures, connect_errors=connect_errors)
@wraps(func)
def wrapper(*args, **kwargs):
tries_remaining = 10
while True:
try:
return func(*args, **kwargs)
except RuntimeError as error:
if str(error) in connect_errors:
tries_remaining -= 1
if tries_remaining == 0:
raise
time.sleep(random.random())
continue
raise
return wrapper
# Decorator to retry upon certain Exceptions.
def retry(ExceptionToCheck, tries=3, delay=3, skip_after_retries=False):
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
print(msg)
time.sleep(mdelay)
mtries -= 1
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
raise unittest.SkipTest(f"Skipping after {tries} consecutive {str(e)}") from e if skip_after_retries else e
return f_retry # true decorator
return deco_retry
# Methods for matrix and tensor generation
def make_tensor(size, device: torch.device, dtype: torch.dtype, *, low=None, high=None,
requires_grad: bool = False, noncontiguous: bool = False,
exclude_zero: bool = False) -> torch.Tensor:
""" Creates a random tensor with the given size, device and dtype.
By default, the tensor's values are in the range [-9, 9] for most dtypes. If low
and/or high are specified then the values will be in the range [max(-9, low), min(9, high)].
For unsigned types the values are in the range[0, 9] and for complex types the real and imaginary
parts are each in the range [-9, 9].
If noncontiguous=True, a noncontiguous tensor with the given size will be returned unless the size
specifies a tensor with a 1 or 0 elements in which case the noncontiguous parameter is ignored because
it is not possible to create a noncontiguous Tensor with a single element.
If exclude_zero is passed with True (default is False), all the matching values (with zero) in
created tensor are replaced with an epsilon value if floating type, [`eps + `eps`.j] if
complex type and 1 if integer/boolean type.
"""
assert low is None or low < 9, "low value too high!"
assert high is None or high > -9, "high value too low!"
if dtype is torch.bool:
result = torch.randint(0, 2, size, device=device, dtype=dtype)
elif dtype is torch.uint8:
low = math.floor(0 if low is None else max(low, 0))
high = math.ceil(10 if high is None else min(high, 10))
result = torch.randint(low, high, size, device=device, dtype=dtype)
elif dtype in integral_types():
low = math.floor(-9 if low is None else max(low, -9))
high = math.ceil(10 if high is None else min(high, 10))
result = torch.randint(low, high, size, device=device, dtype=dtype)
elif dtype in floating_types_and(torch.half, torch.bfloat16):
low = -9 if low is None else max(low, -9)
high = 9 if high is None else min(high, 10)
span = high - low
# Windows doesn't support torch.rand(bfloat16) on CUDA
if IS_WINDOWS and torch.device(device).type == 'cuda' and dtype is torch.bfloat16:
result = (torch.rand(size, device=device, dtype=torch.float32) * span + low).to(torch.bfloat16)
else:
result = torch.rand(size, device=device, dtype=dtype) * span + low
else:
assert dtype in complex_types()
low = -9 if low is None else max(low, -9)
high = 9 if high is None else min(high, 10)
span = high - low
float_dtype = torch.float if dtype is torch.cfloat else torch.double
real = torch.rand(size, device=device, dtype=float_dtype) * span + low
imag = torch.rand(size, device=device, dtype=float_dtype) * span + low
result = torch.complex(real, imag)
if noncontiguous and result.numel() > 1:
result = torch.repeat_interleave(result, 2, dim=-1)
result = result[..., ::2]
if exclude_zero:
if dtype in integral_types() or dtype is torch.bool:
replace_with = torch.tensor(1, device=device, dtype=dtype)
elif dtype in floating_types_and(torch.half, torch.bfloat16):
replace_with = torch.tensor(torch.finfo(dtype).eps, device=device, dtype=dtype)
else:
assert dtype in complex_types()
float_dtype = torch.float if dtype is torch.cfloat else torch.double
float_eps = torch.tensor(torch.finfo(float_dtype).eps, device=device, dtype=float_dtype)
replace_with = torch.complex(float_eps, float_eps)
result[result == 0] = replace_with
if dtype in floating_types_and(torch.half, torch.bfloat16) or\
dtype in complex_types():
result.requires_grad = requires_grad
return result
def random_square_matrix_of_rank(l, rank, dtype=torch.double, device='cpu'):
assert rank <= l
A = torch.randn(l, l, dtype=dtype, device=device)
u, s, vh = torch.linalg.svd(A, full_matrices=False)
for i in range(l):
if i >= rank:
s[i] = 0
elif s[i] == 0:
s[i] = 1
return (u * s.to(dtype).unsqueeze(-2)) @ vh
def random_well_conditioned_matrix(*shape, dtype, device, mean=1.0, sigma=0.001):
"""
Returns a random rectangular matrix (batch of matrices)
with singular values sampled from a Gaussian with
mean `mean` and standard deviation `sigma`.
The smaller the `sigma`, the better conditioned
the output matrix is.
"""
primitive_dtype = {
torch.float: torch.float,
torch.double: torch.double,
torch.cfloat: torch.float,
torch.cdouble: torch.double
}
x = torch.rand(shape, dtype=dtype, device=device)
m = x.size(-2)
n = x.size(-1)
u, _, vh = torch.linalg.svd(x, full_matrices=False)
s = (torch.randn(*(shape[:-2] + (min(m, n),)), dtype=primitive_dtype[dtype], device=device) * sigma + mean) \
.sort(-1, descending=True).values.to(dtype)
return (u * s.unsqueeze(-2)) @ vh
# TODO: remove this (prefer make_symmetric_matrices below)
def random_symmetric_matrix(l, *batches, **kwargs):
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
A = (A + A.transpose(-2, -1)).div_(2)
return A
# Creates a symmetric matrix or batch of symmetric matrices
# Shape must be a square matrix or batch of square matrices
def make_symmetric_matrices(*shape, device, dtype):
assert shape[-1] == shape[-2]
t = make_tensor(shape, device=device, dtype=dtype)
t = t + t.transpose(-2, -1).div_(2)
return t
def random_hermitian_matrix(l, *batches, **kwargs):
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
A = (A + A.transpose(-2, -1).conj()).div_(2)
return A
def random_symmetric_psd_matrix(l, *batches, **kwargs):
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device)
return torch.matmul(A, A.transpose(-2, -1))
def random_hermitian_psd_matrix(matrix_size, *batch_dims, dtype=torch.double, device='cpu'):
"""
Returns a batch of random Hermitian semi-positive-definite matrices.
The shape of the result is batch_dims + (matrix_size, matrix_size)
The following example creates a tensor of size 2 x 4 x 3 x 3
>>> matrices = random_hermitian_psd_matrix(3, 2, 4, dtype=dtype, device=device)
"""
A = torch.randn(*(batch_dims + (matrix_size, matrix_size)), dtype=dtype, device=device)
return torch.matmul(A, A.conj().transpose(-2, -1))
# TODO: remove this (prefer make_symmetric_pd_matrices below)
def random_symmetric_pd_matrix(matrix_size, *batch_dims, **kwargs):
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
A = torch.randn(*(batch_dims + (matrix_size, matrix_size)),
dtype=dtype, device=device)
return torch.matmul(A, A.transpose(-2, -1)) \
+ torch.eye(matrix_size, dtype=dtype, device=device) * 1e-5
# Creates a symmetric positive-definite matrix or batch of
# such matrices
def make_symmetric_pd_matrices(*shape, device, dtype):
assert shape[-1] == shape[-2]
t = make_tensor(shape, device=device, dtype=dtype)
t = torch.matmul(t, t.transpose(-2, -1))
i = torch.eye(shape[-1], device=device, dtype=dtype) * 1e-5
return t + i
def random_hermitian_pd_matrix(matrix_size, *batch_dims, dtype, device):
"""
Returns a batch of random Hermitian positive-definite matrices.
The shape of the result is batch_dims + (matrix_size, matrix_size)
The following example creates a tensor of size 2 x 4 x 3 x 3
>>> matrices = random_hermitian_pd_matrix(3, 2, 4, dtype=dtype, device=device)
"""
A = torch.randn(*(batch_dims + (matrix_size, matrix_size)),
dtype=dtype, device=device)
return torch.matmul(A, A.transpose(-2, -1).conj()) \
+ torch.eye(matrix_size, dtype=dtype, device=device)
# TODO: remove this (prefer make_fullrank_matrices_with_distinct_singular_values below)
def random_fullrank_matrix_distinct_singular_value(matrix_size, *batch_dims,
**kwargs):
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
silent = kwargs.get("silent", False)
if silent and not torch._C.has_lapack:
return torch.ones(matrix_size, matrix_size, dtype=dtype, device=device)
A = torch.randn(batch_dims + (matrix_size, matrix_size), dtype=dtype, device=device)
u, _, vh = torch.linalg.svd(A, full_matrices=False)
real_dtype = A.real.dtype if A.dtype.is_complex else A.dtype
s = torch.arange(1., matrix_size + 1, dtype=real_dtype, device=device).mul_(1.0 / (matrix_size + 1))
return (u * s.to(A.dtype)) @ vh
# Creates a full rank matrix with distinct signular values or
# a batch of such matrices
# Shape must be a square matrix or batch of square matrices
def make_fullrank_matrices_with_distinct_singular_values(*shape, device, dtype):
assert shape[-1] == shape[-2]
t = make_tensor(shape, device=device, dtype=dtype)
u, _, vh = torch.linalg.svd(t, full_matrices=False)
# TODO: improve the handling of complex tensors here
real_dtype = t.real.dtype if t.dtype.is_complex else t.dtype
s = torch.arange(1., shape[-1] + 1, dtype=real_dtype, device=device).mul_(1.0 / (shape[-1] + 1))
return (u * s.to(dtype)) @ vh
def random_matrix(rows, columns, *batch_dims, **kwargs):
"""Return rectangular matrix or batches of rectangular matrices.
Parameters:
dtype - the data type
device - the device kind
singular - when True, the output will be singular
"""
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
silent = kwargs.get("silent", False)
singular = kwargs.get("singular", False)
if silent and not torch._C.has_lapack:
return torch.ones(rows, columns, dtype=dtype, device=device)
A = torch.randn(batch_dims + (rows, columns), dtype=dtype, device=device)
u, _, vh = torch.linalg.svd(A, full_matrices=False)
k = min(rows, columns)
s = torch.linspace(1 / (k + 1), 1, k, dtype=dtype, device=device)
if singular:
# make matrix singular
s[k - 1] = 0
if k > 2:
# increase the order of singularity so that the pivoting
# in LU factorization will be non-trivial
s[0] = 0
return (u * s.unsqueeze(-2)) @ vh
def random_lowrank_matrix(rank, rows, columns, *batch_dims, **kwargs):
"""Return rectangular matrix or batches of rectangular matrices with
given rank.
"""
B = random_matrix(rows, rank, *batch_dims, **kwargs)
C = random_matrix(rank, columns, *batch_dims, **kwargs)
return B.matmul(C)
def random_sparse_matrix(rows, columns, density=0.01, **kwargs):
"""Return rectangular random sparse matrix within given density.
The density of the result approaches to given density as the size
of the matrix is increased and a relatively small value of density
is specified but higher than min(rows, columns)/(rows * columns)
for non-singular matrices.
"""
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
singular = kwargs.get("singular", False)
k = min(rows, columns)
nonzero_elements = max(min(rows, columns), int(rows * columns * density))
row_indices = [i % rows for i in range(nonzero_elements)]
column_indices = [i % columns for i in range(nonzero_elements)]
random.shuffle(column_indices)
indices = [row_indices, column_indices]
values = torch.randn(nonzero_elements, dtype=dtype, device=device)
# ensure that the diagonal dominates
values *= torch.tensor([-float(i - j)**2 for i, j in zip(*indices)], dtype=dtype, device=device).exp()
indices_tensor = torch.tensor(indices)
A = torch.sparse_coo_tensor(indices_tensor, values, (rows, columns), device=device)
return A.coalesce()
def random_sparse_pd_matrix(matrix_size, density=0.01, **kwargs):
"""Return random sparse positive-definite matrix with given density.
The eigenvalues of the matrix are defined as::
arange(1, matrix_size+1)/matrix_size
Algorithm:
A = diag(arange(1, matrix_size+1)/matrix_size)
while <A density is smaller than required>:
<choose random i, j in range(matrix_size), theta in [0, 2*pi]>
R = <rotation matrix (i,j,theta)>
A = R^T A R
"""
import math
torch = kwargs.get('torch', globals()['torch'])
dtype = kwargs.get('dtype', torch.double)
device = kwargs.get('device', 'cpu')
data = dict([((i, i), float(i + 1) / matrix_size)
for i in range(matrix_size)])
def multiply(data, N, i, j, cs, sn, left=True):
for k in range(N):
if left:
ik, jk = (k, i), (k, j)
else:
ik, jk = (i, k), (j, k)
aik, ajk = data.get(ik, 0), data.get(jk, 0)
aik, ajk = cs * aik + sn * ajk, -sn * aik + cs * ajk
if aik:
data[ik] = aik
else:
data.pop(ik, None)
if ajk:
data[jk] = ajk
else:
data.pop(jk, None)
target_nnz = density * matrix_size * matrix_size
while len(data) < target_nnz:
i = random.randint(0, matrix_size - 1)
j = random.randint(0, matrix_size - 1)
if i != j:
theta = random.uniform(0, 2 * math.pi)
cs = math.cos(theta)
sn = math.sin(theta)
multiply(data, matrix_size, i, j, cs, sn, left=True)
multiply(data, matrix_size, i, j, cs, sn, left=False)
icoords, jcoords, values = [], [], []
for (i, j), v in sorted(data.items()):
icoords.append(i)
jcoords.append(j)
values.append(v)
indices_tensor = torch.tensor([icoords, jcoords])
return torch.sparse_coo_tensor(indices_tensor, values, (matrix_size, matrix_size), dtype=dtype, device=device)
def do_test_dtypes(self, dtypes, layout, device):
for dtype in dtypes:
if dtype != torch.float16:
out = torch.zeros((2, 3), dtype=dtype, layout=layout, device=device)
self.assertIs(dtype, out.dtype)
self.assertIs(layout, out.layout)
self.assertEqual(device, out.device)
def do_test_empty_full(self, dtypes, layout, device):
shape = torch.Size([2, 3])
def check_value(tensor, dtype, layout, device, value, requires_grad):
self.assertEqual(shape, tensor.shape)
self.assertIs(dtype, tensor.dtype)
self.assertIs(layout, tensor.layout)
self.assertEqual(tensor.requires_grad, requires_grad)
if tensor.is_cuda and device is not None:
self.assertEqual(device, tensor.device)
if value is not None:
fill = tensor.new(shape).fill_(value)
self.assertEqual(tensor, fill)
def get_int64_dtype(dtype):
module = '.'.join(str(dtype).split('.')[1:-1])
if not module:
return torch.int64
return operator.attrgetter(module)(torch).int64
default_dtype = torch.get_default_dtype()
check_value(torch.empty(shape), default_dtype, torch.strided, -1, None, False)
check_value(torch.full(shape, -5.), default_dtype, torch.strided, -1, None, False)
for dtype in dtypes:
for rg in {dtype.is_floating_point, False}:
int64_dtype = get_int64_dtype(dtype)
v = torch.empty(shape, dtype=dtype, device=device, layout=layout, requires_grad=rg)
check_value(v, dtype, layout, device, None, rg)
out = v.new()
check_value(torch.empty(shape, out=out, device=device, layout=layout, requires_grad=rg),
dtype, layout, device, None, rg)
check_value(v.new_empty(shape), dtype, layout, device, None, False)
check_value(v.new_empty(shape, dtype=int64_dtype, device=device, requires_grad=False),
int64_dtype, layout, device, None, False)
check_value(torch.empty_like(v), dtype, layout, device, None, False)
check_value(torch.empty_like(v, dtype=int64_dtype, layout=layout, device=device, requires_grad=False),
int64_dtype, layout, device, None, False)
if dtype is not torch.float16 and layout != torch.sparse_coo:
fv = 3
v = torch.full(shape, fv, dtype=dtype, layout=layout, device=device, requires_grad=rg)
check_value(v, dtype, layout, device, fv, rg)
check_value(v.new_full(shape, fv + 1), dtype, layout, device, fv + 1, False)
out = v.new()
check_value(torch.full(shape, fv + 2, out=out, device=device, layout=layout, requires_grad=rg),
dtype, layout, device, fv + 2, rg)
check_value(v.new_full(shape, fv + 3, dtype=int64_dtype, device=device, requires_grad=False),
int64_dtype, layout, device, fv + 3, False)
check_value(torch.full_like(v, fv + 4), dtype, layout, device, fv + 4, False)
check_value(torch.full_like(v, fv + 5,
dtype=int64_dtype, layout=layout, device=device, requires_grad=False),
int64_dtype, layout, device, fv + 5, False)
# this helper method is to recursively
# clone the tensor-type input of operators tested by OpInfo
def clone_input_helper(input):
if isinstance(input, torch.Tensor):
return torch.clone(input)
if isinstance(input, Sequence):
return tuple(map(clone_input_helper, input))
return input
THESE_TAKE_WAY_TOO_LONG = {
'test_Conv3d_groups',
'test_conv_double_backward',
'test_conv_double_backward_groups',
'test_Conv3d_dilated',
'test_Conv3d_stride_padding',
'test_Conv3d_dilated_strided',
'test_Conv3d',
'test_Conv2d_dilated',
'test_ConvTranspose3d_dilated',
'test_ConvTranspose2d_dilated',
'test_snli',
'test_Conv2d',
'test_Conv2d_padding',
'test_ConvTranspose2d_no_bias',
'test_ConvTranspose2d',
'test_ConvTranspose3d',
'test_Conv2d_no_bias',
'test_matmul_4d_4d',
'test_multinomial_invalid_probs',
}
running_script_path = None
def set_running_script_path():
global running_script_path
try:
running_file = os.path.abspath(os.path.realpath(sys.argv[0]))
if running_file.endswith('.py'): # skip if the running file is not a script
running_script_path = running_file
except Exception:
pass
def check_test_defined_in_running_script(test_case):
if running_script_path is None:
return
test_case_class_file = os.path.abspath(os.path.realpath(inspect.getfile(test_case.__class__)))
assert test_case_class_file == running_script_path, "Class of loaded TestCase \"{}\" " \
"is not defined in the running script \"{}\", but in \"{}\". Did you " \
"accidentally import a unittest.TestCase from another file?".format(
test_case.id(), running_script_path, test_case_class_file)
def load_tests(loader, tests, pattern):
set_running_script_path()
test_suite = unittest.TestSuite()
for test_group in tests:
for test in test_group:
check_test_defined_in_running_script(test)
test_suite.addTest(test)
return test_suite
class BytesIOContext(io.BytesIO):
def __enter__(self):
return self
def __exit__(self, *args):
pass
# Tentative value for nondet_tol for gradcheck when backward implementation
# relies on nondeterministic operations, i.e., those listed here:
# https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html
#
# For more information see https://github.com/pytorch/pytorch/issues/56202
GRADCHECK_NONDET_TOL = 1e-12
def gradcheck(fn, inputs, **kwargs):
# Wrapper around gradcheck that enables certain keys by default.
# Use this testing-internal gradcheck instead of autograd.gradcheck so that new features like vmap and
# forward-mode AD are tested by default. We create this wrapper because we'd like to keep new checks
# to be disabled to default for the public-facing api to avoid breaking user code.
#
# All PyTorch devs doing testing should use this wrapper instead of autograd.gradcheck.
default_values = {
"check_batched_grad": True,
"fast_mode": True,
}
if os.environ.get('PYTORCH_TEST_WITH_SLOW_GRADCHECK', "0FF") == "ON":
default_values["fast_mode"] = False
for key, value in default_values.items():
# default value override values explicitly set to None
k = kwargs.get(key, None)
kwargs[key] = k if k is not None else value
return torch.autograd.gradcheck(fn, inputs, **kwargs)
def gradgradcheck(fn, inputs, grad_outputs=None, **kwargs):
# Wrapper around gradgradcheck that enables certain keys by default
# See gradcheck above for an explanation of why we need something like this.
#
# All PyTorch devs doing testing should use this wrapper instead of autograd.gradgradcheck
default_values = {
"check_batched_grad": True,
"fast_mode": True,
}
if os.environ.get('PYTORCH_TEST_WITH_SLOW_GRADCHECK', "0FF") == "ON":
default_values["fast_mode"] = False
for key, value in default_values.items():
# default value override values explicitly set to None
k = kwargs.get(key, None)
kwargs[key] = k if k is not None else value
return torch.autograd.gradgradcheck(fn, inputs, grad_outputs, **kwargs)
def _assertGradAndGradgradChecks(test_case, apply_fn, inputs, **kwargs):
# call assert function rather than returning a bool since it's nicer
# if we get whether this failed on the gradcheck or the gradgradcheck.
test_case.assertTrue(gradcheck(apply_fn, inputs, **kwargs))
test_case.assertTrue(gradgradcheck(apply_fn, inputs, **kwargs))
@contextmanager
def set_cwd(path: str) -> Iterator[None]:
old_cwd = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(old_cwd)
# Using @precisionOverride specific to your test is the recommended way
# of doing this. These are just some values that worked for test_nn.
dtype2prec_DONTUSE = {torch.float: 1e-5,
torch.double: 1e-5,
torch.half: 1e-2,
torch.bfloat16: 1e-1}
def _wrap_warn_once(regex):
def decorator(fn):
def inner(self, *args, **kwargs):
with self.assertWarnsOnceRegex(UserWarning, regex):
fn(self, *args, **kwargs)
return inner
return decorator
# This is a wrapper that wraps a test to run this test twice, one with
# coalesced=True, another with coalesced=False for coalesced/uncoalesced sparse tensors.
def coalescedonoff(f):
@wraps(f)
def wrapped(self, *args, **kwargs):
f(self, *args, **kwargs, coalesced=True)
f(self, *args, **kwargs, coalesced=False)
return wrapped
@contextlib.contextmanager
def disable_gc():
if gc.isenabled():
try:
gc.disable()
yield
finally:
gc.enable()
else:
yield
|
jQuery(document).ready(function() {
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
}); |
/**
* @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would like to build CKEditor online again
* (for example to upgrade), visit one the following links:
*
* (1) http://ckeditor.com/builder
* Visit online builder to build CKEditor from scratch.
*
* (2) http://ckeditor.com/builder/5eeb23bb8f3ef46f63078cbcd7402ba8
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/5eeb23bb8f3ef46f63078cbcd7402ba8
* Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'kama',
preset: 'standard',
ignore: [
'.bender',
'bender.js',
'bender-err.log',
'bender-out.log',
'dev',
'.DS_Store',
'.gitattributes',
'.gitignore',
'Gruntfile.js',
'.idea',
'.jscsrc',
'.jshintignore',
'.jshintrc',
'.mailmap',
'node_modules',
'package.json',
'README.md',
'tests'
],
plugins : {
'a11yhelp' : 1,
'about' : 1,
'basicstyles' : 1,
'blockquote' : 1,
'codesnippet' : 1,
'contextmenu' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'horizontalrule' : 1,
'htmlwriter' : 1,
'image' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastefromword' : 1,
'pastetext' : 1,
'removeformat' : 1,
'resize' : 1,
'scayt' : 1,
'showborders' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'toolbar' : 1,
'undo' : 1,
'wsc' : 1,
'wysiwygarea' : 1
},
languages : {
'en' : 1,
'fr' : 1
}
}; |
import math
import numpy
def prune_nodes(points, cells):
# Only points/cells that actually used
uvertices, uidx = numpy.unique(cells, return_inverse=True)
cells = uidx.reshape(cells.shape)
points = points[uvertices]
return points, cells
def get_triangle_volumes(pts, cells):
# Works in any dimension; taken from voropy
local_idx = numpy.array([[1, 2], [2, 0], [0, 1]]).T
idx_hierarchy = cells.T[local_idx]
half_edge_coords = pts[idx_hierarchy[1]] - pts[idx_hierarchy[0]]
ei_dot_ej = numpy.einsum(
"ijk, ijk->ij", half_edge_coords[[1, 2, 0]], half_edge_coords[[2, 0, 1]]
)
vols = 0.5 * numpy.sqrt(
+ei_dot_ej[2] * ei_dot_ej[0]
+ ei_dot_ej[0] * ei_dot_ej[1]
+ ei_dot_ej[1] * ei_dot_ej[2]
)
return vols
def get_simplex_volumes(pts, cells):
"""Signed volume of a simplex in nD. Note that signing only makes sense for
n-simplices in R^n.
"""
n = pts.shape[1]
assert cells.shape[1] == n + 1
p = pts[cells]
p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1)
return numpy.abs(numpy.linalg.det(p) / math.factorial(n))
def compute_volume(mesh):
if "tetra" in mesh.cells:
vol = math.fsum(
get_simplex_volumes(*prune_nodes(mesh.points, mesh.cells["tetra"]))
)
elif "triangle" in mesh.cells or "quad" in mesh.cells:
vol = 0.0
if "triangle" in mesh.cells:
# triangles
vol += math.fsum(
get_triangle_volumes(*prune_nodes(mesh.points, mesh.cells["triangle"]))
)
if "quad" in mesh.cells:
# quad: treat as two triangles
quads = mesh.cells["quad"].T
split_cells = numpy.column_stack(
[[quads[0], quads[1], quads[2]], [quads[0], quads[2], quads[3]]]
).T
vol += math.fsum(
get_triangle_volumes(*prune_nodes(mesh.points, split_cells))
)
else:
assert "line" in mesh.cells
segs = numpy.diff(mesh.points[mesh.cells["line"]], axis=1).squeeze()
vol = numpy.sum(numpy.sqrt(numpy.einsum("...j, ...j", segs, segs)))
return vol
def plot(filename, points, cells):
import matplotlib.pyplot as plt
pts = points[:, :2]
for e in cells["triangle"]:
for idx in [[0, 1], [1, 2], [2, 0]]:
X = pts[e[idx]]
plt.plot(X[:, 0], X[:, 1], "-k")
plt.gca().set_aspect("equal", "datalim")
plt.axis("off")
# plt.show()
plt.savefig(filename, transparent=True)
return
|
from builtins import str
from builtins import range
import fixtures
from vnc_api.vnc_api import *
from tcutils.util import retry, get_random_name
from time import sleep
from tcutils.services import get_status
from vm_test import VMFixture
from svc_hc_fixture import HealthCheckFixture
try:
from webui_test import *
except ImportError:
pass
class SvcInstanceFixture(fixtures.Fixture):
def __init__(self,
connections,
si_name,
svc_template,
if_details,
max_inst=1,
static_route=None,
availability_zone=None,
hc_list=None,
virtualization_type=None,
left_svc_vlan=None,
right_svc_vlan=None,
left_svc_asn_srx=None,
left_svc_asn_qfx=None,
right_svc_asn_qfx=None,
port_tuples_props=[]):
'''
svc_template : instance of ServiceTemplate
'''
self.static_route = static_route or {'management': None,
'left': None,
'right': None}
self.port_tuples_props = port_tuples_props or []
self.connections = connections
self.orch = connections.orch
self.vnc_lib = connections.vnc_lib
self.api_s_inspect = connections.api_server_inspect
self.nova_h = connections.nova_h
self.domain_name = connections.domain_name
self.project_name = connections.project_name
self.si_name = si_name
self.svc_template = svc_template
self.st_name = svc_template.name
self.si_version = svc_template.service_template_properties.version
self.si_obj = None
self.domain_fq_name = [self.domain_name]
self.project_fq_name = [self.domain_name, self.project_name]
self.si_fq_name = [self.domain_name, self.project_name, self.si_name]
self.fq_name_str = ':'.join(self.si_fq_name)
self.inputs = connections.inputs
self.logger = self.inputs.logger
self.already_present = False
self.if_details = if_details
self.max_inst = max_inst
self.virtualization_type = virtualization_type
self.left_svc_vlan = left_svc_vlan
self.right_svc_vlan = right_svc_vlan
self.left_svc_asn_srx = left_svc_asn_srx
self.left_svc_asn_qfx = left_svc_asn_qfx
self.right_svc_asn_qfx = right_svc_asn_qfx
self.si = None
self.svm_ids = []
self.cs_svc_vns = []
self.cs_svc_ris = []
self.availability_zone = self.inputs.availability_zone or availability_zone
self.svn_list = ['svc-vn-mgmt', 'svc-vn-left', 'svc-vn-right']
self.hc_list = hc_list or []
# List of dicts of eg: [{'uuid': '1', 'intf_type': 'left'},
# {'uuid': '2', 'intf_type': 'right'}]
self._vnc = self.connections.orch.vnc_h
if self.inputs.verify_thru_gui():
self.browser = connections.browser
self.browser_openstack = connections.browser_openstack
self.webui = WebuiTest(connections, self.inputs)
self.si_v2 = self.si_version == 2 or False
self.si_v1 = self.si_version == 1 or False
self.service_mode = svc_template.service_template_properties.service_mode
self.port_tuples_uuids = []
self.left_vn_fq_name = if_details.get('left', {}).get('vn_name', None)
self.right_vn_fq_name = if_details.get(
'right', {}).get('vn_name', None)
self.mgmt_vn_fq_name = if_details.get(
'management', {}).get('vn_name', None)
self.intf_rt_table = []
# Dict of svms with uuid as key
self.svms = {}
# end __init__
def setUp(self):
super(SvcInstanceFixture, self).setUp()
self._create_si()
# end setUp
def cleanUp(self):
do_cleanup = True
if self.inputs.fixture_cleanup == 'no':
do_cleanup = False
if self.already_present:
do_cleanup = False
if self.inputs.fixture_cleanup == 'force':
do_cleanup = True
if do_cleanup:
if self.inputs.is_gui_based_config():
self.webui.delete_svc_instance(self)
else:
self._delete_si()
self.logger.info("Deleted SI %s" % (self.si_fq_name))
assert self.verify_on_cleanup()
else:
self.logger.debug('Skipping deletion of SI %s' %
(self.si_fq_name))
super(SvcInstanceFixture, self).cleanUp()
# end cleanUp
def _create_si(self):
try:
svc_instance = self.vnc_lib.service_instance_read(
fq_name=self.si_fq_name)
self.already_present = True
self.uuid = svc_instance.uuid
self.logger.debug(
"Service instance: %s already exists", self.si_fq_name)
except NoIdError:
self.logger.debug("Creating service instance: %s", self.si_fq_name)
project = self.vnc_lib.project_read(fq_name=self.project_fq_name)
svc_instance = ServiceInstance(self.si_name, parent_obj=project)
si_type_args = None
si_intf_type_args = {}
left_vn_name = self.left_vn_fq_name.split(':')[-1] if self.left_vn_fq_name else None
right_vn_name = self.right_vn_fq_name.split(':')[-1] if self.right_vn_fq_name else None
mgmt_vn_name = self.mgmt_vn_fq_name.split(':')[-1] if self.mgmt_vn_fq_name else None
si_prop = ServiceInstanceType(
left_virtual_network=left_vn_name,
right_virtual_network=right_vn_name,
management_virtual_network=mgmt_vn_name)
for itf in self.if_details:
virtual_network = None
if itf == 'left':
virtual_network = left_vn_name
elif itf == 'right':
virtual_network = right_vn_name
elif itf == 'management':
virtual_network = mgmt_vn_name
if self.service_mode == 'transparent' and self.si_v1:
virtual_network = None
if_type = ServiceInstanceInterfaceType(
virtual_network=virtual_network)
si_prop.add_interface_list(if_type)
if self.virtualization_type:
si_prop.set_service_virtualization_type(
self.virtualization_type)
kvp_array = []
kvp = KeyValuePair("left-svc-vlan", str(self.left_svc_vlan))
kvp_array.append(kvp)
kvp = KeyValuePair("right-svc-vlan", str(self.right_svc_vlan))
kvp_array.append(kvp)
left_svc_asns = str(self.left_svc_asn_srx) + \
"," + str(self.left_svc_asn_qfx)
right_svc_asns = str(self.left_svc_asn_srx) + \
"," + str(self.right_svc_asn_qfx)
kvp = KeyValuePair("left-svc-asns", left_svc_asns)
kvp_array.append(kvp)
kvp = KeyValuePair("right-svc-asns", right_svc_asns)
kvp_array.append(kvp)
kvps = KeyValuePairs()
kvps.set_key_value_pair(kvp_array)
svc_instance.set_annotations(kvps)
svc_instance.set_service_instance_properties(si_prop)
svc_instance.set_service_template(self.svc_template)
if self.inputs.is_gui_based_config():
self.webui.create_svc_instance(self)
elif self.inputs.vro_based:
self.orch.create_si(self.si_name, self.svc_template, self.if_details)
else:
self.vnc_lib.service_instance_create(svc_instance)
self.si_obj = self.vnc_lib.service_instance_read(
fq_name=self.si_fq_name)
for port_tuple_props in self.port_tuples_props:
if self.inputs.vro_based:
self.orch.add_port_tuple(self.si_name, self.if_details, port_tuple_props)
else:
self.add_port_tuple(port_tuple_props)
for hc in self.hc_list:
self.associate_hc(hc['uuid'], hc['intf_type'])
if self.static_route:
self.associate_static_route_table(project, self.static_route)
return self.si_obj
# end _create_si
def associate_static_route_table(self, project, static_rt_dict):
for intf in list(static_rt_dict.keys()):
name = '%s_%s' % (self.si_name, intf)
prefix = static_rt_dict[intf]
if prefix:
prefixes = prefix if type(prefix) is list else [prefix]
self.logger.debug("Creating interface route table "
"%s with prefixes %s"%(name, prefixes))
intf_rt_table = self._vnc.create_interface_route_table(
name, parent_obj=project, prefixes=prefixes)
self.logger.debug("Associating static route table %s to %s" % (
intf_rt_table.name, self.si_fq_name))
self._vnc.assoc_intf_rt_table_to_si(
self.si_fq_name, intf_rt_table.uuid, intf)
d = {'uuid': intf_rt_table.uuid, 'intf_type': intf}
self.intf_rt_table.append(d)
def disassociate_static_route_table(self, irt_uuid):
self.logger.debug(
"Disassociating static route table %s from %s" % (irt_uuid, self.si_fq_name))
self._vnc.disassoc_intf_rt_table_from_si(self.si_fq_name, irt_uuid)
self.logger.debug("Deleting interface route table %s"%irt_uuid)
self._vnc.delete_interface_route_table(irt_uuid)
def associate_hc(self, hc_uuid, intf_type):
self.logger.debug("Associating hc(%s) to si (%s)" %
(hc_uuid, self.si_fq_name))
self._vnc.assoc_health_check_to_si(self.si_fq_name, hc_uuid, intf_type)
d = {'uuid': hc_uuid, 'intf_type': intf_type}
if d not in self.hc_list:
self.hc_list.append(d)
def disassociate_hc(self, hc_uuid):
self.logger.debug(
"Disassociating hc(%s) from si (%s)" % (hc_uuid, self.si_fq_name))
self._vnc.disassoc_health_check_from_si(self.si_fq_name, hc_uuid)
assert self.verify_hc_ref_not_in_vmi()
for hc in list(self.hc_list):
if hc['uuid'] == hc_uuid:
self.hc_list.remove(hc)
def _get_vn_of_intf_type(self, intf_type):
if (intf_type == 'left'):
return self.left_vn_fq_name
elif (intf_type == 'right'):
return self.right_vn_fq_name
elif (intf_type == 'management'):
return self.management_vn_fq_name
def get_hc_status(self):
if self.hc_list == []:
return False
for svm in self.svm_list:
inspect_h = self.connections.agent_inspect[svm.vm_node_ip]
for hc in self.hc_list:
virtual_network = self._get_vn_of_intf_type(hc['intf_type'])
vmi_id = svm.get_vmi_id(virtual_network)
hc_obj = inspect_h.get_health_check(hc['uuid'])
if not hc_obj or not vmi_id:
return False
if not hc_obj.is_hc_active(vmi_id):
return False
return True
@retry(delay=2, tries=10)
def verify_hc_is_active(self):
return self.get_hc_status()
@retry(delay=2, tries=10)
def verify_hc_is_not_active(self):
return not self.get_hc_status()
@retry(delay=2, tries=10)
def verify_hc_ref_not_in_vmi(self):
for svm in self.svm_list:
inspect_h = self.connections.agent_inspect[svm.vm_node_ip]
for hc in self.hc_list:
virtual_network = self._get_vn_of_intf_type(hc['intf_type'])
vmi_id = svm.get_vmi_id(virtual_network)
vmi_obj = self.vnc_lib.virtual_machine_interface_read(
id=vmi_id)
hc_refs = vmi_obj.get_service_health_check_refs()
if hc_refs:
for hc_ref in hc_refs:
if hc_ref['uuid'] == hc['uuid']:
self.logger.info('VMI has SHC refs')
return False
return True
# end verify_hc_ref_in_vmi
@retry(delay=2, tries=10)
def verify_hc_in_agent(self):
for svm in self.svm_list:
vm_node_ip = svm.vm_node_ip
for hc in self.hc_list:
hc_obj = self.useFixture(HealthCheckFixture(connections=self.connections,
uuid=hc['uuid']))
if not hc_obj.verify_in_agent(vm_node_ip):
return False
return True
@retry(delay=2, tries=10)
def verify_hc_not_in_agent(self, hc_list):
for svm in self.svm_list:
inspect_h = self.connections.agent_inspect[svm.vm_node_ip]
for hc in hc_list:
hc_obj = inspect_h.get_health_check(hc['uuid'])
if hc_obj:
return False
return True
def _delete_si(self):
curr_hc_list = list(self.hc_list)
for hc in curr_hc_list:
self.disassociate_hc(hc['uuid'])
self.verify_hc_not_in_agent(curr_hc_list)
intf_rt_table_list = list(self.intf_rt_table)
for irt in intf_rt_table_list:
self.disassociate_static_route_table(irt['uuid'])
self.logger.debug("Deleting service instance: %s", self.si_fq_name)
if self.inputs.vro_based:
self.orch.delete_si(self.si_name)
else:
self.vnc_lib.service_instance_delete(fq_name=self.si_fq_name)
# end _delete_si
@property
def svm_list(self):
vms = getattr(self, '_svm_list', [])
if not vms or len(vms) != len(self.svm_ids):
# Reduce the svm_list to take care of reduce in ecmp instances
self._svm_list = [vm for vm in vms if vm.get_uuid() in self.svm_ids]
self.svms = {k:v for k,v in list(self.svms.items()) if k in self.svm_ids}
# Increase the svm_list to take care of increase in ecmp instances
for vmid in set(self.svm_ids) - set([vm.get_uuid() for vm in self._svm_list]):
vm = VMFixture(self.connections, uuid=vmid)
vm.setUp()
vm.wait_till_vm_is_active()
# Populate tap intf details on the VM objects
# Faster than calling wait_till_vm_is_up()
if not vm.verify_vm_in_agent():
self.logger.error('VM %s not found in vrouter agent' %(
vmid))
self._svm_list.append(vm)
self.svms[vmid] = vm
return self._svm_list
def get_svms(self):
return self.svm_list
@retry(delay=2, tries=10)
def verify_si(self):
"""check service instance"""
self.project = self.vnc_lib.project_read(fq_name=self.project_fq_name)
try:
self.si = self.vnc_lib.service_instance_read(
fq_name=self.si_fq_name)
self.logger.debug(
"Service instance: %s created succesfully", self.si_fq_name)
except NoIdError:
errmsg = "Service instance: %s not found." % self.si_fq_name
self.logger.warn(errmsg)
return (False, errmsg)
return True, None
@retry(delay=2, tries=10)
def verify_st(self):
"""check service template"""
self.cs_si = self.api_s_inspect.get_cs_si(
domain=self.domain_name, project=self.project.name, si=self.si_name, refresh=True)
try:
st_refs = self.cs_si['service-instance']['service_template_refs']
except KeyError:
st_refs = None
if not st_refs:
errmsg = "No service template refs in SI '%s'" % self.si_name
self.logger.warn(errmsg)
return (False, errmsg)
st_ref_name = [st_ref['to'][-1]
for st_ref in st_refs if st_ref['to'][-1] == self.st_name]
if not st_ref_name:
errmsg = "SI '%s' has no service template ref to %s" % (
self.si_name, self.st_name)
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("SI '%s' has service template ref to %s",
self.si_name, self.st_name)
return True, None
@retry(delay=5, tries=5)
def verify_pt(self):
"""check Service PT"""
self.cs_si = self.api_s_inspect.get_cs_si(
domain=self.domain_name, project=self.project.name, si=self.si_name, refresh=True)
try:
self.pt_refs = self.cs_si[
'service-instance']['port_tuples']
except KeyError:
self.pt_refs = None
if not self.pt_refs:
errmsg = "SI %s does not have any Port Tuple" % self.si_name
self.logger.warn(errmsg)
return (False, errmsg)
self.pts = [pts['to'][-1] for pts in self.pt_refs]
self.logger.debug("SI %s has Port Tuple: %s", self.si_name, self.pts)
return True, None
def get_vm_refs(self):
'''
Returns a list of VM UUIDs referred by this SI
'''
vm_refs = None
self.cs_si = self.api_s_inspect.get_cs_si(
domain=self.domain_name,
project=self.project.name,
si=self.si_name,
refresh=True)
try:
self.pt_refs = self.cs_si[
'service-instance']['port_tuples']
except KeyError:
self.pt_refs = None
if self.pt_refs:
vm_refs = []
for pt in self.pt_refs:
cs_pt = self.api_s_inspect.get_cs_pt_by_id(pt['uuid'])
pt_vmi_refs = cs_pt[
'port-tuple'].get('virtual_machine_interface_back_refs', [])
for vmi in pt_vmi_refs:
vmi = self.api_s_inspect.get_cs_vmi_by_id(vmi['uuid'])
vm_refs_vmi = vmi[
'virtual-machine-interface'].get('virtual_machine_refs')
if not vm_refs_vmi:
msg = 'VM refs not seen in VMI %s' %(vmi)
self.logger.warn(msg)
return (None, msg)
for vm_ref in vm_refs_vmi:
vm_refs.append(vm_ref['to'][0])
else:
vm_refs = self.cs_si.get('service-instance', {}).get('virtual_machine_back_refs')
vm_refs = [vm_ref['to'][0] for vm_ref in vm_refs]
return (set(vm_refs), None)
# end get_vm_refs
@retry(delay=5, tries=10)
def verify_svm(self, wait_for_vms=True):
"""check Service VM"""
# Get the pt_refs in case of v2 and vm_refs in case of v1
# From the pt_refs, get the vmi_refs and then get the VMs from vmi_refs
# From svm_ids, get the svm_list
# Verify the SVMs in the svm_list
(vm_refs, msg) = self.get_vm_refs()
if not vm_refs:
errmsg = "SI %s does not have any Service VM" % self.si_name
self.logger.warn(errmsg)
return (False, errmsg)
self.svm_ids = vm_refs
self.logger.debug('The SVMs in the SI are : %s' %self.svm_list)
if self.svc_template.service_template_properties.version == 1:
if len(vm_refs) != self.max_inst:
errmsg = ("SI %s does not have all Service VMs. Expected: %s"
", Got : %s" % (self.si_name, self.max_inst, len(vm_refs)))
self.logger.warn(errmsg)
return (False, errmsg)
# Populate the SVMs
self.get_svms()
for svm_id in self.svm_ids:
cs_svm = self.api_s_inspect.get_cs_vm(vm_id=svm_id, refresh=True)
if not cs_svm:
errmsg = "Service VM for SI '%s' not launched" % self.si_name
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("Service VM for SI '%s' is launched", self.si_name)
if wait_for_vms:
if self.service_mode != 'transparent':
for vm in self.svm_list:
assert vm.wait_till_vm_is_up(), 'SVM is not up'
self.vm_refs = vm_refs
return True, None
@retry(delay=1, tries=5)
def verify_interface_props(self, svc_vm_if):
"""check if properties"""
try:
vm_if_props = svc_vm_if[
'virtual-machine-interface']['virtual_machine_interface_properties']
except KeyError:
vm_if_props = None
if not vm_if_props:
errmsg = "No VM interface in Service VM of SI %s" % self.si_name
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug(
"VM interface present in Service VM of SI %s", self.si_name)
self.if_type = vm_if_props['service_interface_type']
if (not self.if_type and self.if_type not in list(self.if_details.keys())):
errmsg = "Interface type '%s' is not present in Servcice VM of SI '%s'" % (
self.if_type, self.si_name)
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug(
"Interface type '%s' is present in Service VM of SI '%s'", self.if_type, self.si_name)
return True, None
@retry(delay=1, tries=5)
def verify_vn_links(self, svc_vm_if):
"""check vn links"""
try:
vn_refs = svc_vm_if[
'virtual-machine-interface']['virtual_network_refs']
except KeyError:
vn_refs = None
if not vn_refs:
errmsg = "IF %s has no back refs to vn" % self.if_type
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("IF %s has back refs to vn", self.if_type)
for vn in vn_refs:
self.svc_vn = self.api_s_inspect.get_cs_vn(
# project=self.project.name, vn=vn['to'][-1], refresh=True)
domain=vn['to'][0],project=vn['to'][1], vn=vn['to'][-1], refresh=True)
if not self.svc_vn:
errmsg = "IF %s has no vn" % self.if_type
self.logger.warn(errmsg)
return (False, errmsg)
if self.svc_vn['virtual-network']['name'] in self.svn_list:
self.cs_svc_vns.append(vn['to'][-1])
self.logger.debug('SVC_VNs = %s' % self.cs_svc_vns)
self.logger.debug("IF %s has vn '%s'", self.if_type,
self.svc_vn['virtual-network']['name'])
return True, None
@retry(delay=1, tries=5)
def verify_ri(self, svc_vm_if):
"""check routing instance"""
try:
ri_refs = svc_vm_if[
'virtual-machine-interface']['routing_instance_refs']
except KeyError:
ri_refs = None
vn_name = self.svc_vn['virtual-network']['name']
if not ri_refs:
errmsg = "IF %s, VN %s has no back refs to routing instance" % (
self.if_type, vn_name)
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug(
"IF %s, VN %s has back refs to routing instance", self.if_type, vn_name)
for ri in ri_refs:
svc_ri = self.api_s_inspect.get_cs_ri_by_id(ri['uuid'])
if not svc_ri:
errmsg = "IF %s VN %s has no RI" % (self.if_type, vn_name)
self.logger.warn(errmsg)
return (False, errmsg)
if svc_ri['routing-instance']['name'] in self.svn_list:
self.cs_svc_ris.append(ri['uuid'])
ri_name = svc_ri['routing-instance']['name']
self.logger.debug("IF %s VN %s has RI", self.if_type, vn_name)
if ri_name == vn_name:
continue
else:
if not ri['attr']:
errmsg = "IF %s VN %s RI %s no attributes" % (
self.if_type, vn_name, ri_name)
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("IF %s VN %s RI %s has attributes",
self.if_type, vn_name, ri_name)
# check service chain
sc_info = svc_ri[
'routing-instance']['service_chain_information']
if not sc_info:
errmsg = "IF %s VN %s RI %s has no SCINFO" % (
self.if_type, vn_name, ri_name)
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("IF %s VN %s RI %s has SCINFO",
self.if_type, vn_name, ri_name)
return True, None
@retry(delay=2, tries=10)
def verify_svm_interface(self):
# check VM interfaces
pt = self.cs_si['service-instance'].get('port_tuples', None)
if not pt:
for svm_id in self.svm_ids:
cs_svm = self.api_s_inspect.get_cs_vm(
vm_id=svm_id, refresh=True)
svm_ifs = (cs_svm['virtual-machine'].get('virtual_machine_interfaces') or
cs_svm['virtual-machine'].get('virtual_machine_interface_back_refs'))
if svm_ifs is None:
errmsg = "Service VM hasn't come up."
self.logger.warn(errmsg)
return False, errmsg
elif len(svm_ifs) != len(self.if_details):
errmsg = ('Service VM does not have all the interfaces. Got %s,'
'Expected : %s' % (svm_ifs, self.if_details))
self.logger.warn(errmsg)
return False, errmsg
svc_vm_ifs = self.api_s_inspect.get_cs_vmi_of_vm(
svm_id, refresh=True)
for svc_vm_if in svc_vm_ifs:
result, msg = self.verify_interface_props(svc_vm_if)
if not result:
return result, msg
result, msg = self.verify_vn_links(svc_vm_if)
if not result:
return result, msg
result, msg = self.verify_ri(svc_vm_if)
if not result:
return result, msg
return True, None
def verify_on_setup(self, report=True, wait_for_vms=True):
if report:
self.report(self.verify_si())
self.report(self.verify_st())
self.report(self.verify_svm(wait_for_vms))
if self.svc_template.service_template_properties.version == 2:
self.report(self.verify_pt())
self.report(self.verify_svm_interface())
else:
# Need verifications to be run without asserting so that they can
# retried to wait for instances to come up
result = True
msg = ""
result1, msg1 = self.verify_si()
if not result1:
result = False
msg = msg + msg1
result1, msg1 = self.verify_st()
if not result1:
result = False
msg = msg + msg1
result1, msg1 = self.verify_svm()
if not result1:
result = False
msg = msg + msg1
else:
# verification has dependency on verify_svm
result1, msg1 = self.verify_svm_interface()
if not result1:
result = False
msg = msg + msg1
return result, msg
return True, None
# end verify_on_setup
def report(self, result):
if type(result) is tuple:
result, errmsg = result
if not result:
assert False, errmsg
@retry(delay=2, tries=15)
def verify_si_not_in_api_server(self):
if not self.si:
return (True, None)
si = self.api_s_inspect.get_cs_si(
domain=self.domain_name, project=self.project.name, si=self.si_name, refresh=True)
if si:
errmsg = "Service instance %s not removed from api server" % self.si_name
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("Service instance %s removed from api server" %
self.si_name)
return (True, None)
@retry(delay=5, tries=20)
def verify_svm_not_in_api_server(self):
'''
SVM can still be present , but it should not be linked to the SI
'''
for svm_id in self.svm_ids:
cs_svm = self.api_s_inspect.get_cs_vm(vm_id=svm_id, refresh=True)
if cs_svm and cs_svm.service_instance_refs():
errmsg = "Service VM %s still has ref for SI %s" % (
cs_svm.fq_name, cs_svm.service_instance_refs)
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("All Service VMs unlinked from SI %s" % (self.si_name))
return (True, None)
def si_exists(self):
svc_instances = self.vnc_lib.service_instances_list()[
'service-instances']
self.logger.debug("%s svc intances found in all projects. They are %s" % (
len(svc_instances), svc_instances))
# Filter SI's in current project as the above list call gives SIs in
# all projects
project_si_list = []
for x in svc_instances:
proj_of_x = [x['fq_name'][0], x['fq_name'][1]]
if proj_of_x == self.project_fq_name:
project_si_list.append(x)
self.logger.debug("%s svc intances found in current project. They are %s" % (
len(project_si_list), project_si_list))
if (len(project_si_list) == 0 and len(svc_instances) == 0):
return False
else:
return True
@retry(delay=2, tries=35)
def verify_svn_not_in_api_server(self):
if self.si_exists():
self.logger.info(
"Some Service Instance exists; skip SVN check in API server")
return (True, None)
for vn in self.cs_svc_vns:
svc_vn = self.api_s_inspect.get_cs_vn(
domain=self.domain_name, project=self.project.name, vn=vn, refresh=True)
self.logger.debug('Service VN %s seen' % svc_vn)
# We will not worry about the Service-VNs not generated via
# fixtures
if (svc_vn and (svc_vn not in self.svn_list)):
errmsg = "Service VN %s is not removed from api server" % vn
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("Service VN %s is removed from api server", vn)
return (True, None)
@retry(delay=2, tries=15)
def verify_ri_not_in_api_server(self):
if self.si_exists():
self.logger.debug(
"Some Service Instance exists; skip RI check in API server")
return (True, None)
for ri in self.cs_svc_ris:
svc_ri = self.api_s_inspect.get_cs_ri_by_id(ri)
if svc_ri:
errmsg = "RI %s is not removed from api server" % ri
self.logger.warn(errmsg)
return (False, errmsg)
self.logger.debug("RI %s is removed from api server", ri)
return (True, None)
def verify_on_cleanup(self):
result = True
result, msg = self.verify_si_not_in_api_server()
assert result, msg
result, msg = self.verify_svm_not_in_api_server()
assert result, msg
if self.service_mode != 'in-network-nat':
result, msg = self.verify_svn_not_in_api_server()
assert result, msg
result, msg = self.verify_ri_not_in_api_server()
assert result, msg
return result
# end verify_on_cleanup
def delete_port_tuple(self, port_tuples):
pt_name = port_tuples.get('name')
si_obj = port_tuples.get('si_obj')
pt_uuid = port_tuples.get('pt_uuid')
for intf_type, vmi_id in port_tuples.items():
if intf_type == 'name' or intf_type == 'si_obj' or intf_type == 'pt_uuid':
continue
vmi_obj = self.vnc_lib.virtual_machine_interface_read(id=vmi_id)
pt_obj = PortTuple(name=pt_name, parent_obj=self.si_obj)
vmi_obj.del_port_tuple(pt_obj)
self.vnc_lib.virtual_machine_interface_update(vmi_obj)
self.vnc_lib.port_tuple_delete(id=pt_uuid)
# def add_port_tuple(self, svm, pt_name):
def add_port_tuple(self, svm_pt_props={}):
'''
svm_pt_props : { 'manangement' : VMI uuid ,
'left' : VMI uuid , etc }
'''
if not svm_pt_props:
return
pt_name = svm_pt_props.get('name', get_random_name('port_tuple'))
pt_obj = PortTuple(name=pt_name, parent_obj=self.si_obj)
pt_uuid = self.vnc_lib.port_tuple_create(pt_obj)
self.port_tuples_uuids.append(pt_uuid)
# ports_list = []
for intf_type, vmi_id in svm_pt_props.items():
if intf_type == 'name':
continue
vmi_obj = self.vnc_lib.virtual_machine_interface_read(id=vmi_id)
vmi_props = vmi_obj.virtual_machine_interface_properties or \
VirtualMachineInterfacePropertiesType()
vmi_props.set_service_interface_type(intf_type)
vmi_obj.set_virtual_machine_interface_properties(vmi_props)
vmi_obj.add_port_tuple(pt_obj)
self.vnc_lib.virtual_machine_interface_update(vmi_obj)
# end add_port_tuple
def add_port_tuple_subIntf(self, mgmt_vmi_id, left_vmi_id, right_vmi_id, pt_name):
pt_obj = PortTuple(name=pt_name, parent_obj=self.si_obj)
pt_uuid = self.vnc_lib.port_tuple_create(pt_obj)
ports_list = []
ports_list.append(mgmt_vmi_id)
ports_list.append(left_vmi_id)
ports_list.append(right_vmi_id)
intf_type = ['management', 'left', 'right']
for index in range(0, len(ports_list)):
port_id = ports_list[index]
vmi_obj = self.vnc_lib.virtual_machine_interface_read(id=port_id)
vmi_props = vmi_obj.virtual_machine_interface_properties or \
VirtualMachineInterfacePropertiesType()
vmi_props.set_service_interface_type(intf_type[index])
vmi_obj.set_virtual_machine_interface_properties(vmi_props)
vmi_obj.add_port_tuple(pt_obj)
self.vnc_lib.virtual_machine_interface_update(vmi_obj)
# end add_port_tuple
# end SvcInstanceFixture
|
//@ts-check
import WhereClause from "../whereclause/WhereClause";
import OrderbyTypes from "./OrderbyTypes";
import Querylang07CommandCreator from "./Querylang07CommandCreator";
import { createOrGetSheet, getHeaderValues } from "../spreadsheetUtils";
import { createColumnProfilesFromNames } from "../columns";
import _ from "underscore";
import QueryExecutor from "./QueryExecutor";
import SelectResult from "../SelectResult";
class Querylang07 {
/**
*
* @param {String} spreadsheetId
* @param {String} sheetName
* @param {String[]} selectingColumnNames
*/
constructor(spreadsheetId, sheetName, selectingColumnNames) {
this._spreadsheet = SpreadsheetApp.openById(spreadsheetId);
this._selectingColumnNames = selectingColumnNames;
this._ran = false;
this._selectResult = undefined;
this._targetSheetName = sheetName;
this._targetSheet = this._spreadsheet.getSheetByName(sheetName);
const headerValues = getHeaderValues(this._targetSheet);
const columnProfiles = createColumnProfilesFromNames(headerValues);
const sortedColumnProfiles = _.sortBy(columnProfiles, "base0Index");
this._mostLeftColumnID = _.first(sortedColumnProfiles).id;
this._mostRightColumnID = _.last(sortedColumnProfiles).id;
/**
* @type {Querylang07CommandCreator}
*/
this._commandCreator = new Querylang07CommandCreator(
sheetName,
columnProfiles,
selectingColumnNames
);
this._workingSheetName = `temp_spreadsheets-query_${Utilities.getUuid()}`;
this._deleteWorkingSheetOnFinished = true;
}
/**
*
* @param {WhereClause} whereClause
* @returns {Querylang07}
*/
where(whereClause) {
this._commandCreator.where(whereClause);
return this;
}
/**
*
* @param {String} columnName
* @param {OrderbyTypes} type
* @returns {Querylang07}
*/
orderby(columnName, type) {
this._commandCreator.orderby(columnName, type);
return this;
}
/**
*
* @param {String} columnName
* @returns {Querylang07}
*/
asc(columnName) {
this.orderby(columnName, OrderbyTypes.ASC);
return this;
}
/**
*
* @param {String} columnName
* @returns {Querylang07}
*/
desc(columnName) {
this.orderby(columnName, OrderbyTypes.DESC);
return this;
}
/**
*
* @param {Number} limit
* @returns {Querylang07}
*/
limit(limit) {
this._commandCreator.limit(limit);
return this;
}
/**
* @param {Number} offset
* @returns {Querylang07}
*/
offset(offset) {
this._commandCreator.offset(offset);
return this;
}
hasRan() {
return this._ran;
}
workingSheetName(workingSheetName) {
this._workingSheetName = workingSheetName;
this._deleteWorkingSheetOnFinished = false;
return this;
}
/**
*
* @returns {SelectResult}
*/
run() {
const querylang07Command = this._commandCreator.create();
const executor = new QueryExecutor(
this._spreadsheet,
this._workingSheetName,
this._targetSheetName,
this._mostLeftColumnID,
this._mostRightColumnID,
this._targetSheet.getLastRow(),
this._deleteWorkingSheetOnFinished
);
this._selectResult = executor.execute(querylang07Command);
this._ran = true;
return this._selectResult;
}
objects() {
if (!this._ran) this.run();
return this._selectResult.objects();
}
arrays() {
if (!this._ran) this.run();
return this._selectResult.arrays();
}
result() {
if (!this._ran) this.run();
return this._selectResult;
}
}
export default Querylang07;
|
import React from 'react';
import styled from 'styled-components';
const ResultCount = styled.div`
background-color: rgba(217, 217, 217, 0.5);
.openSans {
font-family: 'Open Sans', sans-serif;
}
.fs-16 {
font-size: 16px;
}
.lh-40 {
line-height: 40px;
}
.fw-bold {
font-weight: bold;
}
.innerWrapper {
width: 90%;
margin: 0 auto;
}
@media (min-width: 1120px) {
.innerWrapper{
width: 1120px;
}
}
`;
const ShelfNote = props => {
return (
<ResultCount>
<div className="innerWrapper fs-16 lh-40 openSans">
{props.note}
</div>
</ResultCount>
);
};
export default ShelfNote;
|
const qs = require('querystring')
const RuleSet = require('webpack/lib/RuleSet')
const id = 'vue-loader-plugin'
const NS = 'vue-loader'
class VueLoaderPlugin {
apply (compiler) {
// add NS marker so that the loader can detect and report missing plugin
if (compiler.hooks) {
// webpack 4
compiler.hooks.compilation.tap(id, compilation => {
compilation.hooks.normalModuleLoader.tap(id, loaderContext => {
loaderContext[NS] = true
})
})
} else {
// webpack < 4
compiler.plugin('compilation', compilation => {
compilation.plugin('normal-module-loader', loaderContext => {
loaderContext[NS] = true
})
})
}
// use webpack's RuleSet utility to normalize user rules
const rawRules = compiler.options.module.rules
const { rules } = new RuleSet(rawRules)
// find the rule that applies to vue files
let vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue`))
if (vueRuleIndex < 0) {
vueRuleIndex = rawRules.findIndex(createMatcher(`foo.vue.html`))
}
const vueRule = rules[vueRuleIndex]
if (!vueRule) {
throw new Error(
`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +
`Make sure there is at least one root-level rule that matches .vue or .vue.html files.`
)
}
if (vueRule.oneOf) {
throw new Error(
`[VueLoaderPlugin Error] vue-loader 15 currently does not support vue rules with oneOf.`
)
}
// get the normlized "use" for vue files
const vueUse = vueRule.use
// get vue-loader options
const vueLoaderUseIndex = vueUse.findIndex(u => {
return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader)
})
if (vueLoaderUseIndex < 0) {
throw new Error(
`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +
`Make sure the rule matching .vue files include vue-loader in its use.`
)
}
// make sure vue-loader options has a known ident so that we can share
// options by reference in the template-loader by using a ref query like
// template-loader??vue-loader-options
const vueLoaderUse = vueUse[vueLoaderUseIndex]
vueLoaderUse.ident = 'vue-loader-options'
vueLoaderUse.options = vueLoaderUse.options || {}
// for each user rule (expect the vue rule), create a cloned rule
// that targets the corresponding language blocks in *.vue files.
const clonedRules = rules
.filter(r => r !== vueRule)
.map(cloneRule)
// global pitcher (responsible for injecting template compiler loader & CSS
// post loader)
const pitcher = {
loader: require.resolve('./loaders/pitcher'),
resourceQuery: query => {
const parsed = qs.parse(query.slice(1))
return parsed.vue != null
},
options: {
cacheDirectory: vueLoaderUse.options.cacheDirectory,
cacheIdentifier: vueLoaderUse.options.cacheIdentifier
}
}
// replace original rules
compiler.options.module.rules = [
pitcher,
...clonedRules,
...rules
]
}
}
function createMatcher (fakeFile) {
return (rule, i) => {
// #1201 we need to skip the `include` check when locating the vue rule
const clone = Object.assign({}, rule)
delete clone.include
const normalized = RuleSet.normalizeRule(clone, {}, '')
return (
!rule.enforce &&
normalized.resource &&
normalized.resource(fakeFile)
)
}
}
function cloneRule (rule) {
const { resource, resourceQuery } = rule
// Assuming `test` and `resourceQuery` tests are executed in series and
// synchronously (which is true based on RuleSet's implementation), we can
// save the current resource being matched from `test` so that we can access
// it in `resourceQuery`. This ensures when we use the normalized rule's
// resource check, include/exclude are matched correctly.
let currentResource
const res = Object.assign({}, rule, {
resource: {
test: resource => {
currentResource = resource
return true
}
},
resourceQuery: query => {
const parsed = qs.parse(query.slice(1))
if (parsed.vue == null) {
return false
}
if (resource && parsed.lang == null) {
return false
}
const fakeResourcePath = `${currentResource}.${parsed.lang}`
if (resource && !resource(fakeResourcePath)) {
return false
}
if (resourceQuery && !resourceQuery(query)) {
return false
}
return true
}
})
if (rule.oneOf) {
res.oneOf = rule.oneOf.map(cloneRule)
}
return res
}
VueLoaderPlugin.NS = NS
module.exports = VueLoaderPlugin
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_role_list import V1RoleList
class TestV1RoleList(unittest.TestCase):
""" V1RoleList unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1RoleList(self):
"""
Test V1RoleList
"""
# FIXME: construct object with mandatory attributes with example values
#model = kubernetes.client.models.v1_role_list.V1RoleList()
pass
if __name__ == '__main__':
unittest.main()
|
import warnings
from itertools import product
import numpy as np
from ._c99_config import _have_c99_complex
from ._extensions._dwt import idwt_single
from ._extensions._swt import swt_max_level, swt as _swt, swt_axis as _swt_axis
from ._extensions._pywt import Wavelet, Modes, _check_dtype
from ._multidim import idwt2, idwtn
from ._utils import _as_wavelet, _wavelets_per_axis
__all__ = ["swt", "swt_max_level", 'iswt', 'swt2', 'iswt2', 'swtn', 'iswtn']
def _rescale_wavelet_filterbank(wavelet, sf):
wav = Wavelet(wavelet.name + 'r',
[np.asarray(f) * sf for f in wavelet.filter_bank])
# copy attributes from the original wavelet
wav.orthogonal = wavelet.orthogonal
wav.biorthogonal = wavelet.biorthogonal
return wav
def swt(data, wavelet, level=None, start_level=0, axis=-1,
trim_approx=False, norm=False):
"""
Multilevel 1D stationary wavelet transform.
Parameters
----------
data :
Input signal
wavelet :
Wavelet to use (Wavelet object or name)
level : int, optional
The number of decomposition steps to perform.
start_level : int, optional
The level at which the decomposition will begin (it allows one to
skip a given number of transform steps and compute
coefficients starting from start_level) (default: 0)
axis: int, optional
Axis over which to compute the SWT. If not given, the
last axis is used.
trim_approx : bool, optional
If True, approximation coefficients at the final level are retained.
norm : bool, optional
If True, transform is normalized so that the energy of the coefficients
will be equal to the energy of ``data``. In other words,
``np.linalg.norm(data.ravel())`` will equal the norm of the
concatenated transform coefficients when ``trim_approx`` is True.
Returns
-------
coeffs : list
List of approximation and details coefficients pairs in order
similar to wavedec function::
[(cAn, cDn), ..., (cA2, cD2), (cA1, cD1)]
where n equals input parameter ``level``.
If ``start_level = m`` is given, then the beginning m steps are
skipped::
[(cAm+n, cDm+n), ..., (cAm+1, cDm+1), (cAm, cDm)]
If ``trim_approx`` is ``True``, then the output list is exactly as in
``pywt.wavedec``, where the first coefficient in the list is the
approximation coefficient at the final level and the rest are the
detail coefficients::
[cAn, cDn, ..., cD2, cD1]
Notes
-----
The implementation here follows the "algorithm a-trous" and requires that
the signal length along the transformed axis be a multiple of ``2**level``.
If this is not the case, the user should pad up to an appropriate size
using a function such as ``numpy.pad``.
A primary benefit of this transform in comparison to its decimated
counterpart (``pywt.wavedecn``), is that it is shift-invariant. This comes
at cost of redundancy in the transform (the size of the output coefficients
is larger than the input).
When the following three conditions are true:
1. The wavelet is orthogonal
2. ``swt`` is called with ``norm=True``
3. ``swt`` is called with ``trim_approx=True``
the transform has the following additional properties that may be
desirable in applications:
1. energy is conserved
2. variance is partitioned across scales
When used with ``norm=True``, this transform is closely related to the
multiple-overlap DWT (MODWT) as popularized for time-series analysis,
although the underlying implementation is slightly different from the one
published in [1]_. Specifically, the implementation used here requires a
signal that is a multiple of ``2**level`` in length.
References
----------
.. [1] DB Percival and AT Walden. Wavelet Methods for Time Series Analysis.
Cambridge University Press, 2000.
"""
if not _have_c99_complex and np.iscomplexobj(data):
data = np.asarray(data)
coeffs_real = swt(data.real, wavelet, level, start_level, trim_approx)
coeffs_imag = swt(data.imag, wavelet, level, start_level, trim_approx)
if not trim_approx:
coeffs_cplx = []
for (cA_r, cD_r), (cA_i, cD_i) in zip(coeffs_real, coeffs_imag):
coeffs_cplx.append((cA_r + 1j*cA_i, cD_r + 1j*cD_i))
else:
coeffs_cplx = [cr + 1j*ci
for (cr, ci) in zip(coeffs_real, coeffs_imag)]
return coeffs_cplx
# accept array_like input; make a copy to ensure a contiguous array
dt = _check_dtype(data)
data = np.array(data, dtype=dt)
wavelet = _as_wavelet(wavelet)
if norm:
if not wavelet.orthogonal:
warnings.warn(
"norm=True, but the wavelet is not orthogonal: \n"
"\tThe conditions for energy preservation are not satisfied.")
wavelet = _rescale_wavelet_filterbank(wavelet, 1/np.sqrt(2))
if axis < 0:
axis = axis + data.ndim
if not 0 <= axis < data.ndim:
raise ValueError("Axis greater than data dimensions")
if level is None:
level = swt_max_level(data.shape[axis])
if data.ndim == 1:
ret = _swt(data, wavelet, level, start_level, trim_approx)
else:
ret = _swt_axis(data, wavelet, level, start_level, axis, trim_approx)
return ret
def iswt(coeffs, wavelet, norm=False):
"""
Multilevel 1D inverse discrete stationary wavelet transform.
Parameters
----------
coeffs : array_like
Coefficients list of tuples::
[(cAn, cDn), ..., (cA2, cD2), (cA1, cD1)]
where cA is approximation, cD is details. Index 1 corresponds to
``start_level`` from ``pywt.swt``.
wavelet : Wavelet object or name string
Wavelet to use
norm : bool, optional
Controls the normalization used by the inverse transform. This must
be set equal to the value that was used by ``pywt.swt`` to preserve the
energy of a round-trip transform.
Returns
-------
1D array of reconstructed data.
Examples
--------
>>> import pywt
>>> coeffs = pywt.swt([1,2,3,4,5,6,7,8], 'db2', level=2)
>>> pywt.iswt(coeffs, 'db2')
array([ 1., 2., 3., 4., 5., 6., 7., 8.])
"""
# copy to avoid modification of input data
# If swt was called with trim_approx=False, first element is a tuple
trim_approx = not isinstance(coeffs[0], (tuple, list))
if trim_approx:
cA = coeffs[0]
coeffs = coeffs[1:]
else:
cA = coeffs[0][0]
dt = _check_dtype(cA)
output = np.array(cA, dtype=dt, copy=True)
if not _have_c99_complex and np.iscomplexobj(output):
# compute real and imaginary separately then combine
if trim_approx:
coeffs_real = [c.real for c in coeffs]
coeffs_imag = [c.imag for c in coeffs]
else:
coeffs_real = [(cA.real, cD.real) for (cA, cD) in coeffs]
coeffs_imag = [(cA.imag, cD.imag) for (cA, cD) in coeffs]
return iswt(coeffs_real, wavelet) + 1j*iswt(coeffs_imag, wavelet)
# num_levels, equivalent to the decomposition level, n
num_levels = len(coeffs)
wavelet = _as_wavelet(wavelet)
if norm:
wavelet = _rescale_wavelet_filterbank(wavelet, np.sqrt(2))
mode = Modes.from_object('periodization')
for j in range(num_levels, 0, -1):
step_size = int(pow(2, j-1))
last_index = step_size
if trim_approx:
cD = coeffs[-j]
else:
_, cD = coeffs[-j]
cD = np.asarray(cD, dtype=_check_dtype(cD))
if cD.dtype != output.dtype:
# upcast to a common dtype (float64 or complex128)
if output.dtype.kind == 'c' or cD.dtype.kind == 'c':
dtype = np.complex128
else:
dtype = np.float64
output = np.asarray(output, dtype=dtype)
cD = np.asarray(cD, dtype=dtype)
for first in range(last_index): # 0 to last_index - 1
# Getting the indices that we will transform
indices = np.arange(first, len(cD), step_size)
# select the even indices
even_indices = indices[0::2]
# select the odd indices
odd_indices = indices[1::2]
# perform the inverse dwt on the selected indices,
# making sure to use periodic boundary conditions
# Note: indexing with an array of ints returns a contiguous
# copy as required by idwt_single.
x1 = idwt_single(output[even_indices],
cD[even_indices],
wavelet, mode)
x2 = idwt_single(output[odd_indices],
cD[odd_indices],
wavelet, mode)
# perform a circular shift right
x2 = np.roll(x2, 1)
# average and insert into the correct indices
output[indices] = (x1 + x2)/2.
return output
def swt2(data, wavelet, level, start_level=0, axes=(-2, -1),
trim_approx=False, norm=False):
"""
Multilevel 2D stationary wavelet transform.
Parameters
----------
data : array_like
2D array with input data
wavelet : Wavelet object or name string, or 2-tuple of wavelets
Wavelet to use. This can also be a tuple of wavelets to apply per
axis in ``axes``.
level : int
The number of decomposition steps to perform.
start_level : int, optional
The level at which the decomposition will start (default: 0)
axes : 2-tuple of ints, optional
Axes over which to compute the SWT. Repeated elements are not allowed.
trim_approx : bool, optional
If True, approximation coefficients at the final level are retained.
norm : bool, optional
If True, transform is normalized so that the energy of the coefficients
will be equal to the energy of ``data``. In other words,
``np.linalg.norm(data.ravel())`` will equal the norm of the
concatenated transform coefficients when ``trim_approx`` is True.
Returns
-------
coeffs : list
Approximation and details coefficients (for ``start_level = m``).
If ``trim_approx`` is ``True``, approximation coefficients are
retained for all levels::
[
(cA_m+level,
(cH_m+level, cV_m+level, cD_m+level)
),
...,
(cA_m+1,
(cH_m+1, cV_m+1, cD_m+1)
),
(cA_m,
(cH_m, cV_m, cD_m)
)
]
where cA is approximation, cH is horizontal details, cV is
vertical details, cD is diagonal details and m is ``start_level``.
If ``trim_approx`` is ``False``, approximation coefficients are only
retained at the final level of decomposition. This matches the format
used by ``pywt.wavedec2``::
[
cA_m+level,
(cH_m+level, cV_m+level, cD_m+level),
...,
(cH_m+1, cV_m+1, cD_m+1),
(cH_m, cV_m, cD_m),
]
Notes
-----
The implementation here follows the "algorithm a-trous" and requires that
the signal length along the transformed axes be a multiple of ``2**level``.
If this is not the case, the user should pad up to an appropriate size
using a function such as ``numpy.pad``.
A primary benefit of this transform in comparison to its decimated
counterpart (``pywt.wavedecn``), is that it is shift-invariant. This comes
at cost of redundancy in the transform (the size of the output coefficients
is larger than the input).
When the following three conditions are true:
1. The wavelet is orthogonal
2. ``swt2`` is called with ``norm=True``
3. ``swt2`` is called with ``trim_approx=True``
the transform has the following additional properties that may be
desirable in applications:
1. energy is conserved
2. variance is partitioned across scales
"""
axes = tuple(axes)
data = np.asarray(data)
if len(axes) != 2:
raise ValueError("Expected 2 axes")
if len(axes) != len(set(axes)):
raise ValueError("The axes passed to swt2 must be unique.")
if data.ndim < len(np.unique(axes)):
raise ValueError("Input array has fewer dimensions than the specified "
"axes")
coefs = swtn(data, wavelet, level, start_level, axes, trim_approx, norm)
ret = []
if trim_approx:
ret.append(coefs[0])
coefs = coefs[1:]
for c in coefs:
if trim_approx:
ret.append((c['da'], c['ad'], c['dd']))
else:
ret.append((c['aa'], (c['da'], c['ad'], c['dd'])))
return ret
def iswt2(coeffs, wavelet, norm=False):
"""
Multilevel 2D inverse discrete stationary wavelet transform.
Parameters
----------
coeffs : list
Approximation and details coefficients::
[
(cA_n,
(cH_n, cV_n, cD_n)
),
...,
(cA_2,
(cH_2, cV_2, cD_2)
),
(cA_1,
(cH_1, cV_1, cD_1)
)
]
where cA is approximation, cH is horizontal details, cV is
vertical details, cD is diagonal details and n is the number of
levels. Index 1 corresponds to ``start_level`` from ``pywt.swt2``.
wavelet : Wavelet object or name string, or 2-tuple of wavelets
Wavelet to use. This can also be a 2-tuple of wavelets to apply per
axis.
norm : bool, optional
Controls the normalization used by the inverse transform. This must
be set equal to the value that was used by ``pywt.swt2`` to preserve
the energy of a round-trip transform.
Returns
-------
2D array of reconstructed data.
Examples
--------
>>> import pywt
>>> coeffs = pywt.swt2([[1,2,3,4],[5,6,7,8],
... [9,10,11,12],[13,14,15,16]],
... 'db1', level=2)
>>> pywt.iswt2(coeffs, 'db1')
array([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[ 13., 14., 15., 16.]])
"""
# If swt was called with trim_approx=False, first element is a tuple
trim_approx = not isinstance(coeffs[0], (tuple, list))
if trim_approx:
cA = coeffs[0]
coeffs = coeffs[1:]
else:
cA = coeffs[0][0]
# copy to avoid modification of input data
dt = _check_dtype(cA)
output = np.array(cA, dtype=dt, copy=True)
if output.ndim != 2:
raise ValueError(
"iswt2 only supports 2D arrays. see iswtn for a general "
"n-dimensionsal ISWT")
# num_levels, equivalent to the decomposition level, n
num_levels = len(coeffs)
wavelets = _wavelets_per_axis(wavelet, axes=(0, 1))
if norm:
wavelets = [_rescale_wavelet_filterbank(wav, np.sqrt(2))
for wav in wavelets]
for j in range(num_levels):
step_size = int(pow(2, num_levels-j-1))
last_index = step_size
if trim_approx:
(cH, cV, cD) = coeffs[j]
else:
_, (cH, cV, cD) = coeffs[j]
# We are going to assume cH, cV, and cD are of equal size
if (cH.shape != cV.shape) or (cH.shape != cD.shape):
raise RuntimeError(
"Mismatch in shape of intermediate coefficient arrays")
# make sure output shares the common dtype
# (conversion of dtype for individual coeffs is handled within idwt2 )
common_dtype = np.result_type(*(
[dt, ] + [_check_dtype(c) for c in [cH, cV, cD]]))
if output.dtype != common_dtype:
output = output.astype(common_dtype)
for first_h in range(last_index): # 0 to last_index - 1
for first_w in range(last_index): # 0 to last_index - 1
# Getting the indices that we will transform
indices_h = slice(first_h, cH.shape[0], step_size)
indices_w = slice(first_w, cH.shape[1], step_size)
even_idx_h = slice(first_h, cH.shape[0], 2*step_size)
even_idx_w = slice(first_w, cH.shape[1], 2*step_size)
odd_idx_h = slice(first_h + step_size, cH.shape[0], 2*step_size)
odd_idx_w = slice(first_w + step_size, cH.shape[1], 2*step_size)
# perform the inverse dwt on the selected indices,
# making sure to use periodic boundary conditions
x1 = idwt2((output[even_idx_h, even_idx_w],
(cH[even_idx_h, even_idx_w],
cV[even_idx_h, even_idx_w],
cD[even_idx_h, even_idx_w])),
wavelets, 'periodization')
x2 = idwt2((output[even_idx_h, odd_idx_w],
(cH[even_idx_h, odd_idx_w],
cV[even_idx_h, odd_idx_w],
cD[even_idx_h, odd_idx_w])),
wavelets, 'periodization')
x3 = idwt2((output[odd_idx_h, even_idx_w],
(cH[odd_idx_h, even_idx_w],
cV[odd_idx_h, even_idx_w],
cD[odd_idx_h, even_idx_w])),
wavelets, 'periodization')
x4 = idwt2((output[odd_idx_h, odd_idx_w],
(cH[odd_idx_h, odd_idx_w],
cV[odd_idx_h, odd_idx_w],
cD[odd_idx_h, odd_idx_w])),
wavelets, 'periodization')
# perform a circular shifts
x2 = np.roll(x2, 1, axis=1)
x3 = np.roll(x3, 1, axis=0)
x4 = np.roll(x4, 1, axis=0)
x4 = np.roll(x4, 1, axis=1)
output[indices_h, indices_w] = (x1 + x2 + x3 + x4) / 4
return output
def swtn(data, wavelet, level, start_level=0, axes=None, trim_approx=False,
norm=False):
"""
n-dimensional stationary wavelet transform.
Parameters
----------
data : array_like
n-dimensional array with input data.
wavelet : Wavelet object or name string, or tuple of wavelets
Wavelet to use. This can also be a tuple of wavelets to apply per
axis in ``axes``.
level : int
The number of decomposition steps to perform.
start_level : int, optional
The level at which the decomposition will start (default: 0)
axes : sequence of ints, optional
Axes over which to compute the SWT. A value of ``None`` (the
default) selects all axes. Axes may not be repeated.
trim_approx : bool, optional
If True, approximation coefficients at the final level are retained.
norm : bool, optional
If True, transform is normalized so that the energy of the coefficients
will be equal to the energy of ``data``. In other words,
``np.linalg.norm(data.ravel())`` will equal the norm of the
concatenated transform coefficients when ``trim_approx`` is True.
Returns
-------
[{coeffs_level_n}, ..., {coeffs_level_1}]: list of dict
Results for each level are arranged in a dictionary, where the key
specifies the transform type on each dimension and value is a
n-dimensional coefficients array.
For example, for a 2D case the result at a given level will look
something like this::
{'aa': <coeffs> # A(LL) - approx. on 1st dim, approx. on 2nd dim
'ad': <coeffs> # V(LH) - approx. on 1st dim, det. on 2nd dim
'da': <coeffs> # H(HL) - det. on 1st dim, approx. on 2nd dim
'dd': <coeffs> # D(HH) - det. on 1st dim, det. on 2nd dim
}
For user-specified ``axes``, the order of the characters in the
dictionary keys map to the specified ``axes``.
If ``trim_approx`` is ``True``, the first element of the list contains
the array of approximation coefficients from the final level of
decomposition, while the remaining coefficient dictionaries contain
only detail coefficients. This matches the behavior of `pywt.wavedecn`.
Notes
-----
The implementation here follows the "algorithm a-trous" and requires that
the signal length along the transformed axes be a multiple of ``2**level``.
If this is not the case, the user should pad up to an appropriate size
using a function such as ``numpy.pad``.
A primary benefit of this transform in comparison to its decimated
counterpart (``pywt.wavedecn``), is that it is shift-invariant. This comes
at cost of redundancy in the transform (the size of the output coefficients
is larger than the input).
When the following three conditions are true:
1. The wavelet is orthogonal
2. ``swtn`` is called with ``norm=True``
3. ``swtn`` is called with ``trim_approx=True``
the transform has the following additional properties that may be
desirable in applications:
1. energy is conserved
2. variance is partitioned across scales
"""
data = np.asarray(data)
if not _have_c99_complex and np.iscomplexobj(data):
real = swtn(data.real, wavelet, level, start_level, axes, trim_approx)
imag = swtn(data.imag, wavelet, level, start_level, axes, trim_approx)
if trim_approx:
cplx = [real[0] + 1j * imag[0]]
offset = 1
else:
cplx = []
offset = 0
for rdict, idict in zip(real[offset:], imag[offset:]):
cplx.append(
dict((k, rdict[k] + 1j * idict[k]) for k in rdict.keys()))
return cplx
if data.dtype == np.dtype('object'):
raise TypeError("Input must be a numeric array-like")
if data.ndim < 1:
raise ValueError("Input data must be at least 1D")
if axes is None:
axes = range(data.ndim)
axes = [a + data.ndim if a < 0 else a for a in axes]
if len(axes) != len(set(axes)):
raise ValueError("The axes passed to swtn must be unique.")
num_axes = len(axes)
wavelets = _wavelets_per_axis(wavelet, axes)
if norm:
if not np.all([wav.orthogonal for wav in wavelets]):
warnings.warn(
"norm=True, but the wavelets used are not orthogonal: \n"
"\tThe conditions for energy preservation are not satisfied.")
wavelets = [_rescale_wavelet_filterbank(wav, 1/np.sqrt(2))
for wav in wavelets]
ret = []
for i in range(start_level, start_level + level):
coeffs = [('', data)]
for axis, wavelet in zip(axes, wavelets):
new_coeffs = []
for subband, x in coeffs:
cA, cD = _swt_axis(x, wavelet, level=1, start_level=i,
axis=axis)[0]
new_coeffs.extend([(subband + 'a', cA),
(subband + 'd', cD)])
coeffs = new_coeffs
coeffs = dict(coeffs)
ret.append(coeffs)
# data for the next level is the approximation coeffs from this level
data = coeffs['a' * num_axes]
if trim_approx:
coeffs.pop('a' * num_axes)
if trim_approx:
ret.append(data)
ret.reverse()
return ret
def iswtn(coeffs, wavelet, axes=None, norm=False):
"""
Multilevel nD inverse discrete stationary wavelet transform.
Parameters
----------
coeffs : list
[{coeffs_level_n}, ..., {coeffs_level_1}]: list of dict
wavelet : Wavelet object or name string, or tuple of wavelets
Wavelet to use. This can also be a tuple of wavelets to apply per
axis in ``axes``.
axes : sequence of ints, optional
Axes over which to compute the inverse SWT. Axes may not be repeated.
The default is ``None``, which means transform all axes
(``axes = range(data.ndim)``).
norm : bool, optional
Controls the normalization used by the inverse transform. This must
be set equal to the value that was used by ``pywt.swtn`` to preserve
the energy of a round-trip transform.
Returns
-------
nD array of reconstructed data.
Examples
--------
>>> import pywt
>>> coeffs = pywt.swtn([[1,2,3,4],[5,6,7,8],
... [9,10,11,12],[13,14,15,16]],
... 'db1', level=2)
>>> pywt.iswtn(coeffs, 'db1')
array([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[ 13., 14., 15., 16.]])
"""
# key length matches the number of axes transformed
ndim_transform = max(len(key) for key in coeffs[-1].keys())
trim_approx = not isinstance(coeffs[0], dict)
if trim_approx:
cA = coeffs[0]
coeffs = coeffs[1:]
else:
cA = coeffs[0]['a'*ndim_transform]
# copy to avoid modification of input data
dt = _check_dtype(cA)
output = np.array(cA, dtype=dt, copy=True)
ndim = output.ndim
if axes is None:
axes = range(output.ndim)
axes = [a + ndim if a < 0 else a for a in axes]
if len(axes) != len(set(axes)):
raise ValueError("The axes passed to swtn must be unique.")
if ndim_transform != len(axes):
raise ValueError("The number of axes used in iswtn must match the "
"number of dimensions transformed in swtn.")
# num_levels, equivalent to the decomposition level, n
num_levels = len(coeffs)
wavelets = _wavelets_per_axis(wavelet, axes)
if norm:
wavelets = [_rescale_wavelet_filterbank(wav, np.sqrt(2))
for wav in wavelets]
# initialize various slice objects used in the loops below
# these will remain slice(None) only on axes that aren't transformed
indices = [slice(None), ]*ndim
even_indices = [slice(None), ]*ndim
odd_indices = [slice(None), ]*ndim
odd_even_slices = [slice(None), ]*ndim
for j in range(num_levels):
step_size = int(pow(2, num_levels-j-1))
last_index = step_size
if not trim_approx:
a = coeffs[j].pop('a'*ndim_transform) # will restore later
details = coeffs[j]
# make sure dtype matches the coarsest level approximation coefficients
common_dtype = np.result_type(*(
[dt, ] + [v.dtype for v in details.values()]))
if output.dtype != common_dtype:
output = output.astype(common_dtype)
# We assume all coefficient arrays are of equal size
shapes = [v.shape for k, v in details.items()]
if len(set(shapes)) != 1:
raise RuntimeError(
"Mismatch in shape of intermediate coefficient arrays")
# shape of a single coefficient array, excluding non-transformed axes
coeff_trans_shape = tuple([shapes[0][ax] for ax in axes])
# nested loop over all combinations of axis offsets at this level
for firsts in product(*([range(last_index), ]*ndim_transform)):
for first, sh, ax in zip(firsts, coeff_trans_shape, axes):
indices[ax] = slice(first, sh, step_size)
even_indices[ax] = slice(first, sh, 2*step_size)
odd_indices[ax] = slice(first+step_size, sh, 2*step_size)
# nested loop over all combinations of odd/even inidices
approx = output.copy()
output[tuple(indices)] = 0
ntransforms = 0
for odds in product(*([(0, 1), ]*ndim_transform)):
for o, ax in zip(odds, axes):
if o:
odd_even_slices[ax] = odd_indices[ax]
else:
odd_even_slices[ax] = even_indices[ax]
# extract the odd/even indices for all detail coefficients
details_slice = {}
for key, value in details.items():
details_slice[key] = value[tuple(odd_even_slices)]
details_slice['a'*ndim_transform] = approx[
tuple(odd_even_slices)]
# perform the inverse dwt on the selected indices,
# making sure to use periodic boundary conditions
x = idwtn(details_slice, wavelets, 'periodization', axes=axes)
for o, ax in zip(odds, axes):
# circular shift along any odd indexed axis
if o:
x = np.roll(x, 1, axis=ax)
output[tuple(indices)] += x
ntransforms += 1
output[tuple(indices)] /= ntransforms # normalize
if not trim_approx:
coeffs[j]['a'*ndim_transform] = a # restore approx coeffs to dict
return output
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('adapter:preprint', 'Unit | Adapter | preprint', {
// Specify the other units that are required for this test.
// needs: ['serializer:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let adapter = this.subject();
assert.ok(adapter);
});
|
import React from "react"
export default ({ width = 102, height = 28 }) => (
<svg
width={width}
height={height}
viewBox="0 0 147 40"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<radialGradient
id="a"
cy="0%"
r="100.11%"
gradientTransform="matrix(0 .9989 -1.152 0 .5 -.5)"
>
<stop offset="0" stopColor="#20c6b7" />
<stop offset="1" stopColor="#4d9abf" />
</radialGradient>
<g fill="none" fillRule="evenodd">
<path
fill="#0e1e25"
d="m53.37 12.978.123 2.198c1.403-1.7 3.245-2.55 5.525-2.55 3.951 0 5.962 2.268 6.032 6.804v12.568h-4.26v-12.322c0-1.207-.26-2.1-.78-2.681-.52-.58-1.371-.87-2.552-.87-1.719 0-3 .78-3.84 2.338v13.535h-4.262v-19.02h4.016zm24.378 19.372c-2.7 0-4.89-.852-6.567-2.557-1.678-1.705-2.517-3.976-2.517-6.812v-.527c0-1.898.365-3.595 1.096-5.089.73-1.494 1.757-2.657 3.078-3.49 1.321-.831 2.794-1.247 4.42-1.247 2.583 0 4.58.826 5.988 2.478 1.41 1.653 2.114 3.99 2.114 7.014v1.723h-12.4c.13 1.57.652 2.812 1.57 3.726s2.073 1.371 3.464 1.371c1.952 0 3.542-.79 4.77-2.373l2.297 2.198c-.76 1.136-1.774 2.018-3.042 2.645-1.269.627-2.692.94-4.27.94zm-.508-16.294c-1.17 0-2.113.41-2.832 1.23-.72.82-1.178 1.963-1.377 3.428h8.12v-.317c-.094-1.43-.474-2.51-1.14-3.243-.667-.732-1.59-1.098-2.771-1.098zm16.765-7.7v4.623h3.35v3.164h-3.35v10.617c0 .726.144 1.25.43 1.573.286.322.798.483 1.535.483a6.55 6.55 0 0 0 1.49-.176v3.305c-.97.27-1.905.404-2.806.404-3.273 0-4.91-1.81-4.91-5.431v-10.776h-3.124v-3.164h3.122v-4.623h4.261zm11.137 23.643h-4.262v-27h4.262zm9.172 0h-4.262v-19.02h4.262zm-4.525-23.96c0-.655.207-1.2.622-1.634.416-.433 1.009-.65 1.78-.65.772 0 1.368.217 1.79.65.42.434.63.979.63 1.635 0 .644-.21 1.18-.63 1.608-.422.428-1.018.642-1.79.642-.771 0-1.364-.214-1.78-.642-.415-.427-.622-.964-.622-1.608zm10.663 23.96v-15.857h-2.894v-3.164h2.894v-1.74c0-2.11.584-3.738 1.753-4.887 1.17-1.148 2.806-1.722 4.91-1.722.749 0 1.544.105 2.386.316l-.105 3.34a8.375 8.375 0 0 0 -1.631-.14c-2.035 0-3.052 1.048-3.052 3.146v1.687h3.858v3.164h-3.858v15.856h-4.261zm17.87-6.117 3.858-12.903h4.542l-7.54 21.903c-1.158 3.199-3.122 4.799-5.893 4.799-.62 0-1.304-.106-2.052-.317v-3.305l.807.053c1.075 0 1.885-.196 2.429-.589.543-.392.973-1.051 1.289-1.977l.613-1.635-6.664-18.932h4.595z"
/>
<path
fill="url(#a)"
fillRule="nonzero"
d="m28.589 14.135-.014-.006c-.008-.003-.016-.006-.023-.013a.11.11 0 0 1 -.028-.093l.773-4.726 3.625 3.626-3.77 1.604a.083.083 0 0 1 -.033.006h-.015c-.005-.003-.01-.007-.02-.017a1.716 1.716 0 0 0 -.495-.381zm5.258-.288 3.876 3.876c.805.806 1.208 1.208 1.355 1.674.022.069.04.138.054.209l-9.263-3.923a.728.728 0 0 0 -.015-.006c-.037-.015-.08-.032-.08-.07s.044-.056.081-.071l.012-.005zm5.127 7.003c-.2.376-.59.766-1.25 1.427l-4.37 4.369-5.652-1.177-.03-.006c-.05-.008-.103-.017-.103-.062a1.706 1.706 0 0 0 -.655-1.193c-.023-.023-.017-.059-.01-.092 0-.005 0-.01.002-.014l1.063-6.526.004-.022c.006-.05.015-.108.06-.108a1.73 1.73 0 0 0 1.16-.665c.009-.01.015-.021.027-.027.032-.015.07 0 .103.014l9.65 4.082zm-6.625 6.801-7.186 7.186 1.23-7.56.002-.01c.001-.01.003-.02.006-.029.01-.024.036-.034.061-.044l.012-.005a1.85 1.85 0 0 0 .695-.517c.024-.028.053-.055.09-.06a.09.09 0 0 1 .029 0l5.06 1.04zm-8.707 8.707-.81.81-8.955-12.942a.424.424 0 0 0 -.01-.014c-.014-.019-.029-.038-.026-.06 0-.016.011-.03.022-.042l.01-.013c.027-.04.05-.08.075-.123l.02-.035.003-.003c.014-.024.027-.047.051-.06.021-.01.05-.006.073-.001l9.921 2.046a.164.164 0 0 1 .076.033c.013.013.016.027.019.043a1.757 1.757 0 0 0 1.028 1.175c.028.014.016.045.003.078a.238.238 0 0 0 -.015.045c-.125.76-1.197 7.298-1.485 9.063zm-1.692 1.691c-.597.591-.949.904-1.347 1.03a2 2 0 0 1 -1.206 0c-.466-.148-.869-.55-1.674-1.356l-8.993-8.993 2.349-3.643c.011-.018.022-.034.04-.047.025-.018.061-.01.091 0a2.434 2.434 0 0 0 1.638-.083c.027-.01.054-.017.075.002a.19.19 0 0 1 .028.032l8.999 13.059zm-14.087-10.186-2.063-2.063 4.074-1.738a.084.084 0 0 1 .033-.007c.034 0 .054.034.072.065a2.91 2.91 0 0 0 .13.184l.013.016c.012.017.004.034-.008.05l-2.25 3.493zm-2.976-2.976-2.61-2.61c-.444-.444-.766-.766-.99-1.043l7.936 1.646a.84.84 0 0 0 .03.005c.049.008.103.017.103.063 0 .05-.059.073-.109.092l-.023.01zm-4.056-4.995a2 2 0 0 1 .09-.495c.148-.466.55-.868 1.356-1.674l3.34-3.34a2175.525 2175.525 0 0 0 4.626 6.687c.027.036.057.076.026.106-.146.161-.292.337-.395.528a.16.16 0 0 1 -.05.062c-.013.008-.027.005-.042.002h-.002l-8.949-1.877zm5.68-6.403 4.489-4.491c.423.185 1.96.834 3.333 1.414 1.04.44 1.988.84 2.286.97.03.012.057.024.07.054.008.018.004.041 0 .06a2.003 2.003 0 0 0 .523 1.828c.03.03 0 .073-.026.11l-.014.021-4.56 7.063c-.012.02-.023.037-.043.05-.024.015-.058.008-.086.001a2.274 2.274 0 0 0 -.543-.074c-.164 0-.342.03-.522.063h-.001c-.02.003-.038.007-.054-.005a.21.21 0 0 1 -.045-.051l-4.808-7.013zm5.398-5.398 5.814-5.814c.805-.805 1.208-1.208 1.674-1.355a2 2 0 0 1 1.206 0c.466.147.869.55 1.674 1.355l1.26 1.26-4.135 6.404a.155.155 0 0 1 -.041.048c-.025.017-.06.01-.09 0a2.097 2.097 0 0 0 -1.92.37c-.027.028-.067.012-.101-.003-.54-.235-4.74-2.01-5.341-2.265zm12.506-3.676 3.818 3.818-.92 5.698v.015a.135.135 0 0 1 -.008.038c-.01.02-.03.024-.05.03a1.83 1.83 0 0 0 -.548.273.154.154 0 0 0 -.02.017c-.011.012-.022.023-.04.025a.114.114 0 0 1 -.043-.007l-5.818-2.472-.011-.005c-.037-.015-.081-.033-.081-.071a2.198 2.198 0 0 0 -.31-.915c-.028-.046-.059-.094-.035-.141zm-3.932 8.606 5.454 2.31c.03.014.063.027.076.058a.106.106 0 0 1 0 .057c-.016.08-.03.171-.03.263v.153c0 .038-.039.054-.075.069l-.011.004c-.864.369-12.13 5.173-12.147 5.173s-.035 0-.052-.017c-.03-.03 0-.072.027-.11a.76.76 0 0 0 .014-.02l4.482-6.94.008-.012c.026-.042.056-.089.104-.089l.045.007c.102.014.192.027.283.027.68 0 1.31-.331 1.69-.897a.16.16 0 0 1 .034-.04c.027-.02.067-.01.098.004zm-6.246 9.185 12.28-5.237s.018 0 .035.017c.067.067.124.112.179.154l.027.017c.025.014.05.03.052.056 0 .01 0 .016-.002.025l-1.052 6.462-.004.026c-.007.05-.014.107-.061.107a1.729 1.729 0 0 0 -1.373.847l-.005.008c-.014.023-.027.045-.05.057-.021.01-.048.006-.07.001l-9.793-2.02c-.01-.002-.152-.519-.163-.52z"
transform="translate(-.702)"
/>
</g>
</svg>
)
|
const AbilityDsl = require('../../abilitydsl');
const DrawCard = require('../../drawcard.js');
class ShapeTheFlesh extends DrawCard {
setupCardAbilities() {
this.whileAttached({
effect: [
AbilityDsl.effects.cardCannot('honor'),
AbilityDsl.effects.addKeyword('covert')
]
});
}
isTemptationsMaho() {
return true;
}
}
ShapeTheFlesh.id = 'shape-the-flesh';
module.exports = ShapeTheFlesh;
|
#: Use "yield from" instead of yield inside of a for loop
# yield-from
seq = range(10)
for x in seq:
yield x
# ==>
seq = range(10)
yield from seq
|
import fs from 'fs-extra';
import loaderUtils from 'loader-utils';
import generateLoaderContent from '../generateLoaderContent';
import isLocaleFile, { localeFilter } from '../isLocaleFile';
import isLoaderFile, { noChunks } from '../isLoaderFile';
module.exports = function localeLoader(content) {
const callback = this.async();
const options = loaderUtils.getOptions(this) || {};
const supportedLocales = options.supportedLocales || [];
if (isLoaderFile(content)) {
(async () => {
const files = (await fs.readdir(this.context))
.filter((f) => isLocaleFile(f))
.filter(localeFilter(supportedLocales));
callback(
null,
generateLoaderContent({
files,
chunk: !noChunks(content),
supportedLocales,
}),
);
})();
} else {
callback(null, content);
}
};
|
d2hStoreMenuItems("TX__2446", [["Documents/expertise.htm", "right", "Expertise"],["Documents/expertise1.htm", "right", "Expertise"]]); |
#!/usr/bin/env node
"use strict";
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var n = parseInt(readLine());
let arr = readLine().split(' ');
arr = arr.map(Number);
let np = 0, nn = 0, nz = 0
arr.forEach(v => {
if (v === 0)
nz++
else if (v > 0)
np++
else
nn++
})
console.log((np / arr.length).toPrecision(6))
console.log((nn / arr.length).toPrecision(6))
console.log((nz / arr.length).toPrecision(6))
}
|
import React, {Component} from 'react';
import {Image, Text, Slide, Heading} from "spectacle";
import Completable from '../../assets/completable.png'
export default class CompletableSlide extends Component {
render() {
return (
<Slide>
<Heading size={4}>Completable</Heading>
<Text margin="20px 0px 0px 0px">a flow without items but only a completion or error signal</Text>
<Image src={Completable} width={500}/>
</Slide>
)
}
} |
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
disableSelectAll,
snackBarOpen,
} from '/imports/ui/redux/actions';
import RecyclePage from '../Recycle';
const mapStateToProps = (state) => ({
selectImages: state.selectCounter.selectImages,
counter: state.selectCounter.counter,
});
const mapDispatchToProps = (dispatch) => bindActionCreators({
disableSelectAll,
snackBarOpen,
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(RecyclePage);
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-ddf383ec"],{"014b":function(e,t,n){"use strict";var a=n("e53d"),r=n("07e3"),i=n("8e60"),o=n("63b6"),s=n("9138"),c=n("ebfd").KEY,l=n("294c"),u=n("dbdb"),f=n("45f2"),d=n("62a0"),m=n("5168"),p=n("ccb9"),_=n("6718"),v=n("47ee"),h=n("9003"),b=n("e4ae"),g=n("f772"),y=n("241e"),w=n("36c3"),k=n("1bc3"),C=n("aebd"),O=n("a159"),x=n("0395"),j=n("bf0b"),S=n("9aa9"),P=n("d9f6"),F=n("c3a1"),q=j.f,E=P.f,D=x.f,N=a.Symbol,A=a.JSON,L=A&&A.stringify,R="prototype",I=m("_hidden"),T=m("toPrimitive"),Y={}.propertyIsEnumerable,$=u("symbol-registry"),z=u("symbols"),M=u("op-symbols"),V=Object[R],B="function"==typeof N&&!!S.f,J=a.QObject,G=!J||!J[R]||!J[R].findChild,U=i&&l((function(){return 7!=O(E({},"a",{get:function(){return E(this,"a",{value:7}).a}})).a}))?function(e,t,n){var a=q(V,t);a&&delete V[t],E(e,t,n),a&&e!==V&&E(V,t,a)}:E,K=function(e){var t=z[e]=O(N[R]);return t._k=e,t},Q=B&&"symbol"==typeof N.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof N},W=function(e,t,n){return e===V&&W(M,t,n),b(e),t=k(t,!0),b(n),r(z,t)?(n.enumerable?(r(e,I)&&e[I][t]&&(e[I][t]=!1),n=O(n,{enumerable:C(0,!1)})):(r(e,I)||E(e,I,C(1,{})),e[I][t]=!0),U(e,t,n)):E(e,t,n)},H=function(e,t){b(e);var n,a=v(t=w(t)),r=0,i=a.length;while(i>r)W(e,n=a[r++],t[n]);return e},Z=function(e,t){return void 0===t?O(e):H(O(e),t)},X=function(e){var t=Y.call(this,e=k(e,!0));return!(this===V&&r(z,e)&&!r(M,e))&&(!(t||!r(this,e)||!r(z,e)||r(this,I)&&this[I][e])||t)},ee=function(e,t){if(e=w(e),t=k(t,!0),e!==V||!r(z,t)||r(M,t)){var n=q(e,t);return!n||!r(z,t)||r(e,I)&&e[I][t]||(n.enumerable=!0),n}},te=function(e){var t,n=D(w(e)),a=[],i=0;while(n.length>i)r(z,t=n[i++])||t==I||t==c||a.push(t);return a},ne=function(e){var t,n=e===V,a=D(n?M:w(e)),i=[],o=0;while(a.length>o)!r(z,t=a[o++])||n&&!r(V,t)||i.push(z[t]);return i};B||(N=function(){if(this instanceof N)throw TypeError("Symbol is not a constructor!");var e=d(arguments.length>0?arguments[0]:void 0),t=function(n){this===V&&t.call(M,n),r(this,I)&&r(this[I],e)&&(this[I][e]=!1),U(this,e,C(1,n))};return i&&G&&U(V,e,{configurable:!0,set:t}),K(e)},s(N[R],"toString",(function(){return this._k})),j.f=ee,P.f=W,n("6abf").f=x.f=te,n("355d").f=X,S.f=ne,i&&!n("b8e3")&&s(V,"propertyIsEnumerable",X,!0),p.f=function(e){return K(m(e))}),o(o.G+o.W+o.F*!B,{Symbol:N});for(var ae="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),re=0;ae.length>re;)m(ae[re++]);for(var ie=F(m.store),oe=0;ie.length>oe;)_(ie[oe++]);o(o.S+o.F*!B,"Symbol",{for:function(e){return r($,e+="")?$[e]:$[e]=N(e)},keyFor:function(e){if(!Q(e))throw TypeError(e+" is not a symbol!");for(var t in $)if($[t]===e)return t},useSetter:function(){G=!0},useSimple:function(){G=!1}}),o(o.S+o.F*!B,"Object",{create:Z,defineProperty:W,defineProperties:H,getOwnPropertyDescriptor:ee,getOwnPropertyNames:te,getOwnPropertySymbols:ne});var se=l((function(){S.f(1)}));o(o.S+o.F*se,"Object",{getOwnPropertySymbols:function(e){return S.f(y(e))}}),A&&o(o.S+o.F*(!B||l((function(){var e=N();return"[null]"!=L([e])||"{}"!=L({a:e})||"{}"!=L(Object(e))}))),"JSON",{stringify:function(e){var t,n,a=[e],r=1;while(arguments.length>r)a.push(arguments[r++]);if(n=t=a[1],(g(t)||void 0!==e)&&!Q(e))return h(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!Q(t))return t}),a[1]=t,L.apply(A,a)}}),N[R][T]||n("35e8")(N[R],T,N[R].valueOf),f(N,"Symbol"),f(Math,"Math",!0),f(a.JSON,"JSON",!0)},"0395":function(e,t,n){var a=n("36c3"),r=n("6abf").f,i={}.toString,o="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(e){try{return r(e)}catch(t){return o.slice()}};e.exports.f=function(e){return o&&"[object Window]"==i.call(e)?s(e):r(a(e))}},"0d6d":function(e,t,n){var a=n("d3f4"),r=n("67ab").onFreeze;n("5eda")("freeze",(function(e){return function(t){return e&&a(t)?e(r(t)):t}}))},"2c0f":function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var a,r=n("d225"),i=n("b0b4"),o=n("6db2"),s=n("f645"),c=function(){function e(){Object(r["a"])(this,e)}return Object(i["a"])(e,[{key:"store",value:function(e){return a=o["a"].client.post(s["a"].end_point.admin.e_commerce.city_options,e),a}},{key:"update",value:function(e,t){return a=o["a"].client.put(s["a"].end_point.admin.e_commerce.city_options+"/"+e,t),a}},{key:"list",value:function(e){return a=o["a"].client.get(s["a"].end_point.admin.e_commerce.city_options,{params:e}),a}},{key:"show",value:function(e){return a=o["a"].client.get(s["a"].end_point.admin.e_commerce.city_options+"/"+e),a}},{key:"delete",value:function(e){return a=o["a"].client.delete(s["a"].end_point.admin.e_commerce.city_options+"/"+e),a}}]),e}(),l=new c},"454f":function(e,t,n){n("46a7");var a=n("584a").Object;e.exports=function(e,t,n){return a.defineProperty(e,t,n)}},"46a7":function(e,t,n){var a=n("63b6");a(a.S+a.F*!n("8e60"),"Object",{defineProperty:n("d9f6").f})},"47ee":function(e,t,n){var a=n("c3a1"),r=n("9aa9"),i=n("355d");e.exports=function(e){var t=a(e),n=r.f;if(n){var o,s=n(e),c=i.f,l=0;while(s.length>l)c.call(e,o=s[l++])&&t.push(o)}return t}},"5d58":function(e,t,n){e.exports=n("d8d6")},6718:function(e,t,n){var a=n("e53d"),r=n("584a"),i=n("b8e3"),o=n("ccb9"),s=n("d9f6").f;e.exports=function(e){var t=r.Symbol||(r.Symbol=i?{}:a.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:o.f(e)})}},"67bb":function(e,t,n){e.exports=n("f921")},"69d3":function(e,t,n){n("6718")("asyncIterator")},"6abf":function(e,t,n){var a=n("e6f3"),r=n("1691").concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return a(e,r)}},"6db2":function(e,t,n){"use strict";n("551c"),n("5d58"),n("67bb");n("a481"),n("ac6a");var a=n("bc3a"),r=n.n(a),i=n("f645"),o=r.a.create({baseURL:i["a"].api_url,timeout:3e5,headers:{"Content-Type":"application/json"}});window.isLogin=function(){return document.cookie.indexOf("auth_token")>=0},o.interceptors.response.use((function(e){var t=localStorage.getItem("auth_token");return t&&(e.headers["api-token"]=t),e}),(function(e){return"/login"==window.location.pathname?Promise.reject(e.response.data):401!==e.response.status?e:(localStorage.removeItem("auth_token"),void(location.href="/login"))}));t["a"]={client:o}},7333:function(e,t,n){"use strict";var a=n("9e1e"),r=n("0d58"),i=n("2621"),o=n("52a7"),s=n("4bf8"),c=n("626a"),l=Object.assign;e.exports=!l||n("79e5")((function(){var e={},t={},n=Symbol(),a="abcdefghijklmnopqrst";return e[n]=7,a.split("").forEach((function(e){t[e]=e})),7!=l({},e)[n]||Object.keys(l({},t)).join("")!=a}))?function(e,t){var n=s(e),l=arguments.length,u=1,f=i.f,d=o.f;while(l>u){var m,p=c(arguments[u++]),_=f?r(p).concat(f(p)):r(p),v=_.length,h=0;while(v>h)m=_[h++],a&&!d.call(p,m)||(n[m]=p[m])}return n}:l},"765d":function(e,t,n){n("6718")("observable")},"85f2":function(e,t,n){e.exports=n("454f")},"8cb3":function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var a,r=n("d225"),i=n("b0b4"),o=n("aa8d"),s=n("f645"),c=function(){function e(){Object(r["a"])(this,e)}return Object(i["a"])(e,[{key:"userList",value:function(e){return a=o["a"].client_analytics.get(s["a"].end_point.analytics.user_analytics.user_list,{params:e}),a}},{key:"userByLocation",value:function(e){return a=o["a"].client_analytics.get(s["a"].end_point.analytics.user_analytics.user_by_location,{params:e}),a}},{key:"userByQuest",value:function(e){return a=o["a"].client_analytics.get(s["a"].end_point.analytics.user_analytics.user_by_quest,{params:e}),a}},{key:"userByDemographics",value:function(e){return a=o["a"].client_analytics.get(s["a"].end_point.analytics.user_analytics.user_by_demographics,{params:e}),a}}]),e}(),l=new c},a8a0:function(e,t,n){"use strict";n.r(t);var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"card-body"},[n("div",{staticClass:"collapse-title cell-ellipsis filters-collapse",attrs:{"data-toggle":"collapse","data-target":"#collapse"},on:{click:function(t){return e.toggleFilterCollapse()}}},[n("h5",{staticClass:"mb-0"},[e._v("List of Users")]),e._m(0)]),n("form",{staticClass:"form-inline row collapse filters-cont",attrs:{action:"",id:"collapse"}},[e._m(1),n("div",{staticClass:"col-2 form-group"},[n("label",{staticClass:"pr-3 pb-2"},[e._v("Age Range")]),n("small"),n("div",{staticClass:"d-flex w-100 filter-age"},[n("input",{directives:[{name:"model",rawName:"v-model",value:e.filter.age_from,expression:"filter.age_from"}],staticClass:"form-control",attrs:{type:"number",name:"age-start"},domProps:{value:e.filter.age_from},on:{keyup:function(t){return e.ageValidation(e.filter.age_from,e.filter.age_to)},input:function(t){t.target.composing||e.$set(e.filter,"age_from",t.target.value)}}}),n("label",{staticClass:"px-2"},[e._v("–")]),n("input",{directives:[{name:"model",rawName:"v-model",value:e.filter.age_to,expression:"filter.age_to"}],staticClass:"form-control",attrs:{type:"number",name:"age-end"},domProps:{value:e.filter.age_to},on:{keyup:function(t){return e.ageValidation(e.filter.age_from,e.filter.age_to)},input:function(t){t.target.composing||e.$set(e.filter,"age_to",t.target.value)}}})]),e.validAge?e._e():n("small",{staticClass:"text-danger"},[e._v("Invalid age range")])]),n("div",{staticClass:"col-3 pr-3 form-group"},[n("label",{staticClass:"pb-2"},[e._v("Gender")]),n("select",{directives:[{name:"model",rawName:"v-model",value:e.filter.gender,expression:"filter.gender"}],staticClass:"form-control w-100",attrs:{name:"gender"},on:{change:function(t){var n=Array.prototype.filter.call(t.target.options,(function(e){return e.selected})).map((function(e){var t="_value"in e?e._value:e.value;return t}));e.$set(e.filter,"gender",t.target.multiple?n:n[0])}}},[n("option",{attrs:{value:""}},[e._v("All")]),n("option",{attrs:{value:"Male"}},[e._v("Male")]),n("option",{attrs:{value:"Female"}},[e._v("Female")]),n("option",{attrs:{value:"Other"}},[e._v("Other")]),n("option",{attrs:{value:"Rather not say"}},[e._v("Rather not say")])])]),n("div",{staticClass:"col-4 pr-3 form-group"},[n("label",{staticClass:"pb-2"},[e._v("Interest")]),n("select",{directives:[{name:"model",rawName:"v-model",value:e.filter.interest_option_id,expression:"filter.interest_option_id"}],staticClass:"form-control w-100",attrs:{name:"interest"},on:{change:function(t){var n=Array.prototype.filter.call(t.target.options,(function(e){return e.selected})).map((function(e){var t="_value"in e?e._value:e.value;return t}));e.$set(e.filter,"interest_option_id",t.target.multiple?n:n[0])}}},[n("option",{attrs:{value:""}},[e._v("All")]),e._l(e.interestList,(function(t,a){return n("option",{key:a,domProps:{value:t.id}},[e._v(e._s(t.name)+"\n ")])}))],2)]),n("div",{staticClass:"col-3 form-group"},[n("label",{staticClass:"pb-2"},[e._v("City")]),n("select",{directives:[{name:"model",rawName:"v-model",value:e.filter.city,expression:"filter.city"}],staticClass:"form-control w-100",attrs:{name:"city"},on:{change:function(t){var n=Array.prototype.filter.call(t.target.options,(function(e){return e.selected})).map((function(e){var t="_value"in e?e._value:e.value;return t}));e.$set(e.filter,"city",t.target.multiple?n:n[0])}}},[n("option",{attrs:{value:""}},[e._v("All")]),e._l(e.cityList,(function(t,a){return n("option",{key:a,domProps:{value:t.name}},[e._v(e._s(t.name))])}))],2)]),n("div",{staticClass:"col-5 mt-3 form-group"},[n("VueCtkDateTimePicker",{attrs:{"only-date":e.demo[0].options.onlyDate,format:e.demo[0].options.dateFormat,formatted:e.demo[0].options.dateFormatted,label:e.demo[0].options.dateFrom},on:{input:function(t){return e.dateValidation(e.filter.date_from,e.filter.date_to)}},model:{value:e.filter.date_from,callback:function(t){e.$set(e.filter,"date_from",t)},expression:"filter.date_from"}}),e.validDate?e._e():n("small",{staticClass:"text-danger"},[e._v("Invalid date range")])],1),n("div",{staticClass:"col-5 mt-3 form-group"},[n("VueCtkDateTimePicker",{attrs:{"only-date":e.demo[0].options.onlyDate,format:e.demo[0].options.dateFormat,formatted:e.demo[0].options.dateFormatted,label:e.demo[0].options.dateTo},on:{input:function(t){return e.dateValidation(e.filter.date_from,e.filter.date_to)}},model:{value:e.filter.date_to,callback:function(t){e.$set(e.filter,"date_to",t)},expression:"filter.date_to"}})],1),n("div",{staticClass:"col-2 mt-3 d-flex"},[n("button",{staticClass:"btn btn-primary form-control w-100 mr-1",attrs:{type:"button"},on:{click:function(t){return e.search()}}},[e._v("Apply Filters")]),n("button",{staticClass:"btn btn-danger form-control",attrs:{type:"button"},on:{click:function(t){return e.resetOptions()}}},[n("i",{staticClass:"icon-refresh"})])])]),n("hr"),n("div",{staticClass:"row"},[n("div",{staticClass:"col-12"},[n("div",{staticClass:"table-responsive"},[n("table",{staticClass:"table table-bordered"},[e._m(2),n("tbody",e._l(e.data.data,(function(t,a){return n("tr",[n("td",{staticClass:"cell-wordbreak"},[n("p",[e._v(e._s(t.username))])]),n("td",[e._v(e._s(t.country_code)+e._s(t.phone_number))]),n("td",{staticClass:"cell-wordbreak"},[n("p",[e._v(e._s(t.email))])]),n("td",[e._v(e._s(t.gender))]),n("td",[e._v(e._s(t.birthday))]),n("td",[e._v(e._s(t.age))]),n("td",{staticClass:"cell-wordbreak"},[n("p",[e._v(e._s(t.has_one_user_address?t.has_one_user_address.full_address:t.has_one_user_address))])]),n("td",{staticClass:"cell-wordbreak"},e._l(t.has_many_user_interest,(function(t,a){return n("span",[a>0?n("span",[e._v(", ")]):e._e(),e._v(e._s(t.interest_option.name))])})),0)])})),0)]),e.toPageCount(e.data.total,e.data.per_page)>1?n("paginate",{attrs:{"page-count":e.toPageCount(e.data.total,e.data.per_page),"prev-text":"Prev","next-text":"Next","container-class":"pagination","next-class":"page-link","prev-class":"page-link","page-class":"page-item","page-link-class":"page-link","click-handler":e.paginate},model:{value:e.filter.page,callback:function(t){e.$set(e.filter,"page",t)},expression:"filter.page"}}):e._e()],1)])])])},r=[function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("span",{staticClass:"collapse-icon filter"},[n("span",{staticClass:"mr-2"},[e._v("Show Filters")]),n("i",{staticClass:"fa fa-chevron-right"})])},function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"col-12 mb-2"},[n("hr"),n("small",[n("b",[e._v("Search Filters")])])])},function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("thead",[n("tr",[n("th",{attrs:{width:"15%"}},[e._v("Name")]),n("th",{attrs:{width:"8%"}},[e._v("Phone")]),n("th",{attrs:{width:"12%"}},[e._v("Email")]),n("th",{attrs:{width:"10%"}},[e._v("Gender")]),n("th",{attrs:{width:"12%"}},[e._v("Date of Birth")]),n("th",{attrs:{width:"5%"}},[e._v("Age")]),n("th",{attrs:{width:"23%"}},[e._v("Address")]),n("th",{attrs:{width:"15%"}},[e._v("Interests")])])])}],i=(n("f751"),n("96cf"),n("3b8d")),o=n("8cb3"),s=n("b4d3"),c=n("2c0f"),l=n("a026"),u=(n("c1df"),n("e30a")),f=n.n(u);n("b40d");l["default"].component("VueCtkDateTimePicker",f.a);var d={data:function(){return{data:[],page_count:100,filter:{paginate:!0,per_page:10,page:1,status_option_id:1,age_from:null,age_to:null,gender:"",date_from:null,date_to:null,interest_option_id:"",city:""},date:{},demo:[{options:{format:"h:mm a",formatted:"h:mm a",onlyTime:!0,color:"firebrick",minuteInterval:"15",label:"Select time",id:"TimePicker",noLabel:!0,onlyDate:!0,dateFormat:"YYYY-MM-DD",dateFormatted:"YYYY-MM-DD",title:"Select date",dateFrom:"From",dateTo:"To"}}],filter_options:{paginate:!1},interestList:[],cityList:[]}},mounted:function(){var e=Object(i["a"])(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:return e.next=2,this.list(this.filter);case 2:return e.next=4,this.getInterestOption(this.filter_options);case 4:return e.next=6,this.getCityOption(this.filter_options);case 6:case"end":return e.stop()}}),e,this)})));function t(){return e.apply(this,arguments)}return t}(),methods:{search:function(){var e=Object(i["a"])(regeneratorRuntime.mark((function e(t){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:if(!this.validAge||!this.validDate){e.next=4;break}return this.filter=Object.assign(this.filter,t),e.next=4,this.list(this.filter);case 4:case"end":return e.stop()}}),e,this)})));function t(t){return e.apply(this,arguments)}return t}(),list:function(){var e=Object(i["a"])(regeneratorRuntime.mark((function e(t){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:return e.next=2,o["a"].userList(t);case 2:this.data=e.sent;case 3:case"end":return e.stop()}}),e,this)})));function t(t){return e.apply(this,arguments)}return t}(),paginate:function(){var e=Object(i["a"])(regeneratorRuntime.mark((function e(t){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:return this.filter.page=t,e.next=3,this.list(this.filter);case 3:case"end":return e.stop()}}),e,this)})));function t(t){return e.apply(this,arguments)}return t}(),getInterestOption:function(){var e=Object(i["a"])(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:return e.next=2,s["a"].list(this.filter_options);case 2:this.interestList=e.sent;case 3:case"end":return e.stop()}}),e,this)})));function t(){return e.apply(this,arguments)}return t}(),getCityOption:function(){var e=Object(i["a"])(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:return e.next=2,c["a"].list(this.filter_options);case 2:this.cityList=e.sent;case 3:case"end":return e.stop()}}),e,this)})));function t(){return e.apply(this,arguments)}return t}()}},m=d,p=n("2877"),_=Object(p["a"])(m,a,r,!1,null,null,null);t["default"]=_.exports},aa8d:function(e,t,n){"use strict";n("551c"),n("a481"),n("ac6a");var a=n("bc3a"),r=n.n(a),i=n("f645"),o=r.a.create({baseURL:i["a"].api_analytics_url,timeout:3e4,headers:{"Content-Type":"application/json",Authorization:i["a"].api_analytics_token}});function s(e){function t(e){return e.forEach((function(t,n){var a=s(t);e[n]=a})),e}function n(e){return e instanceof Array}function a(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function r(e){var r;if(n(e))r=t(e);else for(var i in r={},e)r[a(i)]=e[i],n(e[i])&&(r[a(i)]=t(e[i]));return r}return r(e)}window.isLogin=function(){return document.cookie.indexOf("auth_token")>=0},o.interceptors.response.use((function(e){var t=localStorage.getItem("auth_token");t&&(e.headers["Authorization"]="Bearer "+t);e=e.data.data;return s(e)}),(function(e){return"/login"==window.location.pathname?Promise.reject(e.response.data):401!==e.response.status?e.response.data:(localStorage.removeItem("auth_token"),void(location.href="/login"))})),t["a"]={client_analytics:o}},b0b4:function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var a=n("85f2"),r=n.n(a);function i(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),r()(e,a.key,a)}}function o(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}},b4d3:function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var a,r=n("d225"),i=n("b0b4"),o=n("6db2"),s=n("f645"),c=function(){function e(){Object(r["a"])(this,e)}return Object(i["a"])(e,[{key:"store",value:function(e){return a=o["a"].client.post(s["a"].end_point.admin.analytics.interest_options,e),a}},{key:"update",value:function(e,t){return a=o["a"].client.put(s["a"].end_point.admin.analytics.interest_options+"/"+e,t),a}},{key:"list",value:function(e){return a=o["a"].client.get(s["a"].end_point.admin.analytics.interest_options,{params:e}),a}},{key:"show",value:function(e){return a=o["a"].client.get(s["a"].end_point.admin.analytics.interest_options+"/"+e),a}},{key:"delete",value:function(e){return a=o["a"].client.delete(s["a"].end_point.admin.analytics.interest_options+"/"+e),a}}]),e}(),l=new c},bf0b:function(e,t,n){var a=n("355d"),r=n("aebd"),i=n("36c3"),o=n("1bc3"),s=n("07e3"),c=n("794b"),l=Object.getOwnPropertyDescriptor;t.f=n("8e60")?l:function(e,t){if(e=i(e),t=o(t,!0),c)try{return l(e,t)}catch(n){}if(s(e,t))return r(!a.f.call(e,t),e[t])}},ccb9:function(e,t,n){t.f=n("5168")},d225:function(e,t,n){"use strict";function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}n.d(t,"a",(function(){return a}))},d8d6:function(e,t,n){n("1654"),n("6c1c"),e.exports=n("ccb9").f("iterator")},ebfd:function(e,t,n){var a=n("62a0")("meta"),r=n("f772"),i=n("07e3"),o=n("d9f6").f,s=0,c=Object.isExtensible||function(){return!0},l=!n("294c")((function(){return c(Object.preventExtensions({}))})),u=function(e){o(e,a,{value:{i:"O"+ ++s,w:{}}})},f=function(e,t){if(!r(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,a)){if(!c(e))return"F";if(!t)return"E";u(e)}return e[a].i},d=function(e,t){if(!i(e,a)){if(!c(e))return!0;if(!t)return!1;u(e)}return e[a].w},m=function(e){return l&&p.NEED&&c(e)&&!i(e,a)&&u(e),e},p=e.exports={KEY:a,NEED:!1,fastKey:f,getWeak:d,onFreeze:m}},f645:function(e,t,n){"use strict";n("0d6d");var a=Object.freeze({base_url:"/",api_url:"http://merchblitz-env-1.eba-m2eiva36.ap-southeast-1.elasticbeanstalk.com",api_analytics_url:"http://merchblitz-admin.s3-website-ap-southeast-1.amazonaws.com/",api_analytics_token:"Lvh5nmUYTsDUYYBKWcG1xCD7Ig7Cvp5G4pQzMHsQ",end_point:{admin:{e_commerce:{samples:"/admin/e-commerce/samples",items:"/admin/e-commerce/items",item_categories:"/admin/e-commerce/item-categories",category_headers:"/admin/e-commerce/category-headers",color_options:"/admin/e-commerce/color-options",size_options:"/admin/e-commerce/size-options",item_stocks:"/admin/e-commerce/item-stocks",item_variants:"/admin/e-commerce/item-variants",featured_items:"/admin/e-commerce/featured-items",orders:"/admin/e-commerce/orders",city_options:"/admin/e-commerce/city-option",province_options:"/admin/e-commerce/province-option",region_options:"/admin/e-commerce/region-option",country_options:"/admin/e-commerce/country-option",vouchers:"/admin/e-commerce/vouchers",pushNotifications:"/admin/e-commerce/push-notifications",reports:{most_sold_by_price:"/admin/e-commerce/reports/most-sold-by-price",most_sold_by_quantity:"/admin/e-commerce/reports/most-sold-by-quantity"}},analytics:{interest_options:"admin/analytics/interest-options"},wallet:{gem_packages:"admin/wallet/gem-packages",gem_setting:"admin/wallet/gem-setting",accounts:"admin/wallet/wallet-accounts",transfer_fund:"admin/wallet/transfer-fund",balance_inquiry:"admin/wallet/wallet-accounts/balance-inquiry",transaction_history:"admin/wallet/transaction-history",exchange_rate:"admin/wallet/exchange-rate",orders:"/admin/wallet/orders"},images:"/admin/images",upload:{image:"/admin/upload/single/image"},search:{customer_info:"admin/search/customer-info",order_info:"admin/search/order-info",gem_order_info:"admin/search/gem-order-info",item_info:"admin/search/item-info",wallet_account_info:"admin/search/wallet-account-info",event_info:"admin/search/event-info",company_info:"admin/search/company-info"},management:{company:"/company",administrator:"/admin/users",subscription_plan:"/admin/subscription-plan"}},analytics:{sales_report:{top_wish_listed_item:"/sales-report/top-wish-listed-item",top_viewed_category:"/sales-report/top-viewed-category",top_purchased_gem_package:"/sales-report/top-purchased-gem-package",top_online_store_searches:"/sales-report/top-online-searches",top_items_added_to_cart:"/sales-report/top-items-added-cart",top_items_removed_to_cart:"/sales-report/top-items-remove-from-cart",sales_by_customer_name:"/sales-report/sales-by-customer-name",sales_by_demographics:"/sales-report/sales-by-demographics",sales_by_item:"/sales-report/sales-by-item"},user_analytics:{user_list:"/user/user-lists",user_by_location:"/user/user-by-location",user_by_quest:"/user/user-by-quest",user_by_demographics:"/user/user-by-gender"},event_analytics:{number_of_times_quest_viewed:"/quests/most-viewed",number_of_quest_finished:"/quests/number-of-finished",check_ins:"/events/user-checked-ins",check_in_with_quests:"/events/user-checked-in-with-finish-quests",interest:"/events/user-event-interest",quest_viewed:"/quests/quest-analytics/view",quest_started:"/quests/quest-analytics/start",quest_finished:"/quests/quest-analytics/finish"}}}});t["a"]=a},f751:function(e,t,n){var a=n("5ca1");a(a.S+a.F,"Object",{assign:n("7333")})},f921:function(e,t,n){n("014b"),n("c207"),n("69d3"),n("765d"),e.exports=n("584a").Symbol}}]);
//# sourceMappingURL=chunk-ddf383ec.44511ec6.js.map |
"""
Faça um programa que leia um número qualquer e mostre
o seu fatorial.
"""
numero = int(input('Digite um número inteiro: '))
n = 1
fatorial = 1
while n <= numero:
fatorial = fatorial * n
n += 1
print('{}! = {}'.format(numero, fatorial))
fatorial = 1
for i in range(1, numero+1):
fatorial = fatorial * i
print('{}! = {}'.format(numero, fatorial))
|
/** @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @externs
*/
/**
* @typedef {{
* timestamp: number,
* id: number,
* type: string,
* fromAdaptation: boolean,
* bandwidth: ?number
* }}
*
* @property {number} timestamp
* The timestamp the choice was made, in seconds since 1970
* (i.e. <code>Date.now() / 1000</code>).
* @property {number} id
* The id of the track that was chosen.
* @property {string} type
* The type of track chosen (<code>'variant'</code> or <code>'text'</code>).
* @property {boolean} fromAdaptation
* <code>true</code> if the choice was made by AbrManager for adaptation;
* <code>false</code> if it was made by the application through
* <code>selectTrack</code>.
* @property {?number} bandwidth
* The bandwidth of the chosen track (<code>null</code> for text).
* @exportDoc
*/
shaka.extern.TrackChoice;
/**
* @typedef {{
* timestamp: number,
* state: string,
* duration: number
* }}
*
* @property {number} timestamp
* The timestamp the state was entered, in seconds since 1970
* (i.e. <code>Date.now() / 1000</code>).
* @property {string} state
* The state the player entered. This could be <code>'buffering'</code>,
* <code>'playing'</code>, <code>'paused'</code>, or <code>'ended'</code>.
* @property {number} duration
* The number of seconds the player was in this state. If this is the last
* entry in the list, the player is still in this state, so the duration will
* continue to increase.
* @exportDoc
*/
shaka.extern.StateChange;
/**
* @typedef {{
* width: number,
* height: number,
* streamBandwidth: number,
*
* decodedFrames: number,
* droppedFrames: number,
* corruptedFrames: number,
* estimatedBandwidth: number,
*
* loadLatency: number,
* manifestTimeSeconds: number,
* drmTimeSeconds: number,
* playTime: number,
* pauseTime: number,
* bufferingTime: number,
* licenseTime: number,
*
* switchHistory: !Array.<shaka.extern.TrackChoice>,
* stateHistory: !Array.<shaka.extern.StateChange>
* }}
*
* @description
* Contains statistics and information about the current state of the player.
* This is meant for applications that want to log quality-of-experience (QoE)
* or other stats. These values will reset when <code>load()</code> is called
* again.
*
* @property {number} width
* The width of the current video track.
* @property {number} height
* The height of the current video track.
* @property {number} streamBandwidth
* The bandwidth required for the current streams (total, in bit/sec).
* It takes into account the playbackrate.
*
* @property {number} decodedFrames
* The total number of frames decoded by the Player. This may be
* <code>NaN</code> if this is not supported by the browser.
* @property {number} droppedFrames
* The total number of frames dropped by the Player. This may be
* <code>NaN</code> if this is not supported by the browser.
* @property {number} corruptedFrames
* The total number of corrupted frames dropped by the browser. This may be
* <code>NaN</code> if this is not supported by the browser.
* @property {number} estimatedBandwidth
* The current estimated network bandwidth (in bit/sec).
*
* @property {number} loadLatency
* This is the number of seconds it took for the video element to have enough
* data to begin playback. This is measured from the time load() is called to
* the time the <code>'loadeddata'</code> event is fired by the media element.
* @property {number} manifestTimeSeconds
* The amount of time it took to download and parse the manifest.
* @property {number} drmTimeSeconds
* The amount of time it took to download the first drm key.
* @property {number} playTime
* The total time spent in a playing state in seconds.
* @property {number} pauseTime
* The total time spent in a paused state in seconds.
* @property {number} bufferingTime
* The total time spent in a buffering state in seconds.
* @property {number} licenseTime
* The time spent on license requests during this session in seconds, or NaN.
*
* @property {!Array.<shaka.extern.TrackChoice>} switchHistory
* A history of the stream changes.
* @property {!Array.<shaka.extern.StateChange>} stateHistory
* A history of the state changes.
* @exportDoc
*/
shaka.extern.Stats;
/**
* @typedef {{
* start: number,
* end: number
* }}
*
* @description
* Contains the times of a range of buffered content.
*
* @property {number} start
* The start time of the range, in seconds.
* @property {number} end
* The end time of the range, in seconds.
* @exportDoc
*/
shaka.extern.BufferedRange;
/**
* @typedef {{
* total: !Array.<shaka.extern.BufferedRange>,
* audio: !Array.<shaka.extern.BufferedRange>,
* video: !Array.<shaka.extern.BufferedRange>,
* text: !Array.<shaka.extern.BufferedRange>
* }}
*
* @description
* Contains information about the current buffered ranges.
*
* @property {!Array.<shaka.extern.BufferedRange>} total
* The combined audio/video buffered ranges, reported by
* <code>video.buffered</code>.
* @property {!Array.<shaka.extern.BufferedRange>} audio
* The buffered ranges for audio content.
* @property {!Array.<shaka.extern.BufferedRange>} video
* The buffered ranges for video content.
* @property {!Array.<shaka.extern.BufferedRange>} text
* The buffered ranges for text content.
* @exportDoc
*/
shaka.extern.BufferedInfo;
/**
* @typedef {{
* id: number,
* active: boolean,
*
* type: string,
* bandwidth: number,
*
* language: string,
* label: ?string,
* kind: ?string,
* width: ?number,
* height: ?number,
* frameRate: ?number,
* pixelAspectRatio: ?string,
* mimeType: ?string,
* codecs: ?string,
* audioCodec: ?string,
* videoCodec: ?string,
* primary: boolean,
* roles: !Array.<string>,
* audioRoles: Array.<string>,
* videoId: ?number,
* audioId: ?number,
* channelsCount: ?number,
* audioSamplingRate: ?number,
* audioBandwidth: ?number,
* videoBandwidth: ?number,
* originalVideoId: ?string,
* originalAudioId: ?string,
* originalTextId: ?string
* }}
*
* @description
* An object describing a media track. This object should be treated as
* read-only as changing any values does not have any effect. This is the
* public view of an audio/video paring (variant type) or text track (text
* type).
*
* @property {number} id
* The unique ID of the track.
* @property {boolean} active
* If true, this is the track being streamed (another track may be
* visible/audible in the buffer).
*
* @property {string} type
* The type of track, either <code>'variant'</code> or <code>'text'</code>.
* @property {number} bandwidth
* The bandwidth required to play the track, in bits/sec.
*
* @property {string} language
* The language of the track, or <code>'und'</code> if not given. This is the
* exact value provided in the manifest; it may need to be normalized.
* @property {?string} label
* The track label, which is unique text that should describe the track.
* @property {?string} kind
* (only for text tracks) The kind of text track, either
* <code>'caption'</code> or <code>'subtitle'</code>.
* @property {?number} width
* The video width provided in the manifest, if present.
* @property {?number} height
* The video height provided in the manifest, if present.
* @property {?number} frameRate
* The video framerate provided in the manifest, if present.
* @property {?string} pixelAspectRatio
* The video pixel aspect ratio provided in the manifest, if present.
* @property {?string} mimeType
* The MIME type of the content provided in the manifest.
* @property {?string} codecs
* The audio/video codecs string provided in the manifest, if present.
* @property {?string} audioCodec
* The audio codecs string provided in the manifest, if present.
* @property {?string} videoCodec
* The video codecs string provided in the manifest, if present.
* @property {boolean} primary
* True indicates that this in the primary language for the content.
* This flag is based on signals from the manifest.
* This can be a useful hint about which language should be the default, and
* indicates which track Shaka will use when the user's language preference
* cannot be satisfied.
* @property {!Array.<string>} roles
* The roles of the track, e.g. <code>'main'</code>, <code>'caption'</code>,
* or <code>'commentary'</code>.
* @property {Array.<string>} audioRoles
* The roles of the audio in the track, e.g. <code>'main'</code> or
* <code>'commentary'</code>. Will be null for text tracks or variant tracks
* without audio.
* @property {?number} videoId
* (only for variant tracks) The video stream id.
* @property {?number} audioId
* (only for variant tracks) The audio stream id.
* @property {?number} channelsCount
* The count of the audio track channels.
* @property {?number} audioSamplingRate
* Specifies the maximum sampling rate of the content.
* @property {?number} audioBandwidth
* (only for variant tracks) The audio stream's bandwidth if known.
* @property {?number} videoBandwidth
* (only for variant tracks) The video stream's bandwidth if known.
* @property {?string} originalVideoId
* (variant tracks only) The original ID of the video part of the track, if
* any, as it appeared in the original manifest.
* @property {?string} originalAudioId
* (variant tracks only) The original ID of the audio part of the track, if
* any, as it appeared in the original manifest.
* @property {?string} originalTextId
* (text tracks only) The original ID of the text track, if any, as it
* appeared in the original manifest.
* @exportDoc
*/
shaka.extern.Track;
/**
* @typedef {{
* minWidth: number,
* maxWidth: number,
* minHeight: number,
* maxHeight: number,
* minPixels: number,
* maxPixels: number,
*
* minFrameRate: number,
* maxFrameRate: number,
*
* minBandwidth: number,
* maxBandwidth: number
* }}
*
* @description
* An object describing application restrictions on what tracks can play. All
* restrictions must be fulfilled for a track to be playable/selectable.
* The restrictions system behaves somewhat differently at the ABR level and the
* player level, so please refer to the documentation for those specific
* settings.
*
* @see shaka.extern.PlayerConfiguration
* @see shaka.extern.AbrConfiguration
*
* @property {number} minWidth
* The minimum width of a video track, in pixels.
* @property {number} maxWidth
* The maximum width of a video track, in pixels.
* @property {number} minHeight
* The minimum height of a video track, in pixels.
* @property {number} maxHeight
* The maximum height of a video track, in pixels.
* @property {number} minPixels
* The minimum number of total pixels in a video track (i.e.
* <code>width * height</code>).
* @property {number} maxPixels
* The maximum number of total pixels in a video track (i.e.
* <code>width * height</code>).
*
* @property {number} minFrameRate
* The minimum framerate of a variant track.
* @property {number} maxFrameRate
* The maximum framerate of a variant track.
*
* @property {number} minBandwidth
* The minimum bandwidth of a variant track, in bit/sec.
* @property {number} maxBandwidth
* The maximum bandwidth of a variant track, in bit/sec.
* @exportDoc
*/
shaka.extern.Restrictions;
/**
* @typedef {{
* persistentState: boolean
* }}
*
* @property {boolean} persistentState
* Whether this key system supports persistent state.
* @exportDoc
*/
shaka.extern.DrmSupportType;
/**
* @typedef {{
* manifest: !Object.<string, boolean>,
* media: !Object.<string, boolean>,
* drm: !Object.<string, ?shaka.extern.DrmSupportType>
* }}
*
* @description
* An object detailing browser support for various features.
*
* @property {!Object.<string, boolean>} manifest
* A map of supported manifest types.
* The keys are manifest MIME types and file extensions.
* @property {!Object.<string, boolean>} media
* A map of supported media types.
* The keys are media MIME types.
* @property {!Object.<string, ?shaka.extern.DrmSupportType>} drm
* A map of supported key systems.
* The keys are the key system names. The value is <code>null</code> if it is
* not supported. Key systems not probed will not be in this dictionary.
*
* @exportDoc
*/
shaka.extern.SupportType;
/**
* @typedef {{
* schemeIdUri: string,
* value: string,
* startTime: number,
* endTime: number,
* id: string,
* eventElement: Element
* }}
*
* @description
* Contains information about a region of the timeline that will cause an event
* to be raised when the playhead enters or exits it. In DASH this is the
* EventStream element.
*
* @property {string} schemeIdUri
* Identifies the message scheme.
* @property {string} value
* Specifies the value for the region.
* @property {number} startTime
* The presentation time (in seconds) that the region should start.
* @property {number} endTime
* The presentation time (in seconds) that the region should end.
* @property {string} id
* Specifies an identifier for this instance of the region.
* @property {Element} eventElement
* The XML element that defines the Event.
* @exportDoc
*/
shaka.extern.TimelineRegionInfo;
/**
* @typedef {{
* schemeIdUri: string,
* value: string,
* startTime: number,
* endTime: number,
* timescale: number,
* presentationTimeDelta: number,
* eventDuration: number,
* id: number,
* messageData: Uint8Array
* }}
*
* @description
* Contains information about an EMSG MP4 box.
*
* @property {string} schemeIdUri
* Identifies the message scheme.
* @property {string} value
* Specifies the value for the event.
* @property {number} startTime
* The time that the event starts (in presentation time).
* @property {number} endTime
* The time that the event ends (in presentation time).
* @property {number} timescale
* Provides the timescale, in ticks per second.
* @property {number} presentationTimeDelta
* The offset that the event starts, relative to the start of the segment
* this is contained in (in units of timescale).
* @property {number} eventDuration
* The duration of the event (in units of timescale).
* @property {number} id
* A field identifying this instance of the message.
* @property {Uint8Array} messageData
* Body of the message.
* @exportDoc
*/
shaka.extern.EmsgInfo;
/**
* @typedef {function(!Element):Array.<shaka.extern.DrmInfo>}
* @see shaka.extern.DashManifestConfiguration
* @exportDoc
*/
shaka.extern.DashContentProtectionCallback;
/**
* @typedef {{
* distinctiveIdentifierRequired: boolean,
* persistentStateRequired: boolean,
* videoRobustness: string,
* audioRobustness: string,
* serverCertificate: Uint8Array,
* individualizationServer: string
* }}
*
* @property {boolean} distinctiveIdentifierRequired
* <i>Defaults to false.</i> <br>
* True if the application requires the key system to support distinctive
* identifiers.
* @property {boolean} persistentStateRequired
* <i>Defaults to false.</i> <br>
* True if the application requires the key system to support persistent
* state, e.g., for persistent license storage.
* @property {string} videoRobustness
* A key-system-specific string that specifies a required security level for
* video.
* <i>Defaults to <code>''</code>, i.e., no specific robustness required.</i>
* @property {string} audioRobustness
* A key-system-specific string that specifies a required security level for
* audio.
* <i>Defaults to <code>''</code>, i.e., no specific robustness required.</i>
* @property {Uint8Array} serverCertificate
* <i>Defaults to null.</i> <br>
* <i>An empty certificate (<code>byteLength==0</code>) will be treated as
* <code>null</code>.</i> <br>
* <i>A certificate will be requested from the license server if
* required.</i> <br>
* A key-system-specific server certificate used to encrypt license requests.
* Its use is optional and is meant as an optimization to avoid a round-trip
* to request a certificate.
* @property {string} individualizationServer
* The server that handles an <code>'individualiation-request'</code>. If the
* server isn't given, it will default to the license server.
*
* @exportDoc
*/
shaka.extern.AdvancedDrmConfiguration;
/**
* @typedef {{
* retryParameters: shaka.extern.RetryParameters,
* servers: !Object.<string, string>,
* clearKeys: !Object.<string, string>,
* delayLicenseRequestUntilPlayed: boolean,
* advanced: Object.<string, shaka.extern.AdvancedDrmConfiguration>,
* initDataTransform:
* ((function(!Uint8Array, ?shaka.extern.DrmInfo):!Uint8Array)|undefined),
* logLicenseExchange: boolean
* }}
*
* @property {shaka.extern.RetryParameters} retryParameters
* Retry parameters for license requests.
* @property {!Object.<string, string>} servers
* <i>Required for all but the clear key CDM.</i> <br>
* A dictionary which maps key system IDs to their license servers.
* For example,
* <code>{'com.widevine.alpha': 'https://example.com/drm'}</code>.
* @property {!Object.<string, string>} clearKeys
* <i>Forces the use of the Clear Key CDM.</i>
* A map of key IDs (hex) to keys (hex).
* @property {boolean} delayLicenseRequestUntilPlayed
* <i>Defaults to false.</i> <br>
* True to configure drm to delay sending a license request until a user
* actually starts playing content.
* @property {Object.<string, shaka.extern.AdvancedDrmConfiguration>} advanced
* <i>Optional.</i> <br>
* A dictionary which maps key system IDs to advanced DRM configuration for
* those key systems.
* @property
* {((function(!Uint8Array, ?shaka.extern.DrmInfo):!Uint8Array)|undefined)}
* initDataTransform
* <i>Optional.</i><br>
* If given, this function is called with the init data from the
* manifest/media and should return the (possibly transformed) init data to
* pass to the browser.
* @property {boolean} logLicenseExchange
* <i>Optional.</i><br>
* If set to <code>true</code>, prints logs containing the license exchange.
* This includes the init data, request, and response data, printed as base64
* strings. Don't use in production, for debugging only; has no affect in
* release builds as logging is removed.
*
* @exportDoc
*/
shaka.extern.DrmConfiguration;
/**
* @typedef {{
* customScheme: shaka.extern.DashContentProtectionCallback,
* clockSyncUri: string,
* ignoreDrmInfo: boolean,
* xlinkFailGracefully: boolean,
* defaultPresentationDelay: number,
* ignoreMinBufferTime: boolean,
* autoCorrectDrift: boolean,
* initialSegmentLimit: number,
* ignoreSuggestedPresentationDelay: boolean,
* ignoreEmptyAdaptationSet: boolean
* }}
*
* @property {shaka.extern.DashContentProtectionCallback} customScheme
* If given, invoked by a DASH manifest parser to interpret custom or
* non-standard DRM schemes found in the manifest. The argument is a
* ContentProtection node. Return null if not recognized.
* @property {string} clockSyncUri
* A default clock sync URI to be used with live streams which do not
* contain any clock sync information. The <code>Date</code> header from this
* URI will be used to determine the current time.
* @property {boolean} ignoreDrmInfo
* If true will cause DASH parser to ignore DRM information specified
* by the manifest and treat it as if it signaled no particular key
* system and contained no init data. Defaults to false if not provided.
* @property {boolean} xlinkFailGracefully
* If true, xlink-related errors will result in a fallback to the tag's
* existing contents. If false, xlink-related errors will be propagated
* to the application and will result in a playback failure. Defaults to
* false if not provided.
* @property {number} defaultPresentationDelay
* A default <code>presentationDelay</code> if
* <code>suggestedPresentationDelay</code> is missing in the MPEG DASH
* manifest. This has to be bigger than <code>minBufferTime * 1.5</code>.
* @property {boolean} ignoreMinBufferTime
* If true will cause DASH parser to ignore <code>minBufferTime</code> from
* manifest. It allows player config to take precedence over manifest for
* <code>rebufferingGoal</code>. Defaults to <code>false</code> if not
* provided.
* @property {boolean} autoCorrectDrift
* If <code>true</code>, ignore the <code>availabilityStartTime</code> in the
* manifest and instead use the segments to determine the live edge. This
* allows us to play streams that have a lot of drift. If <code>false</code>,
* we can't play content where the manifest specifies segments in the future.
* Defaults to <code>true</code>.
* @property {number} initialSegmentLimit
* The maximum number of initial segments to generate for
* <code>SegmentTemplate</code> with fixed-duration segments. This is limited
* to avoid excessive memory consumption with very large
* <code>timeShiftBufferDepth</code> values.
* @property {boolean} ignoreSuggestedPresentationDelay
* If true will cause DASH parser to ignore
* <code>suggestedPresentationDelay</code> from manifest. Defaults to
* <code>false</code> if not provided.
* @property {boolean} ignoreEmptyAdaptationSet
* If true will cause DASH parser to ignore
* empty <code>AdaptationSet</code> from manifest. Defaults to
* <code>false</code> if not provided.
* @exportDoc
*/
shaka.extern.DashManifestConfiguration;
/**
* @typedef {{
* ignoreTextStreamFailures: boolean
* }}
*
* @property {boolean} ignoreTextStreamFailures
* If <code>true</code>, ignore any errors in a text stream and filter out
* those streams.
* @exportDoc
*/
shaka.extern.HlsManifestConfiguration;
/**
* @typedef {{
* retryParameters: shaka.extern.RetryParameters,
* availabilityWindowOverride: number,
* disableAudio: boolean,
* disableVideo: boolean,
* disableText: boolean,
* dash: shaka.extern.DashManifestConfiguration,
* hls: shaka.extern.HlsManifestConfiguration
* }}
*
* @property {shaka.extern.RetryParameters} retryParameters
* Retry parameters for manifest requests.
* @property {number} availabilityWindowOverride
* A number, in seconds, that overrides the availability window in the
* manifest, or <code>NaN</code> if the default value should be used. This is
* enforced by the manifest parser, so custom manifest parsers should take
* care to honor this parameter.
* @property {boolean} disableAudio
* If <code>true</code>, the audio tracks are ignored.
* Defaults to <code>false</code>.
* @property {boolean} disableVideo
* If <code>true</code>, the video tracks are ignored.
* Defaults to <code>false</code>.
* @property {boolean} disableText
* If <code>true</code>, the text tracks are ignored.
* Defaults to <code>false</code>.
* @property {shaka.extern.DashManifestConfiguration} dash
* Advanced parameters used by the DASH manifest parser.
* @property {shaka.extern.HlsManifestConfiguration} hls
* Advanced parameters used by the HLS manifest parser.
*
* @exportDoc
*/
shaka.extern.ManifestConfiguration;
/**
* @typedef {{
* retryParameters: shaka.extern.RetryParameters,
* failureCallback: function(!shaka.util.Error),
* rebufferingGoal: number,
* bufferingGoal: number,
* bufferBehind: number,
* ignoreTextStreamFailures: boolean,
* alwaysStreamText: boolean,
* startAtSegmentBoundary: boolean,
* smallGapLimit: number,
* jumpLargeGaps: boolean,
* durationBackoff: number,
* forceTransmuxTS: boolean,
* safeSeekOffset: number,
* stallEnabled: boolean,
* stallThreshold: number,
* stallSkip: number,
* useNativeHlsOnSafari: boolean
* }}
*
* @description
* The StreamingEngine's configuration options.
*
* @property {shaka.extern.RetryParameters} retryParameters
* Retry parameters for segment requests.
* @property {function(!shaka.util.Error)} failureCallback
* A callback to decide what to do on a streaming failure. Default behavior
* is to retry on live streams and not on VOD.
* @property {number} rebufferingGoal
* The minimum number of seconds of content that the StreamingEngine must
* buffer before it can begin playback or can continue playback after it has
* entered into a buffering state (i.e., after it has depleted one more
* more of its buffers).
* @property {number} bufferingGoal
* The number of seconds of content that the StreamingEngine will attempt to
* buffer ahead of the playhead. This value must be greater than or equal to
* the rebuffering goal.
* @property {number} bufferBehind
* The maximum number of seconds of content that the StreamingEngine will keep
* in buffer behind the playhead when it appends a new media segment.
* The StreamingEngine will evict content to meet this limit.
* @property {boolean} ignoreTextStreamFailures
* If <code>true</code>, the player will ignore text stream failures and
* continue playing other streams.
* @property {boolean} alwaysStreamText
* If <code>true</code>, always stream text tracks, regardless of whether or
* not they are shown. This is necessary when using the browser's built-in
* controls, which are not capable of signaling display state changes back to
* Shaka Player.
* Defaults to <code>false</code>.
* @property {boolean} startAtSegmentBoundary
* If <code>true</code>, adjust the start time backwards so it is at the start
* of a segment. This affects both explicit start times and calculated start
* time for live streams. This can put us further from the live edge. Defaults
* to <code>false</code>.
* @property {number} smallGapLimit
* The limit (in seconds) for a gap in the media to be considered "small".
* Small gaps are jumped automatically without events. Large gaps result
* in a Player event and can be jumped.
* @property {boolean} jumpLargeGaps
* If <code>true</code>, jump large gaps in addition to small gaps. A
* <code>largegap</code> event will be raised first. Then, if the app doesn't
* call <code>preventDefault()</code> on the event, the Player will jump the
* gap. If <code>false</code>, then the event will be raised, but the gap
* will not be jumped.
* @property {number} durationBackoff
* By default, we will not allow seeking to exactly the duration of a
* presentation. This field is the number of seconds before duration we will
* seek to when the user tries to seek to or start playback at the duration.
* To disable this behavior, the config can be set to 0. We recommend using
* the default value unless you have a good reason not to.
* @property {boolean} forceTransmuxTS
* If this is <code>true</code>, we will transmux TS content even if not
* strictly necessary for the assets to be played. Shaka Player currently
* only supports CEA 708 captions by transmuxing, so this value is necessary
* for enabling them on platforms with native TS support like Edge or
* Chromecast. This value defaults to <code>false</code>.
* @property {number} safeSeekOffset
* The amount of seconds that should be added when repositioning the playhead
* after falling out of the availability window or seek. This gives the player
* more time to buffer before falling outside again, but increases the forward
* jump in the stream skipping more content. This is helpful for lower
* bandwidth scenarios. Defaults to 5 if not provided.
* @property {boolean} stallEnabled
* When set to <code>true</code>, the stall detector logic will run, skipping
* forward <code>stallSkip</code> seconds whenever the playhead stops moving
* for <code>stallThreshold</code> seconds.
* @property {number} stallThreshold
* The maximum number of seconds that may elapse without the playhead moving
* (when playback is expected) before it will be labeled as a stall.
* @property {number} stallSkip
* The number of seconds that the player will skip forward when a stall has
* been detected.
* @property {boolean} useNativeHlsOnSafari
* Desktop Safari has both MediaSource and their native HLS implementation.
* Depending on the application's needs, it may prefer one over the other.
* Examples: FairPlay is only supported via Safari's native HLS, but it
* doesn't have an API for selecting specific tracks.
* @exportDoc
*/
shaka.extern.StreamingConfiguration;
/**
* @typedef {{
* enabled: boolean,
* defaultBandwidthEstimate: number,
* restrictions: shaka.extern.Restrictions,
* switchInterval: number,
* bandwidthUpgradeTarget: number,
* bandwidthDowngradeTarget: number
* }}
*
* @property {boolean} enabled
* If true, enable adaptation by the current AbrManager. Defaults to true.
* @property {number} defaultBandwidthEstimate
* The default bandwidth estimate to use if there is not enough data, in
* bit/sec.
* @property {shaka.extern.Restrictions} restrictions
* The restrictions to apply to ABR decisions. These are "soft" restrictions.
* Any track that fails to meet these restrictions will not be selected
* automatically, but will still appear in the track list and can still be
* selected via <code>selectVariantTrack()</code>. If no tracks meet these
* restrictions, AbrManager should not fail, but choose a low-res or
* low-bandwidth variant instead. It is the responsibiliy of AbrManager
* implementations to follow these rules and implement this behavior.
* @property {number} switchInterval
* The minimum amount of time that must pass between switches, in
* seconds. This keeps us from changing too often and annoying the user.
* @property {number} bandwidthUpgradeTarget
* The fraction of the estimated bandwidth which we should try to use when
* upgrading.
* @property {number} bandwidthDowngradeTarget
* The largest fraction of the estimated bandwidth we should use. We should
* downgrade to avoid this.
* @exportDoc
*/
shaka.extern.AbrConfiguration;
/**
* @typedef {{
* trackSelectionCallback:
* function(!Array.<shaka.extern.Track>):!Array.<shaka.extern.Track>,
* progressCallback: function(shaka.extern.StoredContent,number),
* usePersistentLicense: boolean
* }}
*
* @property {function(!Array.<shaka.extern.Track>):!Array.<shaka.extern.Track>}
* trackSelectionCallback
* Called inside <code>store()</code> to determine which tracks to save from a
* manifest. It is passed an array of Tracks from the manifest and it should
* return an array of the tracks to store. This is called for each Period in
* the manifest (in order).
* @property {function(shaka.extern.StoredContent,number)} progressCallback
* Called inside <code>store()</code> to give progress info back to the app.
* It is given the current manifest being stored and the progress of it being
* stored.
* @property {boolean} usePersistentLicense
* If <code>true</code>, store protected content with a persistent license so
* that no network is required to view.
* If <code>false</code>, store protected content without a persistent
* license. A network will be required to retrieve a temporary license to
* view.
* Defaults to <code>true</code>.
* @exportDoc
*/
shaka.extern.OfflineConfiguration;
/**
* @typedef {{
* drm: shaka.extern.DrmConfiguration,
* manifest: shaka.extern.ManifestConfiguration,
* streaming: shaka.extern.StreamingConfiguration,
* abrFactory: shaka.extern.AbrManager.Factory,
* abr: shaka.extern.AbrConfiguration,
* offline: shaka.extern.OfflineConfiguration,
* preferredAudioLanguage: string,
* preferredTextLanguage: string,
* preferredVariantRole: string,
* preferredTextRole: string,
* preferredAudioChannelCount: number,
* restrictions: shaka.extern.Restrictions,
* playRangeStart: number,
* playRangeEnd: number,
* textDisplayFactory: shaka.extern.TextDisplayer.Factory
* }}
*
* @property {shaka.extern.DrmConfiguration} drm
* DRM configuration and settings.
* @property {shaka.extern.ManifestConfiguration} manifest
* Manifest configuration and settings.
* @property {shaka.extern.StreamingConfiguration} streaming
* Streaming configuration and settings.
* @property {shaka.extern.AbrManager.Factory} abrFactory
* A factory to construct an abr manager.
* @property {shaka.extern.AbrConfiguration} abr
* ABR configuration and settings.
* @property {shaka.extern.OfflineConfiguration} offline
* Offline configuration and settings.
* @property {string} preferredAudioLanguage
* The preferred language to use for audio tracks. If not given it will use
* the <code>'main'</code> track.
* Changing this during playback will not affect the current playback.
* @property {string} preferredTextLanguage
* The preferred language to use for text tracks. If a matching text track
* is found, and the selected audio and text tracks have different languages,
* the text track will be shown.
* Changing this during playback will not affect the current playback.
* @property {string} preferredVariantRole
* The preferred role to use for variants.
* @property {string} preferredTextRole
* The preferred role to use for text tracks.
* @property {number} preferredAudioChannelCount
* The preferred number of audio channels.
* @property {shaka.extern.Restrictions} restrictions
* The application restrictions to apply to the tracks. These are "hard"
* restrictions. Any track that fails to meet these restrictions will not
* appear in the track list. If no tracks meet these restrictions, playback
* will fail.
* @property {number} playRangeStart
* Optional playback and seek start time in seconds. Defaults to 0 if
* not provided.
* @property {number} playRangeEnd
* Optional playback and seek end time in seconds. Defaults to the end of
* the presentation if not provided.
* @property {shaka.extern.TextDisplayer.Factory} textDisplayFactory
* A factory to construct a text displayer. Note that, if this is changed
* during playback, it will cause the text tracks to be reloaded.
* @exportDoc
*/
shaka.extern.PlayerConfiguration;
/**
* @typedef {{
* language: string,
* role: string
* }}
*
* @property {string} language
* The language code for the stream.
* @property {string} role
* The role name for the stream. If the stream has no role, <code>role</code>
* will be <code>''</code>.
* @exportDoc
*/
shaka.extern.LanguageRole;
|
// 三角函数:
// cosh(..)
// 双曲余弦函数
// acosh(..)
// 双曲反余弦函数
// sinh(..)
// 双曲正弦函数
// asinh(..)
// 双曲反正弦函数
// tanh(..)
// 双曲正切函数
// atanh(..)
// 双曲反正切函数
// hypot(..)
// 平方和的平方根(也即:广义勾股定理)
// 算术:
// cbrt(..)
// 立方根
// clz32(..)
// 计算 32 位二进制表示的前导 0 个数
// expm1(..)
// 等价于 exp(x) - 1
// log2(..)
// 二进制对数(以 2 为底的对数)
// log10(..)
// 以 10 为底的对数
// log1p(..)
// 等价于 log(x + 1)
// imul(..)
// 两个数字的 32 位整数乘法
// 元工具:
// sign(..)
// 返回数字符号
// trunc(..)
// 返回数字的整数部分
// fround(..)
// 向最接近的 32 位(单精度)浮点值取整 |
import { gql } from 'graphql.macro';
export default gql`
mutation Register(
$email: String!
$password: String!
$name: String!
$paymentMethodToken: String,
$planName: String
$billingType: BillingType
) {
register(
email: $email
password: $password
name: $name
paymentMethodToken: $paymentMethodToken
planName: $planName
billingType: $billingType
) {
token
}
}
`;
|
const SCREEN_WIDTH = window.innerWidth;
const SCREEN_HEIGHT = window.innerHeight;
const VIEW_ANGLE = 45;
const ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT;
const NEAR = 1;
const FAR = 10000;
let scene;
let camera;
let renderer;
let axisHelper;
let gridHelper;
let orbit;
let stats;
let lights;
let mesh;
let bones;
let skeletonHelper;
const state = {
animateBones: true,
};
const origin = new THREE.Vector3(0, 0, 0);
function initStats() {
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '20px';
stats.setMode(0); // 0: fps, 1: ms
document.getElementById('stats').appendChild(stats.domElement);
}
function createGeometry(sizing) {
const geometry = new THREE.CylinderGeometry(
5, // radiusTop
5, // radiusBottom
sizing.height, // height
4, // radiusSegments
sizing.segmentCount, // heightSegments
true, // openEnded
);
// Vertices of the shape
for (let i = 0; i < geometry.vertices.length; i += 1) {
// Each vertex corresponds to one skin index
// which corresponds to one skin weight.
//
// The skin index is the index of the bone that
// the particular vertex is influenced by
// (each vertex can only belong to one bone).
//
// The skin weight is the amount of influence
// that bone has over that vertex.
//
// http://stackoverflow.com/questions/23052306/what-is-the-meaning-of-skin-indices-and-skin-weights
// Current vertex
const vertex = geometry.vertices[i];
// The cylinder geometry is centered at (0, 0, 0) which means that
// half of cylinder has negative y coordinates, and
// half of cylinder has positive y coordinates.
// Create a `y` value that is offset from zero by adding half the height.
// So our `y` values will be 0, 8, 16, 24 and 32.
const y = (vertex.y + sizing.halfHeight);
// The skin index is the index of the bone that
// the particular vertex is influenced by
// (each vertex can only belong to one bone).
//
// Our shape has a segment height of 8.
// Our `y` value rage from 0 to 32.
// Work out which bone influences this vertex
//
// We get:
// y = 0, bone = 0
// y = 8, bone = 1
// y = 16, bone = 2
// y = 24, bone = 3
// y = 32, bone = 4
//
// It's important to note that a bone is a POINT not a line.
// Two Bone points are required to make a visual bone line.
// In this example, there are 5 bones.
//
// The skinIndices' values correspond to the geometry's vertices.
// Each vertex can have up to 4 bones associated with it.
// So if you look at the first vertex, and the first skinIndex,
// this will tell you the bones associated with that vertex.
//
// For example the first vertex could have a value of ( 10.05, 30.10, 12.12 ).
// Then the first skin index could have the value of ( 10, 2, 0, 0 ).
// The first skin weight could have the value of ( 0.8, 0.2, 0, 0 ).
// In affect this would take the first vertex, and then the bone mesh.bones[10]
// and apply it 80% of the way. Then it would take the bone skeleton.bones[2]
// and apply it 20% of the way. The next two values have a weight of 0,
// so they would have no affect.
const skinIndex = Math.floor(y / sizing.segmentHeight);
// When working with a SkinnedMesh, each vertex can have
// up to 4 bones affecting it. The skinWeights property
// is an array of weight values that correspond to the
// order of the vertices in the geometry.
//
// So for instance, the first skinWeight would correspond
// to the first vertex in the geometry.
//
// Since each vertex can be modified by 4 bones,
// a Vector4 is used to represent the skin weights for that vertex.
//
// The values of the vector should typically be between 0 and 1.
// For instance when set to 0 the bone transformation will have no affect.
//
// When set to 0.5 it will have 50% affect.
// When set to 100%, it will have 100% affect.
//
// If there is only 1 bone associated with the vertex
// then you only need to worry about the first component of the vector,
// the rest can be ignored and set to 0.
const skinWeight = (y % sizing.segmentHeight) / sizing.segmentHeight;
geometry.skinIndices.push(new THREE.Vector4(skinIndex, skinIndex + 1, 0, 0));
geometry.skinWeights.push(new THREE.Vector4(1 - skinWeight, skinWeight, 0, 0));
}
return geometry;
}
function createBones(sizing) {
bones = [];
let prevBone = new THREE.Bone();
bones.push(prevBone);
prevBone.position.y = -sizing.halfHeight;
for (let i = 0; i < sizing.segmentCount; i += 1) {
const bone = new THREE.Bone();
bone.position.y = sizing.segmentHeight;
bones.push(bone);
prevBone.add(bone);
prevBone = bone;
}
return bones;
}
function createMesh(geometry, theBones) {
const material = new THREE.MeshPhongMaterial({
skinning: true,
color: 0x156289,
emissive: 0x072534,
side: THREE.DoubleSide,
shading: THREE.FlatShading,
});
const theMesh = new THREE.SkinnedMesh(geometry, material);
const skeleton = new THREE.Skeleton(theBones);
theMesh.add(theBones[0]);
theMesh.bind(skeleton);
skeletonHelper = new THREE.SkeletonHelper(theMesh);
skeletonHelper.material.linewidth = 2;
scene.add(skeletonHelper);
return theMesh;
}
function initBones() {
const segmentHeight = 8;
const segmentCount = 4;
const height = segmentHeight * segmentCount;
const halfHeight = height * 0.5;
const sizing = {
segmentHeight,
segmentCount,
height,
halfHeight,
};
const geometry = createGeometry(sizing);
const theBones = createBones(sizing);
mesh = createMesh(geometry, theBones);
mesh.scale.multiplyScalar(1);
scene.add(mesh);
}
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.set(50, 50, 50);
camera.lookAt(origin);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
orbit = new THREE.OrbitControls(camera, renderer.domElement);
THREEx.WindowResize(renderer, camera);
document.body.appendChild(renderer.domElement);
initStats();
gridHelper = new THREE.GridHelper(30, 10);
scene.add(gridHelper);
axisHelper = new THREE.AxisHelper(30);
scene.add(axisHelper);
lights = [];
lights[0] = new THREE.PointLight(0xffffff, 1, 0);
lights[1] = new THREE.PointLight(0xffffff, 1, 0);
lights[2] = new THREE.PointLight(0xffffff, 1, 0);
lights[0].position.set(0, 200, 0);
lights[1].position.set(100, 200, 100);
lights[2].position.set(-100, -200, -100);
scene.add(lights[0]);
scene.add(lights[1]);
scene.add(lights[2]);
initBones();
}
function update() {
const time = Date.now() * 0.001;
if (state.animateBones) {
for (let i = 0; i < mesh.skeleton.bones.length; i += 1) {
mesh.skeleton.bones[i].rotation.z = Math.sin(time) * 2 / mesh.skeleton.bones.length;
}
}
skeletonHelper.update();
stats.update();
orbit.update();
}
function render() {
renderer.render(scene, camera);
}
function tick() {
update();
render();
requestAnimationFrame(tick);
}
init();
tick();
|
import {Dialog} from "primereact/dialog";
import {DataView} from "primereact/dataview";
import UpdateAssigneeRow from "./UpdateAssigneeRow/UpdateAssigneeRow";
import {useCallback, useState} from "react";
import axios from "axios";
export default function UpdateAssigneeDialog({ item, anonymousId, members, updateItem, display, setDisplay, displayError }) {
const [assigneeSelectedId, setAssigneeSelectedId] = useState("");
const updateAssignee = useCallback((member, count) => {
const assignee = item.assignees.filter(a => a.memberId === member._id)?.[0];
if (assignee === undefined) {
axios.post(
`/items/${ item._id }/assignees`,
{ memberId: member._id, count },
{ params: anonymousId !== null ? { anonymousId } : {} }
)
.then(
item => {
updateItem(item.data);
setAssigneeSelectedId("");
},
error => displayError(error.response.data.error)
);
} else {
axios.put(
`/items/${ item._id }/assignees/${ assignee._id }`,
{ count },
{ params: anonymousId !== null ? { anonymousId } : {} }
)
.then(
item => {
updateItem(item.data);
setAssigneeSelectedId("");
},
error => displayError(error.response.data.error)
);
}
}, [item, anonymousId, updateItem, displayError]);
return (
<Dialog
className={"md:w-8 m-3 pb-6 " + (members.length > 3 ? " h-20rem" : null )}
header="Assign the item to"
visible={ display }
onHide={ () => setDisplay(false) }
dismissableMask={ true }
draggable={ false }
resizable={ false }
closable={ false }
>
<DataView
value={ members }
itemTemplate={
member =>
<UpdateAssigneeRow
item={ item }
member={ member }
updateAssignee={ updateAssignee }
assigneeSelectedId={ assigneeSelectedId }
setAssigneeSelectedId={ setAssigneeSelectedId }
/>
}
alwaysShowPaginator={ false }
/>
</Dialog>
);
}
|
/*!
* vuex v3.6.2
* (c) 2021 Evan You
* @license MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Vuex = factory());
}(this, (function () { 'use strict';
function applyMixin (Vue) {
var version = Number(Vue.version.split('.')[0]);
if (version >= 2) {
Vue.mixin({ beforeCreate: vuexInit });
} else {
// override init and inject vuex init procedure
// for 1.x backwards compatibility.
var _init = Vue.prototype._init;
Vue.prototype._init = function (options) {
if ( options === void 0 ) options = {};
options.init = options.init
? [vuexInit].concat(options.init)
: vuexInit;
_init.call(this, options);
};
}
/**
* Vuex init hook, injected into each instances init hooks list.
*/
function vuexInit () {
var options = this.$options;
// store injection
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store;
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store;
}
}
}
var target = typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
function devtoolPlugin (store) {
if (!devtoolHook) { return }
store._devtoolHook = devtoolHook;
devtoolHook.emit('vuex:init', store);
devtoolHook.on('vuex:travel-to-state', function (targetState) {
store.replaceState(targetState);
});
store.subscribe(function (mutation, state) {
devtoolHook.emit('vuex:mutation', mutation, state);
}, { prepend: true });
store.subscribeAction(function (action, state) {
devtoolHook.emit('vuex:action', action, state);
}, { prepend: true });
}
/**
* Get the first item that pass the test
* by second argument function
*
* @param {Array} list
* @param {Function} f
* @return {*}
*/
function find (list, f) {
return list.filter(f)[0]
}
/**
* Deep copy the given object considering circular structure.
* This function caches all nested objects and its copies.
* If it detects circular structure, use cached copy to avoid infinite loop.
*
* @param {*} obj
* @param {Array<Object>} cache
* @return {*}
*/
function deepCopy (obj, cache) {
if ( cache === void 0 ) cache = [];
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
var hit = find(cache, function (c) { return c.original === obj; });
if (hit) {
return hit.copy
}
var copy = Array.isArray(obj) ? [] : {};
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy: copy
});
Object.keys(obj).forEach(function (key) {
copy[key] = deepCopy(obj[key], cache);
});
return copy
}
/**
* forEach for object
*/
function forEachValue (obj, fn) {
Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
}
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
function isPromise (val) {
return val && typeof val.then === 'function'
}
function assert (condition, msg) {
if (!condition) { throw new Error(("[vuex] " + msg)) }
}
function partial (fn, arg) {
return function () {
return fn(arg)
}
}
// Base data struct for store's module, package with some attribute and method
var Module = function Module (rawModule, runtime) {
this.runtime = runtime;
// Store some children item
this._children = Object.create(null);
// Store the origin module object which passed by programmer
this._rawModule = rawModule;
var rawState = rawModule.state;
// Store the origin module's state
this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
};
var prototypeAccessors = { namespaced: { configurable: true } };
prototypeAccessors.namespaced.get = function () {
return !!this._rawModule.namespaced
};
Module.prototype.addChild = function addChild (key, module) {
this._children[key] = module;
};
Module.prototype.removeChild = function removeChild (key) {
delete this._children[key];
};
Module.prototype.getChild = function getChild (key) {
return this._children[key]
};
Module.prototype.hasChild = function hasChild (key) {
return key in this._children
};
Module.prototype.update = function update (rawModule) {
this._rawModule.namespaced = rawModule.namespaced;
if (rawModule.actions) {
this._rawModule.actions = rawModule.actions;
}
if (rawModule.mutations) {
this._rawModule.mutations = rawModule.mutations;
}
if (rawModule.getters) {
this._rawModule.getters = rawModule.getters;
}
};
Module.prototype.forEachChild = function forEachChild (fn) {
forEachValue(this._children, fn);
};
Module.prototype.forEachGetter = function forEachGetter (fn) {
if (this._rawModule.getters) {
forEachValue(this._rawModule.getters, fn);
}
};
Module.prototype.forEachAction = function forEachAction (fn) {
if (this._rawModule.actions) {
forEachValue(this._rawModule.actions, fn);
}
};
Module.prototype.forEachMutation = function forEachMutation (fn) {
if (this._rawModule.mutations) {
forEachValue(this._rawModule.mutations, fn);
}
};
Object.defineProperties( Module.prototype, prototypeAccessors );
var ModuleCollection = function ModuleCollection (rawRootModule) {
// register root module (Vuex.Store options)
this.register([], rawRootModule, false);
};
ModuleCollection.prototype.get = function get (path) {
return path.reduce(function (module, key) {
return module.getChild(key)
}, this.root)
};
ModuleCollection.prototype.getNamespace = function getNamespace (path) {
var module = this.root;
return path.reduce(function (namespace, key) {
module = module.getChild(key);
return namespace + (module.namespaced ? key + '/' : '')
}, '')
};
ModuleCollection.prototype.update = function update$1 (rawRootModule) {
update([], this.root, rawRootModule);
};
ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
var this$1 = this;
if ( runtime === void 0 ) runtime = true;
{
assertRawModule(path, rawModule);
}
var newModule = new Module(rawModule, runtime);
if (path.length === 0) {
this.root = newModule;
} else {
var parent = this.get(path.slice(0, -1));
parent.addChild(path[path.length - 1], newModule);
}
// register nested modules
if (rawModule.modules) {
forEachValue(rawModule.modules, function (rawChildModule, key) {
this$1.register(path.concat(key), rawChildModule, runtime);
});
}
};
ModuleCollection.prototype.unregister = function unregister (path) {
var parent = this.get(path.slice(0, -1));
var key = path[path.length - 1];
var child = parent.getChild(key);
if (!child) {
{
console.warn(
"[vuex] trying to unregister module '" + key + "', which is " +
"not registered"
);
}
return
}
if (!child.runtime) {
return
}
parent.removeChild(key);
};
ModuleCollection.prototype.isRegistered = function isRegistered (path) {
var parent = this.get(path.slice(0, -1));
var key = path[path.length - 1];
if (parent) {
return parent.hasChild(key)
}
return false
};
function update (path, targetModule, newModule) {
{
assertRawModule(path, newModule);
}
// update target module
targetModule.update(newModule);
// update nested modules
if (newModule.modules) {
for (var key in newModule.modules) {
if (!targetModule.getChild(key)) {
{
console.warn(
"[vuex] trying to add a new module '" + key + "' on hot reloading, " +
'manual reload is needed'
);
}
return
}
update(
path.concat(key),
targetModule.getChild(key),
newModule.modules[key]
);
}
}
}
var functionAssert = {
assert: function (value) { return typeof value === 'function'; },
expected: 'function'
};
var objectAssert = {
assert: function (value) { return typeof value === 'function' ||
(typeof value === 'object' && typeof value.handler === 'function'); },
expected: 'function or object with "handler" function'
};
var assertTypes = {
getters: functionAssert,
mutations: functionAssert,
actions: objectAssert
};
function assertRawModule (path, rawModule) {
Object.keys(assertTypes).forEach(function (key) {
if (!rawModule[key]) { return }
var assertOptions = assertTypes[key];
forEachValue(rawModule[key], function (value, type) {
assert(
assertOptions.assert(value),
makeAssertionMessage(path, key, type, value, assertOptions.expected)
);
});
});
}
function makeAssertionMessage (path, key, type, value, expected) {
var buf = key + " should be " + expected + " but \"" + key + "." + type + "\"";
if (path.length > 0) {
buf += " in module \"" + (path.join('.')) + "\"";
}
buf += " is " + (JSON.stringify(value)) + ".";
return buf
}
var Vue; // bind on install
var Store = function Store (options) {
var this$1 = this;
if ( options === void 0 ) options = {};
// Auto install if it is not done yet and `window` has `Vue`.
// To allow users to avoid auto-installation in some cases,
// this code should be placed here. See #731
if (!Vue && typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
{
assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
assert(this instanceof Store, "store must be called with the new operator.");
}
var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
var strict = options.strict; if ( strict === void 0 ) strict = false;
// store internal state
this._committing = false;
this._actions = Object.create(null);
this._actionSubscribers = [];
this._mutations = Object.create(null);
this._wrappedGetters = Object.create(null);
this._modules = new ModuleCollection(options);
this._modulesNamespaceMap = Object.create(null);
this._subscribers = [];
this._watcherVM = new Vue();
this._makeLocalGettersCache = Object.create(null);
// bind commit and dispatch to self
var store = this;
var ref = this;
var dispatch = ref.dispatch;
var commit = ref.commit;
this.dispatch = function boundDispatch (type, payload) {
return dispatch.call(store, type, payload)
};
this.commit = function boundCommit (type, payload, options) {
return commit.call(store, type, payload, options)
};
// strict mode
this.strict = strict;
var state = this._modules.root.state;
// init root module.
// this also recursively registers all sub-modules
// and collects all module getters inside this._wrappedGetters
installModule(this, state, [], this._modules.root);
// initialize the store vm, which is responsible for the reactivity
// (also registers _wrappedGetters as computed properties)
resetStoreVM(this, state);
// apply plugins
plugins.forEach(function (plugin) { return plugin(this$1); });
var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools;
if (useDevtools) {
devtoolPlugin(this);
}
};
var prototypeAccessors$1 = { state: { configurable: true } };
prototypeAccessors$1.state.get = function () {
return this._vm._data.$$state
};
prototypeAccessors$1.state.set = function (v) {
{
assert(false, "use store.replaceState() to explicit replace store state.");
}
};
Store.prototype.commit = function commit (_type, _payload, _options) {
var this$1 = this;
// check object-style commit
var ref = unifyObjectStyle(_type, _payload, _options);
var type = ref.type;
var payload = ref.payload;
var options = ref.options;
var mutation = { type: type, payload: payload };
var entry = this._mutations[type];
if (!entry) {
{
console.error(("[vuex] unknown mutation type: " + type));
}
return
}
this._withCommit(function () {
entry.forEach(function commitIterator (handler) {
handler(payload);
});
});
this._subscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.forEach(function (sub) { return sub(mutation, this$1.state); });
if (
options && options.silent
) {
console.warn(
"[vuex] mutation type: " + type + ". Silent option has been removed. " +
'Use the filter functionality in the vue-devtools'
);
}
};
Store.prototype.dispatch = function dispatch (_type, _payload) {
var this$1 = this;
// check object-style dispatch
var ref = unifyObjectStyle(_type, _payload);
var type = ref.type;
var payload = ref.payload;
var action = { type: type, payload: payload };
var entry = this._actions[type];
if (!entry) {
{
console.error(("[vuex] unknown action type: " + type));
}
return
}
try {
this._actionSubscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.filter(function (sub) { return sub.before; })
.forEach(function (sub) { return sub.before(action, this$1.state); });
} catch (e) {
{
console.warn("[vuex] error in before action subscribers: ");
console.error(e);
}
}
var result = entry.length > 1
? Promise.all(entry.map(function (handler) { return handler(payload); }))
: entry[0](payload);
return new Promise(function (resolve, reject) {
result.then(function (res) {
try {
this$1._actionSubscribers
.filter(function (sub) { return sub.after; })
.forEach(function (sub) { return sub.after(action, this$1.state); });
} catch (e) {
{
console.warn("[vuex] error in after action subscribers: ");
console.error(e);
}
}
resolve(res);
}, function (error) {
try {
this$1._actionSubscribers
.filter(function (sub) { return sub.error; })
.forEach(function (sub) { return sub.error(action, this$1.state, error); });
} catch (e) {
{
console.warn("[vuex] error in error action subscribers: ");
console.error(e);
}
}
reject(error);
});
})
};
Store.prototype.subscribe = function subscribe (fn, options) {
return genericSubscribe(fn, this._subscribers, options)
};
Store.prototype.subscribeAction = function subscribeAction (fn, options) {
var subs = typeof fn === 'function' ? { before: fn } : fn;
return genericSubscribe(subs, this._actionSubscribers, options)
};
Store.prototype.watch = function watch (getter, cb, options) {
var this$1 = this;
{
assert(typeof getter === 'function', "store.watch only accepts a function.");
}
return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
};
Store.prototype.replaceState = function replaceState (state) {
var this$1 = this;
this._withCommit(function () {
this$1._vm._data.$$state = state;
});
};
Store.prototype.registerModule = function registerModule (path, rawModule, options) {
if ( options === void 0 ) options = {};
if (typeof path === 'string') { path = [path]; }
{
assert(Array.isArray(path), "module path must be a string or an Array.");
assert(path.length > 0, 'cannot register the root module by using registerModule.');
}
this._modules.register(path, rawModule);
installModule(this, this.state, path, this._modules.get(path), options.preserveState);
// reset store to update getters...
resetStoreVM(this, this.state);
};
Store.prototype.unregisterModule = function unregisterModule (path) {
var this$1 = this;
if (typeof path === 'string') { path = [path]; }
{
assert(Array.isArray(path), "module path must be a string or an Array.");
}
this._modules.unregister(path);
this._withCommit(function () {
var parentState = getNestedState(this$1.state, path.slice(0, -1));
Vue.delete(parentState, path[path.length - 1]);
});
resetStore(this);
};
Store.prototype.hasModule = function hasModule (path) {
if (typeof path === 'string') { path = [path]; }
{
assert(Array.isArray(path), "module path must be a string or an Array.");
}
return this._modules.isRegistered(path)
};
Store.prototype.hotUpdate = function hotUpdate (newOptions) {
this._modules.update(newOptions);
resetStore(this, true);
};
Store.prototype._withCommit = function _withCommit (fn) {
var committing = this._committing;
this._committing = true;
fn();
this._committing = committing;
};
Object.defineProperties( Store.prototype, prototypeAccessors$1 );
function genericSubscribe (fn, subs, options) {
if (subs.indexOf(fn) < 0) {
options && options.prepend
? subs.unshift(fn)
: subs.push(fn);
}
return function () {
var i = subs.indexOf(fn);
if (i > -1) {
subs.splice(i, 1);
}
}
}
function resetStore (store, hot) {
store._actions = Object.create(null);
store._mutations = Object.create(null);
store._wrappedGetters = Object.create(null);
store._modulesNamespaceMap = Object.create(null);
var state = store.state;
// init all modules
installModule(store, state, [], store._modules.root, true);
// reset vm
resetStoreVM(store, state, hot);
}
function resetStoreVM (store, state, hot) {
var oldVm = store._vm;
// bind store public getters
store.getters = {};
// reset local getters cache
store._makeLocalGettersCache = Object.create(null);
var wrappedGetters = store._wrappedGetters;
var computed = {};
forEachValue(wrappedGetters, function (fn, key) {
// use computed to leverage its lazy-caching mechanism
// direct inline function use will lead to closure preserving oldVm.
// using partial to return function with only arguments preserved in closure environment.
computed[key] = partial(fn, store);
Object.defineProperty(store.getters, key, {
get: function () { return store._vm[key]; },
enumerable: true // for local getters
});
});
// use a Vue instance to store the state tree
// suppress warnings just in case the user has added
// some funky global mixins
var silent = Vue.config.silent;
Vue.config.silent = true;
store._vm = new Vue({
data: {
$$state: state
},
computed: computed
});
Vue.config.silent = silent;
// enable strict mode for new vm
if (store.strict) {
enableStrictMode(store);
}
if (oldVm) {
if (hot) {
// dispatch changes in all subscribed watchers
// to force getter re-evaluation for hot reloading.
store._withCommit(function () {
oldVm._data.$$state = null;
});
}
Vue.nextTick(function () { return oldVm.$destroy(); });
}
}
function installModule (store, rootState, path, module, hot) {
var isRoot = !path.length;
var namespace = store._modules.getNamespace(path);
// register in namespace map
if (module.namespaced) {
if (store._modulesNamespaceMap[namespace] && true) {
console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
}
store._modulesNamespaceMap[namespace] = module;
}
// set state
if (!isRoot && !hot) {
var parentState = getNestedState(rootState, path.slice(0, -1));
var moduleName = path[path.length - 1];
store._withCommit(function () {
{
if (moduleName in parentState) {
console.warn(
("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"")
);
}
}
Vue.set(parentState, moduleName, module.state);
});
}
var local = module.context = makeLocalContext(store, namespace, path);
module.forEachMutation(function (mutation, key) {
var namespacedType = namespace + key;
registerMutation(store, namespacedType, mutation, local);
});
module.forEachAction(function (action, key) {
var type = action.root ? key : namespace + key;
var handler = action.handler || action;
registerAction(store, type, handler, local);
});
module.forEachGetter(function (getter, key) {
var namespacedType = namespace + key;
registerGetter(store, namespacedType, getter, local);
});
module.forEachChild(function (child, key) {
installModule(store, rootState, path.concat(key), child, hot);
});
}
/**
* make localized dispatch, commit, getters and state
* if there is no namespace, just use root ones
*/
function makeLocalContext (store, namespace, path) {
var noNamespace = namespace === '';
var local = {
dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
var args = unifyObjectStyle(_type, _payload, _options);
var payload = args.payload;
var options = args.options;
var type = args.type;
if (!options || !options.root) {
type = namespace + type;
if ( !store._actions[type]) {
console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
return
}
}
return store.dispatch(type, payload)
},
commit: noNamespace ? store.commit : function (_type, _payload, _options) {
var args = unifyObjectStyle(_type, _payload, _options);
var payload = args.payload;
var options = args.options;
var type = args.type;
if (!options || !options.root) {
type = namespace + type;
if ( !store._mutations[type]) {
console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
return
}
}
store.commit(type, payload, options);
}
};
// getters and state object must be gotten lazily
// because they will be changed by vm update
Object.defineProperties(local, {
getters: {
get: noNamespace
? function () { return store.getters; }
: function () { return makeLocalGetters(store, namespace); }
},
state: {
get: function () { return getNestedState(store.state, path); }
}
});
return local
}
function makeLocalGetters (store, namespace) {
if (!store._makeLocalGettersCache[namespace]) {
var gettersProxy = {};
var splitPos = namespace.length;
Object.keys(store.getters).forEach(function (type) {
// skip if the target getter is not match this namespace
if (type.slice(0, splitPos) !== namespace) { return }
// extract local getter type
var localType = type.slice(splitPos);
// Add a port to the getters proxy.
// Define as getter property because
// we do not want to evaluate the getters in this time.
Object.defineProperty(gettersProxy, localType, {
get: function () { return store.getters[type]; },
enumerable: true
});
});
store._makeLocalGettersCache[namespace] = gettersProxy;
}
return store._makeLocalGettersCache[namespace]
}
function registerMutation (store, type, handler, local) {
var entry = store._mutations[type] || (store._mutations[type] = []);
entry.push(function wrappedMutationHandler (payload) {
handler.call(store, local.state, payload);
});
}
function registerAction (store, type, handler, local) {
var entry = store._actions[type] || (store._actions[type] = []);
entry.push(function wrappedActionHandler (payload) {
var res = handler.call(store, {
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state
}, payload);
if (!isPromise(res)) {
res = Promise.resolve(res);
}
if (store._devtoolHook) {
return res.catch(function (err) {
store._devtoolHook.emit('vuex:error', err);
throw err
})
} else {
return res
}
});
}
function registerGetter (store, type, rawGetter, local) {
if (store._wrappedGetters[type]) {
{
console.error(("[vuex] duplicate getter key: " + type));
}
return
}
store._wrappedGetters[type] = function wrappedGetter (store) {
return rawGetter(
local.state, // local state
local.getters, // local getters
store.state, // root state
store.getters // root getters
)
};
}
function enableStrictMode (store) {
store._vm.$watch(function () { return this._data.$$state }, function () {
{
assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
}
}, { deep: true, sync: true });
}
function getNestedState (state, path) {
return path.reduce(function (state, key) { return state[key]; }, state)
}
function unifyObjectStyle (type, payload, options) {
if (isObject(type) && type.type) {
options = payload;
payload = type;
type = type.type;
}
{
assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
}
return { type: type, payload: payload, options: options }
}
function install (_Vue) {
if (Vue && _Vue === Vue) {
{
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
);
}
return
}
Vue = _Vue;
applyMixin(Vue);
}
/**
* Reduce the code which written in Vue.js for getting the state.
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
* @param {Object}
*/
var mapState = normalizeNamespace(function (namespace, states) {
var res = {};
if ( !isValidMap(states)) {
console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
}
normalizeMap(states).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedState () {
var state = this.$store.state;
var getters = this.$store.getters;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapState', namespace);
if (!module) {
return
}
state = module.context.state;
getters = module.context.getters;
}
return typeof val === 'function'
? val.call(this, state, getters)
: state[val]
};
// mark vuex getter for devtools
res[key].vuex = true;
});
return res
});
/**
* Reduce the code which written in Vue.js for committing the mutation
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
var mapMutations = normalizeNamespace(function (namespace, mutations) {
var res = {};
if ( !isValidMap(mutations)) {
console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
}
normalizeMap(mutations).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedMutation () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
// Get the commit method from store
var commit = this.$store.commit;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
if (!module) {
return
}
commit = module.context.commit;
}
return typeof val === 'function'
? val.apply(this, [commit].concat(args))
: commit.apply(this.$store, [val].concat(args))
};
});
return res
});
/**
* Reduce the code which written in Vue.js for getting the getters
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} getters
* @return {Object}
*/
var mapGetters = normalizeNamespace(function (namespace, getters) {
var res = {};
if ( !isValidMap(getters)) {
console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
}
normalizeMap(getters).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
// The namespace has been mutated by normalizeNamespace
val = namespace + val;
res[key] = function mappedGetter () {
if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
return
}
if ( !(val in this.$store.getters)) {
console.error(("[vuex] unknown getter: " + val));
return
}
return this.$store.getters[val]
};
// mark vuex getter for devtools
res[key].vuex = true;
});
return res
});
/**
* Reduce the code which written in Vue.js for dispatch the action
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
var mapActions = normalizeNamespace(function (namespace, actions) {
var res = {};
if ( !isValidMap(actions)) {
console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
}
normalizeMap(actions).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedAction () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
// get dispatch function from store
var dispatch = this.$store.dispatch;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
if (!module) {
return
}
dispatch = module.context.dispatch;
}
return typeof val === 'function'
? val.apply(this, [dispatch].concat(args))
: dispatch.apply(this.$store, [val].concat(args))
};
});
return res
});
/**
* Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
* @param {String} namespace
* @return {Object}
*/
var createNamespacedHelpers = function (namespace) { return ({
mapState: mapState.bind(null, namespace),
mapGetters: mapGetters.bind(null, namespace),
mapMutations: mapMutations.bind(null, namespace),
mapActions: mapActions.bind(null, namespace)
}); };
/**
* Normalize the map
* normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
* normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
* @param {Array|Object} map
* @return {Object}
*/
function normalizeMap (map) {
if (!isValidMap(map)) {
return []
}
return Array.isArray(map)
? map.map(function (key) { return ({ key: key, val: key }); })
: Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
}
/**
* Validate whether given map is valid or not
* @param {*} map
* @return {Boolean}
*/
function isValidMap (map) {
return Array.isArray(map) || isObject(map)
}
/**
* Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
* @param {Function} fn
* @return {Function}
*/
function normalizeNamespace (fn) {
return function (namespace, map) {
if (typeof namespace !== 'string') {
map = namespace;
namespace = '';
} else if (namespace.charAt(namespace.length - 1) !== '/') {
namespace += '/';
}
return fn(namespace, map)
}
}
/**
* Search a special module from store by namespace. if module not exist, print error message.
* @param {Object} store
* @param {String} helper
* @param {String} namespace
* @return {Object}
*/
function getModuleByNamespace (store, helper, namespace) {
var module = store._modulesNamespaceMap[namespace];
if ( !module) {
console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
}
return module
}
// Credits: borrowed code from fcomb/redux-logger
function createLogger (ref) {
if ( ref === void 0 ) ref = {};
var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true;
var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; };
var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; };
var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; };
var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; };
var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; };
var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true;
var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true;
var logger = ref.logger; if ( logger === void 0 ) logger = console;
return function (store) {
var prevState = deepCopy(store.state);
if (typeof logger === 'undefined') {
return
}
if (logMutations) {
store.subscribe(function (mutation, state) {
var nextState = deepCopy(state);
if (filter(mutation, prevState, nextState)) {
var formattedTime = getFormattedTime();
var formattedMutation = mutationTransformer(mutation);
var message = "mutation " + (mutation.type) + formattedTime;
startMessage(logger, message, collapsed);
logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState));
logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation);
logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState));
endMessage(logger);
}
prevState = nextState;
});
}
if (logActions) {
store.subscribeAction(function (action, state) {
if (actionFilter(action, state)) {
var formattedTime = getFormattedTime();
var formattedAction = actionTransformer(action);
var message = "action " + (action.type) + formattedTime;
startMessage(logger, message, collapsed);
logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction);
endMessage(logger);
}
});
}
}
}
function startMessage (logger, message, collapsed) {
var startMessage = collapsed
? logger.groupCollapsed
: logger.group;
// render
try {
startMessage.call(logger, message);
} catch (e) {
logger.log(message);
}
}
function endMessage (logger) {
try {
logger.groupEnd();
} catch (e) {
logger.log('—— log end ——');
}
}
function getFormattedTime () {
var time = new Date();
return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)))
}
function repeat (str, times) {
return (new Array(times + 1)).join(str)
}
function pad (num, maxLength) {
return repeat('0', maxLength - num.toString().length) + num
}
var index_cjs = {
Store: Store,
install: install,
version: '3.6.2',
mapState: mapState,
mapMutations: mapMutations,
mapGetters: mapGetters,
mapActions: mapActions,
createNamespacedHelpers: createNamespacedHelpers,
createLogger: createLogger
};
return index_cjs;
}))); |
import React from 'react';
import { Link } from 'react-router-dom';
import Main from '../layouts/Main';
import Cell from '../components/Projects/Cell';
import data from '../data/projects';
const Projects = () => (
<Main
title="Projects"
description="Learn about S A Saharukh's projects."
>
<article className="post" id="projects">
<header>
<div className="title">
<h2 data-testid="heading"><Link to="/projects">Projects</Link></h2>
<p>A selection of projects that I'm not too ashamed of</p>
</div>
</header>
{data.map((project) => (
<Cell
data={project}
key={project.title}
/>
))}
</article>
</Main>
);
export default Projects;
|
(function () {
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[15], {
/***/
"./node_modules/@ionic/core/dist/esm/ion-input.entry.js":
/*!**************************************************************!*\
!*** ./node_modules/@ionic/core/dist/esm/ion-input.entry.js ***!
\**************************************************************/
/*! exports provided: ion_input */
/***/
function node_modulesIonicCoreDistEsmIonInputEntryJs(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */
__webpack_require__.d(__webpack_exports__, "ion_input", function () {
return Input;
});
/* harmony import */
var _index_92848855_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(
/*! ./index-92848855.js */
"./node_modules/@ionic/core/dist/esm/index-92848855.js");
/* harmony import */
var _ionic_global_23e7365a_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(
/*! ./ionic-global-23e7365a.js */
"./node_modules/@ionic/core/dist/esm/ionic-global-23e7365a.js");
/* harmony import */
var _helpers_47d562d2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(
/*! ./helpers-47d562d2.js */
"./node_modules/@ionic/core/dist/esm/helpers-47d562d2.js");
/* harmony import */
var _theme_5641d27f_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(
/*! ./theme-5641d27f.js */
"./node_modules/@ionic/core/dist/esm/theme-5641d27f.js");
var inputIosCss = ".sc-ion-input-ios-h{--placeholder-color:initial;--placeholder-font-style:initial;--placeholder-font-weight:initial;--placeholder-opacity:.5;--padding-top:0;--padding-end:0;--padding-bottom:0;--padding-start:0;--background:transparent;--color:initial;display:-ms-flexbox;display:flex;position:relative;-ms-flex:1;flex:1;-ms-flex-align:center;align-items:center;width:100%;padding:0 !important;background:var(--background);color:var(--color);font-family:var(--ion-font-family, inherit);z-index:2}ion-item.sc-ion-input-ios-h:not(.item-label),ion-item:not(.item-label) .sc-ion-input-ios-h{--padding-start:0}.ion-color.sc-ion-input-ios-h{color:var(--ion-color-base)}.native-input.sc-ion-input-ios{border-radius:var(--border-radius);padding-left:var(--padding-start);padding-right:var(--padding-end);padding-top:var(--padding-top);padding-bottom:var(--padding-bottom);font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;display:inline-block;-ms-flex:1;flex:1;width:100%;max-width:100%;max-height:100%;border:0;outline:none;background:transparent;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none;appearance:none}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.native-input.sc-ion-input-ios{padding-left:unset;padding-right:unset;-webkit-padding-start:var(--padding-start);padding-inline-start:var(--padding-start);-webkit-padding-end:var(--padding-end);padding-inline-end:var(--padding-end)}}.native-input.sc-ion-input-ios::-webkit-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-ios::-moz-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-ios:-ms-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-ios::-ms-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-ios::placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-ios:-webkit-autofill{background-color:transparent}.native-input.sc-ion-input-ios:invalid{-webkit-box-shadow:none;box-shadow:none}.native-input.sc-ion-input-ios::-ms-clear{display:none}.native-input[disabled].sc-ion-input-ios{opacity:0.4}.cloned-input.sc-ion-input-ios{left:0;top:0;position:absolute;pointer-events:none}[dir=rtl].sc-ion-input-ios .cloned-input.sc-ion-input-ios,[dir=rtl].sc-ion-input-ios-h .cloned-input.sc-ion-input-ios,[dir=rtl] .sc-ion-input-ios-h .cloned-input.sc-ion-input-ios{left:unset;right:unset;right:0}.input-clear-icon.sc-ion-input-ios{margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;background-position:center;border:0;outline:none;background-color:transparent;background-repeat:no-repeat;visibility:hidden;-webkit-appearance:none;-moz-appearance:none;appearance:none}.input-clear-icon.sc-ion-input-ios:focus{opacity:0.5}.has-value.sc-ion-input-ios-h .input-clear-icon.sc-ion-input-ios{visibility:visible}.has-focus.sc-ion-input-ios-h{pointer-events:none}.has-focus.sc-ion-input-ios-h input.sc-ion-input-ios,.has-focus.sc-ion-input-ios-h a.sc-ion-input-ios,.has-focus.sc-ion-input-ios-h button.sc-ion-input-ios{pointer-events:auto}.sc-ion-input-ios-h{--padding-top:10px;--padding-end:10px;--padding-bottom:10px;--padding-start:0;font-size:inherit}.item-label-stacked.sc-ion-input-ios-h,.item-label-stacked .sc-ion-input-ios-h,.item-label-floating.sc-ion-input-ios-h,.item-label-floating .sc-ion-input-ios-h{--padding-top:8px;--padding-bottom:8px;--padding-start:0px}.input-clear-icon.sc-ion-input-ios{background-image:url(\"data:image/svg+xml;charset=utf-8,<svg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'><path%20fill='var(--ion-color-step-600,%20%23666666)'%20d='M403.1,108.9c-81.2-81.2-212.9-81.2-294.2,0s-81.2,212.9,0,294.2c81.2,81.2,212.9,81.2,294.2,0S484.3,190.1,403.1,108.9z%20M352,340.2L340.2,352l-84.4-84.2l-84,83.8L160,339.8l84-83.8l-84-83.8l11.8-11.8l84,83.8l84.4-84.2l11.8,11.8L267.6,256L352,340.2z'/></svg>\");width:30px;height:30px;background-size:18px}";
var inputMdCss = ".sc-ion-input-md-h{--placeholder-color:initial;--placeholder-font-style:initial;--placeholder-font-weight:initial;--placeholder-opacity:.5;--padding-top:0;--padding-end:0;--padding-bottom:0;--padding-start:0;--background:transparent;--color:initial;display:-ms-flexbox;display:flex;position:relative;-ms-flex:1;flex:1;-ms-flex-align:center;align-items:center;width:100%;padding:0 !important;background:var(--background);color:var(--color);font-family:var(--ion-font-family, inherit);z-index:2}ion-item.sc-ion-input-md-h:not(.item-label),ion-item:not(.item-label) .sc-ion-input-md-h{--padding-start:0}.ion-color.sc-ion-input-md-h{color:var(--ion-color-base)}.native-input.sc-ion-input-md{border-radius:var(--border-radius);padding-left:var(--padding-start);padding-right:var(--padding-end);padding-top:var(--padding-top);padding-bottom:var(--padding-bottom);font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-indent:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;display:inline-block;-ms-flex:1;flex:1;width:100%;max-width:100%;max-height:100%;border:0;outline:none;background:transparent;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none;appearance:none}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.native-input.sc-ion-input-md{padding-left:unset;padding-right:unset;-webkit-padding-start:var(--padding-start);padding-inline-start:var(--padding-start);-webkit-padding-end:var(--padding-end);padding-inline-end:var(--padding-end)}}.native-input.sc-ion-input-md::-webkit-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-md::-moz-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-md:-ms-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-md::-ms-input-placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-md::placeholder{color:var(--placeholder-color);font-family:inherit;font-style:var(--placeholder-font-style);font-weight:var(--placeholder-font-weight);opacity:var(--placeholder-opacity)}.native-input.sc-ion-input-md:-webkit-autofill{background-color:transparent}.native-input.sc-ion-input-md:invalid{-webkit-box-shadow:none;box-shadow:none}.native-input.sc-ion-input-md::-ms-clear{display:none}.native-input[disabled].sc-ion-input-md{opacity:0.4}.cloned-input.sc-ion-input-md{left:0;top:0;position:absolute;pointer-events:none}[dir=rtl].sc-ion-input-md .cloned-input.sc-ion-input-md,[dir=rtl].sc-ion-input-md-h .cloned-input.sc-ion-input-md,[dir=rtl] .sc-ion-input-md-h .cloned-input.sc-ion-input-md{left:unset;right:unset;right:0}.input-clear-icon.sc-ion-input-md{margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;background-position:center;border:0;outline:none;background-color:transparent;background-repeat:no-repeat;visibility:hidden;-webkit-appearance:none;-moz-appearance:none;appearance:none}.input-clear-icon.sc-ion-input-md:focus{opacity:0.5}.has-value.sc-ion-input-md-h .input-clear-icon.sc-ion-input-md{visibility:visible}.has-focus.sc-ion-input-md-h{pointer-events:none}.has-focus.sc-ion-input-md-h input.sc-ion-input-md,.has-focus.sc-ion-input-md-h a.sc-ion-input-md,.has-focus.sc-ion-input-md-h button.sc-ion-input-md{pointer-events:auto}.sc-ion-input-md-h{--padding-top:10px;--padding-end:0;--padding-bottom:10px;--padding-start:8px;font-size:inherit}.item-label-stacked.sc-ion-input-md-h,.item-label-stacked .sc-ion-input-md-h,.item-label-floating.sc-ion-input-md-h,.item-label-floating .sc-ion-input-md-h{--padding-top:8px;--padding-bottom:8px;--padding-start:0}.input-clear-icon.sc-ion-input-md{background-image:url(\"data:image/svg+xml;charset=utf-8,<svg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'><polygon%20fill='var(--ion-color-step-600,%20%23666666)'%20points='405,136.798%20375.202,107%20256,226.202%20136.798,107%20107,136.798%20226.202,256%20107,375.202%20136.798,405%20256,285.798%20375.202,405%20405,375.202%20285.798,256'/></svg>\");width:30px;height:30px;background-size:22px}";
var Input = /*#__PURE__*/function () {
function Input(hostRef) {
var _this = this;
_classCallCheck(this, Input);
Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["r"])(this, hostRef);
this.ionInput = Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["e"])(this, "ionInput", 7);
this.ionChange = Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["e"])(this, "ionChange", 7);
this.ionBlur = Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["e"])(this, "ionBlur", 7);
this.ionFocus = Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["e"])(this, "ionFocus", 7);
this.ionStyle = Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["e"])(this, "ionStyle", 7);
this.inputId = "ion-input-".concat(inputIds++);
this.didBlurAfterEdit = false;
/**
* This is required for a WebKit bug which requires us to
* blur and focus an input to properly focus the input in
* an item with delegatesFocus. It will no longer be needed
* with iOS 14.
*
* @internal
*/
this.fireFocusEvents = true;
this.hasFocus = false;
/**
* Indicates whether and how the text value should be automatically capitalized as it is entered/edited by the user.
*/
this.autocapitalize = 'off';
/**
* Indicates whether the value of the control can be automatically completed by the browser.
*/
this.autocomplete = 'off';
/**
* Whether auto correction should be enabled when the user is entering/editing the text value.
*/
this.autocorrect = 'off';
/**
* This Boolean attribute lets you specify that a form control should have input focus when the page loads.
*/
this.autofocus = false;
/**
* If `true`, a clear icon will appear in the input when there is a value. Clicking it clears the input.
*/
this.clearInput = false;
/**
* Set the amount of time, in milliseconds, to wait to trigger the `ionChange` event after each keystroke.
*/
this.debounce = 0;
/**
* If `true`, the user cannot interact with the input.
*/
this.disabled = false;
/**
* The name of the control, which is submitted with the form data.
*/
this.name = this.inputId;
/**
* If `true`, the user cannot modify the value.
*/
this.readonly = false;
/**
* If `true`, the user must fill in a value before submitting a form.
*/
this.required = false;
/**
* If `true`, the element will have its spelling and grammar checked.
*/
this.spellcheck = false;
/**
* The type of control to display. The default type is text.
*/
this.type = 'text';
/**
* The value of the input.
*/
this.value = '';
this.onInput = function (ev) {
var input = ev.target;
if (input) {
_this.value = input.value || '';
}
_this.ionInput.emit(ev);
};
this.onBlur = function (ev) {
_this.hasFocus = false;
_this.focusChanged();
_this.emitStyle();
if (_this.fireFocusEvents) {
_this.ionBlur.emit(ev);
}
};
this.onFocus = function (ev) {
_this.hasFocus = true;
_this.focusChanged();
_this.emitStyle();
if (_this.fireFocusEvents) {
_this.ionFocus.emit(ev);
}
};
this.onKeydown = function (ev) {
if (_this.shouldClearOnEdit()) {
// Did the input value change after it was blurred and edited?
// Do not clear if user is hitting Enter to submit form
if (_this.didBlurAfterEdit && _this.hasValue() && ev.key !== 'Enter') {
// Clear the input
_this.clearTextInput();
} // Reset the flag
_this.didBlurAfterEdit = false;
}
};
this.clearTextOnEnter = function (ev) {
if (ev.key === 'Enter') {
_this.clearTextInput(ev);
}
};
this.clearTextInput = function (ev) {
if (_this.clearInput && !_this.readonly && !_this.disabled && ev) {
ev.preventDefault();
ev.stopPropagation(); // Attempt to focus input again after pressing clear button
_this.setFocus();
}
_this.value = '';
/**
* This is needed for clearOnEdit
* Otherwise the value will not be cleared
* if user is inside the input
*/
if (_this.nativeInput) {
_this.nativeInput.value = '';
}
};
}
_createClass(Input, [{
key: "debounceChanged",
value: function debounceChanged() {
this.ionChange = Object(_helpers_47d562d2_js__WEBPACK_IMPORTED_MODULE_2__["d"])(this.ionChange, this.debounce);
}
}, {
key: "disabledChanged",
value: function disabledChanged() {
this.emitStyle();
}
/**
* Update the native input element when the value changes
*/
}, {
key: "valueChanged",
value: function valueChanged() {
this.emitStyle();
this.ionChange.emit({
value: this.value == null ? this.value : this.value.toString()
});
}
}, {
key: "componentWillLoad",
value: function componentWillLoad() {
// If the ion-input has a tabindex attribute we get the value
// and pass it down to the native input, then remove it from the
// ion-input to avoid causing tabbing twice on the same element
if (this.el.hasAttribute('tabindex')) {
var tabindex = this.el.getAttribute('tabindex');
this.tabindex = tabindex !== null ? tabindex : undefined;
this.el.removeAttribute('tabindex');
}
}
}, {
key: "connectedCallback",
value: function connectedCallback() {
this.emitStyle();
this.debounceChanged();
{
document.dispatchEvent(new CustomEvent('ionInputDidLoad', {
detail: this.el
}));
}
}
}, {
key: "disconnectedCallback",
value: function disconnectedCallback() {
{
document.dispatchEvent(new CustomEvent('ionInputDidUnload', {
detail: this.el
}));
}
}
/**
* Sets focus on the native `input` in `ion-input`. Use this method instead of the global
* `input.focus()`.
*/
}, {
key: "setFocus",
value: function () {
var _setFocus = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this.nativeInput) {
this.nativeInput.focus();
}
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function setFocus() {
return _setFocus.apply(this, arguments);
}
return setFocus;
}()
/**
* Sets blur on the native `input` in `ion-input`. Use this method instead of the global
* `input.blur()`.
* @internal
*/
}, {
key: "setBlur",
value: function () {
var _setBlur = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.nativeInput) {
this.nativeInput.blur();
}
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function setBlur() {
return _setBlur.apply(this, arguments);
}
return setBlur;
}()
/**
* Returns the native `<input>` element used under the hood.
*/
}, {
key: "getInputElement",
value: function getInputElement() {
return Promise.resolve(this.nativeInput);
}
}, {
key: "shouldClearOnEdit",
value: function shouldClearOnEdit() {
var type = this.type,
clearOnEdit = this.clearOnEdit;
return clearOnEdit === undefined ? type === 'password' : clearOnEdit;
}
}, {
key: "getValue",
value: function getValue() {
return typeof this.value === 'number' ? this.value.toString() : (this.value || '').toString();
}
}, {
key: "emitStyle",
value: function emitStyle() {
this.ionStyle.emit({
'interactive': true,
'input': true,
'has-placeholder': this.placeholder != null,
'has-value': this.hasValue(),
'has-focus': this.hasFocus,
'interactive-disabled': this.disabled
});
}
}, {
key: "focusChanged",
value: function focusChanged() {
// If clearOnEdit is enabled and the input blurred but has a value, set a flag
if (!this.hasFocus && this.shouldClearOnEdit() && this.hasValue()) {
this.didBlurAfterEdit = true;
}
}
}, {
key: "hasValue",
value: function hasValue() {
return this.getValue().length > 0;
}
}, {
key: "render",
value: function render() {
var _Object,
_this2 = this;
var mode = Object(_ionic_global_23e7365a_js__WEBPACK_IMPORTED_MODULE_1__["b"])(this);
var value = this.getValue();
var labelId = this.inputId + '-lbl';
var label = Object(_helpers_47d562d2_js__WEBPACK_IMPORTED_MODULE_2__["f"])(this.el);
if (label) {
label.id = labelId;
}
return Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["h"])(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["H"], {
"aria-disabled": this.disabled ? 'true' : null,
"class": Object(_theme_5641d27f_js__WEBPACK_IMPORTED_MODULE_3__["c"])(this.color, (_Object = {}, _defineProperty(_Object, mode, true), _defineProperty(_Object, 'has-value', this.hasValue()), _defineProperty(_Object, 'has-focus', this.hasFocus), _Object))
}, Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["h"])("input", {
"class": "native-input",
ref: function ref(input) {
return _this2.nativeInput = input;
},
"aria-labelledby": labelId,
disabled: this.disabled,
accept: this.accept,
autoCapitalize: this.autocapitalize,
autoComplete: this.autocomplete,
autoCorrect: this.autocorrect,
autoFocus: this.autofocus,
enterKeyHint: this.enterkeyhint,
inputMode: this.inputmode,
min: this.min,
max: this.max,
minLength: this.minlength,
maxLength: this.maxlength,
multiple: this.multiple,
name: this.name,
pattern: this.pattern,
placeholder: this.placeholder || '',
readOnly: this.readonly,
required: this.required,
spellcheck: this.spellcheck,
step: this.step,
size: this.size,
tabindex: this.tabindex,
type: this.type,
value: value,
onInput: this.onInput,
onBlur: this.onBlur,
onFocus: this.onFocus,
onKeyDown: this.onKeydown
}), this.clearInput && !this.readonly && !this.disabled && Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["h"])("button", {
"aria-label": "reset",
type: "button",
"class": "input-clear-icon",
onTouchStart: this.clearTextInput,
onMouseDown: this.clearTextInput,
onKeyDown: this.clearTextOnEnter
}));
}
}, {
key: "el",
get: function get() {
return Object(_index_92848855_js__WEBPACK_IMPORTED_MODULE_0__["i"])(this);
}
}], [{
key: "watchers",
get: function get() {
return {
"debounce": ["debounceChanged"],
"disabled": ["disabledChanged"],
"value": ["valueChanged"]
};
}
}]);
return Input;
}();
var inputIds = 0;
Input.style = {
ios: inputIosCss,
md: inputMdCss
};
/***/
}
}]);
})();
//# sourceMappingURL=15-es5.js.map |
const mimcHash = require('./mimc');
const shaHash = require('./sha256');
module.exports = {
shaHash,
mimcHash,
};
|
/**
* These types of initializers are called in the middle of the initialization process.
* They are not allowed to depend on another initializers to suppress circular references.
*/
import initComponentHelper from 'src/app/init/component-helper.init';
import initHttpClient from 'src/app/init/http.init';
import initRepository from 'src/app/init/repository.init';
import initMixin from 'src/app/init/mixin.init';
import initCoreModules from 'src/app/init/modules.init';
import initLogin from 'src/app/init/login.init';
import initRouter from 'src/app/init/router.init';
import initFilter from 'src/app/init/filter.init';
import initDirectives from 'src/app/init/directive.init';
import initLocale from 'src/app/init/locale.init';
import initComponents from 'src/app/init/component.init';
import initSvgIcons from 'src/app/init/svg-icons.init';
import initShortcut from 'src/app/init/shortcut.init';
import initFilterFactory from 'src/app/init/filter-factory.init';
import initEntity from 'src/app/init/entity.init';
export default {
coreMixin: initMixin,
coreDirectives: initDirectives,
coreFilter: initFilter,
baseComponents: initComponents,
svgIcons: initSvgIcons,
coreModuleRoutes: initCoreModules,
login: initLogin,
router: initRouter,
locale: initLocale,
repositoryFactory: initRepository,
shortcut: initShortcut,
httpClient: initHttpClient,
componentHelper: initComponentHelper,
filterFactory: initFilterFactory,
entity: initEntity
};
|
import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class RenewBookForm(forms.Form):
renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
def clean_renewal_date(self):
data = self.cleaned_data['renewal_date']
# Check if a date is not in the past.
if data < datetime.date.today():
raise ValidationError(_('Invalid date - renewal in past'))
# Check if a date is in the allowed range (+4 weeis from today).
if data > datetime.date.today() + datetime.timedelta(weeks=4):
raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
# Always return cleaned data
return data
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
upload_file = forms.FileField()
|
import {CallBuilder} from "./call_builder";
export class OperationCallBuilder extends CallBuilder {
/**
* Creates a new {@link OperationCallBuilder} pointed to server defined by serverUrl.
*
* Do not create this object directly, use {@link Server#operations}.
* @see [All Operations](https://www.stellar.org/developers/horizon/reference/operations-all.html)
* @constructor
* @extends CallBuilder
* @param {string} serverUrl Horizon server URL.
*/
constructor(serverUrl) {
super(serverUrl);
this.url.segment('operations');
}
/**
* The operation details endpoint provides information on a single operation. The operation ID provided in the id
* argument specifies which operation to load.
* @see [Operation Details](https://www.stellar.org/developers/horizon/reference/operations-single.html)
* @param {number} operationId Operation ID
* @returns {OperationCallBuilder}
*/
operation(operationId) {
this.filter.push(['operations', operationId]);
return this;
}
/**
* This endpoint represents all operations that were included in valid transactions that affected a particular account.
* @see [Operations for Account](https://www.stellar.org/developers/horizon/reference/operations-for-account.html)
* @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD`
* @returns {OperationCallBuilder}
*/
forAccount(accountId) {
this.filter.push(['accounts', accountId, 'operations']);
return this;
}
forBalance(balanceId, accountId) {
this.url.addQuery('balance_id', balanceId);
this.url.addQuery('account_id', accountId);
return this;
}
/**
* This endpoint returns all operations that occurred in a given ledger.
*
* @see [Operations for Ledger](https://www.stellar.org/developers/horizon/reference/operations-for-ledger.html)
* @param {number} ledgerId Ledger ID
* @returns {OperationCallBuilder}
*/
forLedger(ledgerId) {
this.filter.push(['ledgers', ledgerId, 'operations']);
return this;
}
/**
* This endpoint represents all operations that are part of a given transaction.
* @see [Operations for Transaction](https://www.stellar.org/developers/horizon/reference/operations-for-transaction.html)
* @param {string} transactionId Transaction ID
* @returns {OperationCallBuilder}
*/
forTransaction(transactionId) {
this.filter.push(['transactions', transactionId, 'operations']);
return this;
}
}
|
/**
* Created by Raph on 29/11/2015.
*/
/*$( window ).resize(function() {
var largeur = $(document).width();
if(largeur<720) {
//alert("ok");
//responsive(largeur);
}
});
function responsive(caca)
{
$("#LoginWindow, #footer1").stop();
$("#LoginWindow, #footer1").animate({
width: caca-200+"px"
});
}*/
/*$(document).ready(function() {
$(".LoginButton").click(function(){
window.location.href = "{{ route('login') }}";
});
});*/
$(document).ready(function() {
var speedanime1 = 200;
$('body').hide().fadeIn(speedanime1);
$('body').css({
"margin-top" : "-100px"
}).animate({
"margin-top" : "0px"
},{ queue: false, duration: speedanime1, easing: 'swing' });
$('.Logo').click(function(){
window.location.href= '/';
});
}); |
/*
* Copyright (c) 2015 Intel Corporation.
*
* 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.
*/
// Rotary angle switch
var five = require("johnny-five");
var Edison = require("edison-io");
var board = new five.Board({
io: new Edison()
});
board.on("ready", function() {
var rotary = new five.Sensor("A0");
rotary.on("data", function() {
console.log(this.value);
});
});
|
#!/usr/bin/env node
/**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @noflow
*/
'use strict';
/* eslint
comma-dangle: [1, always-multiline],
prefer-object-spread/prefer-object-spread: 0,
nuclide-internal/no-commonjs: 0,
*/
/* eslint-disable no-console */
const jestCLI = require('jest-cli');
const config = require('../jest.config.js');
const yargs = require('yargs');
const {options} = require('jest-cli/build/cli/args');
// We reach into the internals of Jest to get the options it uses for arg
// parsing with yargs to ensure we parse the args consistently with Jest.
const {argv} = yargs(process.argv.slice(2)).options(options);
// Then we override some of the options with hardcoded values.
argv.watchman = true;
argv.config = JSON.stringify(config);
jestCLI
.runCLI(argv, [process.cwd()])
.then(response => process.exit(response.results.success ? 0 : 1));
|
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Increse and decrease indent commands.
*/
(function () {
var listNodeNames = { ol: 1, ul: 1 },
isNotWhitespaces = CKEDITOR.dom.walker.whitespaces(true),
isNotBookmark = CKEDITOR.dom.walker.bookmark(false, true);
function onSelectionChange(evt) {
if (evt.editor.readOnly)
return null;
var editor = evt.editor,
elementPath = evt.data.path,
list = elementPath && elementPath.contains(listNodeNames),
firstBlock = elementPath.block || elementPath.blockLimit;
if (list)
return this.setState(CKEDITOR.TRISTATE_OFF);
if (!this.useIndentClasses && this.name == 'indent')
return this.setState(CKEDITOR.TRISTATE_OFF);
if (!firstBlock)
return this.setState(CKEDITOR.TRISTATE_DISABLED);
if (this.useIndentClasses) {
var indentClass = firstBlock.$.className.match(this.classNameRegex),
indentStep = 0;
if (indentClass) {
indentClass = indentClass[1];
indentStep = this.indentClassMap[ indentClass ];
}
if (( this.name == 'outdent' && !indentStep ) ||
( this.name == 'indent' && indentStep == editor.config.indentClasses.length ))
return this.setState(CKEDITOR.TRISTATE_DISABLED);
return this.setState(CKEDITOR.TRISTATE_OFF);
}
else {
var indent = parseInt(firstBlock.getStyle(getIndentCssProperty(firstBlock)), 10);
if (isNaN(indent))
indent = 0;
if (indent <= 0)
return this.setState(CKEDITOR.TRISTATE_DISABLED);
return this.setState(CKEDITOR.TRISTATE_OFF);
}
}
function indentCommand(editor, name) {
this.name = name;
this.useIndentClasses = editor.config.indentClasses && editor.config.indentClasses.length > 0;
if (this.useIndentClasses) {
this.classNameRegex = new RegExp('(?:^|\\s+)(' + editor.config.indentClasses.join('|') + ')(?=$|\\s)');
this.indentClassMap = {};
for (var i = 0; i < editor.config.indentClasses.length; i++)
this.indentClassMap[ editor.config.indentClasses[i] ] = i + 1;
}
this.startDisabled = name == 'outdent';
}
// Returns the CSS property to be used for identing a given element.
function getIndentCssProperty(element, dir) {
return ( dir || element.getComputedStyle('direction') ) == 'ltr' ? 'margin-left' : 'margin-right';
}
function isListItem(node) {
return node.type == CKEDITOR.NODE_ELEMENT && node.is('li');
}
indentCommand.prototype = {
exec: function (editor) {
var self = this, database = {};
function indentList(listNode) {
// Our starting and ending points of the range might be inside some blocks under a list item...
// So before playing with the iterator, we need to expand the block to include the list items.
var startContainer = range.startContainer,
endContainer = range.endContainer;
while (startContainer && !startContainer.getParent().equals(listNode))
startContainer = startContainer.getParent();
while (endContainer && !endContainer.getParent().equals(listNode))
endContainer = endContainer.getParent();
if (!startContainer || !endContainer)
return;
// Now we can iterate over the individual items on the same tree depth.
var block = startContainer,
itemsToMove = [],
stopFlag = false;
while (!stopFlag) {
if (block.equals(endContainer))
stopFlag = true;
itemsToMove.push(block);
block = block.getNext();
}
if (itemsToMove.length < 1)
return;
// Do indent or outdent operations on the array model of the list, not the
// list's DOM tree itself. The array model demands that it knows as much as
// possible about the surrounding lists, we need to feed it the further
// ancestor node that is still a list.
var listParents = listNode.getParents(true);
for (var i = 0; i < listParents.length; i++) {
if (listParents[i].getName && listNodeNames[ listParents[i].getName() ]) {
listNode = listParents[i];
break;
}
}
var indentOffset = self.name == 'indent' ? 1 : -1,
startItem = itemsToMove[0],
lastItem = itemsToMove[ itemsToMove.length - 1 ];
// Convert the list DOM tree into a one dimensional array.
var listArray = CKEDITOR.plugins.list.listToArray(listNode, database);
// Apply indenting or outdenting on the array.
var baseIndent = listArray[ lastItem.getCustomData('listarray_index') ].indent;
for (i = startItem.getCustomData('listarray_index'); i <= lastItem.getCustomData('listarray_index'); i++) {
listArray[ i ].indent += indentOffset;
// Make sure the newly created sublist get a brand-new element of the same type. (#5372)
var listRoot = listArray[ i ].parent;
listArray[ i ].parent = new CKEDITOR.dom.element(listRoot.getName(), listRoot.getDocument());
}
for (i = lastItem.getCustomData('listarray_index') + 1;
i < listArray.length && listArray[i].indent > baseIndent; i++)
listArray[i].indent += indentOffset;
// Convert the array back to a DOM forest (yes we might have a few subtrees now).
// And replace the old list with the new forest.
var newList = CKEDITOR.plugins.list.arrayToList(listArray, database, null, editor.config.enterMode, listNode.getDirection());
// Avoid nested <li> after outdent even they're visually same,
// recording them for later refactoring.(#3982)
if (self.name == 'outdent') {
var parentLiElement;
if (( parentLiElement = listNode.getParent() ) && parentLiElement.is('li')) {
var children = newList.listNode.getChildren(),
pendingLis = [],
count = children.count(),
child;
for (i = count - 1; i >= 0; i--) {
if (( child = children.getItem(i) ) && child.is && child.is('li'))
pendingLis.push(child);
}
}
}
if (newList)
newList.listNode.replace(listNode);
// Move the nested <li> to be appeared after the parent.
if (pendingLis && pendingLis.length) {
for (i = 0; i < pendingLis.length; i++) {
var li = pendingLis[ i ],
followingList = li;
// Nest preceding <ul>/<ol> inside current <li> if any.
while (( followingList = followingList.getNext() ) &&
followingList.is &&
followingList.getName() in listNodeNames) {
// IE requires a filler NBSP for nested list inside empty list item,
// otherwise the list item will be inaccessiable. (#4476)
if (CKEDITOR.env.ie && !li.getFirst(function (node) {
return isNotWhitespaces(node) && isNotBookmark(node);
}))
li.append(range.document.createText('\u00a0'));
li.append(followingList);
}
li.insertAfter(parentLiElement);
}
}
}
function indentBlock() {
var iterator = range.createIterator(),
enterMode = editor.config.enterMode;
iterator.enforceRealBlocks = true;
iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;
var block;
while (( block = iterator.getNextParagraph(enterMode == CKEDITOR.ENTER_P ? 'p' : 'div') ))
indentElement(block);
}
function indentElement(element, dir) {
if (element.getCustomData('indent_processed'))
return false;
if (self.useIndentClasses) {
// Transform current class name to indent step index.
var indentClass = element.$.className.match(self.classNameRegex),
indentStep = 0;
if (indentClass) {
indentClass = indentClass[1];
indentStep = self.indentClassMap[ indentClass ];
}
// Operate on indent step index, transform indent step index back to class
// name.
if (self.name == 'outdent')
indentStep--;
else
indentStep++;
if (indentStep < 0)
return false;
indentStep = Math.min(indentStep, editor.config.indentClasses.length);
indentStep = Math.max(indentStep, 0);
element.$.className = CKEDITOR.tools.ltrim(element.$.className.replace(self.classNameRegex, ''));
if (indentStep > 0)
element.addClass(editor.config.indentClasses[ indentStep - 1 ]);
}
else {
var indentCssProperty = getIndentCssProperty(element, dir),
currentOffset = parseInt(element.getStyle(indentCssProperty), 10);
if (isNaN(currentOffset))
currentOffset = 0;
var indentOffset = editor.config.indentOffset || 40;
currentOffset += ( self.name == 'indent' ? 1 : -1 ) * indentOffset;
if (currentOffset < 0)
return false;
currentOffset = Math.max(currentOffset, 0);
currentOffset = Math.ceil(currentOffset / indentOffset) * indentOffset;
element.setStyle(indentCssProperty, currentOffset ? currentOffset + ( editor.config.indentUnit || 'px' ) : '');
if (element.getAttribute('style') === '')
element.removeAttribute('style');
}
CKEDITOR.dom.element.setMarker(database, element, 'indent_processed', 1);
return true;
}
var selection = editor.getSelection(),
bookmarks = selection.createBookmarks(1),
ranges = selection && selection.getRanges(1),
range;
var iterator = ranges.createIterator();
while (( range = iterator.getNextRange() )) {
var rangeRoot = range.getCommonAncestor(),
nearestListBlock = rangeRoot;
while (nearestListBlock && !( nearestListBlock.type == CKEDITOR.NODE_ELEMENT &&
listNodeNames[ nearestListBlock.getName() ] ))
nearestListBlock = nearestListBlock.getParent();
// Avoid having selection enclose the entire list. (#6138)
// [<ul><li>...</li></ul>] =><ul><li>[...]</li></ul>
if (!nearestListBlock) {
var selectedNode = range.getEnclosedNode();
if (selectedNode
&& selectedNode.type == CKEDITOR.NODE_ELEMENT
&& selectedNode.getName() in listNodeNames) {
range.setStartAt(selectedNode, CKEDITOR.POSITION_AFTER_START);
range.setEndAt(selectedNode, CKEDITOR.POSITION_BEFORE_END);
nearestListBlock = selectedNode;
}
}
// Avoid selection anchors under list root.
// <ul>[<li>...</li>]</ul> => <ul><li>[...]</li></ul>
if (nearestListBlock && range.startContainer.type == CKEDITOR.NODE_ELEMENT
&& range.startContainer.getName() in listNodeNames) {
var walker = new CKEDITOR.dom.walker(range);
walker.evaluator = isListItem;
range.startContainer = walker.next();
}
if (nearestListBlock && range.endContainer.type == CKEDITOR.NODE_ELEMENT
&& range.endContainer.getName() in listNodeNames) {
walker = new CKEDITOR.dom.walker(range);
walker.evaluator = isListItem;
range.endContainer = walker.previous();
}
if (nearestListBlock) {
var firstListItem = nearestListBlock.getFirst(isListItem),
hasMultipleItems = !!firstListItem.getNext(isListItem),
rangeStart = range.startContainer,
indentWholeList = firstListItem.equals(rangeStart) || firstListItem.contains(rangeStart);
// Indent the entire list if cursor is inside the first list item. (#3893)
// Only do that for indenting or when using indent classes or when there is something to outdent. (#6141)
if (!( indentWholeList &&
( self.name == 'indent' || self.useIndentClasses || parseInt(nearestListBlock.getStyle(getIndentCssProperty(nearestListBlock)), 10) ) &&
indentElement(nearestListBlock, !hasMultipleItems && firstListItem.getDirection()) ))
indentList(nearestListBlock);
}
else
indentBlock();
}
// Clean up the markers.
CKEDITOR.dom.element.clearAllMarkers(database);
editor.forceNextSelectionCheck();
selection.selectBookmarks(bookmarks);
}
};
CKEDITOR.plugins.add('indent',
{
init: function (editor) {
// Register commands.
var indent = editor.addCommand('indent', new indentCommand(editor, 'indent')),
outdent = editor.addCommand('outdent', new indentCommand(editor, 'outdent'));
// Register the toolbar buttons.
editor.ui.addButton('Indent',
{
label: editor.lang.indent,
command: 'indent'
});
editor.ui.addButton('Outdent',
{
label: editor.lang.outdent,
command: 'outdent'
});
// Register the state changing handlers.
editor.on('selectionChange', CKEDITOR.tools.bind(onSelectionChange, indent));
editor.on('selectionChange', CKEDITOR.tools.bind(onSelectionChange, outdent));
// [IE6/7] Raw lists are using margin instead of padding for visual indentation in wysiwyg mode. (#3893)
if (CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat) {
editor.addCss(
"ul,ol" +
"{" +
" margin-left: 0px;" +
" padding-left: 40px;" +
"}");
}
// Register dirChanged listener.
editor.on('dirChanged', function (e) {
var range = new CKEDITOR.dom.range(editor.document);
range.setStartBefore(e.data.node);
range.setEndAfter(e.data.node);
var walker = new CKEDITOR.dom.walker(range),
node;
while (( node = walker.next() )) {
if (node.type == CKEDITOR.NODE_ELEMENT) {
// A child with the defined dir is to be ignored.
if (!node.equals(e.data.node) && node.getDirection()) {
range.setStartAfter(node);
walker = new CKEDITOR.dom.walker(range);
continue;
}
// Switch alignment classes.
var classes = editor.config.indentClasses;
if (classes) {
var suffix = ( e.data.dir == 'ltr' ) ? [ '_rtl', '' ] : [ '', '_rtl' ];
for (var i = 0; i < classes.length; i++) {
if (node.hasClass(classes[ i ] + suffix[ 0 ])) {
node.removeClass(classes[ i ] + suffix[ 0 ]);
node.addClass(classes[ i ] + suffix[ 1 ]);
}
}
}
// Switch the margins.
var marginLeft = node.getStyle('margin-right'),
marginRight = node.getStyle('margin-left');
marginLeft ? node.setStyle('margin-left', marginLeft) : node.removeStyle('margin-left');
marginRight ? node.setStyle('margin-right', marginRight) : node.removeStyle('margin-right');
}
}
});
},
requires: [ 'domiterator', 'list' ]
});
})();
/**
* Size of each indentation step
* @name CKEDITOR.config.indentOffset
* @type Number
* @default 40
* @example
* config.indentOffset = 4;
*/
/**
* Unit for the indentation style
* @name CKEDITOR.config.indentUnit
* @type String
* @default 'px'
* @example
* config.indentUnit = 'em';
*/
/**
* List of classes to use for indenting the contents. If it's null, no classes will be used
* and instead the {@link #indentUnit} and {@link #indentOffset} properties will be used.
* @name CKEDITOR.config.indentClasses
* @type Array
* @default null
* @example
* // Use the classes 'Indent1', 'Indent2', 'Indent3'
* config.indentClasses = ['Indent1', 'Indent2', 'Indent3'];
*/
|
"use strict";
var _ = require('lodash');
var Promise = require('bluebird');
var InMemoryAdapter = (function () {
function InMemoryAdapter() {
this.db = {};
}
InMemoryAdapter.prototype.get = function (id) {
return Promise.resolve(this.db[id]);
};
/**
* insert a record
*/
InMemoryAdapter.prototype.insert = function (record) {
this.db[record['id']] = record;
return Promise.resolve(record);
};
/**
* get number of matches for the query
*/
InMemoryAdapter.prototype.count = function (query, options) {
return Promise.resolve(_.reduce(this.db, function (sum, rec) { return sum + query(rec) ? 1 : 0; }, 0));
};
// bulkInsert(record:T[]):PromiseLike<T[]>;
/**
* find out all the matched records
*/
InMemoryAdapter.prototype.find = function (query, option) {
return Promise.resolve(_.filter(this.db, query));
};
/**
* find the first matched record
*/
InMemoryAdapter.prototype.findOne = function (query, option) {
return Promise.resolve(_.find(this.db, query));
};
/**
* update all the matched records
*/
InMemoryAdapter.prototype.update = function (query, operations, options) {
var _this = this;
var count = 0;
_.forEach(this.db, function (rec, id) {
if (query(rec)) {
_this.db[id] = operations(rec);
count++;
}
});
return Promise.resolve(count);
};
/**
* remove all the matched records
*/
InMemoryAdapter.prototype.remove = function (query, options) {
var count = _.size(this.db);
this.db = _.reject(this.db, query);
return Promise.resolve(count - _.size(this.db));
};
return InMemoryAdapter;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = InMemoryAdapter;
//# sourceMappingURL=InMemoryAdapter.js.map |
class nginxTask extends nodefony.Task {
constructor(name, command) {
super(name, command);
this.builder = new nodefony.Builder(this.cli);
this.skeleton = path.resolve(__dirname, "skeletons", "nginx", "nginx.skeleton");
this.location = path.resolve("config", "nginx");
this.confName = `${this.kernel.projectName}.conf`;
this.defaultResponse = {
rootdir: this.kernel.rootDir,
publicPath: this.kernel.publicPath,
domain: `${this.kernel.projectName}.com`,
http_port: 80,
https_port: 443,
proxy_domain: this.kernel.domain,
proxy_http_port: this.kernel.httpPort,
proxy_https_port: this.kernel.httpsPort,
config_file_name: this.confName,
config_file_path: this.location
};
}
showHelp() {
this.setHelp("generate:nginx [-i]",
"Generate Nginx Minimal Configuration File as a reverse proxy in front of Nodefony"
);
}
createConfigFile(response) {
try {
this.cli.mkdir("-p", response.config_file_path);
let Path = path.resolve(response.config_file_path, response.config_file_name);
return this.builder.createFile(Path, this.skeleton, true, response);
} catch (e) {
throw e;
}
}
interaction( /*args*/ ) {
return this.cli.showAsciify(this.name)
.then(() => {
return this.cli.prompt([{
type: 'input',
name: 'domain',
default: this.defaultResponse.domain,
message: `Enter Server Domain Name : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'http_port',
default: this.defaultResponse.http_port,
message: `Enter Server HTTP Port : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'https_port',
default: this.defaultResponse.https_port,
message: `Enter Server HTTPS Port : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'proxy_domain',
default: this.defaultResponse.proxy_domain,
message: `Enter Domain Remote Proxy Nodefony : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'proxy_http_port',
default: this.defaultResponse.proxy_http_port,
message: `Enter Proxy Remote Nodefony HTTP Port : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'proxy_https_port',
default: this.defaultResponse.proxy_https_port,
message: `Enter Proxy Remote Nodefony HTTPS Port : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'config_file_name',
default: this.defaultResponse.config_file_name,
message: `Enter Name Configuration File : `,
validate: ( /*value, response*/ ) => {
return true;
}
}, {
type: 'input',
name: 'config_file_path',
default: this.defaultResponse.config_file_path,
message: `Enter Path Configuration File : `,
validate: ( /*value, response*/ ) => {
return true;
}
}]);
});
}
generate(args, response) {
let res = nodefony.extend({}, this.defaultResponse, response);
return this.createConfigFile(res)
.then((file) => {
this.log(`Success Creation Configuration File : ${file.path} `);
return file;
});
}
}
module.exports = nginxTask;
|
# Copyright (c) 2012 OpenStack Foundation
#
# 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 unittest
from swift.common.middleware import keystoneauth
from swift.common.swob import Request, Response
from swift.common.http import HTTP_FORBIDDEN
from test.unit import FakeLogger
class FakeApp(object):
def __init__(self, status_headers_body_iter=None):
self.calls = 0
self.status_headers_body_iter = status_headers_body_iter
if not self.status_headers_body_iter:
self.status_headers_body_iter = iter([('404 Not Found', {}, '')])
def __call__(self, env, start_response):
self.calls += 1
self.request = Request.blank('', environ=env)
if 'swift.authorize' in env:
resp = env['swift.authorize'](self.request)
if resp:
return resp(env, start_response)
status, headers, body = self.status_headers_body_iter.next()
return Response(status=status, headers=headers,
body=body)(env, start_response)
class SwiftAuth(unittest.TestCase):
def setUp(self):
self.test_auth = keystoneauth.filter_factory({})(FakeApp())
self.test_auth.logger = FakeLogger()
def _make_request(self, path=None, headers=None, **kwargs):
if not path:
path = '/v1/%s/c/o' % self.test_auth._get_account_for_tenant('foo')
return Request.blank(path, headers=headers, **kwargs)
def _get_identity_headers(self, status='Confirmed', tenant_id='1',
tenant_name='acct', user='usr', role=''):
return dict(X_IDENTITY_STATUS=status,
X_TENANT_ID=tenant_id,
X_TENANT_NAME=tenant_name,
X_ROLES=role,
X_USER_NAME=user)
def _get_successful_middleware(self):
response_iter = iter([('200 OK', {}, '')])
return keystoneauth.filter_factory({})(FakeApp(response_iter))
def test_invalid_request_authorized(self):
role = self.test_auth.reseller_admin_role
headers = self._get_identity_headers(role=role)
req = self._make_request('/', headers=headers)
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 404)
def test_invalid_request_non_authorized(self):
req = self._make_request('/')
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 404)
def test_confirmed_identity_is_authorized(self):
role = self.test_auth.reseller_admin_role
headers = self._get_identity_headers(role=role)
req = self._make_request('/v1/AUTH_acct/c', headers)
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 200)
def test_detect_reseller_request(self):
role = self.test_auth.reseller_admin_role
headers = self._get_identity_headers(role=role)
req = self._make_request('/v1/AUTH_acct/c', headers)
req.get_response(self._get_successful_middleware())
self.assertTrue(req.environ.get('reseller_request'))
def test_confirmed_identity_is_not_authorized(self):
headers = self._get_identity_headers()
req = self._make_request('/v1/AUTH_acct/c', headers)
resp = req.get_response(self.test_auth)
self.assertEqual(resp.status_int, 403)
def test_anonymous_is_authorized_for_permitted_referrer(self):
req = self._make_request(headers={'X_IDENTITY_STATUS': 'Invalid'})
req.acl = '.r:*'
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 200)
def test_anonymous_with_validtoken_authorized_for_permitted_referrer(self):
req = self._make_request(headers={'X_IDENTITY_STATUS': 'Confirmed'})
req.acl = '.r:*'
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 200)
def test_anonymous_is_not_authorized_for_unknown_reseller_prefix(self):
req = self._make_request(path='/v1/BLAH_foo/c/o',
headers={'X_IDENTITY_STATUS': 'Invalid'})
resp = req.get_response(self.test_auth)
self.assertEqual(resp.status_int, 401)
def test_blank_reseller_prefix(self):
conf = {'reseller_prefix': ''}
test_auth = keystoneauth.filter_factory(conf)(FakeApp())
account = tenant_id = 'foo'
self.assertTrue(test_auth._reseller_check(account, tenant_id))
def test_reseller_prefix_added_underscore(self):
conf = {'reseller_prefix': 'AUTH'}
test_auth = keystoneauth.filter_factory(conf)(FakeApp())
self.assertEqual(test_auth.reseller_prefix, "AUTH_")
def test_reseller_prefix_not_added_double_underscores(self):
conf = {'reseller_prefix': 'AUTH_'}
test_auth = keystoneauth.filter_factory(conf)(FakeApp())
self.assertEqual(test_auth.reseller_prefix, "AUTH_")
def test_override_asked_for_but_not_allowed(self):
conf = {'allow_overrides': 'false'}
self.test_auth = keystoneauth.filter_factory(conf)(FakeApp())
req = self._make_request('/v1/AUTH_account',
environ={'swift.authorize_override': True})
resp = req.get_response(self.test_auth)
self.assertEquals(resp.status_int, 401)
def test_override_asked_for_and_allowed(self):
conf = {'allow_overrides': 'true'}
self.test_auth = keystoneauth.filter_factory(conf)(FakeApp())
req = self._make_request('/v1/AUTH_account',
environ={'swift.authorize_override': True})
resp = req.get_response(self.test_auth)
self.assertEquals(resp.status_int, 404)
def test_override_default_allowed(self):
req = self._make_request('/v1/AUTH_account',
environ={'swift.authorize_override': True})
resp = req.get_response(self.test_auth)
self.assertEquals(resp.status_int, 404)
def test_anonymous_options_allowed(self):
req = self._make_request('/v1/AUTH_account',
environ={'REQUEST_METHOD': 'OPTIONS'})
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 200)
def test_identified_options_allowed(self):
headers = self._get_identity_headers()
headers['REQUEST_METHOD'] = 'OPTIONS'
req = self._make_request('/v1/AUTH_account',
headers=self._get_identity_headers(),
environ={'REQUEST_METHOD': 'OPTIONS'})
resp = req.get_response(self._get_successful_middleware())
self.assertEqual(resp.status_int, 200)
def test_auth_scheme(self):
req = self._make_request(path='/v1/BLAH_foo/c/o',
headers={'X_IDENTITY_STATUS': 'Invalid'})
resp = req.get_response(self.test_auth)
self.assertEqual(resp.status_int, 401)
self.assertTrue('Www-Authenticate' in resp.headers)
class TestAuthorize(unittest.TestCase):
def setUp(self):
self.test_auth = keystoneauth.filter_factory({})(FakeApp())
self.test_auth.logger = FakeLogger()
def _make_request(self, path, **kwargs):
return Request.blank(path, **kwargs)
def _get_account(self, identity=None):
if not identity:
identity = self._get_identity()
return self.test_auth._get_account_for_tenant(
identity['HTTP_X_TENANT_ID'])
def _get_identity(self, tenant_id='tenant_id', tenant_name='tenant_name',
user_id='user_id', user_name='user_name', roles=None):
if roles is None:
roles = []
if isinstance(roles, list):
roles = ','.join(roles)
return {'HTTP_X_USER_ID': user_id,
'HTTP_X_USER_NAME': user_name,
'HTTP_X_TENANT_ID': tenant_id,
'HTTP_X_TENANT_NAME': tenant_name,
'HTTP_X_ROLES': roles,
'HTTP_X_IDENTITY_STATUS': 'Confirmed'}
def _check_authenticate(self, account=None, identity=None, headers=None,
exception=None, acl=None, env=None, path=None):
if not identity:
identity = self._get_identity()
if not account:
account = self._get_account(identity)
if not path:
path = '/v1/%s/c' % account
default_env = {'REMOTE_USER': identity['HTTP_X_TENANT_ID']}
default_env.update(identity)
if env:
default_env.update(env)
req = self._make_request(path, headers=headers, environ=default_env)
req.acl = acl
env_identity = self.test_auth._integral_keystone_identity(req.environ)
result = self.test_auth.authorize(env_identity, req)
# if we have requested an exception but nothing came back then
if exception and not result:
self.fail("error %s was not returned" % (str(exception)))
elif exception:
self.assertEquals(result.status_int, exception)
else:
self.assertTrue(result is None)
return req
def test_authorize_fails_for_unauthorized_user(self):
self._check_authenticate(exception=HTTP_FORBIDDEN)
def test_authorize_fails_for_invalid_reseller_prefix(self):
self._check_authenticate(account='BLAN_a',
exception=HTTP_FORBIDDEN)
def test_authorize_succeeds_for_reseller_admin(self):
roles = [self.test_auth.reseller_admin_role]
identity = self._get_identity(roles=roles)
req = self._check_authenticate(identity=identity)
self.assertTrue(req.environ.get('swift_owner'))
def test_authorize_succeeds_for_insensitive_reseller_admin(self):
roles = [self.test_auth.reseller_admin_role.upper()]
identity = self._get_identity(roles=roles)
req = self._check_authenticate(identity=identity)
self.assertTrue(req.environ.get('swift_owner'))
def test_authorize_succeeds_as_owner_for_operator_role(self):
roles = self.test_auth.operator_roles.split(',')
identity = self._get_identity(roles=roles)
req = self._check_authenticate(identity=identity)
self.assertTrue(req.environ.get('swift_owner'))
def test_authorize_succeeds_as_owner_for_insensitive_operator_role(self):
roles = [r.upper() for r in self.test_auth.operator_roles.split(',')]
identity = self._get_identity(roles=roles)
req = self._check_authenticate(identity=identity)
self.assertTrue(req.environ.get('swift_owner'))
def _check_authorize_for_tenant_owner_match(self, exception=None):
identity = self._get_identity(user_name='same_name',
tenant_name='same_name')
req = self._check_authenticate(identity=identity, exception=exception)
expected = bool(exception is None)
self.assertEqual(bool(req.environ.get('swift_owner')), expected)
def test_authorize_succeeds_as_owner_for_tenant_owner_match(self):
self.test_auth.is_admin = True
self._check_authorize_for_tenant_owner_match()
def test_authorize_fails_as_owner_for_tenant_owner_match(self):
self.test_auth.is_admin = False
self._check_authorize_for_tenant_owner_match(
exception=HTTP_FORBIDDEN)
def test_authorize_succeeds_for_container_sync(self):
env = {'swift_sync_key': 'foo', 'REMOTE_ADDR': '127.0.0.1'}
headers = {'x-container-sync-key': 'foo', 'x-timestamp': '1'}
self._check_authenticate(env=env, headers=headers)
def test_authorize_fails_for_invalid_referrer(self):
env = {'HTTP_REFERER': 'http://invalid.com/index.html'}
self._check_authenticate(acl='.r:example.com', env=env,
exception=HTTP_FORBIDDEN)
def test_authorize_fails_for_referrer_without_rlistings(self):
env = {'HTTP_REFERER': 'http://example.com/index.html'}
self._check_authenticate(acl='.r:example.com', env=env,
exception=HTTP_FORBIDDEN)
def test_authorize_succeeds_for_referrer_with_rlistings(self):
env = {'HTTP_REFERER': 'http://example.com/index.html'}
self._check_authenticate(acl='.r:example.com,.rlistings', env=env)
def test_authorize_succeeds_for_referrer_with_obj(self):
path = '/v1/%s/c/o' % self._get_account()
env = {'HTTP_REFERER': 'http://example.com/index.html'}
self._check_authenticate(acl='.r:example.com', env=env, path=path)
def test_authorize_succeeds_for_user_role_in_roles(self):
acl = 'allowme'
identity = self._get_identity(roles=[acl])
self._check_authenticate(identity=identity, acl=acl)
def test_authorize_succeeds_for_tenant_name_user_in_roles(self):
identity = self._get_identity()
user_name = identity['HTTP_X_USER_NAME']
user_id = identity['HTTP_X_USER_ID']
tenant_id = identity['HTTP_X_TENANT_ID']
for user in [user_id, user_name, '*']:
acl = '%s:%s' % (tenant_id, user)
self._check_authenticate(identity=identity, acl=acl)
def test_authorize_succeeds_for_tenant_id_user_in_roles(self):
identity = self._get_identity()
user_name = identity['HTTP_X_USER_NAME']
user_id = identity['HTTP_X_USER_ID']
tenant_name = identity['HTTP_X_TENANT_NAME']
for user in [user_id, user_name, '*']:
acl = '%s:%s' % (tenant_name, user)
self._check_authenticate(identity=identity, acl=acl)
def test_authorize_succeeds_for_wildcard_tenant_user_in_roles(self):
identity = self._get_identity()
user_name = identity['HTTP_X_USER_NAME']
user_id = identity['HTTP_X_USER_ID']
for user in [user_id, user_name, '*']:
acl = '*:%s' % user
self._check_authenticate(identity=identity, acl=acl)
def test_cross_tenant_authorization_success(self):
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME',
['tenantID:userA']),
'tenantID:userA')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME',
['tenantNAME:userA']),
'tenantNAME:userA')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME', ['*:userA']),
'*:userA')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME',
['tenantID:userID']),
'tenantID:userID')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME',
['tenantNAME:userID']),
'tenantNAME:userID')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME', ['*:userID']),
'*:userID')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME', ['tenantID:*']),
'tenantID:*')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME', ['tenantNAME:*']),
'tenantNAME:*')
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME', ['*:*']),
'*:*')
def test_cross_tenant_authorization_failure(self):
self.assertEqual(
self.test_auth._authorize_cross_tenant(
'userID', 'userA', 'tenantID', 'tenantNAME',
['tenantXYZ:userA']),
None)
def test_delete_own_account_not_allowed(self):
roles = self.test_auth.operator_roles.split(',')
identity = self._get_identity(roles=roles)
account = self._get_account(identity)
self._check_authenticate(account=account,
identity=identity,
exception=HTTP_FORBIDDEN,
path='/v1/' + account,
env={'REQUEST_METHOD': 'DELETE'})
def test_delete_own_account_when_reseller_allowed(self):
roles = [self.test_auth.reseller_admin_role]
identity = self._get_identity(roles=roles)
account = self._get_account(identity)
req = self._check_authenticate(account=account,
identity=identity,
path='/v1/' + account,
env={'REQUEST_METHOD': 'DELETE'})
self.assertEqual(bool(req.environ.get('swift_owner')), True)
def test_identity_set_up_at_call(self):
def fake_start_response(*args, **kwargs):
pass
the_env = self._get_identity(
tenant_id='test', roles=['reselleradmin'])
self.test_auth(the_env, fake_start_response)
subreq = Request.blank(
'/v1/%s/c/o' % self.test_auth._get_account_for_tenant('test'))
subreq.environ.update(
self._get_identity(tenant_id='test', roles=['got_erased']))
authorize_resp = the_env['swift.authorize'](subreq)
self.assertEqual(authorize_resp, None)
if __name__ == '__main__':
unittest.main()
|
var AppCalendar = function() {
return {
//main function to initiate the module
init: function() {
this.initCalendar();
},
initCalendar: function() {
if (!jQuery().fullCalendar) {
return;
}
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var h = {};
if (App.isRTL()) {
if ($('#calendar').parents(".portlet").width() <= 720) {
$('#calendar').addClass("mobile");
h = {
right: 'title, prev, next',
center: '',
left: 'agendaDay, agendaWeek, month, today'
};
} else {
$('#calendar').removeClass("mobile");
h = {
right: 'title',
center: '',
left: 'agendaDay, agendaWeek, month, today, prev,next'
};
}
} else {
if ($('#calendar').parents(".portlet").width() <= 720) {
$('#calendar').addClass("mobile");
h = {
left: 'title, prev, next',
center: '',
right: 'today,month,agendaWeek,agendaDay'
};
} else {
$('#calendar').removeClass("mobile");
h = {
left: 'title',
center: '',
right: 'prev,next,today,month,agendaWeek,agendaDay'
};
}
}
var initDrag = function(el) {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim(el.text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
el.data('eventObject', eventObject);
// make the event draggable using jQuery UI
el.draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
};
var addEvent = function(title) {
title = title.length === 0 ? "Untitled Event" : title;
var html = $('<div class="external-event label label-default">' + title + '</div>');
jQuery('#event_box').append(html);
initDrag(html);
};
$('#external-events div.external-event').each(function() {
initDrag($(this));
});
$('#event_add').unbind('click').click(function() {
var title = $('#event_title').val();
addEvent(title);
});
//predefined events
$('#event_box').html("");
addEvent("Tahun Baru Masehi");
addEvent("Tahun Baru Imlek");
addEvent("Hari Raya Nyepi");
addEvent("Wafat Isa Almasih");
addEvent("Isra Mi'raj Nabi Muhammad SAW");
addEvent("Hari Buruh Internasional");
addEvent("Hari Raya Waisak");
addEvent("Kenaikan Isa Al-Masih");
addEvent("Hari Lahir Pancasila");
addEvent("Hari Raya Idul Fitri");
addEvent("Hari Kemerdekaan RI");
addEvent("Hari Raya Idul Adha");
addEvent("Tahun Baru Islam");
addEvent("Maulid Nabi Muhammad SAW");
addEvent("Hari Raya Natal");
$('#calendar').fullCalendar('destroy'); // destroy the calendar
$('#calendar').fullCalendar({ //re-initialize the calendar
header: h,
defaultView: 'month', // change default view with available options from http://arshaw.com/fullcalendar/docs/views/Available_Views/
slotMinutes: 15,
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
//simpan data
var dstart = date.format();
retrieve_date(dstart,'',$(this).html(),dstart,'simpan');
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
copiedEventObject.className = $(this).attr("data-class");
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
eventDrop: function(event, delta, revertFunc) {
if (event.title) {
var start = event.start.format(),
end = (event.end) ? event.end.format() : '';
retrieve_date(start,end,event.title,event.cal_id,'update');
}
},
eventResize: function(event) {
if (event.title) {
var start = event.start.format(),
end = (event.end) ? event.end.format() : ''; console.log(event);
retrieve_date(start,end,event.title,event.cal_id,'update');
}
},
eventRender: function(event, element) { console.log(element);
element.prepend( "<button type='button' class='close closeon' data-dismiss='modal' style='margin-top: 9px;' aria-hidden='true'>x</button>" );
element.find(".closeon").click(function() {
$('#calendar').fullCalendar('removeEvents',event._id);
//Delete data
retrieve_date('','','',event.cal_id,'del');
});
},
eventSources: [
{
url: 'calendar/get_events',
type: 'POST',
backgroundColor: App.getBrandColor('red'),
textColor: '#3c3d3d' // an option!
}
]
/* events: [{
title: 'All Day Event x',
start: new Date(y, m, 1),
backgroundColor: App.getBrandColor('yellow')
}, {
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2),
backgroundColor: App.getBrandColor('green')
}, {
title: 'Repeating Event',
start: new Date(y, m, d - 3, 16, 0),
allDay: false,
backgroundColor: App.getBrandColor('red')
}, {
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0),
allDay: false,
backgroundColor: App.getBrandColor('green')
}, {
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false,
}, {
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
backgroundColor: App.getBrandColor('grey'),
allDay: false,
}, {
title: 'Birthday Party',
start: new Date(y, m, d + 1, 19, 0),
end: new Date(y, m, d + 1, 22, 30),
backgroundColor: App.getBrandColor('purple'),
allDay: false,
}, {
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
backgroundColor: App.getBrandColor('yellow'),
url: 'http://google.com/',
}] */
});
}
};
}();
jQuery(document).ready(function() {
AppCalendar.init();
});
function retrieve_date(start,end,title,cal_id,tag){
$.ajax({
url: "calendar/save_data",
method: 'POST',//not type
data: { start: start, end: end, title:title, cal_id:cal_id, tag:tag }//no need for submit variable (although you can use it) since this will be submitted on click; no quotes over variables
});
} |
/**
* TencentBlueKing is pleased to support the open source community by making
蓝鲸智云PaaS平台社区版 (BlueKing PaaSCommunity Edition) available.
Copyright (C) 2017-2018 THL A29 Limited,
a Tencent company. All rights reserved.
Licensed under the MIT License (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
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.
*/
export function getPromiseResult (obj, form) {
const p = new Promise((resolve, reject) => {
obj.$refs[form].validate(valid => {
if (valid) {
resolve()
}
})
})
return p
}
export function randomStr (randomFlag, min, max) {
let str = ''
let range = min
const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
if (randomFlag) {
range = Math.round(Math.random() * (max - min)) + min
}
for (let i = 0; i < range; i++) {
const pos = Math.round(Math.random() * (arr.length - 1))
str += arr[pos]
}
return str
}
export function goPage (obj, path, blank = false, query = {}) {
if (blank) {
const routeData = obj.$router.resolve({ path: path, query: query })
window.open(routeData.href, '_blank')
} else {
obj.$router.push({ path: path })
}
}
|
module.exports = new Date(2033, 10, 15)
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'undo', 'gl', {
redo: 'Refacer',
undo: 'Desfacer'
});
|
import Cookies from 'js-cookie'
const TokenKey = 'admin'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
export function removeCookieRoutes() {
return Cookies.remove('routes')
}
// 模拟增加路由
export function mergeMockRoutes(cookieRoutes, accessedMap) {
const cookies = Cookies.get()
const user = cookies.admin ? 'admin' : 'client'
if (!cookieRoutes) return {}
if (cookieRoutes.permissionType === user) return cookieRoutes
return {}
}
|
// Copyright (c) Microsoft. All rights reserved.
import React, { Component } from "react";
import { EMPTY_FIELD_VAL } from 'components/shared/pcsGrid/pcsGridConfig';
import { TimeRenderer } from '../timeRenderer/timeRenderer';
import { Indicator } from 'components/shared';
export class LastTriggerRenderer extends Component {
render() {
const { value } = this.props;
return (
value
? value.error ? EMPTY_FIELD_VAL : <TimeRenderer value={value.response} />
: <Indicator pattern="bar" />
);
}
}
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[357],{1229:function(e,t,a){e.exports=a.p+"assets/img/px4_sitl_overview.d8cf146a.png"},1345:function(e,t,a){e.exports=a.p+"assets/img/px4_simulator_messages.e08a4130.png"},1579:function(e,t,a){"use strict";a.r(t);var o=a(19),r=Object(o.a)({},(function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[o("h1",{attrs:{id:"simulation"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#simulation"}},[e._v("#")]),e._v(" Simulation")]),e._v(" "),o("p",[e._v('Simulators allow PX4 flight code to control a computer modeled vehicle in a simulated "world".\nYou can interact with this vehicle just as you might with a real vehicle, using '),o("em",[e._v("QGroundControl")]),e._v(", an offboard API, or a radio controller/gamepad.")]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Tip")]),e._v(" Simulation is a quick, easy, and most importantly, "),o("em",[e._v("safe")]),e._v(" way to test changes to PX4 code before attempting to fly in the real world.\nIt is also a good way to start flying with PX4 when you haven't yet got a vehicle to experiment with.")])]),e._v(" "),o("p",[e._v("PX4 supports both "),o("em",[e._v("Software In the Loop (SITL)")]),e._v(" simulation, where the flight stack runs on computer (either the same computer or another computer on the same network) and "),o("em",[e._v("Hardware In the Loop (HITL)")]),e._v(" simulation using a simulation firmware on a real flight controller board.")]),e._v(" "),o("p",[e._v("Information about available simulators and how to set them up are provided in the next section.\nThe other sections provide general information about how the simulator works, and are not required to "),o("em",[e._v("use")]),e._v(" the simulators.")]),e._v(" "),o("h2",{attrs:{id:"supported-simulators"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#supported-simulators"}},[e._v("#")]),e._v(" Supported Simulators")]),e._v(" "),o("p",[e._v("The following simulators work with PX4 for HITL and/or SITL simulation.")]),e._v(" "),o("table",[o("thead",[o("tr",[o("th",[e._v("Simulator")]),e._v(" "),o("th",[e._v("Description")])])]),e._v(" "),o("tbody",[o("tr",[o("td",[o("RouterLink",{attrs:{to:"/en/simulation/gazebo.html"}},[e._v("Gazebo")])],1),e._v(" "),o("td",[o("p",[o("strong",[e._v("This simulator is highly recommended.")])]),o("p",[e._v("A powerful 3D simulation environment that is particularly suitable for testing object-avoidance and computer vision. It can also be used for "),o("a",{attrs:{href:"../simulation/multi-vehicle-simulation.md"}},[e._v("multi-vehicle simulation")]),e._v(" and is commonly used with "),o("a",{attrs:{href:"../simulation/ros_interface.md"}},[e._v("ROS")]),e._v(", a collection of tools for automating vehicle control. ")]),o("p",[o("strong",[e._v("Supported Vehicles:")]),e._v(" Quad ("),o("a",{attrs:{href:"../airframes/airframe_reference.md#copter_quadrotor_wide_3dr_iris_quadrotor"}},[e._v("Iris")]),e._v(" and "),o("a",{attrs:{href:"../airframes/airframe_reference.md#copter_quadrotor_x_3dr_solo"}},[e._v("Solo")]),e._v("), Hex (Typhoon H480), "),o("a",{attrs:{href:"../airframes/airframe_reference.md#vtol_standard_vtol_generic_quad_delta_vtol"}},[e._v("Generic quad delta VTOL")]),e._v(", Tailsitter, Plane, Rover, Submarine ")])])]),e._v(" "),o("tr",[o("td",[o("RouterLink",{attrs:{to:"/en/simulation/flightgear.html"}},[e._v("FlightGear")])],1),e._v(" "),o("td",[o("p",[e._v("A simulator that provides physically and visually realistic simulations. In particular it can simulate many weather conditions, including thunderstorms, snow, rain and hail, and can also simulate thermals and different types of atmospheric flows. "),o("a",{attrs:{href:"../simulation/multi_vehicle_flightgear.md"}},[e._v("Multi-vehicle simulation")]),e._v(" is also supported.")]),e._v(" "),o("p",[o("strong",[e._v("Supported Vehicles:")]),e._v(" Plane, Autogyro, Rover")])])]),e._v(" "),o("tr",[o("td",[o("RouterLink",{attrs:{to:"/en/simulation/jsbsim.html"}},[e._v("JSBSim")])],1),e._v(" "),o("td",[o("p",[e._v("A simulator that provides advanced flight dynamics models. This can be used to model realistic flight dynamics based on wind tunnel data.")]),e._v(" "),o("p",[o("strong",[e._v("Supported Vehicles:")]),e._v(" Plane, Quad, Hex")])])]),e._v(" "),o("tr",[o("td",[o("RouterLink",{attrs:{to:"/en/simulation/jmavsim.html"}},[e._v("jMAVSim")])],1),e._v(" "),o("td",[e._v("A simple multirotor simulator that allows you to fly "),o("em",[e._v("copter")]),e._v(" type vehicles around a simulated world. "),o("p",[e._v("It is easy to set up and can be used to test that your vehicle can take off, fly, land, and responds appropriately to various fail conditions (e.g. GPS failure). It can also be used for "),o("a",{attrs:{href:"../simulation/multi_vehicle_jmavsim.md"}},[e._v("multi-vehicle simulation")]),e._v(".")]),o("p",[o("strong",[e._v("Supported Vehicles:")]),e._v(" Quad")])])]),e._v(" "),o("tr",[o("td",[o("RouterLink",{attrs:{to:"/en/simulation/airsim.html"}},[e._v("AirSim")])],1),e._v(" "),o("td",[o("p",[e._v("A cross platform simulator that provides physically and visually realistic simulations. This simulator is resource intensive, and requires a very significantly more powerful computer than the other simulators described here.")]),o("p",[o("strong",[e._v("Supported Vehicles:")]),e._v(" Iris (MultiRotor model and a configuration for PX4 QuadRotor in the X configuration).")])])]),e._v(" "),o("tr",[o("td",[o("RouterLink",{attrs:{to:"/en/simulation/simulation-in-hardware.html"}},[e._v("Simulation-In-Hardware")]),e._v(" (SIH)")],1),e._v(" "),o("td",[o("p",[e._v("An alternative to HITL that offers a hard real-time simulation directly on the hardware autopilot.")]),o("p",[o("strong",[e._v("Supported Vehicles:")]),e._v(" Quad")])])])])]),e._v(" "),o("p",[e._v("Instructions for how to setup and use the simulators are in the topics linked above.")]),e._v(" "),o("hr"),e._v(" "),o("p",[e._v('The remainder of this topic is a "somewhat generic" description of how the simulation infrastructure works.\nIt is not required to '),o("em",[e._v("use")]),e._v(" the simulators.")]),e._v(" "),o("h2",{attrs:{id:"simulator-mavlink-api"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#simulator-mavlink-api"}},[e._v("#")]),e._v(" Simulator MAVLink API")]),e._v(" "),o("p",[e._v("All simulators communicate with PX4 using the Simulator MAVLink API.\nThis API defines a set of MAVLink messages that supply sensor data from the simulated world to PX4 and return motor and actuator values from the flight code that will be applied to the simulated vehicle.\nThe image below shows the message flow.")]),e._v(" "),o("p",[o("img",{attrs:{src:a(1345),alt:"Simulator MAVLink API"}})]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" A SITL build of PX4 uses "),o("a",{attrs:{href:"https://github.com/PX4/PX4-Autopilot/blob/master/src/modules/simulator/simulator_mavlink.cpp",target:"_blank",rel:"noopener noreferrer"}},[e._v("simulator_mavlink.cpp"),o("OutboundLink")],1),e._v(" to handle these messages while a hardware build in HIL mode uses "),o("a",{attrs:{href:"https://github.com/PX4/PX4-Autopilot/blob/master/src/modules/mavlink/mavlink_receiver.cpp",target:"_blank",rel:"noopener noreferrer"}},[e._v("mavlink_receiver.cpp"),o("OutboundLink")],1),e._v(".\nSensor data from the simulator is written to PX4 uORB topics.\nAll motors / actuators are blocked, but internal software is fully operational.")])]),e._v(" "),o("p",[e._v("The messages are described below (see links for specific detail).")]),e._v(" "),o("table",[o("thead",[o("tr",[o("th",[e._v("Message")]),e._v(" "),o("th",[e._v("Direction")]),e._v(" "),o("th",[e._v("Description")])])]),e._v(" "),o("tbody",[o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#MAV_MODE_FLAG_HIL_ENABLED",target:"_blank",rel:"noopener noreferrer"}},[e._v("MAV_MODE:MAV_MODE_FLAG_HIL_ENABLED"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("NA")]),e._v(" "),o("td",[e._v("Mode flag when using simulation. All motors/actuators are blocked, but internal software is fully operational.")])]),e._v(" "),o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_ACTUATOR_CONTROLS",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_ACTUATOR_CONTROLS"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("PX4 to Sim")]),e._v(" "),o("td",[e._v("PX4 control outputs (to motors, actuators).")])]),e._v(" "),o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_SENSOR",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_SENSOR"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("Sim to PX4")]),e._v(" "),o("td",[e._v("Simulated IMU readings in SI units in NED body frame.")])]),e._v(" "),o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_GPS",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_GPS"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("Sim to PX4")]),e._v(" "),o("td",[e._v("The simulated GPS RAW sensor value.")])]),e._v(" "),o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_OPTICAL_FLOW",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_OPTICAL_FLOW"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("Sim to PX4")]),e._v(" "),o("td",[e._v("Simulated optical flow from a flow sensor (e.g. PX4FLOW or optical mouse sensor)")])]),e._v(" "),o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_STATE_QUATERNION",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_STATE_QUATERNION"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("Sim to PX4")]),e._v(" "),o("td",[e._v('Contains the actual "simulated" vehicle position, attitude, speed etc. This can be logged and compared to PX4\'s estimates for analysis and debugging (for example, checking how well an estimator works for noisy (simulated) sensor inputs).')])]),e._v(" "),o("tr",[o("td",[o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_RC_INPUTS_RAW",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_RC_INPUTS_RAW"),o("OutboundLink")],1)]),e._v(" "),o("td",[e._v("Sim to PX4")]),e._v(" "),o("td",[e._v("The RAW values of the RC channels received.")])])])]),e._v(" "),o("h2",{attrs:{id:"default-px4-mavlink-udp-ports"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#default-px4-mavlink-udp-ports"}},[e._v("#")]),e._v(" Default PX4 MAVLink UDP Ports")]),e._v(" "),o("p",[e._v("By default, PX4 uses commonly established UDP ports for MAVLink communication with ground control stations (e.g. "),o("em",[e._v("QGroundControl")]),e._v("), Offboard APIs (e.g. MAVSDK, MAVROS) and simulator APIs (e.g. Gazebo).\nThese ports are:")]),e._v(" "),o("ul",[o("li",[e._v("UDP Port "),o("strong",[e._v("14540")]),e._v(" is used for communication with offboard APIs.\nOffboard APIs are expected to listen for connections on this port.")]),e._v(" "),o("li",[e._v("UDP Port "),o("strong",[e._v("14550")]),e._v(" is used for communication with ground control stations.\nGCS are expected to listen for connections on this port.\n"),o("em",[e._v("QGroundControl")]),e._v(" listens to this port by default.")]),e._v(" "),o("li",[e._v("The simulator's local TCP Port "),o("strong",[e._v("4560")]),e._v(" is used for communication with PX4.\nPX4 listens to this port, and simulators are expected to initiate the communication by broadcasting data to this port.")])]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" The ports for the GCS and offboard APIs are set in configuration files, while the simulator broadcast port is hard-coded in the simulation MAVLink module.")])]),e._v(" "),o("h2",{attrs:{id:"sitl-simulation-environment"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#sitl-simulation-environment"}},[e._v("#")]),e._v(" SITL Simulation Environment")]),e._v(" "),o("p",[e._v("The diagram below shows a typical SITL simulation environment for any of the supported simulators.\nThe different parts of the system connect via UDP, and can be run on either the same computer or another computer on the same network.")]),e._v(" "),o("ul",[o("li",[e._v("PX4 uses a simulation-specific module to connect to the simulator's local TCP port 4560.\nSimulators then exchange information with PX4 using the "),o("a",{attrs:{href:"#simulator-mavlink-api"}},[e._v("Simulator MAVLink API")]),e._v(" described above.\nPX4 on SITL and the simulator can run on either the same computer or different computers on the same network.")]),e._v(" "),o("li",[e._v("PX4 uses the normal MAVLink module to connect to ground stations (which listen on port 14550) and external developer APIs like MAVSDK or ROS (which listen on port 14540).")]),e._v(" "),o("li",[e._v("A serial connection is used to connect Joystick/Gamepad hardware via "),o("em",[e._v("QGroundControl")]),e._v(".")])]),e._v(" "),o("p",[o("img",{attrs:{src:a(1229),alt:"PX4 SITL overview"}})]),e._v(" "),o("p",[e._v("If you use the normal build system SITL "),o("code",[e._v("make")]),e._v(" configuration targets (see next section) then both SITL and the Simulator will be launched on the same computer and the ports above will automatically be configured.\nYou can configure additional MAVLink UDP connections and otherwise modify the simulation environment in the build configuration and initialisation files.")]),e._v(" "),o("h3",{attrs:{id:"starting-building-sitl-simulation"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#starting-building-sitl-simulation"}},[e._v("#")]),e._v(" Starting/Building SITL Simulation")]),e._v(" "),o("p",[e._v("The build system makes it very easy to build and start PX4 on SITL, launch a simulator, and connect them.\nThe syntax (simplified) looks like this:")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("make px4_sitl simulator[_vehicle-model]\n")])])]),o("p",[e._v("where "),o("code",[e._v("simulator")]),e._v(" is "),o("code",[e._v("gazebo")]),e._v(", "),o("code",[e._v("jmavsim")]),e._v(" or some other simulator, and vehicle-model is a particular vehicle type supported by that simulator ("),o("RouterLink",{attrs:{to:"/en/simulation/jmavsim.html"}},[e._v("jMAVSim")]),e._v(" only supports multicopters, while "),o("RouterLink",{attrs:{to:"/en/simulation/gazebo.html"}},[e._v("Gazebo")]),e._v(" supports many different types).")],1),e._v(" "),o("p",[e._v("A number of examples are shown below, and there are many more in the individual pages for each of the simulators:")]),e._v(" "),o("div",{staticClass:"language-sh extra-class"},[o("pre",{pre:!0,attrs:{class:"language-sh"}},[o("code",[o("span",{pre:!0,attrs:{class:"token comment"}},[e._v("# Start Gazebo with plane")]),e._v("\n"),o("span",{pre:!0,attrs:{class:"token function"}},[e._v("make")]),e._v(" px4_sitl gazebo_plane\n\n"),o("span",{pre:!0,attrs:{class:"token comment"}},[e._v("# Start Gazebo with iris and optical flow")]),e._v("\n"),o("span",{pre:!0,attrs:{class:"token function"}},[e._v("make")]),e._v(" px4_sitl gazebo_iris_opt_flow\n\n"),o("span",{pre:!0,attrs:{class:"token comment"}},[e._v("# Start JMavSim with iris (default vehicle model)")]),e._v("\n"),o("span",{pre:!0,attrs:{class:"token function"}},[e._v("make")]),e._v(" px4_sitl jmavsim\n")])])]),o("p",[e._v("The simulation can be further configured via environment variables:")]),e._v(" "),o("ul",[o("li",[o("code",[e._v("PX4_ESTIMATOR")]),e._v(": This variable configures which estimator to use.\nPossible options are: "),o("code",[e._v("ekf2")]),e._v(" (default), "),o("code",[e._v("lpe")]),e._v(" (deprecated).\nIt can be set via "),o("code",[e._v("export PX4_ESTIMATOR=lpe")]),e._v(" before running the simulation.")])]),e._v(" "),o("p",[e._v("The syntax described here is simplified, and there are many other options that you can configure via "),o("em",[e._v("make")]),e._v(" - for example, to set that you wish to connect to an IDE or debugger.\nFor more information see: "),o("RouterLink",{attrs:{to:"/en/setup/building_px4.html#make_targets"}},[e._v("Building the Code > PX4 Make Build Targets")]),e._v(".")],1),e._v(" "),o("p",[o("a",{attrs:{id:"simulation_speed"}})]),e._v(" "),o("h3",{attrs:{id:"run-simulation-faster-than-realtime"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#run-simulation-faster-than-realtime"}},[e._v("#")]),e._v(" Run Simulation Faster than Realtime")]),e._v(" "),o("p",[e._v("SITL can be run faster or slower than realtime when using jMAVSim or Gazebo.")]),e._v(" "),o("p",[e._v("The speed factor is set using the environment variable "),o("code",[e._v("PX4_SIM_SPEED_FACTOR")]),e._v(".\nFor example, to run the jMAVSim simulation at 2 times the real time speed:")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("PX4_SIM_SPEED_FACTOR=2 make px4_sitl jmavsim\n")])])]),o("p",[e._v("To run at half real-time:")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("PX4_SIM_SPEED_FACTOR=0.5 make px4_sitl jmavsim\n")])])]),o("p",[e._v("You can apply the factor to all SITL runs in the current session using "),o("code",[e._v("EXPORT")]),e._v(":")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("export PX4_SIM_SPEED_FACTOR=2\nmake px4_sitl jmavsim\n")])])]),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(' At some point IO or CPU will limit the speed that is possible on your machine and it will be slowed down "automatically".\nPowerful desktop machines can usually run the simulation at around 6-10x, for notebooks the achieved rates can be around 3-4x.')])]),e._v(" "),o("p",[o("span")]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" To avoid PX4 detecting data link timeouts, increase the value of param "),o("RouterLink",{attrs:{to:"/en/advanced/parameter_reference.html#COM_DL_LOSS_T"}},[e._v("COM_DL_LOSS_T")]),e._v(" proportional to the simulation rate.\nFor example, if "),o("code",[e._v("COM_DL_LOSS_T")]),e._v(" is 10 in realtime, at 10x simulation rate increase to 100.")],1)]),e._v(" "),o("h3",{attrs:{id:"lockstep-simulation"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#lockstep-simulation"}},[e._v("#")]),e._v(" Lockstep Simulation")]),e._v(" "),o("p",[e._v("PX4 SITL and the simulators (jMAVSim or Gazebo) have been set up to run in "),o("em",[e._v("lockstep")]),e._v(".\nWhat this means is that PX4 and the simulator wait on each other for sensor and actuator messages, rather than running at their own speeds.")]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" Lockstep makes it possible to "),o("a",{attrs:{href:"#simulation_speed"}},[e._v("run the simulation faster or slower than realtime")]),e._v(", and also to pause it in order to step through code.")])]),e._v(" "),o("p",[e._v("The sequence of steps for lockstep are:")]),e._v(" "),o("ol",[o("li",[e._v("The simulation sends a sensor message "),o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_SENSOR",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_SENSOR"),o("OutboundLink")],1),e._v(" including a timestamp "),o("code",[e._v("time_usec")]),e._v(" to update the sensor state and time of PX4.")]),e._v(" "),o("li",[e._v("PX4 receives this and does one iteration of state estimation, controls, etc. and eventually sends an actuator message "),o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#HIL_ACTUATOR_CONTROLS",target:"_blank",rel:"noopener noreferrer"}},[e._v("HIL_ACTUATOR_CONTROLS"),o("OutboundLink")],1),e._v(".")]),e._v(" "),o("li",[e._v("The simulation waits until it receives the actuator/motor message, then simulates the physics and calculates the next sensor message to send to PX4 again.")])]),e._v(" "),o("p",[e._v('The system starts with a "freewheeling" period where the simulation sends sensor messages including time and therefore runs PX4 until it has initialized and responds with an actuator message.')]),e._v(" "),o("h4",{attrs:{id:"disable-lockstep-simulation"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#disable-lockstep-simulation"}},[e._v("#")]),e._v(" Disable Lockstep Simulation")]),e._v(" "),o("p",[e._v("The lockstep simulation can be disabled if, for example, SITL is to be used with a simulator that does not support this feature.\nIn this case the simulator and PX4 use the host system time and do not wait on each other.")]),e._v(" "),o("p",[e._v("To disable lockstep in PX4, use "),o("code",[e._v("set(ENABLE_LOCKSTEP_SCHEDULER no)")]),e._v(" in the "),o("a",{attrs:{href:"https://github.com/PX4/PX4-Autopilot/blob/77097b6adc70afbe7e5d8ff9797ed3413e96dbf6/boards/px4/sitl/default.cmake#L104",target:"_blank",rel:"noopener noreferrer"}},[e._v("SITL board config"),o("OutboundLink")],1),e._v(".")]),e._v(" "),o("p",[e._v("To disable lockstep in Gazebo, edit "),o("a",{attrs:{href:"https://github.com/PX4/sitl_gazebo/blob/3062d287c322fabf1b41b8e33518eb449d4ac6ed/models/plane/plane.sdf#L449",target:"_blank",rel:"noopener noreferrer"}},[e._v("the model SDF file"),o("OutboundLink")],1),e._v(" and set "),o("code",[e._v("<enable_lockstep>false</enable_lockstep>")]),e._v(" (or for Iris edit the "),o("a",{attrs:{href:"https://github.com/PX4/sitl_gazebo/blob/3062d287c322fabf1b41b8e33518eb449d4ac6ed/models/rotors_description/urdf/iris_base.xacro#L22",target:"_blank",rel:"noopener noreferrer"}},[e._v("xacro file"),o("OutboundLink")],1),e._v(".")]),e._v(" "),o("p",[e._v("To disable lockstep in jMAVSim, remove "),o("code",[e._v("-l")]),e._v(" in "),o("a",{attrs:{href:"https://github.com/PX4/PX4-Autopilot/blob/77097b6adc70afbe7e5d8ff9797ed3413e96dbf6/Tools/sitl_run.sh#L75",target:"_blank",rel:"noopener noreferrer"}},[e._v("jmavsim_run.sh"),o("OutboundLink")],1),e._v(", or make sure otherwise that the java binary is started without the "),o("code",[e._v("-lockstep")]),e._v(" flag.")]),e._v(" "),o("p",[o("a",{attrs:{id:"scripts"}})]),e._v(" "),o("h3",{attrs:{id:"startup-scripts"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#startup-scripts"}},[e._v("#")]),e._v(" Startup Scripts")]),e._v(" "),o("p",[e._v("Scripts are used to control which parameter settings to use or which modules to start.\nThey are located in the "),o("a",{attrs:{href:"https://github.com/PX4/PX4-Autopilot/tree/master/ROMFS/px4fmu_common/init.d-posix",target:"_blank",rel:"noopener noreferrer"}},[e._v("ROMFS/px4fmu_common/init.d-posix"),o("OutboundLink")],1),e._v(" directory, the "),o("code",[e._v("rcS")]),e._v(" file is the main entry point.\nSee "),o("RouterLink",{attrs:{to:"/en/concept/system_startup.html"}},[e._v("System Startup")]),e._v(" for more information.")],1),e._v(" "),o("h3",{attrs:{id:"simulating-failsafes-and-sensor-hardware-failure"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#simulating-failsafes-and-sensor-hardware-failure"}},[e._v("#")]),e._v(" Simulating Failsafes and Sensor/Hardware Failure")]),e._v(" "),o("p",[e._v("The "),o("RouterLink",{attrs:{to:"/en/advanced/parameter_reference.html#sitl"}},[e._v("SITL parameters")]),e._v(" can also be used to simulate common sensor failure cases, including low battery, loss of GPS or barometer, gyro failure, increased GPS noise etc. (e.g. "),o("RouterLink",{attrs:{to:"/en/advanced/parameter_reference.html#SIM_GPS_BLOCK"}},[e._v("SIM_GPS_BLOCK")]),e._v(" can be set to simulate GPS failure).")],1),e._v(" "),o("p",[e._v("Additionally (and with some overlap), "),o("RouterLink",{attrs:{to:"/en/simulation/failsafes.html"}},[e._v("Simulate Failsafes")]),e._v(" explains how to trigger safety failsafes.")],1),e._v(" "),o("h2",{attrs:{id:"hitl-simulation-environment"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#hitl-simulation-environment"}},[e._v("#")]),e._v(" HITL Simulation Environment")]),e._v(" "),o("p",[e._v("With Hardware-in-the-Loop (HITL) simulation the normal PX4 firmware is run on real hardware.\nThe HITL Simulation Environment in documented in: "),o("RouterLink",{attrs:{to:"/en/simulation/hitl.html"}},[e._v("HITL Simulation")]),e._v(".")],1),e._v(" "),o("h2",{attrs:{id:"joystick-gamepad-integration"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#joystick-gamepad-integration"}},[e._v("#")]),e._v(" Joystick/Gamepad Integration")]),e._v(" "),o("p",[o("em",[e._v("QGroundControl")]),e._v(" desktop versions can connect to a USB Joystick/Gamepad and send its movement commands and button presses to PX4 over MAVLink.\nThis works on both SITL and HITL simulations, and allows you to directly control the simulated vehicle.\nIf you don't have a joystick you can alternatively control the vehicle using QGroundControl's onscreen virtual thumbsticks.")]),e._v(" "),o("p",[e._v("For setup information see the "),o("em",[e._v("QGroundControl User Guide")]),e._v(":")]),e._v(" "),o("ul",[o("li",[o("a",{attrs:{href:"https://docs.qgroundcontrol.com/en/SetupView/Joystick.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("Joystick Setup"),o("OutboundLink")],1)]),e._v(" "),o("li",[o("a",{attrs:{href:"https://docs.qgroundcontrol.com/en/SettingsView/VirtualJoystick.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("Virtual Joystick"),o("OutboundLink")],1)])]),e._v(" "),o("h2",{attrs:{id:"camera-simulation"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#camera-simulation"}},[e._v("#")]),e._v(" Camera Simulation")]),e._v(" "),o("p",[e._v("PX4 supports capture of both still images and video from within the "),o("RouterLink",{attrs:{to:"/en/simulation/gazebo.html"}},[e._v("Gazebo")]),e._v(" simulated environment.\nThis can be enabled/set up as described in "),o("RouterLink",{attrs:{to:"/en/simulation/gazebo.html#video"}},[e._v("Gazebo > Video Streaming")]),e._v(".")],1),e._v(" "),o("p",[e._v("The simulated camera is a gazebo plugin that implements the "),o("a",{attrs:{href:"https://mavlink.io/en/protocol/camera.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("MAVLink Camera Protocol"),o("OutboundLink")],1),e._v(".\nPX4 connects/integrates with this camera in "),o("em",[e._v("exactly the same way")]),e._v(" as it would with any other MAVLink camera:")]),e._v(" "),o("ol",[o("li",[o("RouterLink",{attrs:{to:"/en/advanced/parameter_reference.html#TRIG_INTERFACE"}},[e._v("TRIG_INTERFACE")]),e._v(" must be set to "),o("code",[e._v("3")]),e._v(" to configure the camera trigger driver for use with a MAVLink camera\n"),o("blockquote",[o("p",[o("strong",[e._v("Tip")]),e._v(" In this mode the driver just sends a "),o("a",{attrs:{href:"https://mavlink.io/en/messages/common.html#CAMERA_TRIGGER",target:"_blank",rel:"noopener noreferrer"}},[e._v("CAMERA_TRIGGER"),o("OutboundLink")],1),e._v(" message whenever an image capture is requested.\nFor more information see "),o("a",{attrs:{href:"https://docs.px4.io/master/en/peripherals/camera.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("Camera"),o("OutboundLink")],1),e._v(".")])])],1),e._v(" "),o("li",[e._v("PX4 must forward all camera commands between the GCS and the (simulator) MAVLink Camera.\nYou can do this by starting "),o("RouterLink",{attrs:{to:"/en/middleware/modules_communication.html#mavlink"}},[e._v("MAVLink")]),e._v(" with the "),o("code",[e._v("-f")]),e._v(" flag as shown, specifying the UDP ports for the new connection."),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("mavlink start -u 14558 -o 14530 -r 4000 -f -m camera\n")])])]),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" More than just the camera MAVLink messages will be forwarded, but the camera will ignore those that it doesn't consider relevant.")])])],1)]),e._v(" "),o("p",[e._v("The same approach can be used by other simulators to implement camera support.")]),e._v(" "),o("h2",{attrs:{id:"running-simulation-on-a-remote-server"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#running-simulation-on-a-remote-server"}},[e._v("#")]),e._v(" Running Simulation on a Remote Server")]),e._v(" "),o("p",[e._v("It is possible to run the simulator on one computer, and access it from another computer on the same network (or on another network with appropriate routing).\nThis might be useful, for example, if you want to test a drone application running on real companion computer hardware running against a simulated vehicle.")]),e._v(" "),o("p",[e._v('This does not work "out of the box" because PX4 does not route packets to external interfaces by default (in order to avoid spamming the network and different simulations interfering with each other).\nInstead it routes traffic internally - to "localhost".')]),e._v(" "),o("p",[e._v("There are a number of ways to make the UDP packets available on external interfaces, as outlined below.")]),e._v(" "),o("h3",{attrs:{id:"enable-mav-broadcast"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#enable-mav-broadcast"}},[e._v("#")]),e._v(" Enable MAV_BROADCAST")]),e._v(" "),o("p",[e._v("Enable "),o("RouterLink",{attrs:{to:"/en/advanced/parameter_reference.html#MAV_BROADCAST"}},[e._v("MAV_BROADCAST")]),e._v(" to broadcast heartbeats on the local network.")],1),e._v(" "),o("p",[e._v("A remote computer can then connect to the simulator by listening to the appropriate port (i.e. 14550 for "),o("em",[e._v("QGroundControl")]),e._v(").")]),e._v(" "),o("h3",{attrs:{id:"use-mavlink-router"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#use-mavlink-router"}},[e._v("#")]),e._v(" Use MAVLink Router")]),e._v(" "),o("p",[e._v("The "),o("a",{attrs:{href:"https://github.com/intel/mavlink-router",target:"_blank",rel:"noopener noreferrer"}},[e._v("mavlink-router"),o("OutboundLink")],1),e._v(" can be used to route packets from localhost to an external interface.")]),e._v(" "),o("p",[e._v("To route packets between SITL running on one computer (sending MAVLink traffic to localhost on UDP port 14550), and QGC running on another computer (e.g. at address "),o("code",[e._v("10.73.41.30")]),e._v(") you could:")]),e._v(" "),o("ul",[o("li",[e._v("Start "),o("em",[e._v("mavlink-router")]),e._v(" with the following command:"),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("mavlink-routerd -e 10.73.41.30:14550 127.0.0.1:14550\n")])])])]),e._v(" "),o("li",[e._v("Use a "),o("em",[e._v("mavlink-router")]),e._v(" conf file."),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("[UdpEndpoint QGC]\nMode = Normal\nAddress = 10.73.41.30\nPort = 14550\n\n[UdpEndpoint SIM]\nMode = Eavesdropping\nAddress = 127.0.0.1\nPort = 14550\n")])])])])]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" More information about "),o("em",[e._v("mavlink-router")]),e._v(" configuration can be found "),o("a",{attrs:{href:"https://github.com/intel/mavlink-router/#running",target:"_blank",rel:"noopener noreferrer"}},[e._v("here"),o("OutboundLink")],1),e._v(".")])]),e._v(" "),o("h3",{attrs:{id:"modify-configuration-for-external-broadcasting"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#modify-configuration-for-external-broadcasting"}},[e._v("#")]),e._v(" Modify Configuration for External Broadcasting")]),e._v(" "),o("p",[e._v("The "),o("RouterLink",{attrs:{to:"/en/middleware/modules_communication.html#mavlink_usage"}},[e._v("mavlink")]),e._v(" module routes to "),o("em",[e._v("localhost")]),e._v(" by default, but you can specify an external IP address to broadcast to using its "),o("code",[e._v("-t")]),e._v(" option.")],1),e._v(" "),o("p",[e._v("This should be done in various configuration files where "),o("code",[e._v("mavlink start")]),e._v(" is called.\nFor example: "),o("a",{attrs:{href:"https://github.com/PX4/PX4-Autopilot/blob/master/ROMFS/px4fmu_common/init.d-posix/rcS",target:"_blank",rel:"noopener noreferrer"}},[e._v("/ROMFS/px4fmu_common/init.d-posix/rcS"),o("OutboundLink")],1),e._v(".")]),e._v(" "),o("h3",{attrs:{id:"ssh-tunneling"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#ssh-tunneling"}},[e._v("#")]),e._v(" SSH Tunneling")]),e._v(" "),o("p",[e._v("SSH tunneling is a flexible option because the simulation computer and the system using it need not be on the same network.")]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Note")]),e._v(" You might similarly use VPN to provide a tunnel to an external interface (on the same network or another network).")])]),e._v(" "),o("p",[e._v("One way to create the tunnel is to use SSH tunneling options.\nThe tunnel itself can be created by running the following command on "),o("em",[e._v("localhost")]),e._v(", where "),o("code",[e._v("remote.local")]),e._v(" is the name of a remote computer:")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("ssh -C -fR 14551:localhost:14551 remote.local\n")])])]),o("p",[e._v("The UDP packets need to be translated to TCP packets so they can be routed over SSH.\nThe "),o("a",{attrs:{href:"https://en.wikipedia.org/wiki/Netcat",target:"_blank",rel:"noopener noreferrer"}},[e._v("netcat"),o("OutboundLink")],1),e._v(" utility can be used on both sides of the tunnel - first to convert packets from UDP to TCP, and then back to UDP at the other end.")]),e._v(" "),o("blockquote",[o("p",[o("strong",[e._v("Tip")]),e._v(" QGC must be running before executing "),o("em",[e._v("netcat")]),e._v(".")])]),e._v(" "),o("p",[e._v("On the "),o("em",[e._v("QGroundControl")]),e._v(" computer, UDP packet translation may be implemented by running following commands:")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("mkfifo /tmp/tcp2udp\nnetcat -lvp 14551 < /tmp/tcp2udp | netcat -u localhost 14550 > /tmp/tcp2udp\n")])])]),o("p",[e._v("On the simulator side of the SSH tunnel, the command is:")]),e._v(" "),o("div",{staticClass:"language- extra-class"},[o("pre",{pre:!0,attrs:{class:"language-text"}},[o("code",[e._v("mkfifo /tmp/udp2tcp\nnetcat -lvup 14550 < /tmp/udp2tcp | netcat localhost 14551 > /tmp/udp2tcp\n")])])]),o("p",[e._v("The port number "),o("code",[e._v("14550")]),e._v(" is valid for connecting to QGroundControl or another GCS, but should be adjusted for other endpoints (e.g. developer APIs etc.).")]),e._v(" "),o("p",[e._v("The tunnel may in theory run indefinitely, but "),o("em",[e._v("netcat")]),e._v(" connections may need to be restarted if there is a problem.")]),e._v(" "),o("p",[e._v("The "),o("a",{attrs:{href:"https://raw.githubusercontent.com/ThunderFly-aerospace/sitl_gazebo/autogyro-sitl/scripts/QGC_remote_connect.bash",target:"_blank",rel:"noopener noreferrer"}},[e._v("QGC_remote_connect.bash"),o("OutboundLink")],1),e._v(" script can be run on the QGC computer to automatically setup/run the above instructions.\nThe simulation must already be running on the remote server, and you must be able to SSH into that server.")])])}),[],!1,null,null,null);t.default=r.exports}}]); |
import pytest
from django.core.management import call_command
from metarecord.models import Action, Function, Phase, Record
from metarecord.models.bulk_update import BulkUpdate
def _prepare_structural_element(obj, cls, user, user_2):
obj.created_by = user
obj.modified_by = user_2
obj.save(update_fields=['created_by', 'modified_by'])
cls.objects.filter(pk=obj.pk).update(_created_by='', _modified_by='')
@pytest.mark.django_db
def test_function_migration(function, user, user_2):
_prepare_structural_element(function, Function, user, user_2)
function.refresh_from_db()
assert function._created_by == ''
assert function._modified_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
function.refresh_from_db()
assert function._created_by == 'John Rambo'
assert function._modified_by == 'Rocky Balboa'
@pytest.mark.django_db
def test_phase_migration(phase, user, user_2):
_prepare_structural_element(phase, Phase, user, user_2)
phase.refresh_from_db()
assert phase._created_by == ''
assert phase._modified_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
phase.refresh_from_db()
assert phase._created_by == 'John Rambo'
assert phase._modified_by == 'Rocky Balboa'
@pytest.mark.django_db
def test_action_migration(action, user, user_2):
_prepare_structural_element(action, Action, user, user_2)
action.refresh_from_db()
assert action._created_by == ''
assert action._modified_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
action.refresh_from_db()
assert action._created_by == 'John Rambo'
assert action._modified_by == 'Rocky Balboa'
@pytest.mark.django_db
def test_record_migration(record, user, user_2):
_prepare_structural_element(record, Record, user, user_2)
record.refresh_from_db()
assert record._created_by == ''
assert record._modified_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
record.refresh_from_db()
assert record._created_by == 'John Rambo'
assert record._modified_by == 'Rocky Balboa'
@pytest.mark.django_db
def test_bulk_update_migration(bulk_update, user, user_2, super_user):
BulkUpdate.objects.filter(pk=bulk_update.pk).update(
approved_by=super_user,
created_by=user,
modified_by=user_2,
)
bulk_update.refresh_from_db()
assert bulk_update._approved_by == ''
assert bulk_update._created_by == ''
assert bulk_update._modified_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
bulk_update.refresh_from_db()
assert bulk_update._approved_by == 'Kurt Sloane'
assert bulk_update._created_by == 'John Rambo'
assert bulk_update._modified_by == 'Rocky Balboa'
@pytest.mark.django_db
def test_metadata_version_migration(function, user):
_prepare_structural_element(function, Function, user, user)
function.refresh_from_db()
function.create_metadata_version()
function.metadata_versions.update(_modified_by='')
metadata_version = function.metadata_versions.first()
assert metadata_version._modified_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
metadata_version.refresh_from_db()
assert metadata_version._modified_by == 'John Rambo'
@pytest.mark.django_db
def test_migration_without_user(function):
assert function.created_by == None
assert function._created_by == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
function.refresh_from_db()
assert function._created_by == ''
@pytest.mark.django_db
def test_migration_without_first_name(function, user, user_2):
user.first_name = ''
user.save(update_fields=['first_name'])
_prepare_structural_element(function, Function, user, user_2)
function.refresh_from_db()
assert function._created_by == ''
assert function.created_by.get_full_name() == 'Rambo'
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
function.refresh_from_db()
assert function._created_by == 'Rambo'
@pytest.mark.django_db
def test_migration_without_last_name(function, user, user_2):
user.last_name = ''
user.save(update_fields=['last_name'])
_prepare_structural_element(function, Function, user, user_2)
function.refresh_from_db()
assert function._created_by == ''
assert function.created_by.get_full_name() == 'John'
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
function.refresh_from_db()
assert function._created_by == 'John'
@pytest.mark.django_db
def test_migration_wouthout_names(function, user, user_2):
user.first_name = ''
user.last_name = ''
user.save(update_fields=['first_name', 'last_name'])
_prepare_structural_element(function, Function, user, user_2)
function.refresh_from_db()
assert function._created_by == ''
assert function.created_by.get_full_name() == ''
call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)
call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)
function.refresh_from_db()
assert function._created_by == ''
|
webpackJsonp([63],{"/IIi":function(e,t,o){"use strict";function a(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 s=o("oOyB"),n=function(e){return e&&e.__esModule?e:{default:e}}(s);t.default={name:"button-demo",title:"\u6587\u5B57\u94FE\u63A5\u6309\u94AE",titleEnUS:"Text link buttons",codeSandBox:"https://codesandbox.io/s/7zy8yp8zy6",components:a({},n.default.name,n.default)}},"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}},5716: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-button md-example-child-button-0"},[o("md-button",[e._v("Primary")]),e._v(" "),o("md-button",{attrs:{disabled:""}},[e._v("Primary Disabled")])],1)},staticRenderFns:[]}},"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>"}})},"9ALQ":function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=t.info={title:"Button",preview:"https://didi.github.io/mand-mobile/examples/#/button"},a=t.body="<p>Button components for configuring different button styles</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\">import { Button } from <span class=\"hljs-string\">'mand-mobile'</span>\n\nVue.component(<span class=\"hljs-keyword\">Button</span>.name, <span class=\"hljs-keyword\">Button</span>)\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=\"Button Props\">Button Props<a href=\"javascript:jumpAnchor('Button 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<th>Note</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>type</td>\n<td>button type</td>\n<td>String</td>\n<td><code>primary</code></td>\n<td><code>primary</code>, <code>ghost</code>, <code>ghost-primary</code>, <code>link</code></td>\n</tr>\n<tr>\n<td>size</td>\n<td>button size</td>\n<td>String</td>\n<td><code>large</code></td>\n<td><code>large</code>, <code>small</code>(only works if <code>type</code> is <code>ghost/ghost-primary</code>)</td>\n</tr>\n<tr>\n<td>icon</td>\n<td>button icon</td>\n<td>String</td>\n<td>-</td>\n<td>refer to <code>Icon</code> for optional values</td>\n</tr>\n<tr>\n<td>disabled</td>\n<td>disabled or not</td>\n<td>Boolean</td>\n<td><code>false</code></td>\n<td>-</td>\n</tr>\n</tbody>\n</table>\n<h4 id=\"Button Events\">Button Events<a href=\"javascript:jumpAnchor('Button Events')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">#</a></h4><h5 id=\"@click(event)\">@click(event)<a href=\"javascript:jumpAnchor('@click(event)')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h5\">#</a></h5><p>Button click event</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('Button Props')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">Button Props</a><a href=\"javascript:jumpAnchor('Button Events')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h4\">Button Events</a><a href=\"javascript:jumpAnchor('@click(event)')\" class=\"mfe-blog-toc-item mfe-blog-toc-item-h5\">@click(event)</a>"},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:""}])},Di3m: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-button md-example-child-button-1"},[o("md-button",{attrs:{type:"ghost"}},[e._v("Ghost")]),e._v(" "),o("md-button",{staticStyle:{"margin-left":"5px"},attrs:{type:"ghost",disabled:""}},[e._v("Ghost")]),e._v(" "),o("md-button",{staticStyle:{"margin-left":"5px"},attrs:{type:"ghost-primary"}},[e._v("Ghost-P")]),e._v(" "),o("md-button",{staticStyle:{"margin-left":"5px"},attrs:{type:"ghost-primary",disabled:""}},[e._v("Ghost-P")])],1)},staticRenderFns:[]}},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,{})},GE11: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-button md-example-child-button-2"},[o("md-button",{attrs:{type:"ghost",size:"small"}},[e._v("Ghost-S")]),e._v(" "),o("md-button",{staticStyle:{"margin-left":"5px"},attrs:{type:"ghost",size:"small",disabled:""}},[e._v("Ghost-S")]),e._v(" "),o("md-button",{staticStyle:{"margin-left":"5px"},attrs:{type:"ghost-primary",size:"small"}},[e._v("Ghost-P-S")]),e._v(" "),o("md-button",{staticStyle:{"margin-left":"5px"},attrs:{type:"ghost-primary",size:"small",disabled:""}},[e._v("Ghost-P-S")])],1)},staticRenderFns:[]}},JEHN:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("sN7n"),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("Di3m"),i=o("VU/8"),l=i(s.a,d.a,!1,null,null,null);t["default"]=l.exports},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("sI68")},"data-v-104974d4",null);t["default"]=l.exports},LUK8: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-button md-example-child-button-3"},[o("div",{staticClass:"md-example-box-content"},[e._v("\u6BCF\u4E2A\u4EBA\u90FD\u6709\u5C5E\u4E8E\u81EA\u5DF1\u7684\u4E00\u7247\u68EE\u6797\uFF0C\u4E5F\u8BB8\u6211\u4EEC\u4ECE\u6765\u4E0D\u66FE\u53BB\u8FC7\uFF0C\u4F46\u5B83\u4E00\u76F4\u5728\u90A3\u91CC\uFF0C\u603B\u4F1A\u5728\u90A3\u91CC\u3002\u8FF7\u5931\u7684\u4EBA\u8FF7\u5931\u4E86\uFF0C\u76F8\u9022\u7684\u4EBA\u4F1A\u518D\u76F8\u9022\u3002")]),e._v(" "),o("md-button",{attrs:{type:"link"}},[e._v("\u9605\u8BFB\u5168\u6587")]),e._v(" "),o("div",{staticClass:"md-example-box-content",staticStyle:{"margin-top":"10px"}},[e._v("\u5E0C\u671B\u4F60\u53EF\u4EE5\u8BB0\u4F4F\u6211\uFF0C\u8BB0\u4F4F\u6211\u8FD9\u6837\u6D3B\u8FC7\uFF0C\u8FD9\u6837\u5728\u4F60\u8EAB\u8FB9\u5F85\u8FC7\u3002")]),e._v(" "),o("md-button",{attrs:{type:"link",icon:"hollow-plus"}},[e._v("\u52A0\u5165\u6536\u85CF")]),e._v(" "),o("div",{staticClass:"md-example-box-content",staticStyle:{"margin-top":"10px"}},[e._v("\u5C11\u5E74\u65F6\u6211\u4EEC\u8FFD\u6C42\u6FC0\u60C5\uFF0C\u6210\u719F\u540E\u5374\u8FF7\u604B\u5E73\u5EB8\u3002\u5728\u6211\u4EEC\u5BFB\u627E\u3001\u4F24\u5BB3\u3001\u80CC\u79BB\u4E4B\u540E\uFF0C\u8FD8\u80FD\u4E00\u5982\u65E2\u5F80\u5730\u76F8\u4FE1\u7231\u60C5\uFF0C\u8FD9\u662F\u4E00\u79CD\u52C7\u6C14\u3002")]),e._v(" "),o("md-button",{attrs:{type:"link",disabled:""}},[e._v("\u8BC4\u8BBA")])],1)},staticRenderFns:[]}},NNTi:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("tdqY"),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("xY2o"),i=o("VU/8"),l=i(s.a,d.a,!1,null,null,null);t["default"]=l.exports},"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)}}}},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())}}})},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,{})},WEwB:function(e,t,o){"use strict";function a(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 s=o("oOyB"),n=function(e){return e&&e.__esModule?e:{default:e}}(s);t.default={name:"button-demo",title:"\u4E3B\u6309\u94AE",titleEnUS:"Primary buttons",codeSandBox:"https://codesandbox.io/s/kkzq4mylp5",components:a({},n.default.name,n.default)}},WrmE: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:""}])},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,{})},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:""}])},kQOB:function(e,t,o){var a=o("teR1");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("313df269",a,!0,{})},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:[]}},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:[]}},q4m7:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("WEwB"),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("5716"),i=o("VU/8"),l=i(s.a,d.a,!1,null,null,null);t["default"]=l.exports},sI68:function(e,t,o){var a=o("WrmE");"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);o("rjj0")("f864dd84",a,!0,{})},sN7n:function(e,t,o){"use strict";function a(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 s=o("oOyB"),n=function(e){return e&&e.__esModule?e:{default:e}}(s);t.default={name:"button-demo",title:"\u7EBF\u6027\u6309\u94AE",titleEnUS:"Ghost buttons",codeSandBox:"https://codesandbox.io/s/m398mjvx89",components:a({},n.default.name,n.default)}},tSOy:function(e,t,o){"use strict";function a(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 s=o("oOyB"),n=function(e){return e&&e.__esModule?e:{default:e}}(s);t.default={name:"button-demo",title:"\u7EBF\u6027\u6309\u94AE\u5C0F\u5C3A\u5BF8",titleEnUS:"Small size ghost buttons",codeSandBox:"https://codesandbox.io/s/jlv69qoq8v",components:a({},n.default.name,n.default)}},tWco:function(e,t,o){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.demos=void 0;var s=o("q4m7"),n=a(s),d=o("JEHN"),i=a(d),l=o("v8P+"),r=a(l),A=o("yHp8"),c=a(A),p=t.demos=[{component:n.default,code:"<span class=\"xml\"><span class=\"hljs-tag\"><<span class=\"hljs-name\">template</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">div</span> <span class=\"hljs-attr\">class</span>=<span class=\"hljs-string\">\"md-example-child md-example-child-button md-example-child-button-0\"</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span>></span>Primary<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">disabled</span>></span>Primary Disabled<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"></<span class=\"hljs-name\">div</span>></span>\n<span class=\"hljs-tag\"></<span class=\"hljs-name\">template</span>></span>\n\n<span class=\"hljs-tag\"><<span class=\"hljs-name\">script</span>></span><span class=\"actionscript\">\r<span class=\"hljs-meta\"><span class=\"hljs-meta-keyword\">import</span> </span></span></span><span class=\"hljs-template-variable\">{Button}</span><span class=\"xml\"><span class=\"javascript\"> <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> </span></span><span class=\"hljs-template-variable\">{\n name: 'button-demo',\n components: {\n [Button.name]: Button,\n }</span><span class=\"xml\"><span class=\"undefined\">,\n}\n\r</span><span class=\"hljs-tag\"></<span class=\"hljs-name\">script</span>></span>\n\n</span>",raw:"%3Ctemplate%3E%0A%20%20%3Cdiv%20class=%22md-example-child%20md-example-child-button%20md-example-child-button-0%22%3E%0A%20%20%20%20%3Cmd-button%3EPrimary%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20disabled%3EPrimary%20Disabled%3C/md-button%3E%0A%20%20%3C/div%3E%0A%3C/template%3E%0A%0A%3Cscript%3E%0Dimport%20%7BButton%7D%20from%20'mand-mobile'%0A%0Aexport%20default%20%7B%0A%20%20name:%20'button-demo',%0A%20%20/*%20DELETE%20*/%0A%20%20title:%20'%E4%B8%BB%E6%8C%89%E9%92%AE',%0A%20%20titleEnUS:%20'Primary%20buttons',%0A%20%20codeSandBox:%20'https://codesandbox.io/s/kkzq4mylp5',%0A%20%20/*%20DELETE%20*/%0A%20%20components:%20%7B%0A%20%20%20%20%5BButton.name%5D:%20Button,%0A%20%20%7D,%0A%7D%0A%0D%3C/script%3E%0A%0A"},{component:i.default,code:"<span class=\"xml\"><span class=\"hljs-tag\"><<span class=\"hljs-name\">template</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">div</span> <span class=\"hljs-attr\">class</span>=<span class=\"hljs-string\">\"md-example-child md-example-child-button md-example-child-button-1\"</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost\"</span>></span>Ghost<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost\"</span> <span class=\"hljs-attr\">disabled</span> <span class=\"hljs-attr\">style</span>=<span class=\"hljs-string\">\"margin-left:5px\"</span>></span>Ghost<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost-primary\"</span> <span class=\"hljs-attr\">style</span>=<span class=\"hljs-string\">\"margin-left:5px\"</span>></span>Ghost-P<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost-primary\"</span> <span class=\"hljs-attr\">disabled</span> <span class=\"hljs-attr\">style</span>=<span class=\"hljs-string\">\"margin-left:5px\"</span>></span>Ghost-P<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"></<span class=\"hljs-name\">div</span>></span>\n<span class=\"hljs-tag\"></<span class=\"hljs-name\">template</span>></span>\n\n<span class=\"hljs-tag\"><<span class=\"hljs-name\">script</span>></span><span class=\"actionscript\">\r<span class=\"hljs-meta\"><span class=\"hljs-meta-keyword\">import</span> </span></span></span><span class=\"hljs-template-variable\">{Button}</span><span class=\"xml\"><span class=\"javascript\"> <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> </span></span><span class=\"hljs-template-variable\">{\n name: 'button-demo',\n components: {\n [Button.name]: Button,\n }</span><span class=\"xml\"><span class=\"undefined\">,\n}\n\r</span><span class=\"hljs-tag\"></<span class=\"hljs-name\">script</span>></span>\n\n</span>",raw:"%3Ctemplate%3E%0A%20%20%3Cdiv%20class=%22md-example-child%20md-example-child-button%20md-example-child-button-1%22%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost%22%3EGhost%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost%22%20disabled%20style=%22margin-left:5px%22%3EGhost%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost-primary%22%20style=%22margin-left:5px%22%3EGhost-P%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost-primary%22%20disabled%20style=%22margin-left:5px%22%3EGhost-P%3C/md-button%3E%0A%20%20%3C/div%3E%0A%3C/template%3E%0A%0A%3Cscript%3E%0Dimport%20%7BButton%7D%20from%20'mand-mobile'%0A%0Aexport%20default%20%7B%0A%20%20name:%20'button-demo',%0A%20%20/*%20DELETE%20*/%0A%20%20title:%20'%E7%BA%BF%E6%80%A7%E6%8C%89%E9%92%AE',%0A%20%20titleEnUS:%20'Ghost%20buttons',%0A%20%20codeSandBox:%20'https://codesandbox.io/s/m398mjvx89',%0A%20%20/*%20DELETE%20*/%0A%20%20components:%20%7B%0A%20%20%20%20%5BButton.name%5D:%20Button,%0A%20%20%7D,%0A%7D%0A%0D%3C/script%3E%0A%0A"},{component:r.default,code:"<span class=\"xml\"><span class=\"hljs-tag\"><<span class=\"hljs-name\">template</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">div</span> <span class=\"hljs-attr\">class</span>=<span class=\"hljs-string\">\"md-example-child md-example-child-button md-example-child-button-2\"</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost\"</span> <span class=\"hljs-attr\">size</span>=<span class=\"hljs-string\">\"small\"</span>></span>Ghost-S<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost\"</span> <span class=\"hljs-attr\">size</span>=<span class=\"hljs-string\">\"small\"</span> <span class=\"hljs-attr\">disabled</span> <span class=\"hljs-attr\">style</span>=<span class=\"hljs-string\">\"margin-left:5px\"</span>></span>Ghost-S<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost-primary\"</span> <span class=\"hljs-attr\">size</span>=<span class=\"hljs-string\">\"small\"</span> <span class=\"hljs-attr\">style</span>=<span class=\"hljs-string\">\"margin-left:5px\"</span>></span>Ghost-P-S<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"><<span class=\"hljs-name\">md-button</span> <span class=\"hljs-attr\">type</span>=<span class=\"hljs-string\">\"ghost-primary\"</span> <span class=\"hljs-attr\">size</span>=<span class=\"hljs-string\">\"small\"</span> <span class=\"hljs-attr\">disabled</span> <span class=\"hljs-attr\">style</span>=<span class=\"hljs-string\">\"margin-left:5px\"</span>></span>Ghost-P-S<span class=\"hljs-tag\"></<span class=\"hljs-name\">md-button</span>></span>\n <span class=\"hljs-tag\"></<span class=\"hljs-name\">div</span>></span>\n<span class=\"hljs-tag\"></<span class=\"hljs-name\">template</span>></span>\n\n<span class=\"hljs-tag\"><<span class=\"hljs-name\">script</span>></span><span class=\"actionscript\">\r<span class=\"hljs-meta\"><span class=\"hljs-meta-keyword\">import</span> </span></span></span><span class=\"hljs-template-variable\">{Button}</span><span class=\"xml\"><span class=\"javascript\"> <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> </span></span><span class=\"hljs-template-variable\">{\n name: 'button-demo',\n components: {\n [Button.name]: Button,\n }</span><span class=\"xml\"><span class=\"undefined\">,\n}\n\r</span><span class=\"hljs-tag\"></<span class=\"hljs-name\">script</span>></span>\n\n</span>",raw:"%3Ctemplate%3E%0A%20%20%3Cdiv%20class=%22md-example-child%20md-example-child-button%20md-example-child-button-2%22%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost%22%20size=%22small%22%3EGhost-S%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost%22%20size=%22small%22%20disabled%20style=%22margin-left:5px%22%3EGhost-S%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost-primary%22%20size=%22small%22%20style=%22margin-left:5px%22%3EGhost-P-S%3C/md-button%3E%0A%20%20%20%20%3Cmd-button%20type=%22ghost-primary%22%20size=%22small%22%20disabled%20style=%22margin-left:5px%22%3EGhost-P-S%3C/md-button%3E%0A%20%20%3C/div%3E%0A%3C/template%3E%0A%0A%3Cscript%3E%0Dimport%20%7BButton%7D%20from%20'mand-mobile'%0A%0Aexport%20default%20%7B%0A%20%20name:%20'button-demo',%0A%20%20/*%20DELETE%20*/%0A%20%20title:%20'%E7%BA%BF%E6%80%A7%E6%8C%89%E9%92%AE%E5%B0%8F%E5%B0%BA%E5%AF%B8',%0A%20%20titleEnUS:%20'Small%20size%20ghost%20buttons',%0A%20%20codeSandBox:%20'https://codesandbox.io/s/jlv69qoq8v',%0A%20%20/*%20DELETE%20*/%0A%20%20components:%20%7B%0A%20%20%20%20%5BButton.name%5D:%20Button,%0A%20%20%7D,%0A%7D%0A%0D%3C/script%3E%0A%0A"},{component:c.default,code:"<template>\n <<span class=\"hljs-selector-tag\">div</span> class=<span class=\"hljs-string\">\"md-example-child md-example-child-button md-example-child-button-3\"</span>>\n <<span class=\"hljs-selector-tag\">div</span> class=<span class=\"hljs-string\">\"md-example-box-content\"</span>>\u6BCF\u4E2A\u4EBA\u90FD\u6709\u5C5E\u4E8E\u81EA\u5DF1\u7684\u4E00\u7247\u68EE\u6797\uFF0C\u4E5F\u8BB8\u6211\u4EEC\u4ECE\u6765\u4E0D\u66FE\u53BB\u8FC7\uFF0C\u4F46\u5B83\u4E00\u76F4\u5728\u90A3\u91CC\uFF0C\u603B\u4F1A\u5728\u90A3\u91CC\u3002\u8FF7\u5931\u7684\u4EBA\u8FF7\u5931\u4E86\uFF0C\u76F8\u9022\u7684\u4EBA\u4F1A\u518D\u76F8\u9022\u3002</div>\n <md-<span class=\"hljs-selector-tag\">button</span> type=<span class=\"hljs-string\">\"link\"</span>>\u9605\u8BFB\u5168\u6587</md-button>\n <<span class=\"hljs-selector-tag\">div</span> class=<span class=\"hljs-string\">\"md-example-box-content\"</span> style=<span class=\"hljs-string\">\"margin-top:10px\"</span>>\u5E0C\u671B\u4F60\u53EF\u4EE5\u8BB0\u4F4F\u6211\uFF0C\u8BB0\u4F4F\u6211\u8FD9\u6837\u6D3B\u8FC7\uFF0C\u8FD9\u6837\u5728\u4F60\u8EAB\u8FB9\u5F85\u8FC7\u3002</div>\n <md-<span class=\"hljs-selector-tag\">button</span> type=<span class=\"hljs-string\">\"link\"</span> <span class=\"hljs-attribute\">icon</span>=<span class=\"hljs-string\">\"hollow-plus\"</span>>\u52A0\u5165\u6536\u85CF</md-button>\n <<span class=\"hljs-selector-tag\">div</span> class=<span class=\"hljs-string\">\"md-example-box-content\"</span> style=<span class=\"hljs-string\">\"margin-top:10px\"</span>>\u5C11\u5E74\u65F6\u6211\u4EEC\u8FFD\u6C42\u6FC0\u60C5\uFF0C\u6210\u719F\u540E\u5374\u8FF7\u604B\u5E73\u5EB8\u3002\u5728\u6211\u4EEC\u5BFB\u627E\u3001\u4F24\u5BB3\u3001\u80CC\u79BB\u4E4B\u540E\uFF0C\u8FD8\u80FD\u4E00\u5982\u65E2\u5F80\u5730\u76F8\u4FE1\u7231\u60C5\uFF0C\u8FD9\u662F\u4E00\u79CD\u52C7\u6C14\u3002</div>\n <md-<span class=\"hljs-selector-tag\">button</span> type=<span class=\"hljs-string\">\"link\"</span> disabled>\u8BC4\u8BBA</md-button>\n </div>\n</template>\n\n<script>\rimport {Button} from <span class=\"hljs-string\">'mand-mobile'</span>\n\nexport default {\n name: <span class=\"hljs-string\">'button-demo'</span>,\n components: {\n [Button.name]: Button,\n },\n}\n\r</script>\n\n<style lang=<span class=\"hljs-string\">\"stylus\"</span> scoped>\n<span class=\"hljs-selector-class\">.md-example-child-button-3</span>\n <span class=\"hljs-selector-class\">.md-example-box-content</span>\n <span class=\"hljs-attribute\">float</span> left\n <span class=\"hljs-attribute\">width</span> <span class=\"hljs-number\">100%</span>\n <span class=\"hljs-attribute\">padding</span> <span class=\"hljs-number\">60px</span> h-gap-lg\n <span class=\"hljs-attribute\">color</span> color-text-base\n <span class=\"hljs-attribute\">font-size</span> font-minor-large\n <span class=\"hljs-attribute\">text-align</span> left\n <span class=\"hljs-attribute\">background</span> color-bg-base\n <span class=\"hljs-attribute\">box-sizing</span> border-box\n <span class=\"hljs-attribute\">line-height</span> <span class=\"hljs-number\">1.5</span>\n <span class=\"hljs-attribute\">text-indent</span> <span class=\"hljs-number\">2em</span>\n <span class=\"hljs-selector-class\">.md-button</span>\n <span class=\"hljs-attribute\">float</span> left\n</style>\n",raw:"%3Ctemplate%3E%0A%20%20%3Cdiv%20class=%22md-example-child%20%20md-example-child-button%20md-example-child-button-3%22%3E%0A%20%20%20%20%3Cdiv%20class=%22md-example-box-content%22%3E%E6%AF%8F%E4%B8%AA%E4%BA%BA%E9%83%BD%E6%9C%89%E5%B1%9E%E4%BA%8E%E8%87%AA%E5%B7%B1%E7%9A%84%E4%B8%80%E7%89%87%E6%A3%AE%E6%9E%97%EF%BC%8C%E4%B9%9F%E8%AE%B8%E6%88%91%E4%BB%AC%E4%BB%8E%E6%9D%A5%E4%B8%8D%E6%9B%BE%E5%8E%BB%E8%BF%87%EF%BC%8C%E4%BD%86%E5%AE%83%E4%B8%80%E7%9B%B4%E5%9C%A8%E9%82%A3%E9%87%8C%EF%BC%8C%E6%80%BB%E4%BC%9A%E5%9C%A8%E9%82%A3%E9%87%8C%E3%80%82%E8%BF%B7%E5%A4%B1%E7%9A%84%E4%BA%BA%E8%BF%B7%E5%A4%B1%E4%BA%86%EF%BC%8C%E7%9B%B8%E9%80%A2%E7%9A%84%E4%BA%BA%E4%BC%9A%E5%86%8D%E7%9B%B8%E9%80%A2%E3%80%82%3C/div%3E%0A%20%20%20%20%3Cmd-button%20type=%22link%22%3E%E9%98%85%E8%AF%BB%E5%85%A8%E6%96%87%3C/md-button%3E%0A%20%20%20%20%3Cdiv%20class=%22md-example-box-content%22%20style=%22margin-top:10px%22%3E%E5%B8%8C%E6%9C%9B%E4%BD%A0%E5%8F%AF%E4%BB%A5%E8%AE%B0%E4%BD%8F%E6%88%91%EF%BC%8C%E8%AE%B0%E4%BD%8F%E6%88%91%E8%BF%99%E6%A0%B7%E6%B4%BB%E8%BF%87%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%9C%A8%E4%BD%A0%E8%BA%AB%E8%BE%B9%E5%BE%85%E8%BF%87%E3%80%82%3C/div%3E%0A%20%20%20%20%3Cmd-button%20type=%22link%22%20icon=%22hollow-plus%22%3E%E5%8A%A0%E5%85%A5%E6%94%B6%E8%97%8F%3C/md-button%3E%0A%20%20%20%20%3Cdiv%20class=%22md-example-box-content%22%20style=%22margin-top:10px%22%3E%E5%B0%91%E5%B9%B4%E6%97%B6%E6%88%91%E4%BB%AC%E8%BF%BD%E6%B1%82%E6%BF%80%E6%83%85%EF%BC%8C%E6%88%90%E7%86%9F%E5%90%8E%E5%8D%B4%E8%BF%B7%E6%81%8B%E5%B9%B3%E5%BA%B8%E3%80%82%E5%9C%A8%E6%88%91%E4%BB%AC%E5%AF%BB%E6%89%BE%E3%80%81%E4%BC%A4%E5%AE%B3%E3%80%81%E8%83%8C%E7%A6%BB%E4%B9%8B%E5%90%8E%EF%BC%8C%E8%BF%98%E8%83%BD%E4%B8%80%E5%A6%82%E6%97%A2%E5%BE%80%E5%9C%B0%E7%9B%B8%E4%BF%A1%E7%88%B1%E6%83%85%EF%BC%8C%E8%BF%99%E6%98%AF%E4%B8%80%E7%A7%8D%E5%8B%87%E6%B0%94%E3%80%82%3C/div%3E%0A%20%20%20%20%3Cmd-button%20type=%22link%22%20disabled%3E%E8%AF%84%E8%AE%BA%3C/md-button%3E%0A%20%20%3C/div%3E%0A%3C/template%3E%0A%0A%3Cscript%3E%0Dimport%20%7BButton%7D%20from%20'mand-mobile'%0A%0Aexport%20default%20%7B%0A%20%20name:%20'button-demo',%0A%20%20/*%20DELETE%20*/%0A%20%20title:%20'%E6%96%87%E5%AD%97%E9%93%BE%E6%8E%A5%E6%8C%89%E9%92%AE',%0A%20%20titleEnUS:%20'Text%20link%20buttons',%0A%20%20codeSandBox:%20'https://codesandbox.io/s/7zy8yp8zy6',%0A%20%20/*%20DELETE%20*/%0A%20%20components:%20%7B%0A%20%20%20%20%5BButton.name%5D:%20Button,%0A%20%20%7D,%0A%7D%0A%0D%3C/script%3E%0A%0A%3Cstyle%20lang=%22stylus%22%20scoped%3E%0A.md-example-child-button-3%0A%20%20.md-example-box-content%0A%20%20%20%20float%20left%0A%20%20%20%20width%20100%25%0A%20%20%20%20padding%2060px%20h-gap-lg%0A%20%20%20%20color%20color-text-base%0A%20%20%20%20font-size%20font-minor-large%0A%20%20%20%20text-align%20left%0A%20%20%20%20background%20color-bg-base%0A%20%20%20%20box-sizing%20border-box%0A%20%20%20%20line-height%201.5%0A%20%20%20%20text-indent%202em%0A%20%20.md-button%0A%20%20%20%20float%20left%0A%3C/style%3E%0A"}]},tdqY: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("9ALQ"),d=o("tWco");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}}},teR1:function(e,t,o){t=e.exports=o("FZ+f")(!0),t.push([e.i,".md-example-child-button-3 .md-example-box-content[data-v-29d2f8b4]{float:left;width:100%;padding:60px 32px;color:#333;font-size:24px;text-align:left;background:#fff;box-sizing:border-box;line-height:1.5;text-indent:2em}.md-example-child-button-3 .md-button[data-v-29d2f8b4]{float:left}","",{version:3,sources:["/Users/shawnXu/Desktop/Repertory/mand-mobile/site/public/en-US/docs/components/basic/button/demo3.vue"],names:[],mappings:"AACA,oEACE,WAAY,AACZ,WAAY,AACZ,kBAAmB,AACnB,WAAY,AACZ,eAAgB,AAChB,gBAAiB,AACjB,gBAAiB,AACjB,sBAAuB,AACvB,gBAAiB,AACjB,eAAiB,CAClB,AACD,uDACE,UAAY,CACb",file:"demo3.vue",sourcesContent:["\n.md-example-child-button-3 .md-example-box-content[data-v-29d2f8b4] {\n float: left;\n width: 100%;\n padding: 60px 32px;\n color: #333;\n font-size: 24px;\n text-align: left;\n background: #fff;\n box-sizing: border-box;\n line-height: 1.5;\n text-indent: 2em;\n}\n.md-example-child-button-3 .md-button[data-v-29d2f8b4] {\n float: left;\n}"],sourceRoot:""}])},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=c.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=h.length;n<=d&&(o=0,t===p.L?o=h[n][0]:t===p.M?o=h[n][1]:t===p.Q?o=h[n][2]:t===p.H?o=h[n][3]:void 0,!(s<=o));n++)a++;if(a>h.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=g.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=g.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=g.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=g.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=g.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(),g.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),c=0;c<t.length;c++){var r=t[c].dataCount,p=t[c].totalCount-r;n=o(n,r),d=o(d,p),l[c]=Array(r);for(var m=0;m<l[c].length;m++)l[c][m]=255&e.buffer[m+a];a+=r;var i=g.getErrorCorrectPolynomial(p),b=new s(l[c],i.getLength()-1),u=b.mod(i);A[c]=Array(i.getLength()-1);for(var h,m=0;m<A[c].length;m++)h=m+u.getLength()-A[c].length,A[c][m]=0<=h?u.get(h):0}for(var f=0,m=0;m<t.length;m++)f+=t[m].totalCount;for(var C=Array(f),B=0,m=0;m<n;m++)for(var c=0;c<t.length;c++)m<l[c].length&&(C[B++]=l[c][m]);for(var m=0;m<d;m++)for(var c=0;c<t.length;c++)m<A[c].length&&(C[B++]=A[c][m]);return C};for(var c={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},p={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},g={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<=g.getBCHDigit(t)-g.getBCHDigit(g.G15);)t^=g.G15<<g.getBCHDigit(t)-g.getBCHDigit(g.G15);return(e<<10|t)^g.G15_MASK},getBCHTypeNumber:function(e){for(var t=e<<12;0<=g.getBCHDigit(t)-g.getBCHDigit(g.G18);)t^=g.G18<<g.getBCHDigit(t)-g.getBCHDigit(g.G18);return e<<12|t},getBCHDigit:function(e){for(var t=0;0!=e;)t++,e>>>=1;return t},getPatternPosition:function(e){return g.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,b.gexp(o)],0));return t},getLengthInBits:function(e,t){if(1<=t&&10>t)switch(e){case c.MODE_NUMBER:return 10;case c.MODE_ALPHA_NUM:return 9;case c.MODE_8BIT_BYTE:return 8;case c.MODE_KANJI:return 8;default:throw new Error("mode:"+e);}else if(27>t)switch(e){case c.MODE_NUMBER:return 12;case c.MODE_ALPHA_NUM:return 11;case c.MODE_8BIT_BYTE:return 16;case c.MODE_KANJI:return 10;default:throw new Error("mode:"+e);}else if(41>t)switch(e){case c.MODE_NUMBER:return 14;case c.MODE_ALPHA_NUM:return 13;case c.MODE_8BIT_BYTE:return 16;case c.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 c=Math.abs(100*A/t/t-50)/5;return o+=10*c,o}},b={glog:function(e){if(1>e)throw new Error("glog("+e+")");return b.LOG_TABLE[e]},gexp:function(e){for(;0>e;)e+=255;for(;256<=e;)e-=255;return b.EXP_TABLE[e]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)},u=0;8>u;u++)b.EXP_TABLE[u]=1<<u;for(var u=8;256>u;u++)b.EXP_TABLE[u]=b.EXP_TABLE[u-4]^b.EXP_TABLE[u-5]^b.EXP_TABLE[u-6]^b.EXP_TABLE[u-8];for(var u=0;255>u;u++)b.LOG_TABLE[b.EXP_TABLE[u]]=u;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]^=b.gexp(b.glog(this.get(o))+b.glog(t.get(a)));return new s(e,0)},mod:function(t){if(0>this.getLength()-t.getLength())return this;for(var e=b.glog(this.get(0))-b.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]^=b.gexp(b.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===p.L?a.RS_BLOCK_TABLE[4*(e-1)+0]:t===p.M?a.RS_BLOCK_TABLE[4*(e-1)+1]:t===p.Q?a.RS_BLOCK_TABLE[4*(e-1)+2]:t===p.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 h=[[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]],f=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 c=t("use",{x:l+"",y:r+""});c.setAttributeNS("http://www.w3.org/1999/xlink","href","#template"),i.appendChild(c)}},e.prototype.clear=function(){for(;this._el.hasChildNodes();)this._el.removeChild(this._el.lastChild)},e}(),i="svg"===document.documentElement.tagName.toLowerCase(),C=i?f: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 c=arguments.length-1;1<=c;c--)arguments[c]*=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),c=o(l);a.style.setProperty("display","none","important"),this.clear();for(var p=0;p<d;p++)for(var m=0;m<d;m++){var g=e.isDark(p,m),b=m*i,u=p*l;s.strokeStyle=g?n.colorDark:n.colorLight,s.lineWidth=1,s.fillStyle=g?n.colorDark:n.colorLight,s.fillRect(b,u,i,l),s.strokeRect(A(b)+.5,A(u)+.5,r,c),s.strokeRect(t(b)-.5,t(u)-.5,r,c)}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],c=(t.width-r.offsetWidth)/2,p=(t.height-r.offsetHeight)/2;0<c&&0<p&&(r.style.margin=p+"px "+c+"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:p.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&&(C=f),this._android=d(),this._el=e,this._oQRCode=null,this._oDrawing=new C(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=p})(),e&&e.exports&&(e.exports=t)}).call(t,o("3IRH")(e))},"v8P+":function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("tSOy"),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("GE11"),i=o("VU/8"),l=i(s.a,d.a,!1,null,null,null);t["default"]=l.exports},xY2o: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:[]}},yHp8:function(e,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=o("/IIi"),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("LUK8"),i=o("VU/8"),l=i(s.a,d.a,!1,function(){o("kQOB")},"data-v-29d2f8b4",null);t["default"]=l.exports}}); |
(function () {
'use strict';
angular
.module('app')
.controller('Home.IndexController', Controller)
.controller('Home.SidebarController', SidebarController)
.controller('Home.AdminUsersController', AdminUsersController)
.controller('Home.AllUsersController', AllUsersController)
.controller('Home.SkillProfilesController', SkillProfilesController)
.controller('Home.UpdateSkillProfileController', UpdateSkillProfileController)
.controller('Home.AdminController', AdminController)
.controller('Home.UserInfoController', UserInfoController)
.controller('Home.UserModelController', UserModelController)
.controller('Home.ReleaseUserModelController', ReleaseUserModelController)
.controller('Home.PoolUsersController', PoolUsersController)
.controller('Home.PoolLogsController', PoolLogsController)
.filter('allUserSearch', function ($filter) {
return function (input, searchObj) {
var output = input;
if (searchObj.userName && searchObj.userName.length > 0) {
output = $filter('filter')(output, { name: searchObj.userName });
}
if (searchObj.userResourceType && searchObj.userResourceType.length > 0) {
output = $filter('filter')(output, function (item) {
return (searchObj.userResourceType == item.userResourceType);
});
}
if (searchObj.practice && searchObj.practice.length > 0 && searchObj.practice != "All") {
output = $filter('filter')(output, function (item) {
return (searchObj.practice == item.practice);
});
}
if (searchObj.employeeCategory && searchObj.employeeCategory.length > 0 && searchObj.employeeCategory != "All") {
output = $filter('filter')(output, function (item) {
return (searchObj.employeeCategory == item.employeeCategory);
});
}
if (searchObj.isAdmin === true || searchObj.isAdmin === false) {
output = $filter('filter')(output, function (item) {
return (searchObj.isAdmin == item.admin);
});
}
if (searchObj.resourceStatus && searchObj.resourceStatus.length > 0) {
if (searchObj.resourceStatus === "available") {
output = $filter('filter')(output, function (item) {
return (item.resourceInPool === true);
});
} else if (searchObj.resourceStatus === "assigned") {
output = $filter('filter')(output, function (item) {
return (item.resourceInPool !== true);
});
}
}
if (searchObj.skillCategory && searchObj.skillCategory.length > 0 && searchObj.skillCategory != "All") {
output = $filter('filter')(output, { skillCategory: searchObj.skillCategory });
}
if (searchObj.skillName && searchObj.skillName.length > 0) {
var searchCriterias = String(searchObj.skillName).toLowerCase().split(" and ");
_.each(searchCriterias, function (searchCriteria) {
searchCriteria = String(searchCriteria).trim();
searchCriteria.replace(" or ", " ");
var skillNameWords = searchCriteria.split(" ");
var metaSkillLevels = ["basic", "intermediate", "advanced", "expert"];
var skillLevelCriteria = "";
_.each(skillNameWords, function (skillNameWord) {
skillLevelCriteria = metaSkillLevels.indexOf(skillNameWord.toLowerCase());
if (skillLevelCriteria >= 0) {
skillLevelCriteria = metaSkillLevels[skillLevelCriteria];
skillLevelCriteria = String(skillLevelCriteria).charAt(0).toUpperCase() + String(skillLevelCriteria).substring(1);
return true;
} else {
skillLevelCriteria = "";
}
});
output = $filter('filter')(output, function (item, index) {
if (item.userSkills && item.userSkills.length > 0) {
var haveRecords = false;
_.each(skillNameWords, function (skillNameWord) {
if (skillLevelCriteria != "") {
var skillNameSearch = $filter('filter')(item.userSkills, { 'skillName': skillNameWord, 'skillLevel': skillLevelCriteria });
} else {
var skillNameSearch = $filter('filter')(item.userSkills, { 'skillName': skillNameWord });
}
if (skillNameSearch.length > 0) {
haveRecords = true;
return;
}
});
if (haveRecords) {
return true;
}
}
return false;
});
});
}
if (searchObj.isActive == 'true' || searchObj.isActive == 'false') {
output = $filter('filter')(output, function (item, index) {
if (searchObj.isActive == 'true') {
return (item.isActive === true);
} else if (searchObj.isActive == 'false') {
return (item.isActive === false);
} else {
return true;
}
});
}
return output;
}
})
function Controller(UserService, TimesheetService, JobOpeningService, ProjectService, $filter, _, $interval, $window) {
var vm = this;
var currentDate;
vm.widgetDate;
vm.users = null;
vm.totalHours = null;
vm.myHours = null;
vm.monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
vm.dateOptions = {
dateDisabled: function (data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() != 5);
},
formatYear: 'yy',
maxDate: new Date(2030, 12, 31),
startingDay: 1
};
vm.monthOptions = {
datepickerMode: "month", // Remove Single quotes
minMode: 'month'
};
vm.leaveWalletBalance = {
accruedLeaves: 0.00,
creditedLeaves: 0.00,
deductedLOP: 0.00,
leaveBalance: 0.00,
timeoffHours: 0.00,
timeoffDays: 0.00
};
vm.inventories = [];
vm.chartColors = ['#803690', '#00ADF9', '#46BFBD', '#FDB45C', '#949FB1', '#4D5360', '#DCDCDC'];
vm.hoursChart = {
"options": {
legend: {
display: true
}
},
"colors": ['#1caf9a', '#273541']
};
vm.manpowerChart = {
week: "",
weekDate: new Date(),
options: {
legend: {
display: true
}
},
colors: vm.chartColors,
data: [],
labels: []
};
if (vm.manpowerChart.weekDate.getDay() < 5) {
vm.manpowerChart.weekDate.setDate(vm.manpowerChart.weekDate.getDate() - (vm.manpowerChart.weekDate.getDay() + 2));
} else if (vm.manpowerChart.weekDate.getDay() == 6) {
vm.manpowerChart.weekDate.setDate(vm.manpowerChart.weekDate.getDate() - 1);
}
vm.monthHoursChart = {
week: "",
weekDate: new Date(),
options: {
legend: {
display: true
}
},
colors: vm.chartColors,
data: [],
series: [],
labels: []
};
vm.monthHeadCountChart = {
week: "",
weekDate: new Date(),
options: {
legend: {
display: true
}
},
colors: vm.chartColors,
data: [],
series: [],
labels: []
};
vm.projectManpower = {
projectId: "",
week: "",
weekDate: new Date(),
options: {
legend: {
display: true
}
},
colors: vm.chartColors,
data: [],
labels: []
};
if (vm.projectManpower.weekDate.getDay() < 5) {
vm.projectManpower.weekDate.setDate(vm.projectManpower.weekDate.getDate() - (vm.projectManpower.weekDate.getDay() + 2));
} else if (vm.projectManpower.weekDate.getDay() == 6) {
vm.projectManpower.weekDate.setDate(vm.projectManpower.weekDate.getDate() - 1);
}
/*vm.projectMonthlyHours = {
projectId: "",
week: "",
weekDate: new Date(),
options: {
legend: {
display: true
}
},
colors: vm.chartColors,
data: [],
series: [],
labels: []
};*/
vm.utzHeadCountChart = {
week: "",
options: {
legend: {
display: true
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true,
ticks: { beginAtZero: true }
}]
}
},
colors: vm.chartColors,
data: [],
series: ["Enterprise", "Launchpad", "NonBillableProject"],
labels: []
};
vm.utzHoursChart = {
week: "",
options: {
legend: {
display: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: { beginAtZero: true }
}]
}
},
colors: vm.chartColors,
data: [],
series: ["Enterprise", "Launchpad"],
labels: []
};
vm.utilizationHeadCountChart = {
week: "",
options: {
legend: {
display: true
},
scales: {
yAxes: [{
ticks: { beginAtZero: true, max: 100 }
}]
}
},
colors: vm.chartColors,
data: [],
series: ["Utilization"],
labels: []
};
vm.utilizationHoursChart = {
week: "",
options: {
legend: {
display: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: { beginAtZero: true, max: 100 }
}]
}
},
colors: vm.chartColors,
data: [],
series: ["Utilization"],
labels: []
};
vm.utzOrganizationHeadCountChart = {
week: "",
options: {
legend: {
display: true
},
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: { beginAtZero: true, max: 100 }
}]
}
},
colors: vm.chartColors,
data: [],
series: ["Utilization", "NonBillableProject"],
labels: []
};
vm.projects = [];
var currentDay = new Date().getDay();
if (currentDay < 5) {
var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
vm.widgetDate = angular.copy(oneWeekAgo);
currentDate = $filter('date')(oneWeekAgo, "yyyy-Www").toString();
} else {
vm.widgetDate = new Date();
currentDate = $filter('date')(new Date(), "yyyy-Www").toString();
}
var tick = function () {
vm.date = new Date();
}
tick();
$interval(tick, 1000);
vm.jobs = [];
function getActiveJobOpenings() {
JobOpeningService.getActiveJobOpenings().then(function (response) {
if (response.jobOpenings) {
vm.jobs = response.jobOpenings;
}
})
};
getActiveJobOpenings();
function getUsers() {
UserService.getUsers().then(function (users) {
vm.users = users;
getAllReports();
getMyReport();
})
};
function getAllReports() {
TimesheetService.getReportByWeek(currentDate).then(function (reports) {
vm.totalHours = _.sum(_.map(reports, 'totalHours'));
vm.currentCapacity = vm.users.length * 40;
var leave = vm.currentCapacity - vm.totalHours;
vm.hoursChart.data = [vm.totalHours, leave];
vm.hoursChart.labels = ["Filled Hours", "Unfilled Hours"];
});
};
function getMyReport() {
TimesheetService.getMine().then(function (reports) {
vm.myHours = _.sum(_.map(reports, 'totalHours'));
});
};
function getProjectsWithUserCount() {
TimesheetService.getProjectsWithUserCount().then(function (projects) {
vm.projects = projects;
});
};
vm.getAllUserHoursByWeek = function () {
var week = $filter('date')(new Date(vm.manpowerChart.weekDate), "yyyy-Www").toString();
TimesheetService.allUserHoursByWeek(week).then(function (manpowerData) {
vm.manpowerChart.labels = [];
vm.manpowerChart.data = [];
_.each(manpowerData.resourceTypes, function (resourceTypeObj) {
vm.manpowerChart.labels.push(resourceTypeObj.resourceType + ' (' + resourceTypeObj.projectUserCount + ')');
vm.manpowerChart.data.push(resourceTypeObj.projectHours);
});
});
};
vm.getProjectUserHoursByWeek = function () {
if (vm.projectManpower.projectId) {
var week = $filter('date')(new Date(vm.projectManpower.weekDate), "yyyy-Www").toString();
TimesheetService.projectUserHoursByWeek(week, vm.projectManpower.projectId).then(function (manpowerData) {
vm.projectManpower.labels = [];
vm.projectManpower.data = [];
_.each(manpowerData.resourceTypes, function (resourceTypeObj) {
vm.projectManpower.labels.push(resourceTypeObj.resourceType + ' (' + resourceTypeObj.projectUserCount + ')');
vm.projectManpower.data.push(resourceTypeObj.projectHours);
});
});
}
};
vm.getAllUserHoursByMonth = function () {
vm.utilizationByMonth();
vm.monthHoursChart.monthName = vm.monthNames[vm.monthHoursChart.weekDate.getMonth()];
TimesheetService.allUserHoursByMonth(vm.monthHoursChart.weekDate.getMonth(), vm.monthHoursChart.weekDate.getFullYear()).then(function (manpowerData) {
manpowerData = _.sortBy(manpowerData, 'week');
vm.monthHoursChart.labels = [];
vm.monthHoursChart.data = [];
vm.monthHoursChart.series = [];
_.each(manpowerData[0].resourceTypes, function (resourceTypeObj) {
//vm.monthHoursChart.series.push(resourceTypeObj.resourceType + '('+ resourceTypeObj.projectUserCount +')');
vm.monthHoursChart.series.push(resourceTypeObj.resourceType);
});
_.each(manpowerData, function (manpower) {
vm.monthHoursChart.labels.push(manpower.week + "(" + manpower.totalHours + ")");
});
_.each(vm.monthHoursChart.series, function (resourceTypeVal) {
var dataObj = [];
_.each(manpowerData, function (manpowerObj) {
var resourceTypeObj = _.find(manpowerObj.resourceTypes, { "resourceType": resourceTypeVal });
if (resourceTypeObj) {
dataObj.push(resourceTypeObj.projectHours);
}
});
vm.monthHoursChart.data.push(dataObj);
});
vm.monthHeadCountChart.labels = [];
vm.monthHeadCountChart.data = [];
vm.monthHeadCountChart.series = [];
_.each(manpowerData[0].resourceTypes, function (resourceTypeObj) {
vm.monthHeadCountChart.series.push(resourceTypeObj.resourceType);
});
_.each(manpowerData, function (manpower) {
vm.monthHeadCountChart.labels.push(manpower.week + "(" + manpower.totalUserCount + ")");
});
_.each(vm.monthHeadCountChart.series, function (resourceTypeVal) {
var dataObj = [];
_.each(manpowerData, function (manpowerObj) {
var resourceTypeObj = _.find(manpowerObj.resourceTypes, { "resourceType": resourceTypeVal });
if (resourceTypeObj) {
dataObj.push(resourceTypeObj.projectUserCount);
}
});
vm.monthHeadCountChart.data.push(dataObj);
});
});
};
/*vm.getProjectUserHoursByMonth = function() {
if(vm.projectMonthlyHours.projectId) {
TimesheetService.projectUserHoursByMonth(vm.projectMonthlyHours.weekDate.getMonth(), vm.projectMonthlyHours.weekDate.getFullYear(), vm.projectMonthlyHours.projectId).then(function (manpowerData) {
manpowerData = _.sortBy(manpowerData, 'week');
vm.projectMonthlyHours.labels = [];
vm.projectMonthlyHours.data = [];
vm.projectMonthlyHours.series = [];
_.each(manpowerData[0].resourceTypes, function (resourceTypeObj) {
vm.projectMonthlyHours.series.push(resourceTypeObj.resourceType);
});
_.each(manpowerData, function (manpower) {
vm.projectMonthlyHours.labels.push(manpower.week);
});
_.each(vm.projectMonthlyHours.series, function (resourceTypeVal) {
var dataObj = [];
_.each(manpowerData, function (manpowerObj) {
var resourceTypeObj = _.find(manpowerObj.resourceTypes, {"resourceType": resourceTypeVal});
if (resourceTypeObj) {
dataObj.push(resourceTypeObj.projectHours);
}
});
vm.projectMonthlyHours.data.push(dataObj);
});
});
}
};*/
vm.utilizationByMonth = function () {
vm.monthHoursChart.monthName = vm.monthNames[vm.monthHoursChart.weekDate.getMonth()];
TimesheetService.utilizationByMonth(vm.monthHoursChart.weekDate.getMonth(), vm.monthHoursChart.weekDate.getFullYear()).then(function (resultData) {
resultData = _.sortBy(resultData, 'week');
vm.utzHeadCountChart.labels = [];
vm.utzHeadCountChart.data = [];
var enterpriseData = [];
var lanchpadData = [];
var noBillableProjectData = [];
_.each(resultData, function (weekData) {
vm.utzHeadCountChart.labels.push(weekData.week + "(" + weekData.weekHeadCount + ")");
enterpriseData.push(weekData.enterpriseHeadCount);
lanchpadData.push(weekData.launchpadHeadCount);
noBillableProjectData.push(weekData.haveNoBillableProjectHeadCount);
});
vm.utzHeadCountChart.data.push(enterpriseData);
vm.utzHeadCountChart.data.push(lanchpadData);
vm.utzHeadCountChart.data.push(noBillableProjectData);
vm.utzHoursChart.labels = [];
vm.utzHoursChart.data = [];
var enterpriseData = [];
var lanchpadData = [];
_.each(resultData, function (weekData) {
vm.utzHoursChart.labels.push(weekData.week + "(" + weekData.weekBillableHours + ")");
enterpriseData.push(weekData.enterpriseBillableHours);
lanchpadData.push(weekData.launchpadBillableHours);
});
vm.utzHoursChart.data.push(enterpriseData);
vm.utzHoursChart.data.push(lanchpadData);
vm.utilizationHeadCountChart.labels = [];
vm.utilizationHeadCountChart.data = [];
var utilizationData = [];
_.each(resultData, function (weekData) {
vm.utilizationHeadCountChart.labels.push(weekData.week);
var utilizationVal = (weekData.enterpriseHeadCount / weekData.weekHeadCount) * 100;
if (isNaN(utilizationVal)) {
utilizationVal = 0;
}
utilizationVal = parseInt(utilizationVal);
utilizationData.push(utilizationVal);
});
vm.utilizationHeadCountChart.data.push(utilizationData);
vm.utilizationHoursChart.labels = [];
vm.utilizationHoursChart.data = [];
var utilizationData = [];
_.each(resultData, function (weekData) {
vm.utilizationHoursChart.labels.push(weekData.week);
var utilizationVal = (weekData.enterpriseBillableHours / weekData.weekBillableHours) * 100;
if (isNaN(utilizationVal)) {
utilizationVal = 0;
}
utilizationVal = parseInt(utilizationVal);
utilizationData.push(utilizationVal);
});
vm.utilizationHoursChart.data.push(utilizationData);
vm.utzOrganizationHeadCountChart.labels = [];
vm.utzOrganizationHeadCountChart.data = [];
var utilizationData = [];
_.each(resultData, function (weekData) {
vm.utzOrganizationHeadCountChart.labels.push(weekData.week);
var utilizationVal = (weekData.haveBillableProjectHeadCount / weekData.weekHeadCount) * 100;
if (isNaN(utilizationVal)) {
utilizationVal = 0;
}
utilizationVal = parseInt(utilizationVal);
utilizationData.push(utilizationVal);
});
vm.utzOrganizationHeadCountChart.data.push(utilizationData);
});
};
function savePushToken() {
UserService.updatePushToken(vm.user)
.then(function () {
//noty.showSuccess("Updated Successfully")
})
.catch(function (error) {
//FlashService.Error(error);
});
}
function savePushToken() {
UserService.updatePushToken(vm.user)
.then(function () {
//noty.showSuccess("Updated Successfully")
})
.catch(function (error) {
//FlashService.Error(error);
});
}
function getMyLeaveWalletBalnce() {
UserService.getMyLeaveWalletBalance().then(function (response) {
if (response) {
vm.leaveWalletBalance.accruedLeaves = parseFloat(response.accruedLeaves);
vm.leaveWalletBalance.creditedLeaves = parseFloat(response.creditedLeaves);
vm.leaveWalletBalance.deductedLOP = parseFloat(response.deductedLOP);
vm.leaveWalletBalance.leaveBalance = (vm.leaveWalletBalance.accruedLeaves + vm.leaveWalletBalance.creditedLeaves - vm.leaveWalletBalance.deductedLOP);
}
TimesheetService.userTakenLeaveBalance(vm.user._id).then(function (response) {
if (response) {
vm.leaveWalletBalance.timeoffHours = parseFloat(response.totalTimeoffHours);
vm.leaveWalletBalance.timeoffDays = parseFloat(response.totalTimeoffDays);
vm.leaveWalletBalance.leaveBalance = parseFloat(vm.leaveWalletBalance.accruedLeaves + vm.leaveWalletBalance.creditedLeaves - response.totalTimeoffDays - vm.leaveWalletBalance.deductedLOP).toFixed(2);
}
}).catch(function (error) { });
}).catch(function (error) {
//FlashService.Error(error);
});
}
function getMyInventory() {
UserService.getMyInventory().then(function (response) {
if (response.inventories) {
vm.inventories = response.inventories;
}
}).catch(function (error) {
//FlashService.Error(error);
});
}
var init = function () {
getUsers();
getProjectsWithUserCount();
UserService.GetCurrent().then(function (user) {
vm.user = user;
if (vm.user.admin) {
vm.getAllUserHoursByWeek();
vm.getAllUserHoursByMonth();
vm.utilizationByMonth();
}
getMyLeaveWalletBalnce();
getMyInventory();
if ($window && $window.pushToken && vm.user.pushToken != $window.pushToken) {
vm.user.pushToken = $window.pushToken;
savePushToken();
}
});
};
init();
}
function SidebarController(UserService) {
var vm = this;
vm.user = null;
UserService.GetCurrent().then(function (user) {
vm.user = user;
});
}
function AdminUsersController(UserService, $filter, ReportService, _, $scope, FlashService, NgTableParams) {
var vm = this;
vm.user = null;
vm.deleteUser = deleteUser;
vm.tableParams = new NgTableParams({
count: 100 // hides pager
}, {
});
function deleteUser(id) {
UserService.Delete(id).then(function (users) {
getAllUsers();
});
}
function getAllUsers(week) {
var Activeusers = [];
UserService.GetAll().then(function (users) {
for (var i = 0; i < users.length; i++) {
if (users[i].isActive === true) {
Activeusers.push(users[i]);
}
}
vm.users = Activeusers;
_.each(vm.users, function (userObj) {
if (!(userObj.profileImgUrl) || userObj.profileImgUrl == "") {
userObj.profileImgUrl = '/app/app-content/assets/user.jpg';
}
});
vm.tableParams.settings({
dataset: vm.users
});
});
};
vm.changeStatus = function (event) {
if (event == true) {
var Activeusers = [];
UserService.GetAll().then(function (users) {
for (var i = 0; i < users.length; i++) {
if (users[i].isActive === true) {
Activeusers.push(users[i]);
}
}
vm.users = Activeusers;
});
}
else {
var InActiveusers = [];
UserService.GetAll().then(function (users) {
for (var i = 0; i < users.length; i++) {
if (users[i].isActive === false) {
InActiveusers.push(users[i]);
}
}
vm.users = InActiveusers;
});
}
}
initController();
function initController() {
UserService.GetCurrent().then(function (user) {
vm.user = user;
getAllUsers();
if (vm.user.admin) {
vm.isAdmin = true;
} else {
vm.isAdmin = false;
}
});
}
}
function AllUsersController(UserService, _, $uibModal, $state, $window, $http, $timeout) {
var vm = this;
vm.user = null;
vm.users = [];
vm.search = {
userName: "",
practice: "All",
userResourceType: "",
userResourceStatus: "",
employeeCategory: "All",
isActive: 'true',
orderBy: 'name',
sortDESC: false
};
vm.practices = [];
vm.allPractices = [];
vm.userColumns = {
"name": { label: "Name", selected: true },
"practice": { label: "Practice", selected: true },
"userResourceType": { label: "Type", selected: true },
"phone": { label: "Mobile", selected: false },
"employeeId": { label: "Employee ID", selected: true },
"joinDate": { label: "Join Date", selected: true },
"employeeCategory": { label: "Category", selected: true },
"employeeType": { label: "Employee Type", selected: false },
"reportingTo": { label: "Reporting To", selected: false },
"isAdmin": { label: "Is Admin", selected: false },
"userRole": { label: "Role", selected: false },
"isActive": { label: "Status", selected: true }
};
vm.sorting = function (orderBy) {
if (vm.search.orderBy == orderBy) {
vm.search.sortDESC = !vm.search.sortDESC;
} else {
vm.search.sortDESC = false;
}
vm.search.orderBy = orderBy;
};
vm.deleteUser = function (id) {
UserService.Delete(id).then(function (users) {
getAllUsers();
});
}
function getAllUsers() {
UserService.GetAll().then(function (users) {
vm.users = users;
_.each(vm.users, function (userObj) {
if (!(userObj.profileImgUrl) || userObj.profileImgUrl == "") {
userObj.profileImgUrl = '/app/app-content/assets/user.jpg';
}
if (userObj.reportingTo) {
var reportUser = _.find(vm.users, { _id: userObj.reportingTo });
userObj.reportingUserName = reportUser.name;
}
});
});
}
vm.viewUser = function (user) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/editUser.html',
controller: 'Home.UserModelController',
controllerAs: 'vm',
size: 'lg',
resolve: {
user: function () {
return user;
},
practices: function () {
return vm.practices;
},
reportUsers: function () {
var reportUsers = [];
reportUsers.push({ id: null, name: "None" });
_.each(vm.users, function (userObj) {
if (userObj.isActive === true && user._id != userObj._id && userObj.userRole && userObj.userRole == "manager") {
reportUsers.push({ id: userObj._id, name: userObj.name });
}
});
return reportUsers;
}
}
});
modalInstance.result.then(function (userObj) {
getAllUsers();
}, function () {
getAllUsers();
});
}
vm.viewReleaseToPool = function (user) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/releaseToPool.html',
controller: 'Home.ReleaseUserModelController',
controllerAs: 'vm',
size: 'lg',
resolve: {
user: function () {
return user;
}
}
});
modalInstance.result.then(function (userObj) {
getAllUsers();
}, function () {
getAllUsers();
});
}
vm.viewReleaseFromPool = function (user) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/releaseFromPool.html',
controller: 'Home.ReleaseUserModelController',
controllerAs: 'vm',
size: 'lg',
resolve: {
user: function () {
return user;
}
}
});
modalInstance.result.then(function (userObj) {
getAllUsers();
}, function () {
getAllUsers();
});
}
vm.stopPropagation = function (e) {
e.stopPropagation();
}
vm.loginAsUser = function (userObj) {
console.log(userObj);
UserService.loginAsUser({ username: userObj.username }).then(function (data) {
if (data && data.token) {
$window.jwtToken = data.token;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;
$timeout(function () {
//$state.go('home');
console.log(window.location.origin);
window.location = window.location.origin + '/app/';
});
}
}, function (error) {
console.log(error);
noty.showError(error)
});
}
vm.getPractices = function () {
UserService.getPractices().then(function (response) {
vm.practices = response.practices;
vm.allPractices = angular.copy(response.practices);
vm.allPractices.unshift("All");
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
initController();
function initController() {
UserService.GetCurrent().then(function (user) {
vm.user = user;
getAllUsers();
if (vm.user.admin) {
vm.isAdmin = true;
} else {
vm.isAdmin = false;
}
vm.getPractices();
});
}
}
function SkillProfilesController(UserService, AppConfigService, _, $uibModal, $state, $window, $http, $timeout, noty) {
var vm = this;
vm.user = null;
vm.users = [];
vm.metaSkills = [];
vm.search = {
userName: "",
userResourceType: "",
userResourceStatus: "",
employeeCategory: "All",
isActive: 'true',
orderBy: 'name',
sortDESC: false
};
vm.userColumns = {
"name": { label: "Name", selected: true },
"userResourceType": { label: "Type", selected: true },
"isAdmin": { label: "Is Admin", selected: false },
"resourceStatus": { label: "Resource Status", selected: true },
"isActive": { label: "Status", selected: true }
};
vm.sorting = function (orderBy) {
if (vm.search.orderBy == orderBy) {
vm.search.sortDESC = !vm.search.sortDESC;
} else {
vm.search.sortDESC = false;
}
vm.search.orderBy = orderBy;
};
vm.viewUserSkillProfile = function (userObj, userSkillObj) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/editSkillProfile.html',
controller: 'Home.UpdateSkillProfileController',
controllerAs: 'vm',
size: 'lg',
resolve: {
metaSkills: function () {
return vm.metaSkills;
},
userObj: function () {
return userObj;
},
userSkillObj: function () {
return userSkillObj;
}
}
});
modalInstance.result.then(function (userObj) {
vm.getAllUserSkillProfiles();
}, function () {
vm.getAllUserSkillProfiles();
});
}
vm.delUserSkillProfile = function (userSkillObj) {
if (confirm("Do you want to delete this skill ?")) {
UserService.deleteUserSkill(userSkillObj._id).then(function (response) {
noty.showSuccess("User skill has been deleted successfully!");
vm.getAllUserSkillProfiles();
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
vm.getAllUserSkillProfiles();
});
}
}
vm.stopPropagation = function (e) {
e.stopPropagation();
}
vm.getAllUserSkillProfiles = function () {
UserService.getAllUserSkillProfiles().then(function (data) {
if (data.users) {
vm.users = data.users;
}
}, function (error) {
noty.showError(error)
});
}
vm.getMetaSkills = function () {
AppConfigService.getMetaSkills().then(function (data) {
if (data.metaSkills) {
vm.metaSkills = data.metaSkills;
vm.metaSkills.push({ skillName: "Other" });
}
}, function (errors) {
console.log(errors);
});
}
initController();
function initController() {
UserService.GetCurrent().then(function (user) {
vm.user = user;
if (vm.user.admin) {
vm.isAdmin = true;
} else {
vm.isAdmin = false;
$state.go('home');
}
vm.getAllUserSkillProfiles();
vm.getMetaSkills();
});
}
}
function UpdateSkillProfileController(UserService, userObj, metaSkills, userSkillObj, noty, $uibModalInstance) {
var vm = this;
vm.userObj = userObj;
vm.metaSkills = metaSkills;
vm.userSkillObj = {};
vm.alerts = [];
vm.closeAlert = function (index) {
vm.alerts.splice(index, 1);
}
vm.closeUser = function () {
$uibModalInstance.close();
}
vm.metaSkillLevels = ["Basic", "Intermediate", "Advanced", "Expert"];
if (userSkillObj) {
vm.userSkillObj = userSkillObj;
}
vm.saveUserSkillProfile = function (userForm) {
if (userForm.$valid) {
var userSkillObj = {
userId: vm.userObj._id,
skillName: vm.userSkillObj.skillName,
skillVersion: vm.userSkillObj.skillVersion,
skillLevel: vm.userSkillObj.skillLevel,
};
if (vm.userSkillObj._id) {
UserService.updateUserSkill(vm.userSkillObj._id, userSkillObj).then(function (response) {
noty.showSuccess("User skill has been updated successfully!");
$uibModalInstance.close();
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
} else {
UserService.addUserSkill(userSkillObj).then(function (response) {
noty.showSuccess("User skill has been added successfully!");
$uibModalInstance.close();
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
}
}
init();
function init() {
}
}
function UserModelController(UserService, $filter, noty, $uibModalInstance, user, reportUsers, practices) {
var vm = this;
vm.userObj = user;
vm.alerts = [];
vm.userRoles = [];
vm.reportUsers = reportUsers;
vm.enableSaveBtn = true;
vm.closeAlert = function (index) {
vm.alerts.splice(index, 1);
}
vm.joinDateOpened = false;
vm.dateOptions = {
formatYear: 'yy',
maxDate: new Date(2030, 12, 31),
startingDay: 1
};
vm.employeeTypes = [
{ id: "InternalEmployee", label: "Internal Employee" },
{ id: "InternalContractor", label: "Internal Contractor" },
{ id: "ExternalContractor", label: "External Contractor" }
]
vm.practices = practices;
if (vm.userObj.joinDate) {
vm.userObj.joinDate = new Date(vm.userObj.joinDate);
}
vm.saveUser = function (userForm) {
if (userForm.$valid) {
var obj = {
"name": vm.userObj.name,
"phone": vm.userObj.phone,
"username": vm.userObj.username,
"employeeId": vm.userObj.employeeId,
"joinDate": $filter('date')(vm.userObj.joinDate, "yyyy-MM-dd"),
"designation": vm.userObj.designation,
"userResourceType": vm.userObj.userResourceType,
"employeeType": vm.userObj.employeeType,
"userRole": vm.userObj.userRole,
"reportingTo": vm.userObj.reportingTo,
"employeeCategory": vm.userObj.employeeCategory,
"skillCategory": vm.userObj.skillCategory,
"practice": vm.userObj.practice,
"profileImgUrl": vm.userObj.profileImgUrl,
"isActive": vm.userObj.isActive
}
UserService.UpdateEmployeeInfo(vm.userObj._id, obj).then(function (response) {
noty.showSuccess("User has been updated successfully!");
$uibModalInstance.close();
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
}
vm.employeeCategories = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10"];
vm.closeUser = function () {
$uibModalInstance.close();
}
vm.getPractices = function () {
UserService.getPractices().then(function (response) {
vm.practices = response.practices;
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
init();
function init() {
vm.userRoles = UserService.getUserRoles();
}
}
function ReleaseUserModelController(UserService, $filter, noty, $uibModalInstance, user) {
var vm = this;
vm.userObj = user;
vm.alerts = [];
vm.dateOptions = {
formatYear: 'yy',
maxDate: new Date(2030, 12, 31),
startingDay: 1
};
vm.sinceDateOpened = false;
vm.closeAlert = function (index) {
vm.alerts.splice(index, 1);
}
vm.toPool = function (userForm) {
if (userForm.$valid) {
var obj = {
"resourceInPool": true,
"poolSinceDate": vm.userObj.poolSinceDate,
"poolName": vm.userObj.poolName
}
UserService.releaseToPool(vm.userObj._id, obj).then(function (response) {
noty.showSuccess("User has been release to pool successfully!");
$uibModalInstance.close();
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
}
vm.fromPool = function (userForm) {
UserService.releaseFromPool(vm.userObj._id).then(function (response) {
noty.showSuccess("User has been release from pool successfully!");
$uibModalInstance.close();
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
vm.closeUser = function () {
$uibModalInstance.close();
}
init();
function init() {
}
}
function AdminController(UserService, $filter, ReportService, $state, $stateParams) {
var vm = this;
var currentDay = new Date().getDay();
vm.closeAlert = closeAlert;
vm.obj = {
week: new Date()
};
switch (currentDay) {
case 0:
vm.obj.week.setDate(vm.obj.week.getDate() + 5);
case 1:
vm.obj.week.setDate(vm.obj.week.getDate() + 4);
break;
case 2:
vm.obj.week.setDate(vm.obj.week.getDate() + 3);
break;
case 3:
vm.obj.week.setDate(vm.obj.week.getDate() + 2);
break;
case 4:
vm.obj.week.setDate(vm.obj.week.getDate() + 1);
break;
case 6:
vm.obj.week.setDate(vm.obj.week.getDate() - 1);
break;
case 7:
vm.obj.week.setDate(vm.obj.week.getDate() - 2);
break;
}
vm.post = post;
vm.open2 = open2;
vm.popup2 = {
opened: false
};
vm.dateOptions = {
dateDisabled: disabled,
formatYear: 'yy',
maxDate: new Date(2030, 12, 31),
startingDay: 1
};
function disabled(data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() != 5);
}
function open2() {
vm.popup2.opened = true;
};
vm.itemArray = [
{ id: 1, name: 'Care' },
{ id: 2, name: 'Care Intl' },
{ id: 3, name: 'Tapclicks' },
{ id: 4, name: 'SavingStar' },
{ id: 5, name: 'BlueSky' },
{ id: 6, name: 'Upromise' },
{ id: 7, name: 'Coding Labs' },
{ id: 8, name: 'Hariome' },
{ id: 9, name: 'OT' }
];
vm.alerts = [];
function closeAlert(index) {
vm.alerts.splice(index, 1);
};
function getSheet(id) {
ReportService.Get(id).then(function (response) {
if (response.project) {
var projects = response.project.split(',');
vm.obj.selected = [];
for (var i = 0, len = vm.itemArray.length; i < len; i++) {
for (var j = 0, size = projects.length; j < size; j++) {
if (projects[j] == vm.itemArray[i].name) {
vm.obj.selected.push(vm.itemArray[i]);
}
}
}
}
vm.obj.hours = response.hours;
vm.obj.comments = response.comments;
vm.obj.week = new Date(response.cDate);
});
}
function post(form) {
var projects = [];
for (var i = 0, len = vm.obj.selected.length; i < len; i++) {
projects.push(vm.obj.selected[i].name);
}
if (form.$valid && projects.length) {
var obj = {
"week": $filter('date')(vm.obj.week, "yyyy-Www").toString(),
"hours": vm.obj.hours,
"comments": vm.obj.comments,
"cDate": vm.obj.week
}
obj.project = projects.toString();
if (vm.isNew) {
ReportService.Create(obj).then(function (response) {
vm.alerts.push({ msg: "Thank you for the update", type: 'success' });
$state.go('home');
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
} else {
ReportService.adminUpdate($stateParams.id, obj).then(function (response) {
vm.alerts.push({ msg: "Updated Successfully", type: 'success' });
$state.go('home');
}, function (error) {
if (error) {
vm.alerts.push({ msg: error, type: 'danger' });
}
});
}
} else {
vm.alerts.push({ msg: "Please fill the required fields", type: 'danger' });
}
}
initController();
function initController() {
if ($stateParams.id) {
vm.isNew = false;
getSheet($stateParams.id);
} else {
vm.isNew = true;
}
}
}
function UserInfoController(UserService, $stateParams, $state, _, noty, ProjectService) {
var vm = this;
vm.updateUser = updateUser;
vm.addProject = addProject;
vm.deleteProject = deleteProject;
vm.updateBilling = updateBilling;
vm.addDate = addDate;
vm.deleteDate = deleteDate;
vm.open2 = open2;
vm.popup2 = {
opened: false
};
vm.dateOptions = {
formatYear: 'yy',
maxDate: new Date(2025, 5, 22),
startingDay: 1
};
function open2(project, text) {
if (text) {
project[text] = true;
} else {
project.opened = true;
}
};
function getEmployeeInfo() {
UserService.GetEmployeeInfo($stateParams.id).then(function (employee) {
vm.employee = employee;
if (!vm.employee.project) {
vm.employee.project = [];
} else {
_.each(vm.employee.project, function (item) {
item.opened = false;
item.startDate = new Date(item.startDate);
if (!item.date) {
item.date = [];
} else {
_.each(item.date, function (dates) {
dates.startOpened = false;
dates.endOpened = false;
if (dates.start)
dates.start = new Date(dates.start);
if (dates.end)
dates.end = new Date(dates.end);
});
}
});
_.each(vm.projects, function (project) {
_.each(vm.employee.project, function (item) {
if (item._id == project._id) {
item.clientName = project;
}
});
});
}
})
};
function getAllProjects() {
ProjectService.getAll().then(function (projects) {
vm.projects = projects;
getEmployeeInfo();
}, function (error) {
console.log("Error loading projects");
})
}
function addProject() {
if (!vm.employee.project) {
vm.employee.project = [];
} else {
vm.employee.project.push({
"startDate": new Date()
});
}
}
function deleteProject(index) {
vm.employee.project.splice(index, 1);
}
function addDate(project) {
if (!project.date) {
project.date = [{}];
} else {
project.date.push({});
}
}
function deleteDate(project, index) {
project.date.splice(index, 1);
}
function updateBilling(project) {
if (project.isBillable) {
if (!project.date) {
project.date = [{}];
} else
project.date.push({});
} else {
project.date = [];
}
}
function updateUser(userForm) {
if (userForm.$valid) {
_.each(vm.employee.project, function (project) {
delete project.opened;
_.each(project.date, function (item) {
delete item.startOpened;
delete item.endOpened;
});
});
var obj = {
"name": vm.employee.name,
"phone": vm.employee.phone,
"username": vm.employee.username,
"employeeId": vm.employee.employeeId,
"designation": vm.employee.designation,
"userResourceType": vm.employee.userResourceType,
"isActive": vm.employee.isActive
}
var projectObj = [];
_.each(vm.employee.project, function (project) {
projectObj.push({
"_id": project.clientName._id,
"projectName": project.projectName,
"clientName": project.clientName.clientName,
"startDate": project.startDate,
"date": project.date,
"isBillable": project.isBillable
});
});
obj.project = projectObj;
UserService.UpdateEmployeeInfo($stateParams.id, obj).then(function (employee) {
noty.showSuccess("Employee updated Successfully");
$state.go('users');
}, function (error) {
noty.showError("Something went wrong!");
});
} else {
noty.showError("Please fill in the required fields");
}
}
function init() {
UserService.GetCurrent().then(function (user) {
vm.user = user;
if (vm.user.admin && $stateParams.id) {
vm.isAdmin = true;
getAllProjects();
} else {
vm.isAdmin = false;
$state.go('home');
}
});
}
init();
}
function PoolUsersController(UserService, _, $uibModal) {
var vm = this;
vm.showAllUsers = false;
vm.users = [];
vm.search = {
userName: "",
userResourceType: "",
isActive: "",
poolSinceDays: "",
orderBy: 'name',
sortDESC: false
};
vm.sorting = function (orderBy) {
if (vm.search.orderBy == orderBy) {
vm.search.sortDESC = !vm.search.sortDESC;
} else {
vm.search.sortDESC = false;
}
vm.search.orderBy = orderBy;
};
vm.getAllUsers = function () {
vm.users = [];
UserService.GetAll().then(function (users) {
_.each(users, function (userObj) {
if (userObj.isActive == true) {
if (vm.showAllUsers === true) {
userObj.poolSince = vm.calWeeksSinceNow(userObj.poolSinceDate);
userObj.poolSinceDays = vm.calDaysSinceNow(userObj.poolSinceDate);
vm.users.push(userObj);
} else if (vm.showAllUsers === false && userObj.resourceInPool === true) {
userObj.poolSince = vm.calWeeksSinceNow(userObj.poolSinceDate);
userObj.poolSinceDays = vm.calDaysSinceNow(userObj.poolSinceDate);
vm.users.push(userObj);
}
}
if (!(userObj.profileImgUrl) || userObj.profileImgUrl == "") {
userObj.profileImgUrl = '/app/app-content/assets/user.jpg';
}
});
});
}
vm.viewUserPoolLog = function (user) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/userPoolLogs.html',
controller: 'Home.PoolLogsController',
controllerAs: 'vm',
size: 'lg',
resolve: {
user: function () {
return user;
}
}
});
modalInstance.result.then(function (userObj) {
}, function () {
});
}
vm.viewReleaseToPool = function (user) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/releaseToPool.html',
controller: 'Home.ReleaseUserModelController',
controllerAs: 'vm',
size: 'lg',
resolve: {
user: function () {
return user;
}
}
});
modalInstance.result.then(function (userObj) {
vm.getAllUsers();
}, function () {
vm.getAllUsers();
});
}
vm.viewReleaseFromPool = function (user) {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'home/releaseFromPool.html',
controller: 'Home.ReleaseUserModelController',
controllerAs: 'vm',
size: 'lg',
resolve: {
user: function () {
return user;
}
}
});
modalInstance.result.then(function (userObj) {
vm.getAllUsers();
}, function () {
vm.getAllUsers();
});
}
vm.calWeeksSinceNow = function (sinceDate) {
if (sinceDate && sinceDate.length > 0) {
var oneDay = 24 * 60 * 60 * 1000;
var oneWeek = 7 * 24 * 60 * 60 * 1000;
var now = new Date();
var sinceDate = new Date(sinceDate);
var diff = parseInt((now - sinceDate) / oneWeek);
return diff + " Weeks";
} else {
return "";
}
}
vm.calDaysSinceNow = function (sinceDate) {
if (sinceDate && sinceDate.length > 0) {
var oneDay = 24 * 60 * 60 * 1000;
var oneWeek = 7 * 24 * 60 * 60 * 1000;
var now = new Date();
var sinceDate = new Date(sinceDate);
var diff = parseInt((now - sinceDate) / oneDay);
return diff;
} else {
return 0;
}
}
initController();
function initController() {
UserService.GetCurrent().then(function (user) {
vm.user = user;
if (vm.user.admin) {
vm.isAdmin = true;
} else {
vm.isAdmin = false;
}
vm.getAllUsers();
});
}
}
function PoolLogsController(UserService, _, $uibModalInstance, user) {
var vm = this;
vm.user = user;
vm.logs = [];
function getUserPoolLogs(userId) {
vm.logs = [];
UserService.userPoolLogs(vm.user._id).then(function (logs) {
vm.logs = logs;
});
}
vm.close = function () {
$uibModalInstance.close();
}
vm.calWeeksSinceEnd = function (sinceDate, endDate) {
if (sinceDate && sinceDate.length > 0) {
var oneDay = 24 * 60 * 60 * 1000;
var oneWeek = 7 * 24 * 60 * 60 * 1000;
var now = new Date();
var sinceDate = new Date(sinceDate);
var diff = parseInt((now - sinceDate) / oneWeek);
return diff + " Weeks";
} else {
return "";
}
}
initController();
function initController() {
getUserPoolLogs(vm.user._id);
}
}
})(); |
import { dispatch as d3_dispatch } from 'd3-dispatch';
import { select as d3_select } from 'd3-selection';
import { services } from '../../services';
import { t } from '../../util/locale';
import {
utilGetSetValue,
utilNoAuto,
utilRebind
} from '../../util';
export function uiFieldTextarea(field) {
var dispatch = d3_dispatch('change');
var input = d3_select(null);
function textarea(selection) {
var wrap = selection.selectAll('.form-field-input-wrap')
.data([0]);
wrap = wrap.enter()
.append('div')
.attr('class', 'form-field-input-wrap form-field-input-' + field.type)
.merge(wrap);
input = wrap.selectAll('textarea')
.data([0]);
input = input.enter()
.append('textarea')
.attr('id', 'preset-input-' + field.safeid)
.attr('placeholder', field.placeholder() || t('inspector.unknown'))
.attr('maxlength', services.osm.maxCharsForTagValue())
.call(utilNoAuto)
.on('input', change(true))
.on('blur', change())
.on('change', change())
.merge(input);
}
function change(onInput) {
return function() {
var t = {};
t[field.key] = utilGetSetValue(input) || undefined;
dispatch.call('change', this, t, onInput);
};
}
textarea.tags = function(tags) {
utilGetSetValue(input, tags[field.key] || '');
};
textarea.focus = function() {
input.node().focus();
};
return utilRebind(textarea, dispatch, 'on');
}
|
import vsComponent from './vsNavbar';
import vsComponent2 from './vsNavItem';
import vsComponent3 from './vsNavGroup';
import vsComponent4 from './vsNavbarTitle';
import vsComponent5 from './vsNavbarItems';
export default Vue => {
Vue.component(vsComponent.name, vsComponent);
Vue.component(vsComponent2.name, vsComponent2);
Vue.component(vsComponent3.name, vsComponent3);
Vue.component(vsComponent4.name, vsComponent4);
Vue.component(vsComponent5.name, vsComponent5);
};
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AssetReverseDetail(object):
def __init__(self):
self._amount = None
self._assign_item_id = None
self._batch_no = None
self._goods_status = None
self._success = None
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
self._amount = value
@property
def assign_item_id(self):
return self._assign_item_id
@assign_item_id.setter
def assign_item_id(self, value):
self._assign_item_id = value
@property
def batch_no(self):
return self._batch_no
@batch_no.setter
def batch_no(self, value):
self._batch_no = value
@property
def goods_status(self):
return self._goods_status
@goods_status.setter
def goods_status(self, value):
self._goods_status = value
@property
def success(self):
return self._success
@success.setter
def success(self, value):
self._success = value
def to_alipay_dict(self):
params = dict()
if self.amount:
if hasattr(self.amount, 'to_alipay_dict'):
params['amount'] = self.amount.to_alipay_dict()
else:
params['amount'] = self.amount
if self.assign_item_id:
if hasattr(self.assign_item_id, 'to_alipay_dict'):
params['assign_item_id'] = self.assign_item_id.to_alipay_dict()
else:
params['assign_item_id'] = self.assign_item_id
if self.batch_no:
if hasattr(self.batch_no, 'to_alipay_dict'):
params['batch_no'] = self.batch_no.to_alipay_dict()
else:
params['batch_no'] = self.batch_no
if self.goods_status:
if hasattr(self.goods_status, 'to_alipay_dict'):
params['goods_status'] = self.goods_status.to_alipay_dict()
else:
params['goods_status'] = self.goods_status
if self.success:
if hasattr(self.success, 'to_alipay_dict'):
params['success'] = self.success.to_alipay_dict()
else:
params['success'] = self.success
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AssetReverseDetail()
if 'amount' in d:
o.amount = d['amount']
if 'assign_item_id' in d:
o.assign_item_id = d['assign_item_id']
if 'batch_no' in d:
o.batch_no = d['batch_no']
if 'goods_status' in d:
o.goods_status = d['goods_status']
if 'success' in d:
o.success = d['success']
return o
|
import matplotlib.pyplot as plt
import numpy as np
import xlrd
def readdata():
with xlrd.open_workbook('data.xlsx') as workbook :
table = workbook.sheet_by_name('Sheet1')
x1 = table.col_values(0)[1:]
x2 = table.col_values(1)[1:]
label = table.col_values(2)[1:]
return x1,x2,label
x1,x2,label = readdata()
# X:(14,3) W:(3,1) Y,LABEL:(14,1),d(COST)/d(W):(3,1)
# Z = X*W
# Y = 1 / (e^(-Z) + 1)
# COST = (LABEL-1)*log(1-Y) - LABEL*log(Y)
# d(COST) / d(W) = X.T * (Y - LABEL)
X = np.array([[1]*len(x1),x1,x2]).T
W = np.random.rand(3,1)
LABEL = np.array([label]).T
tmp= []
for epoch in range(10000):
Z = np.dot(X,W)
Y = 1 / (np.exp(-1*Z)+1)
W -= 0.001*np.dot(X.T,(Y-LABEL))
if (epoch+1) % 100 == 0:
tmp.append([W.copy(),epoch])
print(W)
#w0 + w1*x1 + w2*x2 = 0 >>> x2 = -w1/w2 * x1 - w0/w2
for Wi in tmp:
plt.clf()
w0 = Wi[0][0,0]
w1 = Wi[0][1,0]
w2 = Wi[0][2,0]
print(w0,w1,w2)
x1 = np.arange(0,7,1)
x2 = -1*x1*w1/w2 - w0/w2
plt.plot(x1,x2,c='r',label='decision boundary')
plt.scatter(np.mat(X)[:,1][np.mat(LABEL)==0].A,np.mat(X)[:,2][np.mat(LABEL)==0].A,s=50,label='label 0')
plt.scatter(np.mat(X)[:,1][np.mat(LABEL)==1].A,np.mat(X)[:,2][np.mat(LABEL)==1].A,s=50,label='label 1',marker='^')
plt.xlabel('x1',size=20)
plt.ylabel('x2',size=20)
plt.legend()
plt.grid()
plt.title('iter:%s' % str(Wi[1]))
plt.pause(0.01)
plt.show()
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
"use strict";
var core_1 = require('@angular/core');
var async_1 = require('../../facade/async');
var collection_1 = require('../../facade/collection');
var exceptions_1 = require('../../facade/exceptions');
var PostMessageBusSink = (function () {
function PostMessageBusSink(_postMessageTarget) {
this._postMessageTarget = _postMessageTarget;
this._channels = collection_1.StringMapWrapper.create();
this._messageBuffer = [];
}
PostMessageBusSink.prototype.attachToZone = function (zone) {
var _this = this;
this._zone = zone;
this._zone.runOutsideAngular(function () { _this._zone.onStable.subscribe({ next: function () { _this._handleOnEventDone(); } }); });
};
PostMessageBusSink.prototype.initChannel = function (channel, runInZone) {
var _this = this;
if (runInZone === void 0) { runInZone = true; }
if (collection_1.StringMapWrapper.contains(this._channels, channel)) {
throw new exceptions_1.BaseException(channel + " has already been initialized");
}
var emitter = new async_1.EventEmitter(false);
var channelInfo = new _Channel(emitter, runInZone);
this._channels[channel] = channelInfo;
emitter.subscribe(function (data) {
var message = { channel: channel, message: data };
if (runInZone) {
_this._messageBuffer.push(message);
}
else {
_this._sendMessages([message]);
}
});
};
PostMessageBusSink.prototype.to = function (channel) {
if (collection_1.StringMapWrapper.contains(this._channels, channel)) {
return this._channels[channel].emitter;
}
else {
throw new exceptions_1.BaseException(channel + " is not set up. Did you forget to call initChannel?");
}
};
PostMessageBusSink.prototype._handleOnEventDone = function () {
if (this._messageBuffer.length > 0) {
this._sendMessages(this._messageBuffer);
this._messageBuffer = [];
}
};
PostMessageBusSink.prototype._sendMessages = function (messages) { this._postMessageTarget.postMessage(messages); };
return PostMessageBusSink;
}());
exports.PostMessageBusSink = PostMessageBusSink;
var PostMessageBusSource = (function () {
function PostMessageBusSource(eventTarget) {
var _this = this;
this._channels = collection_1.StringMapWrapper.create();
if (eventTarget) {
eventTarget.addEventListener('message', function (ev) { return _this._handleMessages(ev); });
}
else {
// if no eventTarget is given we assume we're in a WebWorker and listen on the global scope
var workerScope = self;
workerScope.addEventListener('message', function (ev) { return _this._handleMessages(ev); });
}
}
PostMessageBusSource.prototype.attachToZone = function (zone) { this._zone = zone; };
PostMessageBusSource.prototype.initChannel = function (channel, runInZone) {
if (runInZone === void 0) { runInZone = true; }
if (collection_1.StringMapWrapper.contains(this._channels, channel)) {
throw new exceptions_1.BaseException(channel + " has already been initialized");
}
var emitter = new async_1.EventEmitter(false);
var channelInfo = new _Channel(emitter, runInZone);
this._channels[channel] = channelInfo;
};
PostMessageBusSource.prototype.from = function (channel) {
if (collection_1.StringMapWrapper.contains(this._channels, channel)) {
return this._channels[channel].emitter;
}
else {
throw new exceptions_1.BaseException(channel + " is not set up. Did you forget to call initChannel?");
}
};
PostMessageBusSource.prototype._handleMessages = function (ev) {
var messages = ev.data;
for (var i = 0; i < messages.length; i++) {
this._handleMessage(messages[i]);
}
};
PostMessageBusSource.prototype._handleMessage = function (data) {
var channel = data.channel;
if (collection_1.StringMapWrapper.contains(this._channels, channel)) {
var channelInfo = this._channels[channel];
if (channelInfo.runInZone) {
this._zone.run(function () { channelInfo.emitter.emit(data.message); });
}
else {
channelInfo.emitter.emit(data.message);
}
}
};
return PostMessageBusSource;
}());
exports.PostMessageBusSource = PostMessageBusSource;
var PostMessageBus = (function () {
function PostMessageBus(sink, source) {
this.sink = sink;
this.source = source;
}
PostMessageBus.prototype.attachToZone = function (zone) {
this.source.attachToZone(zone);
this.sink.attachToZone(zone);
};
PostMessageBus.prototype.initChannel = function (channel, runInZone) {
if (runInZone === void 0) { runInZone = true; }
this.source.initChannel(channel, runInZone);
this.sink.initChannel(channel, runInZone);
};
PostMessageBus.prototype.from = function (channel) { return this.source.from(channel); };
PostMessageBus.prototype.to = function (channel) { return this.sink.to(channel); };
/** @nocollapse */
PostMessageBus.decorators = [
{ type: core_1.Injectable },
];
/** @nocollapse */
PostMessageBus.ctorParameters = [
{ type: PostMessageBusSink, },
{ type: PostMessageBusSource, },
];
return PostMessageBus;
}());
exports.PostMessageBus = PostMessageBus;
/**
* Helper class that wraps a channel's {@link EventEmitter} and
* keeps track of if it should run in the zone.
*/
var _Channel = (function () {
function _Channel(emitter, runInZone) {
this.emitter = emitter;
this.runInZone = runInZone;
}
return _Channel;
}());
//# sourceMappingURL=post_message_bus.js.map |
"""Test RainMachine diagnostics."""
from homeassistant.components.diagnostics import REDACTED
from tests.components.diagnostics import get_diagnostics_for_config_entry
async def test_entry_diagnostics(hass, config_entry, hass_client, setup_rainmachine):
"""Test config entry diagnostics."""
assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == {
"entry": {
"title": "Mock Title",
"data": {
"ip_address": "192.168.1.100",
"password": REDACTED,
"port": 8080,
"ssl": True,
},
"options": {},
},
"data": {
"coordinator": {
"programs": [
{
"uid": 1,
"name": "Morning",
"active": True,
"startTime": "06:00",
"cycles": 0,
"soak": 0,
"cs_on": False,
"delay": 0,
"delay_on": False,
"status": 0,
"startTimeParams": {
"offsetSign": 0,
"type": 0,
"offsetMinutes": 0,
},
"frequency": {"type": 0, "param": "0"},
"coef": 0,
"ignoreInternetWeather": False,
"futureField1": 0,
"freq_modified": 0,
"useWaterSense": False,
"nextRun": "2018-06-04",
"startDate": "2018-04-28",
"endDate": None,
"yearlyRecurring": True,
"simulationExpired": False,
"wateringTimes": [
{
"id": 1,
"order": -1,
"name": "Landscaping",
"duration": 0,
"active": True,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 2,
"order": -1,
"name": "Flower Box",
"duration": 0,
"active": True,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 3,
"order": -1,
"name": "TEST",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 4,
"order": -1,
"name": "Zone 4",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 5,
"order": -1,
"name": "Zone 5",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 6,
"order": -1,
"name": "Zone 6",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 7,
"order": -1,
"name": "Zone 7",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 8,
"order": -1,
"name": "Zone 8",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 9,
"order": -1,
"name": "Zone 9",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 10,
"order": -1,
"name": "Zone 10",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 11,
"order": -1,
"name": "Zone 11",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 12,
"order": -1,
"name": "Zone 12",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
],
},
{
"uid": 2,
"name": "Evening",
"active": False,
"startTime": "06:00",
"cycles": 0,
"soak": 0,
"cs_on": False,
"delay": 0,
"delay_on": False,
"status": 0,
"startTimeParams": {
"offsetSign": 0,
"type": 0,
"offsetMinutes": 0,
},
"frequency": {"type": 0, "param": "0"},
"coef": 0,
"ignoreInternetWeather": False,
"futureField1": 0,
"freq_modified": 0,
"useWaterSense": False,
"nextRun": "2018-06-04",
"startDate": "2018-04-28",
"endDate": None,
"yearlyRecurring": True,
"simulationExpired": False,
"wateringTimes": [
{
"id": 1,
"order": -1,
"name": "Landscaping",
"duration": 0,
"active": True,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 2,
"order": -1,
"name": "Flower Box",
"duration": 0,
"active": True,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 3,
"order": -1,
"name": "TEST",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 4,
"order": -1,
"name": "Zone 4",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 5,
"order": -1,
"name": "Zone 5",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 6,
"order": -1,
"name": "Zone 6",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 7,
"order": -1,
"name": "Zone 7",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 8,
"order": -1,
"name": "Zone 8",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 9,
"order": -1,
"name": "Zone 9",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 10,
"order": -1,
"name": "Zone 10",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 11,
"order": -1,
"name": "Zone 11",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
{
"id": 12,
"order": -1,
"name": "Zone 12",
"duration": 0,
"active": False,
"userPercentage": 1,
"minRuntimeCoef": 1,
},
],
},
],
"provision.settings": {
"system": {
"httpEnabled": True,
"rainSensorSnoozeDuration": 0,
"uiUnitsMetric": False,
"programZonesShowInactive": False,
"programSingleSchedule": False,
"standaloneMode": False,
"masterValveAfter": 0,
"touchSleepTimeout": 10,
"selfTest": False,
"useSoftwareRainSensor": False,
"defaultZoneWateringDuration": 300,
"maxLEDBrightness": 40,
"simulatorHistorySize": 0,
"vibration": False,
"masterValveBefore": 0,
"touchProgramToRun": None,
"useRainSensor": False,
"wizardHasRun": True,
"waterLogHistorySize": 365,
"netName": "Home",
"softwareRainSensorMinQPF": 5,
"touchAdvanced": False,
"useBonjourService": True,
"hardwareVersion": 3,
"touchLongPressTimeout": 3,
"showRestrictionsOnLed": False,
"parserDataSizeInDays": 6,
"programListShowInactive": True,
"parserHistorySize": 365,
"allowAlexaDiscovery": False,
"automaticUpdates": True,
"minLEDBrightness": 0,
"minWateringDurationThreshold": 0,
"localValveCount": 12,
"touchAuthAPSeconds": 60,
"useCommandLineArguments": False,
"databasePath": "/rainmachine-app/DB/Default",
"touchCyclePrograms": True,
"zoneListShowInactive": True,
"rainSensorRainStart": None,
"zoneDuration": [
300,
300,
300,
300,
300,
300,
300,
300,
300,
300,
300,
300,
],
"rainSensorIsNormallyClosed": True,
"useCorrectionForPast": True,
"useMasterValve": False,
"runParsersBeforePrograms": True,
"maxWateringCoef": 2,
"mixerHistorySize": 365,
},
"location": {
"elevation": 1593.45141602,
"doyDownloaded": True,
"zip": None,
"windSensitivity": 0.5,
"krs": 0.16,
"stationID": 9172,
"stationSource": "station",
"et0Average": 6.578,
"latitude": REDACTED,
"state": "Default",
"stationName": "MY STATION",
"wsDays": 2,
"stationDownloaded": True,
"address": "Default",
"rainSensitivity": 0.8,
"timezone": "America/Los Angeles",
"longitude": REDACTED,
"name": "Home",
},
},
"restrictions.current": {
"hourly": False,
"freeze": False,
"month": False,
"weekDay": False,
"rainDelay": False,
"rainDelayCounter": -1,
"rainSensor": False,
},
"restrictions.universal": {
"hotDaysExtraWatering": False,
"freezeProtectEnabled": True,
"freezeProtectTemp": 2,
"noWaterInWeekDays": "0000000",
"noWaterInMonths": "000000000000",
"rainDelayStartTime": 1524854551,
"rainDelayDuration": 0,
},
"zones": [
{
"uid": 1,
"name": "Landscaping",
"state": 0,
"active": True,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 4,
"master": False,
"waterSense": False,
},
{
"uid": 2,
"name": "Flower Box",
"state": 0,
"active": True,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 5,
"master": False,
"waterSense": False,
},
{
"uid": 3,
"name": "TEST",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 9,
"master": False,
"waterSense": False,
},
{
"uid": 4,
"name": "Zone 4",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 5,
"name": "Zone 5",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 6,
"name": "Zone 6",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 7,
"name": "Zone 7",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 8,
"name": "Zone 8",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 9,
"name": "Zone 9",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 10,
"name": "Zone 10",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 11,
"name": "Zone 11",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
{
"uid": 12,
"name": "Zone 12",
"state": 0,
"active": False,
"userDuration": 0,
"machineDuration": 0,
"remaining": 0,
"cycle": 0,
"noOfCycles": 0,
"restriction": False,
"type": 2,
"master": False,
"waterSense": False,
},
],
},
"controller": {
"api_version": "4.5.0",
"hardware_version": 3,
"name": "My RainMachine",
"software_version": "4.0.925",
},
},
}
|
$(document).ready(function() {
$('#normal').resizable({
handleSelector: '.splitter',
resizeHeight: false
});
var input = $('#text');
input.val('Suzy has had a bad day. Luckily, Sarah was there to hug Suzy! I am glad Suzy has such a good friend.');
input.focus();
input.prop('selectionStart', input.val().length);
input.prop('selectionEnd', input.val().length);
updateManager = new UpdateManager(input);
updateManager.startUpdating(false);
setTimeout(updateManager.startUpdating, 1700);
$('#normal').animate({
width: '60%'
}, 2000, function() {
updateManager.experiment.fit();
});
});
|
// prefer default export if available
const preferDefault = m => m && m.default || m
exports.components = {
"component---src-pages-404-js": require("gatsby-module-loader?name=component---src-pages-404-js!/Users/ankur/work/wbfilms/src/pages/404.js"),
"component---src-pages-about-js": require("gatsby-module-loader?name=component---src-pages-about-js!/Users/ankur/work/wbfilms/src/pages/about.js"),
"component---src-pages-film-chippa-js": require("gatsby-module-loader?name=component---src-pages-film-chippa-js!/Users/ankur/work/wbfilms/src/pages/film/chippa.js"),
"component---src-pages-film-chuskit-js": require("gatsby-module-loader?name=component---src-pages-film-chuskit-js!/Users/ankur/work/wbfilms/src/pages/film/chuskit.js"),
"component---src-pages-film-sap-js": require("gatsby-module-loader?name=component---src-pages-film-sap-js!/Users/ankur/work/wbfilms/src/pages/film/sap.js"),
"component---src-pages-film-zollywood-js": require("gatsby-module-loader?name=component---src-pages-film-zollywood-js!/Users/ankur/work/wbfilms/src/pages/film/zollywood.js"),
"component---src-pages-index-js": require("gatsby-module-loader?name=component---src-pages-index-js!/Users/ankur/work/wbfilms/src/pages/index.js"),
"component---src-pages-page-2-js": require("gatsby-module-loader?name=component---src-pages-page-2-js!/Users/ankur/work/wbfilms/src/pages/page-2.js"),
"component---src-pages-privacy-policy-js": require("gatsby-module-loader?name=component---src-pages-privacy-policy-js!/Users/ankur/work/wbfilms/src/pages/privacy-policy.js"),
"component---src-pages-submit-js": require("gatsby-module-loader?name=component---src-pages-submit-js!/Users/ankur/work/wbfilms/src/pages/submit.js")
}
exports.json = {
"layout-index.json": require("gatsby-module-loader?name=path---!/Users/ankur/work/wbfilms/.cache/json/layout-index.json"),
"404.json": require("gatsby-module-loader?name=path---404!/Users/ankur/work/wbfilms/.cache/json/404.json"),
"about.json": require("gatsby-module-loader?name=path---about!/Users/ankur/work/wbfilms/.cache/json/about.json"),
"film-chippa.json": require("gatsby-module-loader?name=path---film-chippa!/Users/ankur/work/wbfilms/.cache/json/film-chippa.json"),
"film-chuskit.json": require("gatsby-module-loader?name=path---film-chuskit!/Users/ankur/work/wbfilms/.cache/json/film-chuskit.json"),
"film-sap.json": require("gatsby-module-loader?name=path---film-sap!/Users/ankur/work/wbfilms/.cache/json/film-sap.json"),
"film-zollywood.json": require("gatsby-module-loader?name=path---film-zollywood!/Users/ankur/work/wbfilms/.cache/json/film-zollywood.json"),
"index.json": require("gatsby-module-loader?name=path---index!/Users/ankur/work/wbfilms/.cache/json/index.json"),
"page-2.json": require("gatsby-module-loader?name=path---page-2!/Users/ankur/work/wbfilms/.cache/json/page-2.json"),
"privacy-policy.json": require("gatsby-module-loader?name=path---privacy-policy!/Users/ankur/work/wbfilms/.cache/json/privacy-policy.json"),
"submit.json": require("gatsby-module-loader?name=path---submit!/Users/ankur/work/wbfilms/.cache/json/submit.json"),
"404-html.json": require("gatsby-module-loader?name=path---404-html!/Users/ankur/work/wbfilms/.cache/json/404-html.json")
}
exports.layouts = {
"layout---index": require("gatsby-module-loader?name=component---src-layouts-index-js!/Users/ankur/work/wbfilms/.cache/layouts/index.js")
} |
function nextDay(year, month, day) {
if(year % 2 == 0) {
if(month % 2 !== 0) {
if(day == 30) {
day = 1;
month += 1;
} else {
day += 1;
}
} else if(month % 2 === 0) {
if(day == 28 || day == 29 || day == 31) {
if(month == 2) {
if((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
if(day == 29) {
day = 1;
month += 1;
} else if(day == 28) {
day += 1;
}
} else {
if(day == 28) {
day = 1;
month += 1;
} else {
day += 1;
}
}
}
if(month == 12) {
day = 1;
month = 1;
year += 1;
} else {
day = 1;
month += 1;
}
} else {
day += 1;
}
}
} else if(year % 2 !== 0) {
if(month % 2 !== 0) {
if(day == 31) {
day = 1;
month += 1;
} else {
day += 1;
}
} else if(month % 2 === 0) {
if(day == 28 || day == 29 || day == 30) {
day = 1;
if(month == 12) {
month = 1;
year += 1;
} else {
month += 1;
}
} else {
day += 1;
}
}
}
console.log(`${year}-${month}-${day}`);
}
nextDay(2016, 9, 30);
nextDay(2016, 2, 28); |
import React from "react";
import Widget from "admin/components/Widget";
const Biography = () => {
return (
<Widget styleName="gx-card-profile">
<div className="ant-card-head">
<span className="ant-card-head-title gx-mb-2">Biography</span>
<p className="gx-text-grey gx-fs-sm gx-mb-0">A little flash back of Kiley Brown</p>
</div>
<h3 className="gx-font-weight-light">Donec dignissim gravida sem, ut cursus dolor hendrerit et. Morbi
volutpat.</h3>
<p>Augue mauris dignissim arcu, ut venenatis metus ante eu orci. Donec non maximus neque,
ut finibus ex. Quisque semper ornare magna, sed ullamcorper risus luctus quis. Etiam tristique
dui vitae diam rutrum sodales. Mauris feugiat lectus felis, nec ullamcorper risus elementum at.
Aliquam erat volutpat. Nullam et est eget metus gravida tincidunt.
Phasellus sed odio eu lacus venenatis.
</p>
<p>Suspendisse vel bibendum ex. Interdum et malesuada fames ac ante ipsum primis in faucibus.
Sed a felis nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In molestie ultricies urna non
volutpat.
Nam fermentum cursus elit, et tempus metus scelerisque imperdiet. Sed tincidunt molestie justo,
a vulputate velit sagittis at. Pellentesque consequat leo tortor.
</p>
</Widget>
)
}
export default Biography;
|
/**
* TODO storage工具
*
* @author Mr.He
* 2021/4/22 18:47
* e-mail [email protected]
* qq 294046317
* pc-name mrhe
*/
export default {
getToken: () => sessionStorage.getItem('token'),
setToken: (token) => sessionStorage.setItem('token', token),
getUserInfo: () => JSON.parse(sessionStorage.getItem('userInfo')),
setUserInfo: (userInfo) => sessionStorage.setItem('userInfo', JSON.stringify(userInfo)),
getUserMenus: () => JSON.parse(sessionStorage.getItem('menus')),
setUserMenus: (menus) => sessionStorage.setItem('menus', JSON.stringify(menus)),
getPermissions: () => JSON.parse(sessionStorage.getItem('permissions')),
setPermissions: (permissions) => sessionStorage.setItem('permissions', JSON.stringify(permissions)),
getRouters: () => JSON.parse(sessionStorage.getItem('routers')),
setRouters: (routers) => sessionStorage.setItem('routers', JSON.stringify(routers)),
}
|
// Validates with [jshint]
// The playground site includes JSHint and provides linting as you enter code.
//
// Uncomment the line below to see what happens:
// Error Test
/* jshint strict: true */
(function() {
'use strict';
function setup() {
var valueX = document.getElementById('value-x');
var op = document.querySelector('select');
var valueY = document.getElementById('value-y');
var btn = document.querySelector('button');
btn.onclick = function() {
var data = {
x: valueX.value,
op: op.value,
y: valueY.value,
};
var url = 'calculate';
fetch(url, {
method: 'POST',
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
return response.json();
})
.then(function(data) {
if (!data.success) {
throw data.error;
}
showCalcResult(data.result);
op.selectedIndex = getRandomInt(4);
valueX.value = getRandomInt(1000000);
valueY.value = getRandomInt(1000000);
})
.catch(function(error) {
showCalcResult('Error: ' + error);
});
};
}
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function showCalcResult(text) {
var section = document.querySelector('.calc-result');
var ul = section.querySelector('ul');
var item = document.createElement('li');
item.textContent = text;
ul.insertAdjacentElement('afterbegin', item);
section.style.display = '';
}
function loadPolyfill() {
var url = 'https://polyfill.io/v3/polyfill.min.js?features=fetch';
var script = document.createElement('script');
script.onload = function() { setup(); };
script.onerror = function() {
showCalcResult('Error loading Script: ' + url);
document.querySelector('.calc-result').style.backgroundColor = 'red';
};
script.src = url;
document.head.appendChild(script);
}
// Once content is loaded run [setup] or if using IE or an
// Older Mobile Device download a polyfill for [fetch, Promise, etc].
document.addEventListener('DOMContentLoaded', function() {
if (window.fetch === undefined) {
loadPolyfill();
} else {
setup();
}
});
})();
|
import sessionStore, {rest_url} from "./SessionStore";
import {fetchJson} from "./helpers";
import {EventEmitter} from "events";
import dispatcher from "../dispatcher";
/** Class representing a flux store for the LPWAN Network Type domain */
class NetworkTypeStore extends EventEmitter {
/** Create a store */
constructor () {
super()
//util
this.fetch = fetchJson(`${rest_url}/api/networkTypes`, () => sessionStore.getHeader())
}
/**
* Get a list of network types
* @return {Object[]} list of network types
*/
async getNetworkTypes () {
const { records } = await this.fetch()
return records
}
/**
* Create a network type
* @param {string} name
* @return {string} network type id
*/
async createNetworkType (name) {
const response = await this.fetch('', { method: 'post', body: { name } })
return response.id
}
/**
* Get a network type
* @param {string} id
* @return {Object} network type
*/
getNetworkType (id) {
return this.fetch(id)
}
/**
* Update a network type
* @param {Object} body
* @return {Object} network type
*/
updateNetworkType (body) {
return this.fetch(body.id, { method: 'put', body })
}
/**
* Delete a network type
* @param {string} id
*/
async deleteNetworkType (id) {
await this.fetch(id, { method: 'delete' })
}
/**
* Handle actions from dispatcher
* @param {Object} param0 action
*/
handleActions ({ type }) {
switch (type) {
default: return
}
}
}
const networkTypeStore = new NetworkTypeStore();
dispatcher.register(networkTypeStore.handleActions.bind(networkTypeStore))
export default networkTypeStore;
|
from typing import List
from seedsigner.models import Seed
from seedsigner.models.seed import InvalidSeedException
from seedsigner.models.settings_definition import SettingsConstants
class SeedStorage:
def __init__(self) -> None:
self.seeds: List[Seed] = []
self.pending_seed: Seed = None
self._pending_mnemonic: List[str] = []
def set_pending_seed(self, seed: Seed):
self.pending_seed = seed
def get_pending_seed(self) -> Seed:
return self.pending_seed
def finalize_pending_seed(self) -> int:
# Finally store the pending seed and return its index
if self.pending_seed in self.seeds:
index = self.seeds.index(self.pending_seed)
else:
self.seeds.append(self.pending_seed)
index = len(self.seeds) - 1
self.pending_seed = None
return index
def clear_pending_seed(self):
self.pending_seed = None
def validate_mnemonic(self, mnemonic: List[str]) -> bool:
try:
Seed(mnemonic=mnemonic)
except InvalidSeedException as e:
return False
return True
def num_seeds(self):
return len(self.seeds)
@property
def pending_mnemonic(self) -> List[str]:
# Always return a copy so that the internal List can't be altered
return list(self._pending_mnemonic)
@property
def pending_mnemonic_length(self) -> int:
return len(self._pending_mnemonic)
def init_pending_mnemonic(self, num_words:int = 12):
self._pending_mnemonic = [None] * num_words
def update_pending_mnemonic(self, word: str, index: int):
if index >= len(self._pending_mnemonic):
raise Exception(f"index {index} is too high")
self._pending_mnemonic[index] = word
def get_pending_mnemonic_word(self, index: int) -> str:
if index < len(self._pending_mnemonic):
return self._pending_mnemonic[index]
return None
def get_pending_mnemonic_fingerprint(self, network: str = SettingsConstants.MAINNET) -> str:
try:
seed = Seed(self._pending_mnemonic)
return seed.get_fingerprint(network)
except InvalidSeedException:
return None
def convert_pending_mnemonic_to_pending_seed(self):
self.pending_seed = Seed(self._pending_mnemonic)
self.discard_pending_mnemonic()
def discard_pending_mnemonic(self):
self._pending_mnemonic = []
|
// maximal 100 und minimal 10 sind für die Summe
let max = 100;
let min = 10;
//Hier wird erst die summe brechnet und dann der summand1 danach den summand2!
// minussummand ist der minimal wert für summand1
let minsummand = 1;
// erstellt eine Zufallszahl zwischen 10-100
function zufall(min,max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Diese Funktion erstellt eine Aufgabe und return sie
function neueAufgabe(){
let summe = zufall(min,max);
//bei summand1 wird eine zufalls zahl zwischen 1 und der summe -1
//--> damit summand1 nicht gleich summe sein kann!
let summand1 = zufall(minsummand,summe - 1);
// summand 2 = damit hier das richtige rauskommt wird summe -summand1 gerechnet
let summand2 = summe - summand1;
//array der Aufgabe die gestellt wird
let aufgabe = [summand1,summand2,summe];
return aufgabe;
}
// minimale wert und maximale Wert für die Funktion zahl Anpassung
let min1 = 1;
let max1 = 99;
/**
* Diese Funktion macht das wenn die Zahl kleiner als der minimale Wert ist, dass die zahl angepasst wird als min1
* und größer als der maximale Wert ist wird die Zahl angepasst als max1
* am ende wird die angepasste Zahl zurückgegeben
*
* @param {number} richtigeZahl die Richtige Zahl der Aufgabe die übergeben wird
* @param {number} erhoehungsZahl die Zahl die übergeben wird zur veränderung der Richtigenzahl für die andere Tür
* @returns die Angepasste Zahl
*/
function zahlAnpassung(richtigeZahl,erhoehungsZahl) {
if (richtigeZahl < min1){
richtigeZahl = min1;
}
else if (richtigeZahl > max1){
richtigeZahl = max1;
}
while (richtigeZahl === erhoehungsZahl) {
richtigeZahl = zufall(min1,max1);
}
return richtigeZahl;
}
//Diese Funktion erstellt die Zahlen auf den Türen
//entweder die linke oder rechte Tür ist dann richtig
function setzeTueren(richtigeTuer) {
let zufallsTuer = zufall(0,1);
let zufallsZahl = zufall(-10,10);
if (zufallsZahl === 0) {
zufallsZahl++;
}
if (zufallsTuer === 0) {
linkeTuer.textContent = richtigeTuer;
rechteTuer.textContent = zahlAnpassung(richtigeTuer + zufallsZahl);
linkeTuer.istRichtig = true;
rechteTuer.istRichtig = false;
} else {
rechteTuer.textContent = richtigeTuer;
linkeTuer.textContent = zahlAnpassung(richtigeTuer + zufallsZahl);
rechteTuer.istRichtig = true;
linkeTuer.istRichtig = false;
}
}
//Erstellt eine Zufallsaufgabe wo summand1,summand2 oder summe gesucht wird
/**
* In der Funktion setzteAufgabe wird die aufgabe von der Funktion neueAufgabe genommen,
* aufgeteilt und dann in die richtigen value Felder gesetzt.
* Im Game ist es dann summand1 + summand2 = summe!!!
*/
function setzeAufgabe(){
let raus = zufall(0,2);
[summand1,summand2,summe] = neueAufgabe();
zahl1.value = summand1;
zahl2.value = summand2;
summenFeld.value = summe;
switch (raus) {
case 0:
zahl1.value = "?";
setzeTueren(summand1);
break;
case 1:
zahl2.value = "?";
setzeTueren(summand2);
break;
case 2:
summenFeld.value = "?";
setzeTueren(summe);
break;
}
}
/**
* Farbeetage ist ein Array mit mehreren Farben
* In der Funktion farbwechsel wird per Zufall eine Farbe des Arrays genommen und
* für die Stagezahl benutzt, pro Sekunde eine neue Farbe für die Stagezahl
* Am ende führt sich die Funktion selber aus --> ()
*
*/
(function farbwechsel(){
let farbeetage = ['white','cyan','deepskyblue','yellow','magenta','lime','gold','orange'];
setInterval(function () {
let zufall = Math.floor (farbeetage.length * Math.random());
stagezahl.style.color = farbeetage[zufall];
},1000);
})();
/**
* funktion zum drucken der seite mit der Urkunde die man am ende bekommen soll
*/
function druck() {
window.print();
}
/**
* Diese Funktion macht das im Hauptmenü oder am ende alles verschwinden,
* was dort nicht gebraucht wird
*/
//lässt alles weg von der index html was man beim hauptmenü oder am ende nicht braucht
function gehtWeg(){
spiel.style.display = "none";
aufgabe.style.display = "none";
divtext.style.display = "none";
linkeTuer.style.display= "none";
rechteTuer.style.display= "none";
hauptmenuebutton.style.display = "none";
neustartbutton.style.display = "none";
weiterbutton.style.display = "none"
}
/**
* Diese Funktion lässt die blockierten div-Container wieder auftauchen
*/
function kommtwieder(){
spiel.style.display = "block";
aufgabe.style.display = "block";
divtext.style.display = "block";
linkeTuer.style.display= "block";
rechteTuer.style.display= "block";
}
/**
* Diese Funktion lässt die Button wieder auftauchen
*/
function buttonstrue(){
weiterbutton.style.display = "block";
neustartbutton.style.display = "block";
hauptmenuebutton.style.display = "block";
}
/**
* Diese Funktion lässt die Butoons wieder verschwinden
*/
function buttonsfalse(){
weiterbutton.style.display = "none";
neustartbutton.style.display = "none";
hauptmenuebutton.style.display = "none";
}
/**
* Die Funktion storytextAnpassen passt den text für den Tipp(Tutorial) an.
*/
function storytextAnpassen() {
storytext.innerHTML = "Tipp: <br> Um die Aufgabe zu lösen Klicke auf die richtige Tür";
storytext.style.left = "60%";
storytext.style.top = "70%";
} |
const { compose } = require('ramda');
const { renameKeys } = require('ramda-adjunct');
const transformTxInfo = require('../_common/transformTxInfo');
module.exports = compose(
transformTxInfo,
renameKeys({ lease_id: 'leaseId' })
);
|
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const representativeCommitteeSchema = new Schema({
representative: { type: Schema.Types.ObjectId, ref: 'Reps' },
committee: { type: Schema.Types.ObjectId, ref: 'Committee' }
})
representativeCommitteeSchema.index({ representative: 1, committee: 1 }, { unique: true })
module.exports = mongoose.model('RepresentativeCommittee', representativeCommitteeSchema)
|
var TZFE = function(length) {
this.score = {
now: 0,
max: 0,
}
this.status = {
success: false,
false: false,
}
this.value = this.arrayInit(length)
this.length = length
this.backupData = []
this.merge = []
this.new = []
}
TZFE.prototype.saveScore = function(s) {
/*
记录 分数
*/
this.score.now += s
if (this.score.now > this.score.max) {
this.score.max = this.score.now
}
// console.log(this.score.now, this.score.max);
}
TZFE.prototype.backup = function() {
var data = {
// score: new Object(this.score),
score: {
now: this.score.now,
max: this.score.max,
},
// status: new Object(this.status),
status: {
success: this.status.success,
false: this.status.false,
},
value: this.value,
length: this.length,
merge: this.merge,
new: this.new,
}
// console.log('backup', data, data.score);
// console.log(data.score === this.score);
// console.log(data.status === this.status);
// console.log(data.value === this.value);
this.backupData.push(data)
}
TZFE.prototype.supplementZero = function(array, direction, num) {
/*
给 array 补充 num 个 0
direction 参数: begin 表示在头部补 0
end 表示在尾部补 0
*/
var a = array.slice(0)
if (direction == 'begin') {
for (var i = 0; i < num; i++) {
a.unshift(0)
}
return a
} else if (direction == 'end') {
for (var i = 0; i < num; i++) {
a.push(0)
}
return a
}
}
TZFE.prototype.rejectByIndex = function(array, index, direction='end') {
/*
将 array[index] 剔除,并在头/尾补充 0,保持长度
direction 参数: begin 表示在头部补 0
end 表示在尾部补 0
*/
var a = array.slice(0)
a.splice(index, 1)
a = this.supplementZero(a, direction, 1)
return a
// if (index == 0) {
// a = a.slice(1)
// } else if (index == a.length - 1) {
// a.pop()
// } else if(index > 0 && index < a.length - 1) {
// var qian = a.slice(0, index)
// var hou = a.slice(index+1)
// a = qian.concat(hou)
// }
// if (direction == 'begin') {
// a.unshift(0)
// } else if (direction == 'end') {
// a.push(0)
// }
}
TZFE.prototype.moveArray = function(array, direction) {
/*
移动数组: 根据 direction 让 array 清除 左/右 边的 0 ,
并在另一边用补 0 的方式保持 array 原来的长度
direction 参数: left 表示清除 左 边的 0 ,
right 表示清除 右 边的 0 ,
*/
var a = array.slice(0)
var length = a.length
var index = 0
if (direction == 'left') {
for (var i = 0; i < length; i++) {
if(a[i] != 0) {
index = i
// console.log(index);
a = a.slice(index)
var num = length - a.length
a = this.supplementZero(a, 'end', num)
return a
}
}
} else if(direction == 'right') {
for (var i = 0; i < length; i++) {
if(a[length - 1 - i] != 0) {
index = length - 1 - i
a = a.slice(0, index+1)
// console.log(a, index);
var num = length - a.length
a = this.supplementZero(a, 'begin', num)
return a
}
}
}
return a
}
TZFE.prototype.arrayByClearZero = function(array) {
var a = array.slice(0)
for (var i = 0; i < a.length; i++) {
if(a[i] == 0) {
a.splice(i, 1)
i--
}
}
a = this.supplementZero(a, 'end', array.length-a.length)
return a
}
TZFE.prototype.handleOneLine = function(array, direction) {
/*
处理一行
direction 参数: left 表示在向左滑动处理
right 表示在向右滑动处理
返回处理好的数据 a & 合并位置的坐标 is
*/
var a = array.slice(0)
a = this.arrayByClearZero(a)
var is = []
var length = a.length
a = this.moveArray(a, direction)
for (var i = 0; i < length; i++) {
// if (a[i] == a[i+1] && a[i] != 0) {
// a[i] *= 2
// if (direction == 'left') {
// a = rejectByIndex(a, i+1, 'end')
// } else if (direction == 'right') {
// a = rejectByIndex(a, i+1, 'begin')
// }
// }
if (direction == 'left') {
if (a[i] == a[i+1] && a[i] != 0) {
a[i] *= 2
is.push(i)
this.saveScore(a[i])
a = this.rejectByIndex(a, i+1, 'end')
}
} else if (direction == 'right') {
if (a[length-1-i] == a[length-i-2] && a[length-1-i] != 0) {
a[length-1-i] *= 2
is.push(length-1-i)
this.saveScore(a[length-1-i])
a = this.rejectByIndex(a, length-i-2, 'begin')
}
}
}
// console.log(a);
// a = this.moveArray(a, direction)
return {
a: a,
is: is,
}
}
TZFE.prototype.encodeArray = function(array) {
/*
旋转 array
使得 上下 变 左右
*/
// console.log('encodeArray');
var a = this.copyArray(array)
var length = a.length
var r = this.arrayInit(length)
for (var i = 0; i < length; i++) {
for (var j = 0; j < a[i].length; j++) {
r[i][j] = array[j][i]
}
}
return r
}
TZFE.prototype.decodeArray = function(array) {
/*
复原 array
让 左右 回复成 上下
*/
// console.log('decodeArray');
return this.encodeArray(array)
}
TZFE.prototype.compareArray = function(a1, a2) {
/*
比较两个 二维数组 是否相等
*/
for (var i = 0; i < a1.length; i++) {
for (var j = 0; j < a1[i].length; j++) {
if(a1[i][j] != a2[i][j]) {
// console.log('不相等');
return false
}
}
}
// console.log('相等');
return true
}
TZFE.prototype.newOneOfArray = function(result, array) {
/*
判断是否需要添加一个新元素,需要则添加 并 备份数据,不需要则返回{i:false, j:false}
*/
if(!this.compareArray(array, result)) {
result = this.arrayByCreateZero(result)
return result
} else {
return {
value: result,
i: false,
j: false,
}
}
}
TZFE.prototype.isSameLine = function(array) {
/*
判断 一维数组 是否有相邻 两个 是相等的,如果有则返回 true
*/
for (var i = 0; i < array.length-1; i++) {
if(array[i] == array[i+1]) {
return true
}
}
return false
}
TZFE.prototype.isSuccess = function(array) {
/*
判断 成功 还是 失败, 从而改变全局变量 status
*/
// 判断是否 成功
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if(array[i][j] == 2048) {
this.status.success = true
console.log('成功');
return 1
}
}
}
// 判断是否有有 空格 存在
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if(array[i][j] == 0) {
return 1
}
}
}
// 判断每行相邻是否有相同的值
for (var i = 0; i < array.length; i++) {
if (this.isSameLine(array[i])) {
return 1
}
}
// 判断每列相邻是否有相同的值
var a = this.encodeArray(array)
for (var i = 0; i < a.length; i++) {
if (this.isSameLine(a[i])) {
return 1
}
}
this.status.false = true
console.log('失败');
}
TZFE.prototype.saveMerge = function(i, js) {
/*
将 js 拆成 j1 j2 ...,并和 i 组合成 [i, j] 保存到 this.merge
*/
for (var x = 0; x < js.length; x++) {
var r = []
r.push(i)
r.push(js[x])
this.merge.push(r)
}
}
TZFE.prototype.handleLeftArray = function(array) {
/*
向左滑动时 array 合并 & 移动 & 添加一个新元素 (2)
返回 r [value, i, j] (其中 i j 是增加的新元素的坐标)
并将 合并的坐标 保存到 this.merge
*/
this.merge = []
this.new = []
var a = this.copyArray(array)
var r = []
for (var i = 0; i < a.length; i++) {
var restlt = this.handleOneLine(a[i], 'left')
r.push(restlt.a)
this.saveMerge(i, restlt.is)
}
this.isSuccess(r)
var restlt = this.newOneOfArray(r, array)
var zuobiao = [restlt.i, restlt.j]
this.new.push(zuobiao)
return restlt
}
TZFE.prototype.handleRightArray = function(array) {
/*
向右滑动时 array 合并 & 移动 & 添加一个新元素 (2)
返回 r [value, i, j] (其中 i j 是增加的新元素的坐标)
并将 合并的坐标 保存到 this.merge
将 新加的坐标 保存到 this.new
*/
// console.log('handleRightArray', array);
this.merge = []
this.new = []
var a = this.copyArray(array)
var r = []
for (var i = 0; i < a.length; i++) {
var restlt = this.handleOneLine(a[i], 'right')
r.push(restlt.a)
this.saveMerge(i, restlt.is)
// r.push(this.handleOneLine(a[i], 'right'))
}
this.isSuccess(r)
var restlt = this.newOneOfArray(r, array)
var zuobiao = [restlt.i, restlt.j]
this.new.push(zuobiao)
return restlt
}
// TZFE.prototype.encodeMerge = function() {
// var a = this.merge
// for (var i = 0; i < a.length; i++) {
// var x = a[i][0]
// var y = a[i][1]
// a[i][0] = y
// a[i][1] = x
// }
// }
TZFE.prototype.encodeZuobiao = function(zuobiaoArrray) {
var a = zuobiaoArrray
for (var i = 0; i < a.length; i++) {
var x = a[i][0]
var y = a[i][1]
a[i][0] = y
a[i][1] = x
}
}
TZFE.prototype.handleUpArray = function(array) {
/*
向上滑动时 array 合并 & 移动 & 添加一个新元素 (2)
返回 r {value, i, j} (其中 i j 是增加的新元素的坐标)
*/
var a = this.copyArray(array)
a = this.encodeArray(a)
a = this.handleLeftArray(a)
var r = {}
r.value = this.decodeArray(a.value)
r.i = a.j
r.j = a.i
this.encodeZuobiao(this.merge)
this.encodeZuobiao(this.new)
return r
}
TZFE.prototype.handleDownArray = function(array) {
/*
向下滑动时 array 合并 & 移动 & 添加一个新元素 (2)
返回 r {value, i, j} (其中 i j 是增加的新元素的坐标)
*/
// console.log('handleDownArray');
var a = this.copyArray(array)
a = this.encodeArray(a)
a = this.handleRightArray(a)
var r = {}
r.value = this.decodeArray(a.value)
r.i = a.j
r.j = a.i
this.encodeZuobiao(this.merge)
this.encodeZuobiao(this.new)
return r
}
TZFE.prototype.arrayLine = function(length) {
// 制造一行 0
var array = []
for (var i = 0; i < length; i++) {
array.push(0)
}
return array
}
TZFE.prototype.arrayInit = function(length) {
/*
制造一个 length * length 的矩阵数组, 矩阵数值为 0
*/
var array = []
for (var i = 0; i < length; i++) {
array.push(this.arrayLine(length))
}
return array
}
TZFE.prototype.numOfZeroFromArray = function(array) {
/*
返回: 二维数组中 0 的个数
*/
var num = 0
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if(array[i][j] == 0) {
num++
}
}
}
return num
}
TZFE.prototype.numberRandom = function(count) {
/*
在 0 ~ count 内,产生一个 随机数
*/
var r = Math.random() * count
return Math.ceil(r)
}
TZFE.prototype.copyArray = function(array) {
/*
复制二维数组
*/
// console.log('copyArray');
var r = []
for (var i = 0; i < array.length; i++) {
r.push(array[i].slice(0))
}
return r
}
TZFE.prototype.randomInitValue = function() {
var a = Math.random() * 10
if (a < 8) {
return 2
} else {
return 4
}
}
TZFE.prototype.arrayByCreateZero = function(array) {
/*
随机挑选 二维数组 中的其中一个 0 位置赋值为 2,并返回这个 二维数组 & 坐标
*/
var a = this.copyArray(array)
var count = this.numOfZeroFromArray(a)
var num = this.numberRandom(count)
var n = 0
var initNum = this.randomInitValue()
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < a[i].length; j++) {
if(a[i][j] == 0) {
n++
}
if(num == n) {
a[i][j] = initNum
// console.log('lib new', i, j);
return {
value: a,
i: i,
j: j,
}
}
}
}
}
TZFE.prototype.init2048Array = function(length) {
/*
初始化 2048,即生成一个二维数组,随机数组中有两个 2 ,返回 二维数组 & 坐标
*/
var initaArray = this.arrayInit(length)
var r = this.arrayByCreateZero(initaArray)
initArray = r.value
var result = {
f: {
i: r.i,
j: r.j,
}
}
r = this.arrayByCreateZero(initArray)
result.initArray = r.value
result.s = {
i: r.i,
j: r.j,
}
return result
}
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""Convert the Oxford pet dataset to TFRecord for object_detection.
See: O. M. Parkhi, A. Vedaldi, A. Zisserman, C. V. Jawahar
Cats and Dogs
IEEE Conference on Computer Vision and Pattern Recognition, 2012
http://www.robots.ox.ac.uk/~vgg/data/pets/
Example usage:
./create_pet_tf_record --data_dir=/home/user/pet \
--output_dir=/home/user/pet/output
"""
import hashlib
import io
import logging
import os
import random
import re
import json
from lxml import etree
import PIL.Image
import tensorflow as tf
from object_detection.utils import dataset_util
from object_detection.utils import label_map_util
def dict_to_tf_example(data,
label_map_dict,
image_subdirectory,
ignore_difficult_instances=False):
"""Convert XML derived dict to tf.Example proto.
Notice that this function normalizes the bounding box coordinates provided
by the raw data.
Args:
data: dict holding PASCAL XML fields for a single image (obtained by
running dataset_util.recursive_parse_xml_to_dict)
label_map_dict: A map from string label names to integers ids.
image_subdirectory: String specifying subdirectory within the
Pascal dataset directory holding the actual image data.
ignore_difficult_instances: Whether to skip difficult instances in the
dataset (default: False).
Returns:
example: The converted tf.Example.
Raises:
ValueError: if the image pointed to by data['filename'] is not a valid JPEG
"""
img_path = os.path.join(image_subdirectory, data['filename'])
with tf.gfile.GFile(img_path, 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = PIL.Image.open(encoded_jpg_io)
if image.format != 'JPEG':
raise ValueError('Image format not JPEG')
key = hashlib.sha256(encoded_jpg).hexdigest()
width = int(data['size']['width'])
height = int(data['size']['height'])
xmin = []
ymin = []
xmax = []
ymax = []
classes = []
classes_text = []
truncated = []
poses = []
difficult_obj = []
for obj in data['object']:
difficult_obj.append(int(0))
xmin.append(float(obj['bndbox']['xmin']) / width)
ymin.append(float(obj['bndbox']['ymin']) / height)
xmax.append(float(obj['bndbox']['xmax']) / width)
ymax.append(float(obj['bndbox']['ymax']) / height)
class_name = obj['name']
classes_text.append(class_name.encode('utf8'))
classes.append(label_map_dict[class_name])
truncated.append(int(0))
poses.append('Unspecified'.encode('utf8'))
example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(
data['filename'].encode('utf8')),
'image/source_id': dataset_util.bytes_feature(
data['filename'].encode('utf8')),
'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmin),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmax),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymin),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymax),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
'image/object/difficult': dataset_util.int64_list_feature(difficult_obj),
'image/object/truncated': dataset_util.int64_list_feature(truncated),
'image/object/view': dataset_util.bytes_list_feature(poses),
}))
return example
def create_tf_record(output_filename,
label_map_dict,
annotations_dir,
image_dir,
examples):
"""Creates a TFRecord file from examples.
Args:
output_filename: Path to where output file is saved.
label_map_dict: The label map dictionary.
annotations_dir: Directory where annotation files are stored.
image_dir: Directory where image files are stored.
examples: Examples to parse and save to tf record.
"""
writer = tf.python_io.TFRecordWriter(output_filename)
for idx, example in enumerate(examples):
if idx % 100 == 0:
logging.info('On image %d of %d', idx, len(examples))
path = os.path.join(annotations_dir, 'jsons', example + '.json')
if not os.path.exists(path):
logging.warning('Could not find %s, ignoring example.', path)
continue
# with tf.gfile.GFile(path, 'r') as fid:
# xml_str = fid.read()
# xml = etree.fromstring(xml_str)
# data = dataset_util.recursive_parse_xml_to_dict(xml)['annotation']
with open(path, 'r') as fp:
data = json.load(fp)
tf_example = dict_to_tf_example(data, label_map_dict, image_dir)
writer.write(tf_example.SerializeToString())
writer.close()
def main(_):
label_map_dict = label_map_util.get_label_map_dict('annotations/label_map.pbtxt')
logging.info('Reading from Pet dataset.')
image_dir = 'images'
annotations_dir = 'annotations'
examples_path = os.path.join(annotations_dir, 'trainval.txt')
examples_list = dataset_util.read_examples_list(examples_path)
# Test images are not included in the downloaded data set, so we shall perform
# our own split.
random.seed(42)
random.shuffle(examples_list)
num_examples = len(examples_list)
num_train = int(0.7 * num_examples)
train_examples = examples_list[:num_train]
val_examples = examples_list[num_train:]
logging.info('%d training and %d validation examples.',
len(train_examples), len(val_examples))
train_output_path = 'train.record'
val_output_path = 'val.record'
create_tf_record(train_output_path, label_map_dict, annotations_dir,
image_dir, train_examples)
create_tf_record(val_output_path, label_map_dict, annotations_dir,
image_dir, val_examples)
if __name__ == '__main__':
tf.app.run()
|
const isV8flags = require('./is-v8flags');
module.exports = function (flags, argv) {
if (!argv) {
argv = process.argv;
}
var args = [argv[1]];
argv.slice(2).forEach(function (arg) {
var flag = arg.split('=')[0];
if (isV8flags(flag, flags)) {
args.unshift(arg);
} else {
args.push(arg);
}
});
args.unshift(argv[0]);
return args;
};
|
/*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* 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 <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import ListItemText from '@mui/material/ListItemText';
import ListItemIcon from '@mui/material/ListItemIcon';
import LockOpenOutlinedIcon from '@mui/icons-material/LockOpenOutlined';
import SaveIcon from '@mui/icons-material/Save';
import ClearIcon from '@mui/icons-material/Clear';
import EditIcon from '@mui/icons-material/Edit';
export default function RowActionMenu({
selectedCell,
anchorEl,
handleClose,
handleUnlockAction,
handleEditAction,
handleSaveAction,
handleClearAction
}) {
const { row } = selectedCell;
return (
<Menu
id="row-action-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
MenuListProps={{
'aria-labelledby': 'row-action-button',
}}
PaperProps={{
style: {
minWidth: 120,
},
}}
>
{row && row.lockOwner && (
<MenuItem onClick={handleUnlockAction}>
<ListItemIcon>
<LockOpenOutlinedIcon />
</ListItemIcon>
<ListItemText primary="Unlock" />
</MenuItem>
)}
<MenuItem onClick={handleEditAction}>
<ListItemIcon>
<EditIcon />
</ListItemIcon>
<ListItemText primary="Open Edit Form" />
</MenuItem>
<MenuItem onClick={handleSaveAction}>
<ListItemIcon>
<SaveIcon />
</ListItemIcon>
<ListItemText primary="Save Item" />
</MenuItem>
<MenuItem onClick={handleClearAction}>
<ListItemIcon>
<ClearIcon />
</ListItemIcon>
<ListItemText primary="Clear Change" />
</MenuItem>
</Menu>
);
} |
module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2017,
sourceType: "module"
},
extends: [
"plugin:@typescript-eslint/recommended"
],
rules: {
}
}; |
import cc from 'camelcase';
import reducer, { INITIAL_STATE, EMPTY_ITEM } from 'common/state/preference/reducer';
import actions from 'common/state/preference/actions';
describe('initial state', () => {
it('returns the initial state', () => {
expect(reducer(undefined, {})).toEqual(INITIAL_STATE);
});
});
const key = 'language';
const value = 'en';
const error = new Error('oops');
describe('actions', () => {
[
[
'LOAD_PREFERENCE',
[key],
INITIAL_STATE,
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, loading: true } }
],
[
'LOAD_PREFERENCE_SUCCESS',
[key, value],
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, loading: true } },
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, value } }
],
[
'LOAD_PREFERENCE_FAILED',
[key, error],
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, loading: true } },
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, error } }
],
[
'SAVE_PREFERENCE',
[key, value],
INITIAL_STATE,
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, saving: true } }
],
[
'SAVE_PREFERENCE_SUCCESS',
[key, value],
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, saving: true } },
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, value } }
],
[
'SAVE_PREFERENCE_FAILED',
[key, error],
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, saving: true } },
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, error } }
],
[
'PREFERENCE_CHANGED',
[key, value],
{ ...INITIAL_STATE },
{ ...INITIAL_STATE, [key]: { ...EMPTY_ITEM, value } }
]
].forEach(([key, params, initialState, expected]) => {
const action = actions[cc(key)];
it(`handles ${key}`, () => {
expect(reducer(initialState, action(...params))).toEqual(expected);
});
});
});
|
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'save', 'eu', {
toolbar: 'Gorde'
} );
|
# (c) Copyright 2013-2015 Hewlett Packard Enterprise Development LP
# All Rights Reserved.
#
# Copyright 2012 OpenStack Foundation
#
# 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.
#
"""
Base class for HPE Storage Drivers.
This driver requires 3.1.3 or later firmware on the 3PAR array, using
the 4.x version of the hpe3parclient.
You will need to install the python hpe3parclient.
sudo pip install --upgrade "hpe3parclient>=4.0"
"""
try:
from hpe3parclient import exceptions as hpeexceptions
except ImportError:
hpeexceptions = None
from oslo_log import log as logging
from cinder import exception
from cinder.i18n import _
from cinder import utils
from cinder.volume import driver
from cinder.volume.drivers.hpe import hpe_3par_common as hpecommon
from cinder.volume.drivers.san import san
LOG = logging.getLogger(__name__)
class HPE3PARDriverBase(driver.ManageableVD,
driver.ManageableSnapshotsVD,
driver.MigrateVD,
driver.BaseVD):
"""OpenStack base driver to enable 3PAR storage array.
Version history:
.. code-block:: none
1.0.0 - Initial base driver
1.0.1 - Adds consistency group capability in generic volume groups.
1.0.2 - Adds capability.
1.0.3 - Added Tiramisu feature on 3PAR.
1.0.4 - Fixed Volume migration for "in-use" volume. bug #1744021
1.0.5 - Set proper backend on subsequent operation, after group
failover. bug #1773069
"""
VERSION = "1.0.5"
def __init__(self, *args, **kwargs):
super(HPE3PARDriverBase, self).__init__(*args, **kwargs)
self._active_backend_id = kwargs.get('active_backend_id', None)
self.configuration.append_config_values(hpecommon.hpe3par_opts)
self.configuration.append_config_values(san.san_opts)
self.protocol = None
@staticmethod
def get_driver_options():
return hpecommon.HPE3PARCommon.get_driver_options()
def _init_common(self):
return hpecommon.HPE3PARCommon(self.configuration,
self._active_backend_id)
def _login(self, timeout=None, array_id=None):
common = self._init_common()
# If replication is enabled and we cannot login, we do not want to
# raise an exception so a failover can still be executed.
try:
common.do_setup(None, timeout=timeout, stats=self._stats,
array_id=array_id)
common.client_login()
except Exception:
if common._replication_enabled:
LOG.warning("The primary array is not reachable at this "
"time. Since replication is enabled, "
"listing replication targets and failing over "
"a volume can still be performed.")
else:
raise
return common
def _logout(self, common):
# If replication is enabled and we do not have a client ID, we did not
# login, but can still failover. There is no need to logout.
if common.client is None and common._replication_enabled:
return
common.client_logout()
def _check_flags(self, common):
"""Sanity check to ensure we have required options set."""
required_flags = ['hpe3par_api_url', 'hpe3par_username',
'hpe3par_password', 'san_ip', 'san_login',
'san_password']
common.check_flags(self.configuration, required_flags)
def get_volume_replication_driver_data(self, volume):
if (volume.get("group_id") and volume.get("replication_status") and
volume.get("replication_status") == "failed-over"):
return int(volume.get("replication_driver_data"))
return None
@utils.trace
def get_volume_stats(self, refresh=False):
# NOTE(geguileo): We don't need to login to the backed if we are not
# going to refresh the stats, furthermore if we login, then we'll
# return an empty dict, because the _login method calls calls
# _init_common which returns a new HPE3PARCommon instance each time,
# so it won't have any cached values.
if not refresh:
return self._stats
common = self._login()
try:
self._stats = common.get_volume_stats(
refresh,
self.get_filter_function(),
self.get_goodness_function())
self._stats['storage_protocol'] = self.protocol
self._stats['driver_version'] = self.VERSION
backend_name = self.configuration.safe_get('volume_backend_name')
self._stats['volume_backend_name'] = (backend_name or
self.__class__.__name__)
return self._stats
finally:
self._logout(common)
def check_for_setup_error(self):
"""Setup errors are already checked for in do_setup so return pass."""
pass
@utils.trace
def create_volume(self, volume):
common = self._login()
try:
return common.create_volume(volume)
finally:
self._logout(common)
@utils.trace
def create_cloned_volume(self, volume, src_vref):
"""Clone an existing volume."""
common = self._login()
try:
return common.create_cloned_volume(volume, src_vref)
finally:
self._logout(common)
@utils.trace
def delete_volume(self, volume):
common = self._login()
try:
common.delete_volume(volume)
finally:
self._logout(common)
@utils.trace
def create_volume_from_snapshot(self, volume, snapshot):
"""Creates a volume from a snapshot.
TODO: support using the size from the user.
"""
common = self._login()
try:
return common.create_volume_from_snapshot(volume, snapshot)
finally:
self._logout(common)
@utils.trace
def create_snapshot(self, snapshot):
common = self._login()
try:
common.create_snapshot(snapshot)
finally:
self._logout(common)
@utils.trace
def delete_snapshot(self, snapshot):
common = self._login()
try:
common.delete_snapshot(snapshot)
finally:
self._logout(common)
@utils.trace
def extend_volume(self, volume, new_size):
common = self._login()
try:
common.extend_volume(volume, new_size)
finally:
self._logout(common)
@utils.trace
def create_group(self, context, group):
common = self._login()
try:
return common.create_group(context, group)
finally:
self._logout(common)
@utils.trace
def create_group_from_src(self, context, group, volumes,
group_snapshot=None, snapshots=None,
source_group=None, source_vols=None):
common = self._login()
try:
return common.create_group_from_src(
context, group, volumes, group_snapshot, snapshots,
source_group, source_vols)
finally:
self._logout(common)
@utils.trace
def delete_group(self, context, group, volumes):
common = self._login()
try:
return common.delete_group(context, group, volumes)
finally:
self._logout(common)
@utils.trace
def update_group(self, context, group, add_volumes=None,
remove_volumes=None):
common = self._login()
try:
return common.update_group(context, group, add_volumes,
remove_volumes)
finally:
self._logout(common)
@utils.trace
def create_group_snapshot(self, context, group_snapshot, snapshots):
common = self._login()
try:
return common.create_group_snapshot(context, group_snapshot,
snapshots)
finally:
self._logout(common)
@utils.trace
def delete_group_snapshot(self, context, group_snapshot, snapshots):
common = self._login()
try:
return common.delete_group_snapshot(context, group_snapshot,
snapshots)
finally:
self._logout(common)
@utils.trace
def manage_existing(self, volume, existing_ref):
common = self._login()
try:
return common.manage_existing(volume, existing_ref)
finally:
self._logout(common)
@utils.trace
def manage_existing_snapshot(self, snapshot, existing_ref):
common = self._login()
try:
return common.manage_existing_snapshot(snapshot, existing_ref)
finally:
self._logout(common)
@utils.trace
def manage_existing_get_size(self, volume, existing_ref):
common = self._login()
try:
return common.manage_existing_get_size(volume, existing_ref)
finally:
self._logout(common)
@utils.trace
def manage_existing_snapshot_get_size(self, snapshot, existing_ref):
common = self._login()
try:
return common.manage_existing_snapshot_get_size(snapshot,
existing_ref)
finally:
self._logout(common)
@utils.trace
def unmanage(self, volume):
common = self._login()
try:
common.unmanage(volume)
finally:
self._logout(common)
@utils.trace
def unmanage_snapshot(self, snapshot):
common = self._login()
try:
common.unmanage_snapshot(snapshot)
finally:
self._logout(common)
@utils.trace
def retype(self, context, volume, new_type, diff, host):
"""Convert the volume to be of the new type."""
common = self._login()
try:
return common.retype(volume, new_type, diff, host)
finally:
self._logout(common)
@utils.trace
def migrate_volume(self, context, volume, host):
if volume['status'] == 'in-use':
protocol = host['capabilities']['storage_protocol']
if protocol != self.protocol:
LOG.debug("3PAR %(protocol)s driver cannot migrate in-use "
"volume to a host with "
"storage_protocol=%(storage_protocol)s",
{'protocol': self.protocol,
'storage_protocol': protocol})
return False, None
common = self._login()
try:
return common.migrate_volume(volume, host)
finally:
self._logout(common)
@utils.trace
def update_migrated_volume(self, context, volume, new_volume,
original_volume_status):
"""Update the name of the migrated volume to it's new ID."""
common = self._login()
try:
return common.update_migrated_volume(context, volume, new_volume,
original_volume_status)
finally:
self._logout(common)
@utils.trace
def get_pool(self, volume):
common = self._login()
try:
return common.get_cpg(volume)
except hpeexceptions.HTTPNotFound:
reason = (_("Volume %s doesn't exist on array.") % volume)
LOG.error(reason)
raise exception.InvalidVolume(reason)
finally:
self._logout(common)
@utils.trace
def revert_to_snapshot(self, context, volume, snapshot):
"""Revert volume to snapshot."""
common = self._login()
try:
common.revert_to_snapshot(volume, snapshot)
finally:
self._logout(common)
@utils.trace
def failover_host(self, context, volumes, secondary_id=None, groups=None):
"""Force failover to a secondary replication target."""
common = self._login(timeout=30)
try:
# Update the active_backend_id in the driver and return it.
active_backend_id, volume_updates, group_update_list = (
common.failover_host(
context, volumes, secondary_id, groups))
self._active_backend_id = active_backend_id
return active_backend_id, volume_updates, group_update_list
finally:
self._logout(common)
def enable_replication(self, context, group, volumes):
"""Enable replication for a group.
:param context: the context
:param group: the group object
:param volumes: the list of volumes
:returns: model_update, None
"""
common = self._login()
try:
return common.enable_replication(context, group, volumes)
finally:
self._logout(common)
def disable_replication(self, context, group, volumes):
"""Disable replication for a group.
:param context: the context
:param group: the group object
:param volumes: the list of volumes
:returns: model_update, None
"""
common = self._login()
try:
return common.disable_replication(context, group, volumes)
finally:
self._logout(common)
def failover_replication(self, context, group, volumes,
secondary_backend_id=None):
"""Failover replication for a group.
:param context: the context
:param group: the group object
:param volumes: the list of volumes
:param secondary_backend_id: the secondary backend id - default None
:returns: model_update, vol_model_updates
"""
common = self._login()
try:
return common.failover_replication(
context, group, volumes, secondary_backend_id)
finally:
self._logout(common)
def do_setup(self, context):
common = self._init_common()
common.do_setup(context)
self._check_flags(common)
common.check_for_setup_error()
self._do_setup(common)
def _do_setup(self, common):
pass
def create_export(self, context, volume, connector):
pass
def ensure_export(self, context, volume):
pass
def remove_export(self, context, volume):
pass
def terminate_connection(self, volume, connector, **kwargs):
pass
def initialize_connection(self, volume, connector):
pass
@utils.trace
def _init_vendor_properties(self):
"""Create a dictionary of vendor unique properties.
This method creates a dictionary of vendor unique properties
and returns both created dictionary and vendor name.
Returned vendor name is used to check for name of vendor
unique properties.
- Vendor name shouldn't include colon(:) because of the separator
and it is automatically replaced by underscore(_).
ex. abc:d -> abc_d
- Vendor prefix is equal to vendor name.
ex. abcd
- Vendor unique properties must start with vendor prefix + ':'.
ex. abcd:maxIOPS
Each backend driver needs to override this method to expose
its own properties using _set_property() like this:
self._set_property(
properties,
"vendorPrefix:specific_property",
"Title of property",
_("Description of property"),
"type")
: return dictionary of vendor unique properties
: return vendor name
prefix: HPE:3PAR --> HPE_3PAR
"""
properties = {}
valid_prov_values = ['thin', 'full', 'dedup']
valid_persona_values = ['2 - Generic-ALUA',
'1 - Generic',
'3 - Generic-legacy',
'4 - HPEUX-legacy',
'5 - AIX-legacy',
'6 - EGENERA',
'7 - ONTAP-legacy',
'8 - VMware',
'9 - OpenVMS',
'10 - HPEUX',
'11 - WindowsServer']
self._set_property(
properties,
"HPE:3PAR:hpe3par:snap_cpg",
"Snap CPG Extra-specs.",
_("Specifies the Snap CPG for a volume type. It overrides the "
"hpe3par_cpg_snap setting. Defaults to the hpe3par_cpg_snap "
"setting in the cinder.conf file. If hpe3par_cpg_snap is not "
"set, it defaults to the hpe3par_cpg setting."),
"string")
self._set_property(
properties,
"HPE:3PAR:hpe3par:persona",
"Host Persona Extra-specs.",
_("Specifies the host persona property for a volume type. It "
"overrides the hpe3par_cpg_snap setting. Defaults to the "
"hpe3par_cpg_snap setting in the cinder.conf file. "
"If hpe3par_cpg_snap is not set, "
"it defaults to the hpe3par_cpg setting."),
"string",
enum=valid_persona_values,
default="2 - Generic-ALUA")
self._set_property(
properties,
"HPE:3PAR:hpe3par:vvs",
"Virtual Volume Set Extra-specs.",
_("The virtual volume set name that has been set up by the "
"administrator that would have predefined QoS rules "
"associated with it. If you specify extra_specs "
"hpe3par:vvs, the qos_specs minIOPS, maxIOPS, minBWS, "
"and maxBWS settings are ignored."),
"string")
self._set_property(
properties,
"HPE:3PAR:hpe3par:flash_cache",
"Flash cache Extra-specs.",
_("Enables Flash cache setting for a volume type."),
"boolean",
default=False)
self._set_property(
properties,
"HPE:3PAR:hpe3par:provisioning",
"Storage Provisioning Extra-specs.",
_("Specifies the provisioning for a volume type."),
"string",
enum=valid_prov_values,
default="thin")
self._set_property(
properties,
"HPE:3PAR:hpe3par:compression",
"Storage Provisioning Extra-specs.",
_("Enables compression for a volume type. "
"Minimum requirement of 3par OS version is 3.3.1 "
"with SSD drives only. "
"Volume size must have > 16 GB to enable "
"compression on volume. "
"A full provisioned volume cannot be compressed."),
"boolean",
default=False)
self._set_property(
properties,
"HPE:3PAR:replication_enabled",
"Volume Replication Extra-specs.",
_("The valid value is: <is> True "
"If True, the volume is to be replicated, if supported, "
"by the backend driver. If the option is not specified or "
"false, then replication is not enabled. This option is "
"required to enable replication."),
"string",
enum=["<is> True"],
default=False)
self._set_property(
properties,
"HPE:3PAR:replication:mode",
"Replication Mode Extra-specs.",
_("Sets the replication mode for 3par."),
"string",
enum=["sync", "periodic"],
default="periodic")
self._set_property(
properties,
"HPE:3PAR:replication:sync_period",
"Sync Period for Volume Replication Extra-specs.",
_("Sets the time interval for synchronization. "
"Only needed if replication:mode is periodic."),
"integer",
default=900)
self._set_property(
properties,
"HPE:3PAR:replication:retention_count",
"Retention Count for Replication Extra-specs.",
_("Sets the number of snapshots that will be "
"saved on the primary array."),
"integer",
default=5)
self._set_property(
properties,
"HPE:3PAR:replication:remote_retention_count",
"Remote Retention Count for Replication Extra-specs.",
_("Sets the number of snapshots that will be "
"saved on the secondary array."),
"integer",
default=5)
# ###### QoS Settings ###### #
self._set_property(
properties,
"HPE:3PAR:minIOPS",
"Minimum IOPS QoS.",
_("Sets the QoS, I/O issue count minimum goal. "
"If not specified, there is no limit on I/O issue count."),
"integer")
self._set_property(
properties,
"HPE:3PAR:maxIOPS",
"Maximum IOPS QoS.",
_("Sets the QoS, I/O issue count rate limit. "
"If not specified, there is no limit on I/O issue count."),
"integer")
self._set_property(
properties,
"HPE:3PAR:minBWS",
"Minimum Bandwidth QoS.",
_("Sets the QoS, I/O issue bandwidth minimum goal. "
"If not specified, there is no limit on "
"I/O issue bandwidth rate."),
"integer")
self._set_property(
properties,
"HPE:3PAR:maxBWS",
"Maximum Bandwidth QoS.",
_("Sets the QoS, I/O issue bandwidth rate limit. "
"If not specified, there is no limit on I/O issue "
"bandwidth rate."),
"integer")
self._set_property(
properties,
"HPE:3PAR:latency",
"Latency QoS.",
_("Sets the latency goal in milliseconds."),
"integer")
self._set_property(
properties,
"HPE:3PAR:priority",
"Priority QoS.",
_("Sets the priority of the QoS rule over other rules."),
"string",
enum=["low", "normal", "high"],
default="normal")
return properties, 'HPE:3PAR'
|
const express = require('express');
const app = express();
const server = require('http').Server(app);
const log = require('node-consolog').getLogger('test');
const oled = require('pi-gadgets').oled;
const port = process.env.PORT || 7777;
let display, sleepRef;
app.use(express.json());
// Get status
app.get('/status', (req, res) => {
res.send({ status: 'ready' });
});
app.put('/update', async (req, res) => {
if(typeof req.body === 'object'){
const items = Array.isArray(req.body) ? req.body : [req.body];
display.clear();
for(let i=0; i<items.length; i++){
const item = items[i];
const font = (typeof item.font === 'string') ? item.font : 'small_6x8';
const color = (typeof item.color === 'number') ? item.color : 1;
if(item.x && item.y && item.text){
display.writeText(item.x, item.y, item.text, font, color);
}
else if(item.x && item.y && item.x2 && item.y2){
display.writeRect(item.x, item.y, item.x2, item.y2, color);
}
else if(item.x && item.y){
display.writePixel(item.x, item.y, color);
}
else if(item.x){
display.writeVLine(item.x, color);
}
else if(item.y){
display.writeHLine(item.y, color);
}
else{
log.warn(`Invalid drawing directive: ${JSON.stringify(item)}`);
}
}
await display.update();
startSleepTimer(60);
res.status(204).end();
}
else{
res.status(400).send('Invalid request');
}
});
function startSleepTimer(timeoutSecs){
clearTimeout(sleepRef);
sleepRef = setTimeout(() => {
display.clear();
display.update();
}, (timeoutSecs * 1000));
}
server.listen(port, async callback => {
display = await oled.init(128, 32);
log.info(`Server running on port ${port}`);
});
// Termination event
process.on('SIGINT', function () {
log.warn('Service shutting down!');
display.clear();
display.update().then(() => process.exit());
});
|
import React, { useContext } from 'react';
import AppContext from '../../context/AppContext';
import TextArea from '../../shared/TextArea';
import { hexToRgb, formatDisplayURL } from '../../utils';
const styles = {
header: {
position: 'absolute',
left: 0,
right: 0,
zIndex: 0,
flexDirection: 'column',
justifyContent: 'center',
color: 'white',
backgroundColor: '#222',
height: '160px',
display: 'flex',
alignItems: 'center'
},
section: {
marginTop: '167px',
marginLeft: '20px',
}
};
const Celebi = () => {
const context = useContext(AppContext);
const { state } = context;
const { data, config, theme } = state;
const { r, g, b } = hexToRgb(theme.colors.accent) || {};
const Heading = ({ title, className }) => (
<h5
className={`my-2 text-md uppercase font-semibold tracking-wider pb-1 border-b-2 border-gray-800 ${className}`}
>
{title}
</h5>
);
const Header = () => (
<header style={styles.header}>
<div className="text-center">
<h1 className="tracking-wide uppercase font-semibold" style={{ fontSize: '2.75em' }}>
{data.basics.name}
</h1>
<h6 className="text-lg tracking-wider uppercase">{data.basics.label}</h6>
</div>
</header>
);
const Summary = () =>
data.basics.summary &&
config.summary.enable && (
<div className="mb-6">
<Heading title={config.summary.heading} />
<TextArea
className="my-3 mr-10"
value={data.basics.summary}
readOnly
/>
</div>
);
const ContactItem = ({ title, link='#', value }) =>
value && (
<div className="mb-3">
<h6 className="text-xs font-bold">{title}</h6>
<a href={link}>
<p className="text-sm">{value}</p>
</a>
</div>
);
const Contact = () => (
<div className="mb-6">
<Heading title="Contact" className="mt-8 w-3/4 mx-auto" />
{
(data.basics.location.address || data.basics.location.city
|| data.basics.location.region) &&
<div className="mb-3">
<h6 className="text-xs font-bold">Address</h6>
<p className="text-sm">{data.basics.location.address}</p>
<p className="text-sm">
{data.basics.location.city}
{
data.basics.location.region ?
`, ${data.basics.location.region}`
:
''
}
</p>
</div>
}
<ContactItem
title="Phone"
link={`tel:${data.basics.phone}`}
value={data.basics.phone}
/>
<ContactItem
title="Email Address"
link={`mailto:${data.basics.email}`}
value={data.basics.email}
/>
<ContactItem
title="Website"
link={`http://${data.basics.website}`}
value={data.basics.website}
/>
<ContactItem
title="Github"
value={formatDisplayURL(data.basics.github)}
link={data.basics.github}
/>
<ContactItem
title="Linkedin"
value={formatDisplayURL(data.basics.linkedin)}
link={data.basics.linkedin}
/>
</div>
);
const WorkItem = x => (
<div key={x.id} className="my-3 mr-10">
<div>
<h6 className="font-semibold">{x.company}</h6>
<p className="text-xs text-gray-800">
{x.position}{x.location ? ', ' : ''}{x.location} | {x.startDate} - {x.endDate}
</p>
</div>
<TextArea
className="mt-2"
value={x.description}
readOnly
/>
</div>
);
const Work = () =>
data.work &&
config.work.enable && (
<div className="mb-6">
<Heading title={config.work.heading} />
{data.work.filter(x => x.enable).map(WorkItem)}
</div>
);
const EducationItem = x => (
<div key={x.id} className="my-3 mr-10">
<h6 className="font-semibold">{x.institution}{x.location ? ', ' : ''}{x.location}</h6>
<p className="text-xs">{x.major} | {x.startDate} - {x.endDate}</p>
<TextArea
className="mt-2"
value={x.description}
readOnly
/>
</div>
);
const Education = () =>
data.education &&
config.education.enable && (
<div className="mb-6">
<Heading title={config.education.heading} />
{data.education.filter(x => x.enable).map(EducationItem)}
</div>
);
const Skills = () =>
config.skills.enable && (
<div className="mb-6">
<Heading title="Skills" className="w-3/4 mx-auto" />
<ul className="list-none text-sm">
{data.skills.map(x => (
<li key={x.id} className="my-2">
{x.skill}
</li>
))}
</ul>
</div>
);
const ReferenceItem = x => (
<div key={x.id} className="flex flex-col">
<h6 className="text-sm font-semibold">{x.name}</h6>
<span className="text-sm">{x.position}</span>
<span className="text-sm">{x.phone}</span>
<span className="text-sm">{x.email}</span>
<TextArea
className="mt-2"
value={x.description}
readOnly
/>
</div>
);
const References = () =>
data.references &&
config.references.enable && (
<div className="mb-6">
<Heading title={config.references.heading} />
<div className="grid grid-cols-2 col-gap-4 row-gap-2">
{data.references.filter(x => x.enable).map(ReferenceItem)}
</div>
</div>
);
const AwardItem = x => (
<div key={x.id} className="my-2">
<div className="flex justify-between">
<h6 className="font-semibold">{x.title}</h6>
</div>
<p className="text-xs">{x.awarder}{x.date ? ` | ${x.date}`: ''}</p>
<TextArea
className="mt-2"
value={x.summary}
readOnly
/>
</div>
);
const Awards = () =>
data.awards &&
config.awards.enable && (
<div className="mb-6">
<Heading light title={config.awards.heading} />
{data.awards.filter(x => x.enable).map(AwardItem)}
</div>
);
const CertificationItem = x => (
<div key={x.id} className="my-2 px-6">
<div className="flex justify-between">
<h6 className="font-semibold">{x.title}</h6>
<p className="text-xs font-medium">{x.date}</p>
</div>
<p className="flex text-xs">{x.issuer}</p>
<TextArea
className="mt-2"
value={x.summary}
readOnly
/>
</div>
);
const Certifications = () =>
data.certifications &&
config.certifications.enable && (
<div className="mb-6">
<Heading title={config.certifications.heading} className="w-3/4 mx-auto" />
{data.certifications.filter(x => x.enable).map(CertificationItem)}
</div>
);
return (
<div
style={{
fontFamily: theme.font.family,
backgroundColor: theme.colors.background,
color: theme.colors.primary,
}}
>
<div className="grid grid-cols-12"
style={{'minHeight': 'inherit'}}
>
<div
className="sidebar col-span-4 pb-8 ml-8 z-10 text-center"
style={{ backgroundColor: `rgba(${r}, ${g}, ${b}, 0.1)`, marginTop: '160px' }}
>
<Contact />
<Skills />
<Certifications />
</div>
<div className="col-span-8">
<Header />
<section className="py-4" style={styles.section}>
<Summary />
<Work />
<Education />
<Awards />
<References />
</section>
</div>
</div>
</div>
);
};
export default Celebi;
|
import _plotly_utils.basevalidators
class FillcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(self, plotly_name="fillcolor", parent_name="box", **kwargs):
super(FillcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs,
)
|
import numpy as np
import pandas
from pandas.util.testing import assert_almost_equal, assert_frame_equal
import modin.pandas as pd
from modin.pandas.utils import to_pandas
random_state = np.random.RandomState(seed=42)
# Size of test dataframes
NCOLS = 2 ** 6
NROWS = 2 ** 8
# Range for values for test data
RAND_LOW = 0
RAND_HIGH = 100
# Input data and functions for the tests
# The test data that we will test our code against
test_data = {
# "empty_data": {},
# "columns_only": {"col1": [], "col2": [], "col3": [], "col4": [], "col5": []},
"int_data": {
"col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint(
RAND_LOW, RAND_HIGH, size=(NROWS)
)
for i in range(NCOLS)
},
"float_data": {
"col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.uniform(
RAND_LOW, RAND_HIGH, size=(NROWS)
)
for i in range(NCOLS)
},
"sparse_nan_data": {
"col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [
x if j != i else np.NaN
for j, x in enumerate(
random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS))
)
]
for i in range(NCOLS)
},
"dense_nan_data": {
"col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [
x if j % 4 == 0 else np.NaN
for j, x in enumerate(
random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS))
)
]
for i in range(NCOLS)
},
# "int_float_object_data": {
# "col3": [1, 2, 3, 4],
# "col4": [4, 5, 6, 7],
# "col1": [8.0, 9.4, 10.1, 11.3],
# "col2": ["a", "b", "c", "d"],
# },
# "datetime_timedelta_data": {
# "col3": [
# np.datetime64("2010"),
# np.datetime64("2011"),
# np.datetime64("2011-06-15T00:00"),
# np.datetime64("2009-01-01"),
# ],
# "col4": [
# np.datetime64("2010"),
# np.datetime64("2011"),
# np.datetime64("2011-06-15T00:00"),
# np.datetime64("2009-01-01"),
# ],
# "col1": [
# np.timedelta64(1, "M"),
# np.timedelta64(2, "D"),
# np.timedelta64(3, "Y"),
# np.timedelta64(20, "D"),
# ],
# "col2": [
# np.timedelta64(1, "M"),
# np.timedelta64(2, "D"),
# np.timedelta64(3, "Y"),
# np.timedelta64(20, "D"),
# ],
# },
# "all_data": {
# "col3": 1.0,
# "col4": np.datetime64("2011-06-15T00:00"),
# "col5": np.array([3] * 4, dtype="int32"),
# "col1": "foo",
# "col2": True,
# },
"100x100": {
"col{}".format((i - 50) % 100 + 1): random_state.randint(
RAND_LOW, RAND_HIGH, size=(100)
)
for i in range(100)
},
}
test_data_values = list(test_data.values())
test_data_keys = list(test_data.keys())
numeric_dfs = [
"empty_data",
"columns_only",
"int_data",
"float_data",
"sparse_nan_data",
"dense_nan_data",
"100x100",
]
no_numeric_dfs = ["datetime_timedelta_data"]
# String test data
test_string_data = {
"separator data": [
"abC|DeF,Hik",
"234,3245.67",
"gSaf,qWer|Gre",
"asd3,4sad|",
np.NaN,
]
}
test_string_data_values = list(test_string_data.values())
test_string_data_keys = list(test_string_data.keys())
# List of strings test data
test_string_list_data = {"simple string": [["a"], ["CdE"], ["jDf"], ["werB"]]}
test_string_list_data_values = list(test_string_list_data.values())
test_string_list_data_keys = list(test_string_list_data.keys())
string_seperators = {"empty sep": "", "comma sep": ",", "None sep": None}
string_sep_values = list(string_seperators.values())
string_sep_keys = list(string_seperators.keys())
string_na_rep = {"None na_rep": None, "- na_rep": "-", "nan na_rep": np.NaN}
string_na_rep_values = list(string_na_rep.values())
string_na_rep_keys = list(string_na_rep.keys())
join_type = {"left": "left", "right": "right", "inner": "inner", "outer": "outer"}
join_type_keys = list(join_type.keys())
join_type_values = list(join_type.values())
# Test functions for applymap
test_func = {
"plus one": lambda x: x + 1,
"convert to string": lambda x: str(x),
"square": lambda x: x * x,
"identity": lambda x: x,
"return false": lambda x: False,
}
test_func_keys = list(test_func.keys())
test_func_values = list(test_func.values())
numeric_test_funcs = ["plus one", "square"]
# Test functions for query
query_func = {
"col1 < col2": "col1 < col2",
"col3 > col4": "col3 > col4",
"col1 == col2": "col1 == col2",
"(col2 > col1) and (col1 < col3)": "(col2 > col1) and (col1 < col3)",
}
query_func_keys = list(query_func.keys())
query_func_values = list(query_func.values())
# Test agg functions for apply, agg, and aggregate
agg_func = {
"sum": "sum",
"df sum": lambda df: df.sum(),
"str": str,
"sum mean": ["sum", "mean"],
"sum sum": ["sum", "sum"],
"sum df sum": ["sum", lambda df: df.sum()],
"should raise TypeError": 1,
}
agg_func_keys = list(agg_func.keys())
agg_func_values = list(agg_func.values())
numeric_agg_funcs = ["sum mean", "sum sum", "sum df sum"]
# Test q values for quantiles
quantiles = {
"0.25": 0.25,
"0.5": 0.5,
"0.75": 0.75,
"0.66": 0.66,
"0.01": 0.01,
"list": [0.25, 0.5, 0.75, 0.66, 0.01],
}
quantiles_keys = list(quantiles.keys())
quantiles_values = list(quantiles.values())
# Test indices for get, set_index, __contains__, insert
indices = {
"col1": "col1",
"col2": "col2",
"A": "A",
"B": "B",
"does not exist": "does not exist",
}
indices_keys = list(indices.keys())
indices_values = list(indices.values())
# Test functions for groupby apply
groupby_apply_func = {"sum": lambda df: df.sum(), "negate": lambda df: -df}
groupby_apply_func_keys = list(groupby_apply_func.keys())
groupby_apply_func_values = list(groupby_apply_func.values())
# Test functions for groupby agg
groupby_agg_func = {"min": "min", "max": "max"}
groupby_agg_func_keys = list(groupby_agg_func.keys())
groupby_agg_func_values = list(groupby_agg_func.values())
# Test functions for groupby transform
groupby_transform_func = {
"add 4": lambda df: df + 4,
"negatie and minus 10": lambda df: -df - 10,
}
groupby_transform_func_keys = list(groupby_transform_func.keys())
groupby_transform_func_values = list(groupby_transform_func.values())
# Test functions for groupby pipe
groupby_pipe_func = {"sum": lambda df: df.sum()}
groupby_pipe_func_keys = list(groupby_pipe_func.keys())
groupby_pipe_func_values = list(groupby_pipe_func.values())
# END Test input data and functions
# Parametrizations of common kwargs
axis = {
"over rows int": 0,
"over rows str": "rows",
"over columns int": 1,
"over columns str": "columns",
}
axis_keys = list(axis.keys())
axis_values = list(axis.values())
bool_arg = {"True": True, "False": False, "None": None}
bool_arg_keys = list(bool_arg.keys())
bool_arg_values = list(bool_arg.values())
int_arg = {"-5": -5, "-1": -1, "0": 0, "1": 1, "5": 5}
int_arg_keys = list(int_arg.keys())
int_arg_values = list(int_arg.values())
# END parametrizations of common kwargs
def df_equals(df1, df2):
"""Tests if df1 and df2 are equal.
Args:
df1: (pandas or modin DataFrame or series) dataframe to test if equal.
df2: (pandas or modin DataFrame or series) dataframe to test if equal.
Returns:
True if df1 is equal to df2.
"""
types_for_almost_equals = (
pandas.core.indexes.range.RangeIndex,
pandas.core.indexes.base.Index,
)
# Gets AttributError if modin's groupby object is not import like this
from modin.pandas.groupby import DataFrameGroupBy
groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy)
# The typing behavior of how pandas treats its index is not consistent when the
# length of the DataFrame or Series is 0, so we just verify that the contents are
# the same.
if (
hasattr(df1, "index")
and hasattr(df2, "index")
and len(df1) == 0
and len(df2) == 0
):
if type(df1).__name__ == type(df2).__name__:
if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name:
return
if (
hasattr(df1, "columns")
and hasattr(df2, "columns")
and df1.columns.equals(df2.columns)
):
return
assert False
# Convert to pandas
if isinstance(df1, pd.DataFrame):
df1 = to_pandas(df1)
if isinstance(df2, pd.DataFrame):
df2 = to_pandas(df2)
if isinstance(df1, pd.Series):
df1 = to_pandas(df1)
if isinstance(df2, pd.Series):
df2 = to_pandas(df2)
if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame):
if (df1.empty and not df2.empty) or (df2.empty and not df1.empty):
return False
elif df1.empty and df2.empty and type(df1) != type(df2):
return False
if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame):
try:
assert_frame_equal(
df1.sort_index(axis=1),
df2.sort_index(axis=1),
check_dtype=False,
check_datetimelike_compat=True,
check_index_type=False,
check_column_type=False,
)
except Exception:
assert_frame_equal(
df1,
df2,
check_dtype=False,
check_datetimelike_compat=True,
check_index_type=False,
check_column_type=False,
)
elif isinstance(df1, types_for_almost_equals) and isinstance(
df2, types_for_almost_equals
):
assert_almost_equal(df1, df2, check_dtype=False)
elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series):
assert_almost_equal(df1, df2, check_dtype=False, check_series_type=False)
elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types):
for g1, g2 in zip(df1, df2):
assert g1[0] == g2[0]
df_equals(g1[1], g2[1])
elif (
isinstance(df1, pandas.Series)
and isinstance(df2, pandas.Series)
and df1.empty
and df2.empty
):
assert all(df1.index == df2.index)
assert df1.dtypes == df2.dtypes
else:
if df1 != df2:
print(df1)
print(df2)
np.testing.assert_almost_equal(df1, df2)
def df_is_empty(df):
"""Tests if df is empty.
Args:
df: (pandas or modin DataFrame) dataframe to test if empty.
Returns:
True if df is empty.
"""
assert df.size == 0 and df.empty
assert df.shape[0] == 0 or df.shape[1] == 0
def arg_keys(arg_name, keys):
"""Appends arg_name to the front of all values in keys.
Args:
arg_name: (string) String containing argument name.
keys: (list of strings) Possible inputs of argument.
Returns:
List of strings with arg_name append to front of keys.
"""
return ["{0} {1}".format(arg_name, key) for key in keys]
def name_contains(test_name, vals):
"""Determines if any string in vals is a substring of test_name.
Args:
test_name: (string) String to determine if contains substrings.
vals: (list of strings) List of substrings to test for.
Returns:
True if a substring in vals is in test_name, else False.
"""
return any(val in test_name for val in vals)
|
# Generated by Django 2.2.1 on 2019-05-06 07:18
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contest',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_open', models.BooleanField(default=False)),
('is_active', models.BooleanField(default=False)),
('is_schedule', models.BooleanField(default=True)),
('title', models.CharField(max_length=30, unique=True)),
('contest_tag', models.CharField(max_length=15)),
('start_date', models.DateField(default=django.utils.timezone.now)),
('start_time', models.TimeField()),
('end_date', models.DateField(default=django.utils.timezone.now)),
('end_time', models.TimeField()),
('writer', models.CharField(max_length=30)),
('top_page', models.TextField()),
],
),
migrations.CreateModel(
name='Problem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contest_tag', models.CharField(max_length=15)),
('problem_name', models.CharField(max_length=20)),
('problem_tag', models.CharField(max_length=15)),
('problem_order', models.IntegerField()),
('time_limit', models.IntegerField()),
('memory_limit', models.IntegerField(default=256)),
('problem', models.TextField()),
('input', models.TextField()),
('output', models.TextField()),
('example_input_output', models.TextField()),
('answer', models.BinaryField()),
],
),
migrations.CreateModel(
name='RegistContestUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contest_tag', models.CharField(max_length=15)),
('username', models.CharField(max_length=15)),
],
),
migrations.CreateModel(
name='Submittion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contest_tag', models.CharField(max_length=15)),
('problem_tag', models.CharField(max_length=15)),
('source_code', models.TextField()),
('author', models.CharField(max_length=10)),
('language', models.CharField(max_length=10)),
('status', models.CharField(blank=True, max_length=5)),
('warning', models.TextField(blank=True)),
('error', models.TextField(blank=True)),
('time', models.FloatField(blank=True)),
('memory', models.IntegerField(blank=True)),
('byte', models.IntegerField(blank=True)),
('date', models.DateTimeField(blank=True)),
('is_judge', models.BooleanField(blank=True, default=False)),
],
),
]
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.