text
stringlengths
3
1.05M
"use strict"; const roomlevel_1 = require("./enums.roomlevel"); const RoomRepository = require("./repository.Room"); function getAllRoomsBeingDismantled() { let rooms = []; for (let roomKey in Game.rooms) { let room = Game.rooms[roomKey]; if (room.controller !== undefined && room.controller.my === true && room.memory.isBeingDismantled === true) { rooms.push(room); } } return rooms; } exports.getAllRoomsBeingDismantled = getAllRoomsBeingDismantled; ; function wallsShouldBeRemoved(room) { return room.memory.removeWalls === true || (room.controller !== undefined && (room.controller.level === 1 || room.controller.level === 3)); } exports.wallsShouldBeRemoved = wallsShouldBeRemoved; function roomShouldHaveJanitors(room) { if (room.storage === undefined) { let container = room.getBaseContainer(); return RoomRepository.getRoomLevel(room) >= roomlevel_1.RoomLevel.DefendedColony && room.controller !== undefined && container !== undefined && container.store[RESOURCE_ENERGY] > 500 && !room.isExpansion(); } else { return RoomRepository.getRoomLevel(room) >= roomlevel_1.RoomLevel.DefendedColony && room.controller !== undefined && room.storage.store[RESOURCE_ENERGY] > 5000 && !room.isExpansion(); } } exports.roomShouldHaveJanitors = roomShouldHaveJanitors; function roomShouldHaveBuilders(room) { if (room.storage === undefined) { let container = room.getBaseContainer(); return RoomRepository.getRoomLevel(room) >= roomlevel_1.RoomLevel.DefendedColony && room.controller !== undefined && container !== undefined && container.store[RESOURCE_ENERGY] > 500 && !room.isExpansion(); } else { return RoomRepository.getRoomLevel(room) >= roomlevel_1.RoomLevel.DefendedColony && room.controller !== undefined && room.storage.store[RESOURCE_ENERGY] > 10000 && !room.isExpansion(); } } exports.roomShouldHaveBuilders = roomShouldHaveBuilders; function roomIsHighway(roomName) { let parsed = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName); return (parsed[1] % 10 === 0) || (parsed[2] % 10 === 0); } exports.roomIsHighway = roomIsHighway;
var v0 = (function (){ (this.parent) = null; (this.body1) = null; (this.body2) = null; (this.addedToIsland) = false; }); var v1 = (function (v1){ (v1.registerA) |= v1.registerD; (v1.FZero) = (v1.registerA) == (0); (v1.FSubtract) = (v1.FCarry) = (v1.FHalfCarry) = false; }); // GenBlkBrick for(var v2 = 0;(v2) < (3);v2++){ (v1.prototype.visitInvoke) = (function (v1){ return v1.update(this.visit(v1.expression), this.visitMany(v1.args)); }); } var v3 = (function (v1, v2, v3){ Array.prototype.reduce.call(arguments, v0, v2); }); var v4 = (function (v1, v2, v3){ "use strict"; var v4 = v3(75)(true); v3(76)(String, 'String', (function (v6){ (this._t) = String(v6); (this._i) = 0; }), (function (){ var v7 = this._t; var v8 = this._i; var v9; if((v8) >= (v7.length)){ return ({value : undefined, done : true}); } (v9) = v4(v7, v8); (this._i) += v9.length; return ({value : v9, done : false}); })); }); (v0.PASS_SAMPLER_NAME) = "passSampler"; if(v3.now){ (v0.now) = (function v2(){ return v0.clock.now; }); } (v0.prototype.get) = (function (v1){ if((v1) >= (this.size)){ return v2; } return v1(this._root, v1); });
import { getServerSideProps } from "../pages/performance"; describe("/performance", () => { const anonymousReq = { headers: { cookie: "", }, }; const authenticatedReq = { headers: { cookie: "token=123", }, }; let res; beforeEach(() => { res = { writeHead: jest.fn().mockReturnValue({ end: () => {} }), }; }); describe("getServerSideProps", () => { it("Redirects to the login page if not authenticated", async () => { await getServerSideProps({ req: anonymousReq, res }); expect(res.writeHead).toHaveBeenCalledWith(302, { Location: "/trust-admin/login", }); }); it("Provides the current visit totals as props", async () => { const wardVisitTotalSpy = jest.fn(() => ({ total: 30 })); const tokenProvider = { validate: jest.fn(() => ({ type: "trustAdmin" })), }; const container = { getRetrieveWardVisitTotals: () => wardVisitTotalSpy, getTokenProvider: () => tokenProvider, getRegenerateToken: () => jest.fn().mockReturnValue({}), }; const { props } = await getServerSideProps({ req: authenticatedReq, res, query: {}, container, }); expect(props).toEqual({ visitsScheduled: 30 }); }); }); });
//SainSmart ST7735 1.8" TFT LCD 128x160 pixel class SainSmartTFT18LCD { constructor() { this.keys = ['vcc', 'gnd', 'scl', 'sda', 'dc', 'res', 'cs']; this.required = ['scl', 'sda', 'dc', 'res', 'cs']; this.displayIoNames = { vcc: 'vcc', gnd: 'gnd', scl: 'scl', sda: 'sda', dc: 'dc', res: 'res', cs: 'cs', }; } static info() { return { name: 'SainSmartTFT18LCD', }; } wired(obniz) { this.debugprint = false; this.obniz = obniz; this.io_dc = obniz.getIO(this.params.dc); this.io_res = obniz.getIO(this.params.res); this.io_cs = obniz.getIO(this.params.cs); this.obniz.setVccGnd(this.params.vcc, this.params.gnd, '5v'); this.params.frequency = 16 * 1000 * 1000; //16MHz this.params.mode = 'master'; this.params.clk = this.params.scl; this.params.mosi = this.params.sda; this.params.drive = '3v'; this.spi = this.obniz.getSpiWithConfig(this.params); this.io_dc.output(true); this.io_cs.output(false); this.width = ST7735_TFTWIDTH; this.height = ST7735_TFTHEIGHT; this.writeBuffer = []; //1024bytes bufferring this._setPresetColor(); this.init(); } print_debug(v) { if (this.debugprint) { console.log( 'SainSmartTFT18LCD: ' + Array.prototype.slice.call(arguments).join('') ); } } _deadSleep(waitMsec) { let startMsec = new Date(); while (new Date() - startMsec < waitMsec); } _reset() { this.io_res.output(false); this._deadSleep(10); this.io_res.output(true); this._deadSleep(10); } writeCommand(cmd) { this.io_dc.output(false); this.io_cs.output(false); this.spi.write([cmd]); this.io_cs.output(true); } writeData(data) { this.io_dc.output(true); this.io_cs.output(false); this.spi.write(data); this.io_cs.output(true); } write(cmd, data) { if (data.length == 0) return; this.writeCommand(cmd); this.writeData(data); } async asyncwait() { return await this.spi.writeWait([0x00]); } _writeFlush() { while (this.writeBuffer.length > 0) { if (this.writeBuffer.length > 1024) { let data = this.writeBuffer.slice(0, 1024); this.writeData(data); this.writeBuffer.splice(0, 1024); } else { if (this.writeBuffer.length > 0) this.writeData(this.writeBuffer); this.writeBuffer = []; } } } _writeBuffer(data) { if (data && data.length > 0) { this.writeBuffer = this.writeBuffer.concat(data); } else { this._writeFlush(); } } color16(r, g, b) { // 1st byte (r & 0xF8 | g >> 5) // 2nd byte (g & 0xFC << 3 | b >> 3) return ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3); } _initG() { // initialize for Green Tab this.writeCommand(ST7735_SLPOUT); //Sleep out & booster on this.obniz.wait(120); this.write(ST7735_FRMCTR1, [0x01, 0x2c, 0x2d]); this.write(ST7735_FRMCTR2, [0x01, 0x2c, 0x2d]); this.write(ST7735_FRMCTR3, [0x01, 0x2c, 0x2d, 0x01, 0x2c, 0x2d]); this.write(ST7735_INVCTR, [0x07]); this.write(ST7735_PWCTR1, [0xa2, 0x02, 0x84]); this.write(ST7735_PWCTR2, [0xc5]); this.write(ST7735_PWCTR3, [0x0a, 0x00]); this.write(ST7735_PWCTR4, [0x8a, 0x2a]); this.write(ST7735_PWCTR5, [0x8a, 0xee]); this.write(ST7735_VMCTR1, [0x0e]); this.write(ST7735_GMCTRP1, [ 0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2b, 0x39, 0x00, 0x01, 0x03, 0x10, ]); this.write(ST7735_GMCTRN1, [ 0x03, 0x1d, 0x07, 0x06, 0x2e, 0x2c, 0x29, 0x2d, 0x2e, 0x2e, 0x37, 0x3f, 0x00, 0x00, 0x02, 0x10, ]); this.write(ST7735_COLMOD, [ST7735_16bit]); // color format: 16bit/pixel } init() { this._reset(); this._initG(); this.setDisplayOn(); this.setRotation(0); } setDisplayOn() { this.writeCommand(ST7735_DISPON); } setDisplayOff() { this.writeCommand(ST7735_DISPOFF); } setDisplay(on) { if (on == true) this.setDisplayOn(); else this.setDisplayOff(); } setInversionOn() { this.writeCommand(ST7735_INVON); } setInversionOff() { this.writeCommand(ST7735_INVOFF); } setInversion(inversion) { if (inversion == true) this.setInversionOn(); else this.setInversionOff(); } setRotation(m) { const MADCTL_MY = 0x80; const MADCTL_MX = 0x40; const MADCTL_MV = 0x20; // const MADCTL_ML = 0x10; const MADCTL_RGB = 0x00; //always RGB, never BGR // const MADCTL_MH = 0x04; let data; let rotation = m % 4; // can't be higher than 3 switch (rotation) { case 0: data = [MADCTL_MX | MADCTL_MY | MADCTL_RGB]; this.width = ST7735_TFTWIDTH; this.height = ST7735_TFTHEIGHT; break; case 1: data = [MADCTL_MY | MADCTL_MV | MADCTL_RGB]; this.width = ST7735_TFTHEIGHT; this.height = ST7735_TFTWIDTH; break; case 2: data = [MADCTL_RGB]; this.width = ST7735_TFTWIDTH; this.height = ST7735_TFTHEIGHT; break; case 3: data = [MADCTL_MX | MADCTL_MV | MADCTL_RGB]; this.width = ST7735_TFTHEIGHT; this.height = ST7735_TFTWIDTH; break; } this.write(ST7735_MADCTL, data); this.setAddrWindow(0, 0, this.width - 1, this.height - 1); } setAddrWindow(x0, y0, x1, y1) { this.print_debug( `setAddrWindow: (x0: ${x0}, y0: ${y0}) - (x1: ${x1}, y1: ${y1})` ); if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x1 < 0) x1 = 0; if (y1 < 0) y1 = 0; // column addr set this.write(ST7735_CASET, [0x00, x0, 0x00, x1]); // XSTART-XEND // row addr set this.write(ST7735_RASET, [0x00, y0, 0x00, y1]); // YSTART-YEND // write to RAM this.writeCommand(ST7735_RAMWR); this.writeBuffer = []; } //__swap(a, b) { let t = a; a = b; b = t; } fillScreen(color) { this.fillRect(0, 0, this.width, this.height, color); } fillRect(x, y, w, h, color) { if (x >= this.width || y >= this.height) return; if (x + w - 1 >= this.width) w = this.width - x; if (y + h - 1 >= this.height) h = this.height - y; this.setAddrWindow(x, y, x + w - 1, y + h - 1); let hi = color >> 8, lo = color & 0xff; let data = []; for (y = h; y > 0; y--) { for (x = w; x > 0; x--) { data.push(hi); data.push(lo); } } this._writeBuffer(data); this._writeBuffer(); //for flush } drawRect(x, y, w, h, color) { this.drawHLine(x, y, w, color); this.drawHLine(x, y + h - 1, w, color); this.drawVLine(x, y, h, color); this.drawVLine(x + w - 1, y, h, color); } drawCircle(x0, y0, r, color) { let f = 1 - r; let ddF_x = 1; let ddF_y = -2 * r; let x = 0; let y = r; this.drawPixel(x0, y0 + r, color); this.drawPixel(x0, y0 - r, color); this.drawPixel(x0 + r, y0, color); this.drawPixel(x0 - r, y0, color); while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; this.drawPixel(x0 + x, y0 + y, color); this.drawPixel(x0 - x, y0 + y, color); this.drawPixel(x0 + x, y0 - y, color); this.drawPixel(x0 - x, y0 - y, color); this.drawPixel(x0 + y, y0 + x, color); this.drawPixel(x0 - y, y0 + x, color); this.drawPixel(x0 + y, y0 - x, color); this.drawPixel(x0 - y, y0 - x, color); } } _drawCircleHelper(x0, y0, r, cornername, color) { let f = 1 - r; let ddF_x = 1; let ddF_y = -2 * r; let x = 0; let y = r; while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4) { this.drawPixel(x0 + x, y0 + y, color); this.drawPixel(x0 + y, y0 + x, color); } if (cornername & 0x2) { this.drawPixel(x0 + x, y0 - y, color); this.drawPixel(x0 + y, y0 - x, color); } if (cornername & 0x8) { this.drawPixel(x0 - y, y0 + x, color); this.drawPixel(x0 - x, y0 + y, color); } if (cornername & 0x1) { this.drawPixel(x0 - y, y0 - x, color); this.drawPixel(x0 - x, y0 - y, color); } } } fillCircle(x0, y0, r, color) { this.drawVLine(x0, y0 - r, 2 * r + 1, color); this._fillCircleHelper(x0, y0, r, 3, 0, color); } _fillCircleHelper(x0, y0, r, cornername, delta, color) { let f = 1 - r; let ddF_x = 1; let ddF_y = -2 * r; let x = 0; let y = r; while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x1) { this.drawVLine(x0 + x, y0 - y, 2 * y + 1 + delta, color); this.drawVLine(x0 + y, y0 - x, 2 * x + 1 + delta, color); } if (cornername & 0x2) { this.drawVLine(x0 - x, y0 - y, 2 * y + 1 + delta, color); this.drawVLine(x0 - y, y0 - x, 2 * x + 1 + delta, color); } } } drawRoundRect(x, y, w, h, r, color) { this.drawHLine(x + r, y, w - 2 * r, color); // Top this.drawHLine(x + r, y + h - 1, w - 2 * r, color); // Bottom this.drawVLine(x, y + r, h - 2 * r, color); // Left this.drawVLine(x + w - 1, y + r, h - 2 * r, color); // Right this._drawCircleHelper(x + r, y + r, r, 1, color); this._drawCircleHelper(x + w - r - 1, y + r, r, 2, color); this._drawCircleHelper(x + w - r - 1, y + h - r - 1, r, 4, color); this._drawCircleHelper(x + r, y + h - r - 1, r, 8, color); } fillRoundRect(x, y, w, h, r, color) { this.fillRect(x + r, y, w - 2 * r, h, color); this._fillCircleHelper(x + w - r - 1, y + r, r, 1, h - 2 * r - 1, color); this._fillCircleHelper(x + r, y + r, r, 2, h - 2 * r - 1, color); } drawTriangle(x0, y0, x1, y1, x2, y2, color) { this.drawLine(x0, y0, x1, y1, color); this.drawLine(x1, y1, x2, y2, color); this.drawLine(x2, y2, x0, y0, color); } fillTriangle(x0, y0, x1, y1, x2, y2, color) { let a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1) { y1 = [y0, (y0 = y1)][0]; //this._swap(y0, y1); x1 = [x0, (x0 = x1)][0]; //this._swap(x0, x1); } if (y1 > y2) { y2 = [y1, (y1 = y2)][0]; //this._swap(y2, y1); x2 = [x1, (x1 = x2)][0]; //this._swap(x2, x1); } if (y0 > y1) { y1 = [y0, (y0 = y1)][0]; //this._swap(y0, y1); x1 = [x0, (x0 = x1)][0]; //this._swap(x0, x1); } if (y0 == y2) { // Handle awkward all-on-same-line case as its own thing a = b = x0; if (x1 < a) a = x1; else if (x1 > b) b = x1; if (x2 < a) a = x2; else if (x2 > b) b = x2; this.drawHLine(a, y0, b - a + 1, color); return; } let dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1, sa = 0, sb = 0; if (y1 == y2) last = y1; // include y1 scanline else last = y1 - 1; // skip it for (y = y0; y <= last; y++) { a = x0 + Math.floor(sa / dy01); b = x0 + Math.floor(sb / dy02); sa += dx01; sb += dx02; if (a > b) b = [a, (a = b)][0]; //this._swap(a,b); this.drawHLine(a, y, b - a + 1, color); } sa = dx12 * (y - y1); sb = dx02 * (y - y0); for (; y <= y2; y++) { a = x1 + Math.floor(sa / dy12); b = x0 + Math.floor(sb / dy02); sa += dx12; sb += dx02; if (a > b) b = [a, (a = b)][0]; //this._swap(a,b); this.drawHLine(a, y, b - a + 1, color); } } drawVLine(x, y, h, color) { if (x >= this.width || y >= this.height) return; if (y + h - 1 >= this.height) h = this.height - y; this.setAddrWindow(x, y, x, y + h - 1); let hi = color >> 8, lo = color & 0xff; let data = []; while (h--) { data.push(hi); data.push(lo); } this.writeData(data); } drawHLine(x, y, w, color) { if (x >= this.width || y >= this.height) return; if (x + w - 1 >= this.width) w = this.width - x; this.setAddrWindow(x, y, x + w - 1, y); let hi = color >> 8, lo = color & 0xff; let data = []; while (w--) { data.push(hi); data.push(lo); } this.writeData(data); } drawLine(x0, y0, x1, y1, color) { let step = Math.abs(y1 - y0) > Math.abs(x1 - x0); if (step) { y0 = [x0, (x0 = y0)][0]; //this._swap(x0, y0); y1 = [x1, (x1 = y1)][0]; //this._swap(x1, y1); } if (x0 > x1) { x1 = [x0, (x0 = x1)][0]; //this._swap(x0, x1); y1 = [y0, (y0 = y1)][0]; //this._swap(y0, y1); } let dx = x1 - x0; let dy = Math.abs(y1 - y0); let err = dx / 2; let ystep = y0 < y1 ? 1 : -1; for (; x0 <= x1; x0++) { if (step) { this.drawPixel(y0, x0, color); } else { this.drawPixel(x0, y0, color); } err -= dy; if (err < 0) { y0 += ystep; err += dx; } } } drawPixel(x, y, color) { if (x < 0 || x >= this.width || y < 0 || y >= this.height) return; this.setAddrWindow(x, y, x + 1, y + 1); this.writeData([color >> 8, color & 0xff]); } drawChar(x, y, ch, color, bg, size) { // bg = bg || color; size = size || 1; if ( x >= this.width || // Clip right y >= this.height || // Clip bottom x + 6 * size - 1 < 0 || // Clip left y + 8 * size - 1 < 0 ) // Clip top return; if (color != bg) { this.drawChar2(x, y, ch, color, bg, size); return; } let c = ch.charCodeAt(0); for (let i = 0; i < 6; i++) { let line = i == 5 ? 0 : font[c * 5 + i]; for (let j = 0; j < 8; j++) { if (line & 0x1) { if (size == 1) // default size this.drawPixel(x + i, y + j, color); else { // big size this.fillRect(x + i * size, y + j * size, size, size, color); } } else if (bg != color) { if (size == 1) // default size this.drawPixel(x + i, y + j, bg); else { // big size this.fillRect(x + i * size, y + j * size, size, size, bg); } } line >>= 1; } } } drawChar2(x, y, ch, color, bg, size) { // bg = bg || color; size = size || 1; if ( x >= this.width || // Clip right y >= this.height || // Clip bottom x + 6 * size - 1 < 0 || // Clip left y + 8 * size - 1 < 0 // Clip top ) return; let pixels = new Array(6 * 8 * size * size); let c = ch.charCodeAt(0); for (let i = 0; i < 6; i++) { let line = i == 5 ? 0 : font[c * 5 + i]; for (let j = 0; j < 8; j++) { let cl = line & 0x1 ? color : bg; for (let w = 0; w < size; w++) { for (let h = 0; h < size; h++) { pixels[ i * (1 * size) + w + (j * (6 * size * size) + h * (6 * size)) ] = cl; } } line >>= 1; } } this.rawBound16(x, y, 6 * size, 8 * size, pixels); } rawBound16(x, y, width, height, pixels) { let rgb = []; pixels.forEach(function(v) { rgb.push((v & 0xff00) >> 8); rgb.push(v & 0xff); }); this.setAddrWindow(x, y, x + width - 1, y + height - 1); this._writeBuffer(rgb); this._writeBuffer(); //for flush } drawString(x, y, str, color, bg, size, wrap) { // bg = bg || color; size = size || 1; // wrap = wrap || true; for (let n = 0; n < str.length; n++) { let c = str.charAt(n); if (c == '\n') { y += size * 8; x = 0; } else if (c == '\r') { // skip em } else { this.drawChar(x, y, c, color, bg, size); x += size * 6; if (wrap && x > this.width - size * 6) { y += size * 8; x = 0; } } } return [x, y]; } drawContextBound(context, x0, y0, width, height, x1, y1, gray) { x0 = x0 || 0; y0 = y0 || 0; width = width || context.canvas.clientWidth; height = height || context.canvas.clientHeight; x1 = x1 || 0; y1 = y1 || 0; gray = gray || false; this.write(ST7735_COLMOD, [ST7735_18bit]); //18bit/pixel let imageData = context.getImageData(x0, y0, width, height).data; let rgb = []; for (let n = 0; n < imageData.length; n += 4) { let r = imageData[n + 0]; let g = imageData[n + 1]; let b = imageData[n + 2]; if (!gray) { rgb.push(r); rgb.push(g); rgb.push(b); } else { let gs = Math.round(0.299 * r + 0.587 * g + 0.114 * b); rgb.push(gs); rgb.push(gs); rgb.push(gs); } } this.write(ST7735_COLMOD, [ST7735_18bit]); //18bit/pixel this.setAddrWindow(x1, y1, x1 + width - 1, y1 + height - 1); this._writeBuffer(rgb); this._writeBuffer(); //for flush this.write(ST7735_COLMOD, [ST7735_16bit]); //16bit/pixel } drawContext(context, gray) { gray = gray || false; this.drawContextBound(context, 0, 0, this.width, this.height, 0, 0, gray); } rawBound(x, y, width, height, pixels) { let rgb = []; pixels.forEach(function(v) { rgb.push((v & 0xff0000) >> 16); rgb.push((v & 0xff00) >> 8); rgb.push(v & 0xff); }); this.write(ST7735_COLMOD, [ST7735_18bit]); //18bit/pixel this.setAddrWindow(x, y, x + width - 1, y + height - 1); this._writeBuffer(rgb); this._writeBuffer(); //for flush this.write(ST7735_COLMOD, [ST7735_16bit]); //16bit/pixel } raw(pixels) { this.raw(0, 0, this.width, this.height, pixels); } _setPresetColor() { this.color = { AliceBlue: 0xf7df, AntiqueWhite: 0xff5a, Aqua: 0x07ff, Aquamarine: 0x7ffa, Azure: 0xf7ff, Beige: 0xf7bb, Bisque: 0xff38, Black: 0x0000, BlanchedAlmond: 0xff59, Blue: 0x001f, BlueViolet: 0x895c, Brown: 0xa145, BurlyWood: 0xddd0, CadetBlue: 0x5cf4, Chartreuse: 0x7fe0, Chocolate: 0xd343, Coral: 0xfbea, CornflowerBlue: 0x64bd, Cornsilk: 0xffdb, Crimson: 0xd8a7, Cyan: 0x07ff, DarkBlue: 0x0011, DarkCyan: 0x0451, DarkGoldenRod: 0xbc21, DarkGray: 0xad55, DarkGreen: 0x0320, DarkKhaki: 0xbdad, DarkMagenta: 0x8811, DarkOliveGreen: 0x5345, DarkOrange: 0xfc60, DarkOrchid: 0x9999, DarkRed: 0x8800, DarkSalmon: 0xecaf, DarkSeaGreen: 0x8df1, DarkSlateBlue: 0x49f1, DarkSlateGray: 0x2a69, DarkTurquoise: 0x067a, DarkViolet: 0x901a, DeepPink: 0xf8b2, DeepSkyBlue: 0x05ff, DimGray: 0x6b4d, DodgerBlue: 0x1c9f, FireBrick: 0xb104, FloralWhite: 0xffde, ForestGreen: 0x2444, Fuchsia: 0xf81f, Gainsboro: 0xdefb, GhostWhite: 0xffdf, Gold: 0xfea0, GoldenRod: 0xdd24, Gray: 0x8410, Green: 0x0400, GreenYellow: 0xafe5, HoneyDew: 0xf7fe, HotPink: 0xfb56, IndianRed: 0xcaeb, Indigo: 0x4810, Ivory: 0xfffe, Khaki: 0xf731, Lavender: 0xe73f, LavenderBlush: 0xff9e, LawnGreen: 0x7fe0, LemonChiffon: 0xffd9, LightBlue: 0xaedc, LightCoral: 0xf410, LightCyan: 0xe7ff, LightGoldenRodYellow: 0xffda, LightGray: 0xd69a, LightGreen: 0x9772, LightPink: 0xfdb8, LightSalmon: 0xfd0f, LightSeaGreen: 0x2595, LightSkyBlue: 0x867f, LightSlateGray: 0x7453, LightSteelBlue: 0xb63b, LightYellow: 0xfffc, Lime: 0x07e0, LimeGreen: 0x3666, Linen: 0xff9c, Magenta: 0xf81f, Maroon: 0x8000, MediumAquaMarine: 0x6675, MediumBlue: 0x0019, MediumOrchid: 0xbaba, MediumPurple: 0x939b, MediumSeaGreen: 0x3d8e, MediumSlateBlue: 0x7b5d, MediumSpringGreen: 0x07d3, MediumTurquoise: 0x4e99, MediumVioletRed: 0xc0b0, MidnightBlue: 0x18ce, MintCream: 0xf7ff, MistyRose: 0xff3c, Moccasin: 0xff36, NavajoWhite: 0xfef5, Navy: 0x0010, OldLace: 0xffbc, Olive: 0x8400, OliveDrab: 0x6c64, Orange: 0xfd20, OrangeRed: 0xfa20, Orchid: 0xdb9a, PaleGoldenRod: 0xef55, PaleGreen: 0x9fd3, PaleTurquoise: 0xaf7d, PaleVioletRed: 0xdb92, PapayaWhip: 0xff7a, PeachPuff: 0xfed7, Peru: 0xcc27, Pink: 0xfe19, Plum: 0xdd1b, PowderBlue: 0xb71c, Purple: 0x8010, RebeccaPurple: 0x6193, Red: 0xf800, RosyBrown: 0xbc71, RoyalBlue: 0x435c, SaddleBrown: 0x8a22, Salmon: 0xfc0e, SandyBrown: 0xf52c, SeaGreen: 0x2c4a, SeaShell: 0xffbd, Sienna: 0xa285, Silver: 0xc618, SkyBlue: 0x867d, SlateBlue: 0x6ad9, SlateGray: 0x7412, Snow: 0xffdf, SpringGreen: 0x07ef, SteelBlue: 0x4416, Tan: 0xd5b1, Teal: 0x0410, Thistle: 0xddfb, Tomato: 0xfb08, Turquoise: 0x471a, Violet: 0xec1d, Wheat: 0xf6f6, White: 0xffff, WhiteSmoke: 0xf7be, Yellow: 0xffe0, YellowGreen: 0x9e66, }; } } if (typeof module === 'object') { module.exports = SainSmartTFT18LCD; } //---------------------------------------------------------- // commands // const INITR_GREENTAB = 0x0; // const INITR_REDTAB = 0x1; // const INITR_BLACKTAB = 0x2; const ST7735_TFTWIDTH = 128; const ST7735_TFTHEIGHT = 160; // const ST7735_NOP = 0x00; // const ST7735_SWRESET = 0x01; // const ST7735_RDDID = 0x04; // const ST7735_RDDST = 0x09; // const ST7735_RDDPM = 0x0a; // const ST7735_SLPIN = 0x10; const ST7735_SLPOUT = 0x11; // const ST7735_PTLON = 0x12; // const ST7735_NORON = 0x13; const ST7735_INVOFF = 0x20; const ST7735_INVON = 0x21; const ST7735_DISPOFF = 0x28; const ST7735_DISPON = 0x29; const ST7735_CASET = 0x2a; const ST7735_RASET = 0x2b; const ST7735_RAMWR = 0x2c; // const ST7735_RAMRD = 0x2e; // const ST7735_PTLAR = 0x30; const ST7735_COLMOD = 0x3a; const ST7735_MADCTL = 0x36; const ST7735_FRMCTR1 = 0xb1; const ST7735_FRMCTR2 = 0xb2; const ST7735_FRMCTR3 = 0xb3; const ST7735_INVCTR = 0xb4; // const ST7735_DISSET5 = 0xb6; const ST7735_PWCTR1 = 0xc0; const ST7735_PWCTR2 = 0xc1; const ST7735_PWCTR3 = 0xc2; const ST7735_PWCTR4 = 0xc3; const ST7735_PWCTR5 = 0xc4; const ST7735_VMCTR1 = 0xc5; // const ST7735_RDID1 = 0xda; // const ST7735_RDID2 = 0xdb; // const ST7735_RDID3 = 0xdc; // const ST7735_RDID4 = 0xdd; // const ST7735_PWCTR6 = 0xfc; const ST7735_GMCTRP1 = 0xe0; const ST7735_GMCTRN1 = 0xe1; // Color definitions // const ST7735_BLACK = 0x0000; // const ST7735_BLUE = 0x001f; // const ST7735_RED = 0xf800; // const ST7735_GREEN = 0x07e0; // const ST7735_CYAN = 0x07ff; // const ST7735_MAGENTA = 0xf81f; // const ST7735_YELLOW = 0xffe0; // const ST7735_WHITE = 0xffff; const ST7735_18bit = 0x06; // 18bit/pixel const ST7735_16bit = 0x05; // 16bit/pixel // standard ascii 5x7 font const font = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x5b, 0x4f, 0x5b, 0x3e, 0x3e, 0x6b, 0x4f, 0x6b, 0x3e, 0x1c, 0x3e, 0x7c, 0x3e, 0x1c, 0x18, 0x3c, 0x7e, 0x3c, 0x18, 0x1c, 0x57, 0x7d, 0x57, 0x1c, 0x1c, 0x5e, 0x7f, 0x5e, 0x1c, 0x00, 0x18, 0x3c, 0x18, 0x00, 0xff, 0xe7, 0xc3, 0xe7, 0xff, 0x00, 0x18, 0x24, 0x18, 0x00, 0xff, 0xe7, 0xdb, 0xe7, 0xff, 0x30, 0x48, 0x3a, 0x06, 0x0e, 0x26, 0x29, 0x79, 0x29, 0x26, 0x40, 0x7f, 0x05, 0x05, 0x07, 0x40, 0x7f, 0x05, 0x25, 0x3f, 0x5a, 0x3c, 0xe7, 0x3c, 0x5a, 0x7f, 0x3e, 0x1c, 0x1c, 0x08, 0x08, 0x1c, 0x1c, 0x3e, 0x7f, 0x14, 0x22, 0x7f, 0x22, 0x14, 0x5f, 0x5f, 0x00, 0x5f, 0x5f, 0x06, 0x09, 0x7f, 0x01, 0x7f, 0x00, 0x66, 0x89, 0x95, 0x6a, 0x60, 0x60, 0x60, 0x60, 0x60, 0x94, 0xa2, 0xff, 0xa2, 0x94, 0x08, 0x04, 0x7e, 0x04, 0x08, 0x10, 0x20, 0x7e, 0x20, 0x10, 0x08, 0x08, 0x2a, 0x1c, 0x08, 0x08, 0x1c, 0x2a, 0x08, 0x08, 0x1e, 0x10, 0x10, 0x10, 0x10, 0x0c, 0x1e, 0x0c, 0x1e, 0x0c, 0x30, 0x38, 0x3e, 0x38, 0x30, 0x06, 0x0e, 0x3e, 0x0e, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x00, 0x07, 0x00, 0x07, 0x00, 0x14, 0x7f, 0x14, 0x7f, 0x14, 0x24, 0x2a, 0x7f, 0x2a, 0x12, 0x23, 0x13, 0x08, 0x64, 0x62, 0x36, 0x49, 0x56, 0x20, 0x50, 0x00, 0x08, 0x07, 0x03, 0x00, 0x00, 0x1c, 0x22, 0x41, 0x00, 0x00, 0x41, 0x22, 0x1c, 0x00, 0x2a, 0x1c, 0x7f, 0x1c, 0x2a, 0x08, 0x08, 0x3e, 0x08, 0x08, 0x00, 0x80, 0x70, 0x30, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x60, 0x60, 0x00, 0x20, 0x10, 0x08, 0x04, 0x02, 0x3e, 0x51, 0x49, 0x45, 0x3e, 0x00, 0x42, 0x7f, 0x40, 0x00, 0x72, 0x49, 0x49, 0x49, 0x46, 0x21, 0x41, 0x49, 0x4d, 0x33, 0x18, 0x14, 0x12, 0x7f, 0x10, 0x27, 0x45, 0x45, 0x45, 0x39, 0x3c, 0x4a, 0x49, 0x49, 0x31, 0x41, 0x21, 0x11, 0x09, 0x07, 0x36, 0x49, 0x49, 0x49, 0x36, 0x46, 0x49, 0x49, 0x29, 0x1e, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x40, 0x34, 0x00, 0x00, 0x00, 0x08, 0x14, 0x22, 0x41, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, 0x41, 0x22, 0x14, 0x08, 0x02, 0x01, 0x59, 0x09, 0x06, 0x3e, 0x41, 0x5d, 0x59, 0x4e, 0x7c, 0x12, 0x11, 0x12, 0x7c, 0x7f, 0x49, 0x49, 0x49, 0x36, 0x3e, 0x41, 0x41, 0x41, 0x22, 0x7f, 0x41, 0x41, 0x41, 0x3e, 0x7f, 0x49, 0x49, 0x49, 0x41, 0x7f, 0x09, 0x09, 0x09, 0x01, 0x3e, 0x41, 0x41, 0x51, 0x73, 0x7f, 0x08, 0x08, 0x08, 0x7f, 0x00, 0x41, 0x7f, 0x41, 0x00, 0x20, 0x40, 0x41, 0x3f, 0x01, 0x7f, 0x08, 0x14, 0x22, 0x41, 0x7f, 0x40, 0x40, 0x40, 0x40, 0x7f, 0x02, 0x1c, 0x02, 0x7f, 0x7f, 0x04, 0x08, 0x10, 0x7f, 0x3e, 0x41, 0x41, 0x41, 0x3e, 0x7f, 0x09, 0x09, 0x09, 0x06, 0x3e, 0x41, 0x51, 0x21, 0x5e, 0x7f, 0x09, 0x19, 0x29, 0x46, 0x26, 0x49, 0x49, 0x49, 0x32, 0x03, 0x01, 0x7f, 0x01, 0x03, 0x3f, 0x40, 0x40, 0x40, 0x3f, 0x1f, 0x20, 0x40, 0x20, 0x1f, 0x3f, 0x40, 0x38, 0x40, 0x3f, 0x63, 0x14, 0x08, 0x14, 0x63, 0x03, 0x04, 0x78, 0x04, 0x03, 0x61, 0x59, 0x49, 0x4d, 0x43, 0x00, 0x7f, 0x41, 0x41, 0x41, 0x02, 0x04, 0x08, 0x10, 0x20, 0x00, 0x41, 0x41, 0x41, 0x7f, 0x04, 0x02, 0x01, 0x02, 0x04, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, 0x03, 0x07, 0x08, 0x00, 0x20, 0x54, 0x54, 0x78, 0x40, 0x7f, 0x28, 0x44, 0x44, 0x38, 0x38, 0x44, 0x44, 0x44, 0x28, 0x38, 0x44, 0x44, 0x28, 0x7f, 0x38, 0x54, 0x54, 0x54, 0x18, 0x00, 0x08, 0x7e, 0x09, 0x02, 0x18, 0xa4, 0xa4, 0x9c, 0x78, 0x7f, 0x08, 0x04, 0x04, 0x78, 0x00, 0x44, 0x7d, 0x40, 0x00, 0x20, 0x40, 0x40, 0x3d, 0x00, 0x7f, 0x10, 0x28, 0x44, 0x00, 0x00, 0x41, 0x7f, 0x40, 0x00, 0x7c, 0x04, 0x78, 0x04, 0x78, 0x7c, 0x08, 0x04, 0x04, 0x78, 0x38, 0x44, 0x44, 0x44, 0x38, 0xfc, 0x18, 0x24, 0x24, 0x18, 0x18, 0x24, 0x24, 0x18, 0xfc, 0x7c, 0x08, 0x04, 0x04, 0x08, 0x48, 0x54, 0x54, 0x54, 0x24, 0x04, 0x04, 0x3f, 0x44, 0x24, 0x3c, 0x40, 0x40, 0x20, 0x7c, 0x1c, 0x20, 0x40, 0x20, 0x1c, 0x3c, 0x40, 0x30, 0x40, 0x3c, 0x44, 0x28, 0x10, 0x28, 0x44, 0x4c, 0x90, 0x90, 0x90, 0x7c, 0x44, 0x64, 0x54, 0x4c, 0x44, 0x00, 0x08, 0x36, 0x41, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x41, 0x36, 0x08, 0x00, 0x02, 0x01, 0x02, 0x04, 0x02, 0x3c, 0x26, 0x23, 0x26, 0x3c, 0x1e, 0xa1, 0xa1, 0x61, 0x12, 0x3a, 0x40, 0x40, 0x20, 0x7a, 0x38, 0x54, 0x54, 0x55, 0x59, 0x21, 0x55, 0x55, 0x79, 0x41, 0x21, 0x54, 0x54, 0x78, 0x41, 0x21, 0x55, 0x54, 0x78, 0x40, 0x20, 0x54, 0x55, 0x79, 0x40, 0x0c, 0x1e, 0x52, 0x72, 0x12, 0x39, 0x55, 0x55, 0x55, 0x59, 0x39, 0x54, 0x54, 0x54, 0x59, 0x39, 0x55, 0x54, 0x54, 0x58, 0x00, 0x00, 0x45, 0x7c, 0x41, 0x00, 0x02, 0x45, 0x7d, 0x42, 0x00, 0x01, 0x45, 0x7c, 0x40, 0xf0, 0x29, 0x24, 0x29, 0xf0, 0xf0, 0x28, 0x25, 0x28, 0xf0, 0x7c, 0x54, 0x55, 0x45, 0x00, 0x20, 0x54, 0x54, 0x7c, 0x54, 0x7c, 0x0a, 0x09, 0x7f, 0x49, 0x32, 0x49, 0x49, 0x49, 0x32, 0x32, 0x48, 0x48, 0x48, 0x32, 0x32, 0x4a, 0x48, 0x48, 0x30, 0x3a, 0x41, 0x41, 0x21, 0x7a, 0x3a, 0x42, 0x40, 0x20, 0x78, 0x00, 0x9d, 0xa0, 0xa0, 0x7d, 0x39, 0x44, 0x44, 0x44, 0x39, 0x3d, 0x40, 0x40, 0x40, 0x3d, 0x3c, 0x24, 0xff, 0x24, 0x24, 0x48, 0x7e, 0x49, 0x43, 0x66, 0x2b, 0x2f, 0xfc, 0x2f, 0x2b, 0xff, 0x09, 0x29, 0xf6, 0x20, 0xc0, 0x88, 0x7e, 0x09, 0x03, 0x20, 0x54, 0x54, 0x79, 0x41, 0x00, 0x00, 0x44, 0x7d, 0x41, 0x30, 0x48, 0x48, 0x4a, 0x32, 0x38, 0x40, 0x40, 0x22, 0x7a, 0x00, 0x7a, 0x0a, 0x0a, 0x72, 0x7d, 0x0d, 0x19, 0x31, 0x7d, 0x26, 0x29, 0x29, 0x2f, 0x28, 0x26, 0x29, 0x29, 0x29, 0x26, 0x30, 0x48, 0x4d, 0x40, 0x20, 0x38, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x38, 0x2f, 0x10, 0xc8, 0xac, 0xba, 0x2f, 0x10, 0x28, 0x34, 0xfa, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x08, 0x14, 0x2a, 0x14, 0x22, 0x22, 0x14, 0x2a, 0x14, 0x08, 0xaa, 0x00, 0x55, 0x00, 0xaa, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x00, 0x00, 0x00, 0xff, 0x00, 0x10, 0x10, 0x10, 0xff, 0x00, 0x14, 0x14, 0x14, 0xff, 0x00, 0x10, 0x10, 0xff, 0x00, 0xff, 0x10, 0x10, 0xf0, 0x10, 0xf0, 0x14, 0x14, 0x14, 0xfc, 0x00, 0x14, 0x14, 0xf7, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x14, 0x14, 0xf4, 0x04, 0xfc, 0x14, 0x14, 0x17, 0x10, 0x1f, 0x10, 0x10, 0x1f, 0x10, 0x1f, 0x14, 0x14, 0x14, 0x1f, 0x00, 0x10, 0x10, 0x10, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x10, 0x10, 0x10, 0x10, 0x1f, 0x10, 0x10, 0x10, 0x10, 0xf0, 0x10, 0x00, 0x00, 0x00, 0xff, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0xff, 0x10, 0x00, 0x00, 0x00, 0xff, 0x14, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x1f, 0x10, 0x17, 0x00, 0x00, 0xfc, 0x04, 0xf4, 0x14, 0x14, 0x17, 0x10, 0x17, 0x14, 0x14, 0xf4, 0x04, 0xf4, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xf7, 0x00, 0xf7, 0x14, 0x14, 0x14, 0x17, 0x14, 0x10, 0x10, 0x1f, 0x10, 0x1f, 0x14, 0x14, 0x14, 0xf4, 0x14, 0x10, 0x10, 0xf0, 0x10, 0xf0, 0x00, 0x00, 0x1f, 0x10, 0x1f, 0x00, 0x00, 0x00, 0x1f, 0x14, 0x00, 0x00, 0x00, 0xfc, 0x14, 0x00, 0x00, 0xf0, 0x10, 0xf0, 0x10, 0x10, 0xff, 0x10, 0xff, 0x14, 0x14, 0x14, 0xff, 0x14, 0x10, 0x10, 0x10, 0x1f, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x38, 0x44, 0x44, 0x38, 0x44, 0x7c, 0x2a, 0x2a, 0x3e, 0x14, 0x7e, 0x02, 0x02, 0x06, 0x06, 0x02, 0x7e, 0x02, 0x7e, 0x02, 0x63, 0x55, 0x49, 0x41, 0x63, 0x38, 0x44, 0x44, 0x3c, 0x04, 0x40, 0x7e, 0x20, 0x1e, 0x20, 0x06, 0x02, 0x7e, 0x02, 0x02, 0x99, 0xa5, 0xe7, 0xa5, 0x99, 0x1c, 0x2a, 0x49, 0x2a, 0x1c, 0x4c, 0x72, 0x01, 0x72, 0x4c, 0x30, 0x4a, 0x4d, 0x4d, 0x30, 0x30, 0x48, 0x78, 0x48, 0x30, 0xbc, 0x62, 0x5a, 0x46, 0x3d, 0x3e, 0x49, 0x49, 0x49, 0x00, 0x7e, 0x01, 0x01, 0x01, 0x7e, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x44, 0x44, 0x5f, 0x44, 0x44, 0x40, 0x51, 0x4a, 0x44, 0x40, 0x40, 0x44, 0x4a, 0x51, 0x40, 0x00, 0x00, 0xff, 0x01, 0x03, 0xe0, 0x80, 0xff, 0x00, 0x00, 0x08, 0x08, 0x6b, 0x6b, 0x08, 0x36, 0x12, 0x36, 0x24, 0x36, 0x06, 0x0f, 0x09, 0x0f, 0x06, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x30, 0x40, 0xff, 0x01, 0x01, 0x00, 0x1f, 0x01, 0x01, 0x1e, 0x00, 0x19, 0x1d, 0x17, 0x12, 0x00, 0x3c, 0x3c, 0x3c, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, ];
"use strict"; // Require the max-api module to connect to Max via node.script const maxAPI = require("max-api"); var add = require("vectors/add")(2); var sub = require("vectors/sub")(2); var mult = require("vectors/mult")(2); var div = require("vectors/div")(2); var mag = require("vectors/mag")(2); var dot = require("vectors/dot")(2); var norm = require("vectors/normalize")(2); var heading = require("vectors/heading")(2); var location = []; var speed = []; // When nodescript gets the symbol "text", the remainder will be passed to this function. // The "..." is the spread operator. All of the arguments to this function will go into args as an array. maxAPI.addHandler("text1", (...args) => { // The outlet function sends the arguments right back to Max. Hence, echo. maxAPI.outlet(...args); }); maxAPI.addHandler("textRoute", (...args) => { add(location, speed); // The outlet function sends the arguments right back to Max. Hence, echo. // maxAPI.outlet("textRouteOutput", ...args); maxAPI.outlet("addVectors", 5); }); maxAPI.addHandler("locationVelocity", (...args) => { location = [args[1], args[2]]; speed = [args[3], args[4]]; add(location, speed); maxAPI.outlet(location); maxAPI.outlet("locationVelocityOutput", ...location); }); maxAPI.addHandler("addingVectors", (...args) => { var vector1 = [args[1], args[2]]; var vector2 = [args[3], args[4]]; var vector3 = [args[5], args[6]]; add(vector1, vector2); add(vector1, vector3); maxAPI.outlet(vector1); maxAPI.outlet("addingVectorsOutput", ...vector1); }); maxAPI.addHandler("subtractVectors", (...args) => { var vector1 = [args[1], args[2]]; var vector2 = [args[3], args[4]]; // var vector3 = [args[5], args[6]]; sub(vector1, vector2); // sub(vector1,vector3) maxAPI.outlet(vector1); maxAPI.outlet("subtractVectorsOutput", ...vector1); }); maxAPI.addHandler("multVectors", (...args) => { var vector1 = [args[1], args[2]]; var vector2 = [args[3], args[4]]; // var vector3 = [args[5], args[6]]; mult(vector1, vector2); maxAPI.outlet(vector1); maxAPI.outlet("multVectorsOutput", ...vector1); }); maxAPI.addHandler("divVectors", (...args) => { var vector1 = [args[1], args[2]]; var vector2 = [args[3], args[4]]; // var vector3 = [args[5], args[6]]; div(vector1, vector2); maxAPI.outlet(vector1); maxAPI.outlet("divVectorsOutput", ...vector1); }); maxAPI.addHandler("magVector", (...args) => { var vector1 = [args[1], args[2]]; // var vector3 = [args[5], args[6]]; mag(vector1); maxAPI.outlet(vector1); maxAPI.outlet("magVectorOutput", vector1[1]); }); maxAPI.addHandler("normVector", (...args) => { var vector1 = [args[1], args[2]]; // var vector3 = [args[5], args[6]]; norm(vector1); maxAPI.outlet(vector1); maxAPI.outlet("normVectorOutput", vector1[1]); }); maxAPI.addHandler("headingVector", (...args) => { var vector1 = [args[1], args[2]]; var vector2 = [args[3], args[4]]; var head = (heading(vector1, vector2)) * 180 / Math.PI; maxAPI.outlet(head); maxAPI.outlet("headingVectorOutput", head); }); maxAPI.addHandler("dotVector", (...args) => { var vector1 = [args[1], args[2]]; var vector2 = [args[3], args[4]]; var dots = dot(vector1, vector2); maxAPI.outlet(dots); maxAPI.outlet("dotVectorOutput", dot(vector1, vector2)); });
# https://atcoder.jp/contests/abc157/tasks/abc157_c N, M = map(int, input().split()) start = 10 ** (N - 1) if N != 1 else 0 end = start * 10 - 1 if N != 1 else 9 if M == 0: print(start) exit() sc_set = set() for _ in range(M): s, c = map(int, input().split()) sc_set.add((s, c)) for i in range(start, end + 1): str_i = str(i) hantei = True for sc in sc_set: if int(str_i[sc[0] - 1]) != sc[1]: hantei = False break if hantei: print(i) exit() print(-1)
import numpy as np from scipy.linalg import cholesky def simulate_b(N_sim, N_steps, B_0, mu, sigma_B, dt): """ Parameters ---------- N_sim : TYPE DESCRIPTION. N_steps : TYPE DESCRIPTION. B_0 : TYPE DESCRIPTION. mu : TYPE DESCRIPTION. sigma_B : TYPE DESCRIPTION. dt : TYPE DESCRIPTION. Returns ------- B : TYPE DESCRIPTION. """ size = (N_steps, N_sim) # B(k+1) = B(k) * e^{dM + dW} dM = (mu - 0.5 * sigma_B**2) * dt dW = sigma_B * np.sqrt(dt) * np.random.normal(0, 1, size) B = B_0 * np.exp(np.cumsum(dM + dW, axis=0)) # Shift and include inception value (t=0). B = np.insert(B, 0, B_0, axis=0) return B def simulate_ou_spread(N_sim, N_steps, B_0, X_0, kappa, theta, eta, mu, sigma_B, dt): """ This function simulates Ornstein-Uhlenbeck spread for pairs trading model Parameters ---------- N_sim : TYPE DESCRIPTION. N_steps : TYPE DESCRIPTION. B_0 : TYPE DESCRIPTION. X_0 : TYPE DESCRIPTION. kappa : TYPE DESCRIPTION. theta : TYPE DESCRIPTION. eta : TYPE DESCRIPTION. mu : TYPE DESCRIPTION. sigma_B : TYPE DESCRIPTION. dt : TYPE DESCRIPTION. Returns ------- A : TYPE DESCRIPTION. B : TYPE DESCRIPTION. X : TYPE DESCRIPTION. """ size = (N_steps + 1, N_sim) # Simulate asset b B = simulate_b(N_sim, N_steps, B_0, mu, sigma_B, dt) # Simulate spread X = np.empty(size) X[0, :] = X_0 randn = np.random.normal(0, 1, size) for j in range(N_sim): for i in range(N_steps): dX = kappa*(theta - X[i, j])*dt + eta*np.sqrt(dt) * randn[i, j] X[i+1, j] = X[i, j] + dX # Simulate price path for A A = B * np.exp(X) return A, B, X
/* * Appcelerator Titanium Mobile * Copyright (c) 2021-Present by Axway, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ /* global OS_ANDROID, OS_VERSION_MAJOR */ /* eslint-env mocha */ /* eslint no-unused-expressions: "off" */ /* eslint no-undef: "off" */ /* eslint-disable mocha/no-identical-title */ 'use strict'; const should = require('./utilities/assertions'); describe('Titanium.Media.AudioPlayer', () => { let audioPlayer; const errorLog = e => console.error(e.error); beforeEach(() => { audioPlayer = Ti.Media.createAudioPlayer({ url: '/sample.mp3' }); audioPlayer.addEventListener('error', errorLog); }); afterEach(() => { if (audioPlayer) { audioPlayer.removeEventListener('error', errorLog); if (OS_ANDROID) { audioPlayer.release(); } } audioPlayer = null; }); describe('properties', () => { // FIXME: Add test for this creation-only property // describe.android('.allowBackground', () => { // it('is a Boolean', () => { // should(audioPlayer).have.a.property('allowBackground').which.is.a.Boolean(); // }); // it('defaults to false', () => { // should(audioPlayer.allowBackground).be.false(); // }); // }); describe.ios('.allowsExternalPlayback', () => { it('is a Boolean', () => { should(audioPlayer).have.a.property('allowsExternalPlayback').which.is.a.Boolean(); }); it('defaults to true', () => { should(audioPlayer.allowsExternalPlayback).be.true(); }); }); describe('.apiName', () => { it('is a String', () => { should(audioPlayer).have.a.readOnlyProperty('apiName').which.is.a.String(); }); it('equals Ti.Media.AudioPlayer', () => { should(audioPlayer.apiName).eql('Ti.Media.AudioPlayer'); }); }); // FIXME: Add test for this creation-only property // describe.android('.audioFocus', () => { // it('is a Boolean', () => { // should(audioPlayer).have.a.property('audioFocus').which.is.a.Boolean(); // }); // it('defaults to false', () => { // should(audioPlayer.audioFocus).be.false(); // }); // }); describe.android('audioSessionId', () => { it('is a Number', () => { should(audioPlayer).have.a.property('audioSessionId').which.is.a.Number(); }); }); describe.android('.audioType', () => { it('is a Number', () => { should(audioPlayer).have.a.property('audioType').which.is.a.Number(); }); it('defaults to Titanium.Media.AudioPlayer.AUDIO_TYPE_MEDIA', () => { should(audioPlayer.audioType).eql(Titanium.Media.AudioPlayer.AUDIO_TYPE_MEDIA); }); it('is one of Ti.Media.Sound.AUDIO_TYPE_*', () => { should([ Ti.Media.Sound.AUDIO_TYPE_ALARM, Ti.Media.Sound.AUDIO_TYPE_SIGNALLING, Ti.Media.Sound.AUDIO_TYPE_MEDIA, Ti.Media.Sound.AUDIO_TYPE_NOTIFICATION, Ti.Media.Sound.AUDIO_TYPE_RING, Ti.Media.Sound.AUDIO_TYPE_VOICE, ]).containEql(audioPlayer.audioType); }); }); describe.ios('.bitRate', () => { it('is a Number', () => { should(audioPlayer).have.a.property('bitRate').which.is.a.Number(); }); }); describe.ios('.bufferSize', () => { it('is a Number', () => { should(audioPlayer).have.a.property('bufferSize').which.is.a.Number(); }); }); describe('.duration', () => { it('is a Number', () => { should(audioPlayer).have.a.readOnlyProperty('duration').which.is.a.Number(); }); // FIXME: This hangs on Android 5 and macOS! It's unclear why... it.windowsMissing('gives around 45 seconds for test input', function (finish) { // skip on older android since it intermittently hangs forever on android 5 emulator if (OS_ANDROID && OS_VERSION_MAJOR < 6) { return finish(); } audioPlayer.start(); setTimeout(function () { try { // give a tiny bit of fudge room here. iOS and Android differ by 5ms on this file should(audioPlayer.duration).be.within(45250, 45500); // 45 seconds. iOS gives us 45322, Android gives 45327 } catch (e) { return finish(e); } finish(); }, 1000); }); }); describe.ios('.externalPlaybackActive', () => { it('is a Boolean', () => { should(audioPlayer).have.a.readOnlyProperty('externalPlaybackActive').which.is.a.Boolean(); }); }); describe.ios('.idle', () => { it('is a Boolean', () => { should(audioPlayer).have.a.readOnlyProperty('idle').which.is.a.Boolean(); }); }); describe('.muted', () => { it('is a Boolean', () => { should(audioPlayer).have.a.property('muted').which.is.a.Boolean(); }); }); describe('.paused', () => { it('is a Boolean', () => { should(audioPlayer).have.a.property('paused').which.is.a.Boolean(); }); it('does not have accessors', () => { should(audioPlayer).not.have.accessors('paused'); }); }); describe('.playing', () => { it('is a Boolean', () => { should(audioPlayer).have.a.readOnlyProperty('playing').which.is.a.Boolean(); }); it('does not have accessors', () => { should(audioPlayer).not.have.accessors('playing'); }); }); describe.ios('.progress', () => { it('is a Number', () => { should(audioPlayer).have.a.readOnlyProperty('progress').which.is.a.Number(); }); }); describe.ios('.rate', () => { it('is a Number', () => { should(audioPlayer).have.a.property('rate').which.is.a.Number(); }); it('defaults to 0', () => { should(audioPlayer.rate).eql(0); }); }); describe.ios('.state', () => { it('is a Number', () => { should(audioPlayer).have.a.readOnlyProperty('state').which.is.a.Number(); }); it('is one of Ti.Media.AUDIO_STATE_*', () => { should([ Ti.Media.AUDIO_STATE_BUFFERING, Ti.Media.AUDIO_STATE_INITIALIZED, Ti.Media.AUDIO_STATE_PAUSED, Ti.Media.AUDIO_STATE_PLAYING, Ti.Media.AUDIO_STATE_STARTING, Ti.Media.AUDIO_STATE_STOPPED, Ti.Media.AUDIO_STATE_STOPPING, Ti.Media.AUDIO_STATE_WAITING_FOR_DATA, Ti.Media.AUDIO_STATE_WAITING_FOR_QUEUE, ]).containEql(audioPlayer.state); }); }); describe.android('.time', () => { it('is a Number', () => { should(audioPlayer).have.a.property('time').which.is.a.Number(); }); }); describe('.url', () => { it('is a String', () => { should(audioPlayer).have.a.property('url').which.is.a.String(); }); it('does not have accessors', () => { should(audioPlayer).not.have.accessors('url'); }); it('re-setting does not crash (TIMOB-26334)', () => { // Re-set URL to test TIMOB-26334, this should not crash audioPlayer.url = '/sample.mp3'; }); }); describe('.volume', () => { it('is a Number', () => { should(audioPlayer).have.a.property('volume').which.is.a.Number(); }); }); describe.ios('.waiting', () => { it('is a Boolean', () => { should(audioPlayer).have.a.readOnlyProperty('waiting').which.is.a.Boolean(); }); }); }); describe('methods', () => { // FIXME: This should probably be a read-only property! describe.android('#getAudioSessionId', () => { it('is a Function', () => { should(audioPlayer.getAudioSessionId).be.a.Function(); }); }); describe('#pause', () => { it('is a Function', () => { should(audioPlayer.pause).be.a.Function(); }); it('called delayed after #start()', function (finish) { // skip on older android since it intermittently hangs forever on android 5 emulator if (OS_ANDROID && OS_VERSION_MAJOR < 6) { return finish(); } audioPlayer.start(); setTimeout(function () { try { audioPlayer.pause(); } catch (e) { return finish(e); } finish(); }, 1000); }); }); describe.android('#play', () => { it('is a Function', () => { should(audioPlayer.play).be.a.Function(); }); }); describe('#release', () => { it('is a Function', () => { should(audioPlayer.release).be.a.Function(); }); }); describe('#restart', () => { it('is a Function', () => { should(audioPlayer.restart).be.a.Function(); }); it.windowsBroken('called delayed after #start()', function (finish) { audioPlayer.start(); // I think if the media completes first, then restart may get us into a funky state? Or maybe just calling start() at any time after the on complete event fires? setTimeout(function () { try { audioPlayer.restart(); audioPlayer.stop(); } catch (e) { return finish(e); } finish(); }, 1000); }); }); describe.ios('#seekToTime', () => { it('is a Function', () => { should(audioPlayer.seekToTime).be.a.Function(); }); }); describe.ios('#setPaused', () => { it('is a Function', () => { should(audioPlayer.setPaused).be.a.Function(); }); }); describe('#start', () => { it('is a Function', () => { should(audioPlayer.start).be.a.Function(); }); }); describe.ios('#stateDescription', () => { it('is a Function', () => { should(audioPlayer.stateDescription).be.a.Function(); }); }); describe('#stop', () => { it('is a Function', () => { should(audioPlayer.stop).be.a.Function(); }); it('called delayed after #start', function (finish) { audioPlayer.start(); setTimeout(function () { try { audioPlayer.stop(); } catch (e) { return finish(e); } finish(); }, 1000); }); }); }); describe('constants', () => { describe.android('.AUDIO_TYPE_ALARM', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('AUDIO_TYPE_ALARM').which.is.a.Number(); }); }); describe.android('.AUDIO_TYPE_MEDIA', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('AUDIO_TYPE_MEDIA').which.is.a.Number(); }); }); describe.android('.AUDIO_TYPE_NOTIFICATION', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('AUDIO_TYPE_NOTIFICATION').which.is.a.Number(); }); }); describe.android('.AUDIO_TYPE_RING', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('AUDIO_TYPE_RING').which.is.a.Number(); }); }); describe.android('.AUDIO_TYPE_SIGNALLING', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('AUDIO_TYPE_SIGNALLING').which.is.a.Number(); }); }); describe.android('.AUDIO_TYPE_VOICE', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('AUDIO_TYPE_VOICE').which.is.a.Number(); }); }); describe('.STATE_BUFFERING', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_BUFFERING').which.is.a.Number(); }); }); describe('.STATE_INITIALIZED', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_INITIALIZED').which.is.a.Number(); }); }); describe('.STATE_PAUSED', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_PAUSED').which.is.a.Number(); }); }); describe('.STATE_PLAYING', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_PLAYING').which.is.a.Number(); }); }); describe('.STATE_STARTING', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_STARTING').which.is.a.Number(); }); }); describe('.STATE_STOPPED', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_STOPPED').which.is.a.Number(); }); }); describe('.STATE_STOPPING', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_STOPPING').which.is.a.Number(); }); }); describe('.STATE_WAITING_FOR_DATA', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_WAITING_FOR_DATA').which.is.a.Number(); }); }); describe('.STATE_WAITING_FOR_QUEUE', () => { it('is a Number', () => { should(audioPlayer).have.a.constant('STATE_WAITING_FOR_QUEUE').which.is.a.Number(); }); }); }); it.ios('TIMOB-26533', function (finish) { // Ti.Media.Audio player without url set is crashing while registering for event listener audioPlayer = null; audioPlayer = Ti.Media.createAudioPlayer(); try { audioPlayer.addEventListener('progress', function () {}); } catch (e) { return finish(e); } finish(); }); });
const filterByTerm = require("../filterByTerm") describe('Filter function', function () { test("it should filter by a search term (link)", () => { const input = [ { id: 1, url: "https://www.url1.dev" }, { id: 2, url: "https://www.url2.dev" }, { id: 3, url: "https://www.link3.dev" } ]; const output = [{ id: 3, url: "https://www.link3.dev" }]; expect(filterByTerm(input, 'link')).toEqual(output); expect(filterByTerm(input, "LINK")).toEqual(output); }); });
jQuery(document).ready(function(){ var scripts = document.getElementsByTagName("script"); var jsFolder = ""; for (var i= 0; i< scripts.length; i++) { if( scripts[i].src && scripts[i].src.match(/initslider-1\.js/i)) jsFolder = scripts[i].src.substr(0, scripts[i].src.lastIndexOf("/") + 1); } jQuery("#amazingslider-1").amazingslider({ sliderid:1, jsfolder:jsFolder, width:900, height:360, skinsfoldername:"assets/css", loadimageondemand:false, videohidecontrols:false, fullwidth:false, donotresize:false, enabletouchswipe:true, fullscreen:false, autoplayvideo:false, addmargin:true, transitiononfirstslide:false, forceflash:false, isresponsive:true, forceflashonie11:true, forceflashonie10:true, pauseonmouseover:false, playvideoonclickthumb:true, slideinterval:5000, randomplay:false, scalemode:"fill", loop:0, autoplay:true, navplayvideoimage:"play-32-32-0.png", navpreviewheight:60, timerheight:2, descriptioncssresponsive:"font-size:12px;", shownumbering:false, navthumbresponsivemode:"samesize", skin:"Rotator", textautohide:true, lightboxshowtwitter:true, addgooglefonts:false, navshowplaypause:true, initsocial:false, navshowplayvideo:false, navshowplaypausestandalonemarginx:8, navshowplaypausestandalonemarginy:8, navbuttonradius:2, navthumbcolumn:5, navthumbnavigationarrowimageheight:32, navradius:2, navthumbsmallcolumn:3, lightboxshownavigation:false, showshadow:false, navfeaturedarrowimagewidth:16, lightboxshowsocial:false, navpreviewwidth:120, googlefonts:"", navborderhighlightcolor:"", navcolor:"#e3e3e8", lightboxdescriptionbottomcss:"{color:#333; font-size:12px; font-family:Arial,Helvetica,sans-serif; overflow:hidden; text-align:left; margin:4px 0px 0px; padding: 0px;}", lightboxthumbwidth:80, navthumbnavigationarrowimagewidth:32, navthumbtitlehovercss:"text-decoration:underline;", navthumbmediumheight:64, texteffectresponsivesize:600, arrowwidth:32, texteffecteasing:"easeOutCubic", texteffect:"slide", lightboxthumbheight:60, navspacing:4, navarrowimage:"navarrows-20-20-0.png", ribbonimage:"ribbon_topleft-0.png", navwidth:20, navheight:20, arrowimage:"arrows-32-32-0.png", timeropacity:0.6, titlecssresponsive:"font-size:12px;", navthumbnavigationarrowimage:"carouselarrows-32-32-0.png", navshowplaypausestandalone:false, texteffect1:"slide", navpreviewbordercolor:"#ffffff", texteffect2:"slide", customcss:"", ribbonposition:"topleft", navthumbdescriptioncss:"display:block;position:relative;padding:2px 4px;text-align:left;font:normal 12px Arial,Helvetica,sans-serif;color:#333;", lightboxtitlebottomcss:"{color:#333; font-size:14px; font-family:Armata,sans-serif,Arial; overflow:hidden; text-align:left;}", arrowstyle:"none", navthumbmediumsize:800, navthumbtitleheight:20, navpreviewarrowheight:8, textpositionmargintop:24, navshowbuttons:true, buttoncssresponsive:"", texteffectdelay:800, navswitchonmouseover:false, playvideoimage:"playvideo-64-64-0.png", arrowtop:50, textstyle:"dynamic", playvideoimageheight:64, navfonthighlightcolor:"#ffffff", showbackgroundimage:false, showpinterest:true, navpreviewborder:4, navshowplaypausestandaloneheight:28, navdirection:"horizontal", navbuttonshowbgimage:false, navbuttonbgimage:"navbuttonbgimage-28-28-0.png", textbgcss:"display:none;", playvideoimagewidth:64, buttoncss:"display:block; position:relative; margin-top:10px;", navborder:4, navshowpreviewontouch:false, bottomshadowimagewidth:110, showtimer:true, navmultirows:false, navshowpreview:false, navmarginy:20, navmarginx:20, navfeaturedarrowimage:"featuredarrow-16-8-0.png", texteffectslidedirection1:"bottom", showribbon:false, navstyle:"numbering", textpositionmarginleft:24, descriptioncss:"display:block; position:relative; font:14px \"Lucida Sans Unicode\",\"Lucida Grande\",sans-serif,Arial; color:#e04000; background-color:#fff; margin-top:10px; padding:10px; ", navplaypauseimage:"navplaypause-20-20-0.png", backgroundimagetop:-10, timercolor:"#ffffff", numberingformat:"%NUM/%TOTAL ", navthumbmediumwidth:64, navfontsize:12, navhighlightcolor:"#ff4629", texteffectdelay1:1000, navimage:"bullet-24-24-0.png", texteffectdelay2:1500, texteffectduration1:800, navshowplaypausestandaloneautohide:false, texteffectduration2:800, navbuttoncolor:"#e3e3e8", navshowarrow:true, texteffectslidedirection:"bottom", navshowfeaturedarrow:false, lightboxbarheight:64, showfacebook:true, titlecss:"display:table; position:relative; font:16px \"Lucida Sans Unicode\",\"Lucida Grande\",sans-serif,Arial; color:#fff; white-space:nowrap; background-color:#e04000; padding:10px;", ribbonimagey:0, ribbonimagex:0, texteffectresponsive:true, navthumbsmallheight:48, texteffectslidedistance1:10, texteffectslidedistance2:10, navrowspacing:8, navshowplaypausestandaloneposition:"bottomright", lightboxshowpinterest:true, lightboxthumbbottommargin:8, lightboxthumbtopmargin:12, arrowhideonmouseleave:1000, navshowplaypausestandalonewidth:28, showsocial:false, navthumbresponsive:false, navfeaturedarrowimageheight:8, navopacity:0.8, textpositionmarginright:24, backgroundimagewidth:120, bordercolor:"#ffffff", border:0, navthumbtitlewidth:120, navpreviewposition:"bottom", texteffectseparate:true, arrowheight:32, arrowmargin:8, texteffectduration:600, bottomshadowimage:"bottomshadow-110-95-4.png", lightboxshowfacebook:true, lightboxshowdescription:false, timerposition:"bottom", navfontcolor:"#333333", navthumbnavigationstyle:"arrow", borderradius:0, navbuttonhighlightcolor:"#ff4629", textpositionstatic:"bottom", texteffecteasing2:"easeOutCubic", navthumbstyle:"imageonly", texteffecteasing1:"easeOutCubic", textcss:"display:block; padding:8px 16px; text-align:left;", navthumbsmallwidth:48, navbordercolor:"#ffffff", navthumbmediumcolumn:4, navpreviewarrowimage:"previewarrow-16-8-1.png", showbottomshadow:true, texteffectslidedistance:10, shadowcolor:"#aaaaaa", showtwitter:true, textpositionmarginstatic:0, backgroundimage:"", navposition:"topright", navthumbsmallsize:480, navpreviewarrowwidth:16, textformat:"Red box", texteffectslidedirection2:"bottom", bottomshadowimagetop:95, textpositiondynamic:"bottomleft", shadowsize:5, navthumbtitlecss:"display:block;position:relative;padding:2px 4px;text-align:left;font:bold 14px Arial,Helvetica,sans-serif;color:#333;", textpositionmarginbottom:24, lightboxshowtitle:true, socialmode:"mouseover", slide: { duration:1000, easing:"easeOutCubic", checked:true, effectdirection:0 }, transition:"slide", scalemode:"fill", isfullscreen:false, textformat: { } }); });
from tkinter import * def colorgen(): while True: yield "red" yield "blue" class Application(Frame): def __init__(self, master=None): colors = colorgen() Frame.__init__(self, master) self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) self.grid(sticky=W+E+N+S) rcount = 0 for r in (1, 22, 333): self.rowconfigure(r, weight=rcount) rcount += 1 ccount = 0 for c in (1, 22, 333): self.columnconfigure(c, weight=ccount) ccount += 1 txt = "Item {0}, {1}".format(r, c) l = Label(self, text=txt, bg=next(colors)) l.grid(row=r, column=c, sticky=E+W+N+S) root = Tk() app = Application(master=root) app.mainloop()
var fs = require('fs'), inherits = require('util').inherits, path = require('path'); var THROW_CONFLICTS = true; function getPluginPath(config) { return (config && config.pluginPath) || path.join(__dirname, '../plugins'); } function PluginError(message) { this.name = 'Plugin Error'; this.message = this.name + ':\n' + message; } inherits(PluginError, Error); function findEq(collection, option, value) { return collection.filter(function(item) { return item[option] == value; })[0]; } function mergeByName(acceptor, donor, name, onConflict) { if (!donor || !donor.length) return; donor.forEach(function(note) { var sameOrigNote = findEq(acceptor, name, note[name]); if (sameOrigNote) { onConflict(sameOrigNote, note); } else { acceptor.push(note); } }, this); } var cachedPlugins = {}; function _setMockPlugins(pluginPath, plugins) { cachedPlugins[pluginPath] = plugins; } function getPlugins(config) { if (!config || !config.plugins) { return []; } var pluginPath = getPluginPath(config); if (cachedPlugins[pluginPath]) { return cachedPlugins[pluginPath]; } var dirlist; try { dirlist = fs.readdirSync(pluginPath); } catch (err) { dirlist = []; } var plugins = []; dirlist.reduce(function(plugins, subdir) { var _path = path.resolve(pluginPath, subdir, 'manifest.json'); var manifest; try { manifest = require(_path); // This excludes situation where we have two plugins with same name. if (subdir !== manifest.name) throw new PluginError('Plugin name in manifest.json is different from npm module name'); } catch (e) { console.error('Corrupted manifest.json in %s plugin\n%s\n%s', subdir, e.message, e.stack); return plugins; } validateManifest(manifest); plugins.push(manifest); return plugins; }, plugins); cachedPlugins[pluginPath] = plugins; return plugins; } function validateManifest(manifest) { manifest.session = manifest.session || {}; manifest.protocol = manifest.protocol || {}; manifest.protocol.domains = manifest.protocol.domains || []; } function InspectorJson(config) { var inspectorJsonPath = path.join(__dirname, '../front-end/inspector.json'), inspectorJson = JSON.parse(fs.readFileSync(inspectorJsonPath)), extendedInspectorJsonPath = path.join(__dirname, '../front-end-node/inspector.json'), extendedInspectorJson = JSON.parse(fs.readFileSync(extendedInspectorJsonPath)); this._config = config; this._notes = inspectorJson; this._merge(extendedInspectorJson); if (!config.plugins) return; var plugins = getPlugins(config); plugins.forEach(function(plugin) { var excludes = (plugin.exclude || []).map(function(name) { return { name: name, type: 'exclude' }; }); var overrides = plugin.override || []; var note = { name: 'plugins/' + plugin.name, type: plugin.type || '' }; var notes = excludes.concat(overrides).concat(note); this._merge(notes); }, this); } InspectorJson.prototype._merge = function(toMergeNotes) { var result = []; toMergeNotes.forEach(function(note) { if (note.type == 'exclude') return; result.push(note); }); this._notes.forEach(function(note) { var exists = findEq(toMergeNotes, 'name', note.name); if (exists) return; result.push(note); }); this._notes = result; }; InspectorJson.prototype.toJSON = function() { return this._notes; }; function ProtocolJson(config) { var protocolJsonPath = path.join(__dirname, '../tools/protocol.json'), protocolJson = JSON.parse(fs.readFileSync(protocolJsonPath)), extendedProtocolJsonPath = path.join(__dirname, '../front-end-node/protocol.json'), extendedProtocolJson = JSON.parse(fs.readFileSync(extendedProtocolJsonPath)); this._config = config; this._protocol = protocolJson; this._domains = protocolJson.domains; this._extendedDomains = extendedProtocolJson.domains; if (config.plugins) { var plugins = getPlugins(config); // At first step we merge all plugins in one protocol. // We expect what plugins doesn't have equal methods, events or types, // otherwise we throw an error, because this is unsolvable situation. plugins.forEach(function(plugin) { this._merge(THROW_CONFLICTS, plugin.name, this._extendedDomains, plugin.protocol.domains); }, this); } // At second step we merge plugins with main protocol. // Plugins can override original methods, events or types, // so we don't need to throw error on conflict, we only print a warning to console. this._merge(!THROW_CONFLICTS, '', this._domains, this._extendedDomains); } ProtocolJson.prototype._merge = function(throwConflicts, pluginName, origDomains, toMergeDomains) { if (!toMergeDomains.length) return; var uniqueName = 'domain', state = { throwConflicts: throwConflicts, plugin: pluginName }; mergeByName( origDomains, toMergeDomains, uniqueName, this._onDomainConflict.bind(this, state)); }; ProtocolJson.prototype._onDomainConflict = function(state, origDomain, toMergeDomain) { state.domain = toMergeDomain.domain; ['commands', 'events', 'types'].forEach(function(section) { // TODO(3y3): types are unique for protocol, not for domain. // We need to register types cache and search in it for conflicts. var uniqueName = section == 'types' ? 'id' : 'name', origSection = origDomain[section], toMergeSection = toMergeDomain[section]; if (!toMergeSection || !toMergeSection.length) return; if (!origSection || !origSection.length) { origDomain[section] = toMergeSection; return; } state.section = section; state.uname = uniqueName; mergeByName( origSection, toMergeSection, uniqueName, this._onItemConflict.bind(this, state)); }, this); }; ProtocolJson.prototype._onItemConflict = function(state, origItem, toMergeItem) { if (state.throwConflicts) { throw new PluginError( 'Unresolved conflict in ' + state.section + ' section of `' + state.plugin + '` plugin: ' + 'item with ' + state.uname + ' `' + toMergeItem[state.uname] + '` already exists.'); } else { console.warn( 'Item with ' + state.uname + ' `' + toMergeItem[state.uname] + '`' + ' in ' + state.section + ' section' + ' of ' + state.domain + ' domain' + ' was owerriden.'); } }; ProtocolJson.prototype.toJSON = function() { return this._protocol; }; function init(config) { module.exports.CWD = getPluginPath(config); } module.exports = { _setMockPlugins: _setMockPlugins, getPluginPath: getPluginPath, getPlugins: getPlugins, validateManifest: validateManifest, PluginError: PluginError, InspectorJson: InspectorJson, ProtocolJson: ProtocolJson, init: init };
import { createSvgIcon } from '@mui/material/utils'; export const Menu = () => { return ( <svg width="24" height="26" viewBox="0 0 24 26" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12 15.0265C13.1046 15.0265 14 14.1033 14 12.9643C14 11.8254 13.1046 10.9021 12 10.9021C10.8954 10.9021 10 11.8254 10 12.9643C10 14.1033 10.8954 15.0265 12 15.0265Z" fill="#0559C1"/> <path d="M12 7.80877C13.1046 7.80877 14 6.88548 14 5.74655C14 4.60761 13.1046 3.68433 12 3.68433C10.8954 3.68433 10 4.60761 10 5.74655C10 6.88548 10.8954 7.80877 12 7.80877Z" fill="#0559C1"/> <path d="M12 22.2443C13.1046 22.2443 14 21.321 14 20.1821C14 19.0432 13.1046 18.1199 12 18.1199C10.8954 18.1199 10 19.0432 10 20.1821C10 21.321 10.8954 22.2443 12 22.2443Z" fill="#0559C1"/> </svg> ) }
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("omi")); else if(typeof define === 'function' && define.amd) define(["omi"], factory); else if(typeof exports === 'object') exports["signal-wifi3-bar-lock-rounded"] = factory(require("omi")); else root["signal-wifi3-bar-lock-rounded"] = factory(root["Omi"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_omi__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./esm/signal-wifi3-bar-lock-rounded.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./esm/signal-wifi3-bar-lock-rounded.js": /*!**********************************************!*\ !*** ./esm/signal-wifi3-bar-lock-rounded.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar omi_1 = __webpack_require__(/*! omi */ \"omi\");\nvar createSvgIcon_1 = __webpack_require__(/*! ./utils/createSvgIcon */ \"./esm/utils/createSvgIcon.js\");\nexports.default = createSvgIcon_1.default(omi_1.h(omi_1.h.f, null, omi_1.h(\"path\", {\n fillOpacity: \".3\",\n d: \"M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l10.08 12.56c.8 1 2.32 1 3.12 0l1.94-2.42V14.5z\"\n}), omi_1.h(\"path\", {\n d: \"M15.5 14.5c0-2.19 1.35-3.99 3.27-4.68C17.29 8.98 14.94 8 12 8c-4.81 0-8.04 2.62-8.47 2.95l6.91 8.61c.8 1 2.32 1 3.12 0l1.94-2.42V14.5zM23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z\"\n})), 'SignalWifi3BarLockRounded');\n\n\n//# sourceURL=webpack://%5Bname%5D/./esm/signal-wifi3-bar-lock-rounded.js?"); /***/ }), /***/ "./esm/utils/createSvgIcon.js": /*!************************************!*\ !*** ./esm/utils/createSvgIcon.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar omi_1 = __webpack_require__(/*! omi */ \"omi\");\nvar hyphenateRE = /\\B([A-Z])/g;\nvar hyphenate = function (str) {\n return str.replace(hyphenateRE, '-$1').toLowerCase();\n};\nfunction createSvgIcon(path, displayName) {\n var _a;\n omi_1.define(hyphenate('OIcon' + displayName), (_a = /** @class */ (function (_super) {\n __extends(class_1, _super);\n function class_1() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n class_1.prototype.render = function () {\n return omi_1.h('svg', {\n viewBox: '0 0 24 24',\n }, path);\n };\n return class_1;\n }(omi_1.WeElement)),\n _a.css = \":host {\\n fill: currentColor;\\n width: 1em;\\n height: 1em;\\n display: inline-block;\\n vertical-align: -0.125em;\\n transition: fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;\\n flex-shrink: 0;\\n user-select: none;\\n}\",\n _a));\n}\nexports.default = createSvgIcon;\n\n\n//# sourceURL=webpack://%5Bname%5D/./esm/utils/createSvgIcon.js?"); /***/ }), /***/ "omi": /*!******************************************************************************!*\ !*** external {"commonjs":"omi","commonjs2":"omi","amd":"omi","root":"Omi"} ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("module.exports = __WEBPACK_EXTERNAL_MODULE_omi__;\n\n//# sourceURL=webpack://%5Bname%5D/external_%7B%22commonjs%22:%22omi%22,%22commonjs2%22:%22omi%22,%22amd%22:%22omi%22,%22root%22:%22Omi%22%7D?"); /***/ }) /******/ })["default"]; });
document.getElementById("heading").innerText = "Javascript running inside docker";
/** * Helper function to get the remaining corners of two coordinates. * * @param {array} ne north eastern coordinates. Not a strict requirement, but preferred * @param {array} sw south western coordinates. Not a strict requirement, but preferred * * @returns {array} all corners in an array starting from NW, NE, SE, and SW */ export const cornerCoordinates = (ne, sw) => { return [ [parseFloat(sw[0]), parseFloat(ne[1])], [parseFloat(ne[0]), parseFloat(ne[1])], [parseFloat(ne[0]), parseFloat(sw[1])], [parseFloat(sw[0]), parseFloat(sw[1])] ]; } // export { cornerCoordinates } // Might be a better way to export than the one above!
describe('Visualization', function () { var angular = require('angular'); var $ = require('jquery'); var _ = require('lodash'); var ngMock = require('ngMock'); var expect = require('expect.js'); var sinon = require('auto-release-sinon'); var Private; var Vis; var vis; var filter; var init; beforeEach(ngMock.module('kibana', 'kibi_wordcloud/kibi_wordcloud_vis')); beforeEach(ngMock.inject(function ($injector) { Private = $injector.get('Private'); Vis = Private(require('ui/Vis')); var indexPattern = Private(require('fixtures/stubbed_logstash_index_pattern')); var createFilter = Private(require('ui/agg_types/buckets/create_filter/terms')); init = function () { vis = new Vis(indexPattern, { type: 'kibi_wordcloud', aggs: [ { type: 'terms', schema: 'segment', params: {field: 'machine.os'} } ] }); filter = createFilter(vis.aggs[0], 'mykey'); }; })); it('creates a valid query filter', function () { init(); expect(vis.type.name).to.be('kibi_wordcloud'); expect(filter).to.have.property('query'); expect(filter.query.match).to.have.property('machine.os'); expect(filter.query.match['machine.os'].query).to.be('mykey'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', vis.indexPattern.id); }); });
export default from './FormControl.js'
# -*- coding: utf-8 -*- import DataObj import predict_utils import copy import math from const_map import VM_TYPE_DIRT, VM_PARAM, VM_CPU_QU, VM_MEM_QU import packing_utils_v2 global res_use global vm_size global vm global local_pm_size global pm global try_result global threshold global vm_map global pm_name global origin_pm_size global local_optimal_result global global_optimal_result global local_res_use global global_res_use global local_c_m global global_c_m local_res_use = 0.0 global_res_use = 0.0 origin_pm_size = 0 local_c_m = 0.25 global_c_m = 0.25 pm_name = [] vm_map = {} threshold = 90 res_use = 0 vm_size = 0 vm = [] local_pm_size = 0 pm = [] local_optimal_result = {} global_optimal_result = {} try_result = {} # is_parameter_search = False # 使用深度学习模型 is_deeplearing = False use_smooth = True use_search_maximum = True #86.277 82.638 use_search_u_m_maximum = False def predict_vm(ecs_lines, input_lines, input_test_file_array=None): ''' :param ecs_lines:训练数据list<strLine> :param input_lines:类型要求list<strLine> :return:预测结果 ''' result = [] if ecs_lines is None: print 'ecs information is none' return result if input_lines is None: print 'input file information is none' return result # 生成训练对象 Step 02 dataObj = DataObj.DataObj(input_lines, ecs_lines, input_test_file_array=input_test_file_array) # 使用RNN进行预测 # predict_result = train_RNN(dataObj) predict_result = predict_utils.predict_all(dataObj) # 参数搜索 if is_parameter_search == False: # 预测数据 Step 03 if is_deeplearing: predict_result = predict_utils.predict_deeplearning(dataObj) else: predict_result = predict_utils.predict_all(dataObj) #############################################参数搜索################################## else: parameter = {"alpha": 0, "beta": 0, "gamma": 0} max_score = 0.0 for alpha in range(1, 100, 2): for beta in range(1, 100, 2): for gamma in range(1, 100, 2): predict_result = predict_utils.predict_predict_parameter(dataObj, alpha / 100.0, beta / 100.0, gamma / 100.0) # 评估函数 score = evaluation_parameter(dataObj, predict_result) if score > max_score: parameter['alpha'] = alpha parameter['beta'] = beta parameter['gamma'] = gamma max_score = score print('%d:alpha=%d,beta=%d,gamma=%d,max_score=%f\n' % ( alpha, parameter['alpha'], parameter['beta'], parameter['gamma'], max_score)) print('max_paremeter:') print(parameter) print('max_score:%f' % max_score) #############################################微调数量################################## global global_optimal_result global local_c_m global vm_map global local_pm_size global origin_pm_size global local_c_m global global_c_m global local_res_use origin_use_rate = 0.0 # 虚拟机表 vm_map = dict(zip(dataObj.vm_types, [0] * dataObj.vm_types_size)) vm_size, vm, pm_size, pm, pm_name, local_res_use, pm_free = packing_utils_v2.pack_api(dataObj, predict_result, local_c_m) local_pm_size = pm_size origin_use_rate = local_res_use origin_pm_size = local_pm_size res_use = origin_use_rate #############################################use_pm_average################################## # if use_search_u_m_maximum: # search_u_m_maximum(dataObj, predict_result) # vm_size, vm, pm_size, pm, pm_name, res_use, pm_free = packing_utils_v2.pack_api(dataObj, # try_result) #############################################use_pm_average################################## #############################################use_search_maximum################################## if use_search_maximum: search_maximum_way1(dataObj, predict_result) vm_size, vm, pm_size, pm, pm_name, res_use, pm_free = packing_utils_v2.pack_api(dataObj, global_optimal_result, global_c_m) print('use_search_use_rate=%.5f%%\n' % (res_use)) #############################################use_search_maximum################################## #############################################use_smooth################################## if use_smooth: vm_size, vm, pm_size, pm, add_cpu, add_mem = result_smooth(vm_size, vm, pm_size, pm, dataObj, pm_free) print('use_smooth_use_rate=%.5f%% + cpu=+%d mem=+%d \n' % (res_use, add_cpu, add_mem)) #############################################use_smooth################################## print('origin_use_rate=%.5f%%\n' % (origin_use_rate)) # # 评估函数 # if is_parameter_search == False: # evaluation(dataObj, predict_result) result = result_to_list(vm_size, vm, pm_size, pm, pm_name, dataObj.pm_type_name) print(result) return result def search_maximum_way1(dataObj, predict_result): global vm_size global vm global pm_name global pm global try_result global vm_map global local_optimal_result global local_res_use global local_pm_size global local_c_m global global_c_m global global_res_use global global_optimal_result # 寻找最优CM比例 target_c_m = [0.25, 0.5, 1, None] # 初始化 暂存跟节点情况 pm_size = local_pm_size res_use = local_res_use for i in range(len(target_c_m)): try_vm_size, try_vm, try_pm_size, try_pm, try_pm_name, try_res_use, _ = packing_utils_v2.pack_api(dataObj, predict_result, target_c_m[i]) # if (try_res_use) > (res_use) and try_pm_size <= pm_size: if (try_res_use) > (res_use) and try_pm_size <= pm_size: local_c_m = target_c_m[i] _, _, pm_size, _, _, res_use = try_vm_size, try_vm, try_pm_size, try_pm, try_pm_name, try_res_use # 赋值最优的大小 pm_size += 2 local_pm_size = pm_size local_res_use = res_use global_res_use = local_res_use global_c_m = local_c_m Weight_que1 = [4.0, 2.0, 1.0] Weight_que2 = [2.0, 1.0, 2.0] Weight_que3 = [1.0, 4.0, 2.0] # 搜索优先级 # if dataObj.opt_target == 'CPU': # pading_que = [1.0, 2.0, 4.0] # else: # pading_que = [4.0, 2.0, 1.0] # 根据数量初始化队列 local_optimal_result = copy.deepcopy(predict_result) global_optimal_result = copy.deepcopy(predict_result) # 遍历所有放置队列 九个方向寻找最优解 TODO 可能超时 容易陷入局部最优 pading_que = [1.0, 1.0, 1.0] for i in range(len(Weight_que1)): pading_que[0] = Weight_que1[i] for j in range(len(Weight_que2)): pading_que[1] = Weight_que2[j] for k in range(len(Weight_que3)): pading_que[2] = Weight_que3[k] # 根据数量初始化队列 pre_copy = copy.deepcopy(local_optimal_result) end_vm_pos = 0 # 找到第一个非0位[1,15] for vm_type_index in range(len(VM_TYPE_DIRT) - 1, -1, -1): if pre_copy.has_key(VM_TYPE_DIRT[vm_type_index]) and pre_copy[ VM_TYPE_DIRT[vm_type_index]] > 0: # 键值对存在 end_vm_pos = vm_type_index break for que in range(3): # 在有数量的区间内填充[1,8] for vm_type in range(end_vm_pos, -1, -1): if pre_copy.has_key(VM_TYPE_DIRT[vm_type]) and VM_PARAM[VM_TYPE_DIRT[vm_type]][2] == pading_que[ que]: # 键值对存在,C/M比相等 if pre_copy[VM_TYPE_DIRT[vm_type]][0] > 0: result_search(pre_copy, dataObj, 1, VM_TYPE_DIRT[vm_type], vm_map) result_search(pre_copy, dataObj, -1, VM_TYPE_DIRT[vm_type], vm_map) else: # 找到非0的,最大,虚拟机 result_search(pre_copy, dataObj, 1, VM_TYPE_DIRT[vm_type], vm_map) # 保存最优解 if local_res_use > global_res_use: global_optimal_result = local_optimal_result global_res_use = local_res_use global_c_m = local_c_m # 初始化局部最优解 local_optimal_result = copy.deepcopy(predict_result) # 初始化使用率 local_res_use = res_use # 回滚主机数量 local_pm_size = pm_size def result_search(predict_result, dataObj, try_value, vm_type, try_vm_map): ''' :param predict_result: 虚拟机预测结果 贪心搜索局部优解 :param dataObj: 训练集信息 :param try_value: 尝试值 :param vm_type: 虚拟机类型 :return: ''' global res_use global vm_size global vm global local_pm_size global pm global try_result global vm_map global pm_name global local_c_m global global_c_m global global_optimal_result global local_optimal_result global local_res_use global global_res_use try_predict = copy.deepcopy(predict_result) try_vm_map = copy.deepcopy(vm_map) try_predict[vm_type][0] = try_predict[vm_type][0] + try_value if try_predict[vm_type][0] < 0: # 小于0没有意义 return # try_vm_size, try_vm, try_pm_size, try_pm, try_pm_name, try_res_use, _ = packing_utils_v2.pack_api( # dataObj, try_predict) # 遍历各种不同优化比例 target_c_m = [0.25, 0.5, 1, None] for i in range(len(target_c_m)): try_vm_size, try_vm, try_pm_size, try_pm, try_pm_name, try_res_use, _ = packing_utils_v2.pack_api(dataObj, try_predict, target_c_m[i]) if (try_res_use) > (local_res_use) and try_pm_size <= local_pm_size: # 如果结果优,物理机数量相等或者 【更小,利用率更高 】保存最优结果 _, _, local_pm_size, _, _, local_res_use = try_vm_size, try_vm, try_pm_size, try_pm, try_pm_name, try_res_use local_optimal_result = try_predict try_vm_map[vm_type] += try_value vm_map = try_vm_map local_c_m = target_c_m[i] # 继续深度搜索 result_search(try_predict, dataObj, try_value, vm_type, try_vm_map) else: continue return def result_smooth(vm_size, vm, pm_size, pm, dataObj, pm_free): ''' :param vm:虚拟机列表 :param pm_size:虚拟机数量 :param pm:物理机列表 :param dataObj:数据对象 :return: ''' vm_types = dataObj.vm_types res_use_pro = 0.0 other_res_use_pro = 0.0 VM_QUE = [] free_cpu = 0.0 free_mem = 0.0 # 初始化填充队列 # if dataObj.opt_target == 'CPU': # VM_QUE = VM_CPU_QU # res_use_pro = dataObj.CPU * pm # other_res_use_pro = dataObj.MEM * pm # else: # VM_QUE = VM_MEM_QU # res_use_pro = dataObj.MEM * pm # other_res_use_pro = dataObj.CPU * pm # VM_QUE = VM_CPU_QU # VM_QUE = VM_MEM_QU VM_QUE = VM_PARAM add_cpu = 0 add_mem = 0 epoch = 25 # 遍历物理机 for i in range(0, pm_size): M_C = 0.0 # 进行多轮赋值,防止漏空 for e in range(epoch): # CPU 内存均有空间 if pm_free[i][0] and pm_free[i][1]: # 计算占比 is_all_pack = 0 M_C = computer_MC(pm_free[i]) # while (M_C >= 1 and pm_free[i][0] and pm_free[i][1] and is_all_pack < 1): # CPU 内存均有空间 # 3轮不同比例的检索 for vm_type_index in range(len(VM_PARAM) - 1, -1, -1): # 比例匹配,并且是属于预测列表的最大资源虚拟机 if VM_PARAM[VM_TYPE_DIRT[vm_type_index]][2] == M_C and ( VM_TYPE_DIRT[vm_type_index] in vm_types): # CPU 内存均有空间放入该虚拟机 if VM_PARAM[VM_TYPE_DIRT[vm_type_index]][0] <= pm_free[i][0] and \ VM_PARAM[VM_TYPE_DIRT[vm_type_index]][1] <= pm_free[i][1]: # 虚拟机数量增加 vm_size += 1 if isContainKey(vm, VM_TYPE_DIRT[vm_type_index]): # 列表中数量添加 vm[VM_TYPE_DIRT[vm_type_index]] += 1 else: vm[VM_TYPE_DIRT[vm_type_index]] = 1 # 物理机列表中添加 if isContainKey(pm[i], VM_TYPE_DIRT[vm_type_index]): pm[i][VM_TYPE_DIRT[vm_type_index]] += 1 else: pm[i][VM_TYPE_DIRT[vm_type_index]] = 1 # 剪切空闲空间数 pm_free[i][0] = pm_free[i][0] - VM_PARAM[VM_TYPE_DIRT[vm_type_index]][0] pm_free[i][1] = pm_free[i][1] - VM_PARAM[VM_TYPE_DIRT[vm_type_index]][1] add_cpu += VM_PARAM[VM_TYPE_DIRT[vm_type_index]][0] add_mem += VM_PARAM[VM_TYPE_DIRT[vm_type_index]][1] # 无空闲资源,则跳出循环 if pm_free[i][0] == 0 or pm_free[i][1] == 0: break else: continue else: continue for vm_type_index in range(len(VM_PARAM) - 1, -1, -1): if VM_TYPE_DIRT[vm_type_index] in vm_types and VM_PARAM[VM_TYPE_DIRT[vm_type_index]][0] <= pm_free[i][0] and \ VM_PARAM[VM_TYPE_DIRT[vm_type_index]][1] <= pm_free[i][1]: # 虚拟机数量增加 vm_size += 1 if isContainKey(vm, VM_TYPE_DIRT[vm_type_index]): # 列表中数量添加 vm[VM_TYPE_DIRT[vm_type_index]] += 1 else: vm[VM_TYPE_DIRT[vm_type_index]] = 1 # 物理机列表中添加 if isContainKey(pm[i], VM_TYPE_DIRT[vm_type_index]): pm[i][VM_TYPE_DIRT[vm_type_index]] += 1 else: pm[i][VM_TYPE_DIRT[vm_type_index]] = 1 # 剪切空闲空间数 pm_free[i][0] = pm_free[i][0] - VM_PARAM[VM_TYPE_DIRT[vm_type_index]][0] pm_free[i][1] = pm_free[i][1] - VM_PARAM[VM_TYPE_DIRT[vm_type_index]][1] add_cpu += VM_PARAM[VM_TYPE_DIRT[vm_type_index]][0] add_mem += VM_PARAM[VM_TYPE_DIRT[vm_type_index]][1] # 无空闲资源,则跳出循环 if pm_free[i][0] == 0 or pm_free[i][1] == 0: break # is_all_pack += 1 return vm_size, vm, pm_size, pm, add_cpu, add_mem def search_u_m_maximum(dataObj, predict_result): ''' 搜寻最优的资源CM优化比例 :param dataObj: :param predict_result: :return: ''' global res_use global vm_size global vm global local_pm_size global pm_name global pm global try_result global vm_map pass # 检查dict中是否存在key def isContainKey(dic, key): return key in dic def evaluation_parameter(dataObj, vm): diff, score = diff_dic(dataObj.test_vm_count, vm) return score def evaluation(dataObj, vm): print('train count:\n') print(dataObj.train_vm_count) print('\n') print('test count:\n') print(dataObj.test_vm_count) print('\n') print('predict count:\n') print(vm) print('\n') # diff, score = diff_dic(dataObj.test_vm_count, vm) diff, score = diff_dic(dataObj.test_vm_count, vm) print('diff count:\n') print(diff) print('\n') print('score count:\n') print(score) print('\n') return score def diff_dic(test, predict): ''' 计算差 :param test:测试集 :param predict:预测数据 :return: 差值 ''' diff = {} score = 1.0 n = 0.0 temp_diff = 0.0 temp_y = 0.0 temp_y_hot = 0.0 keys = test.keys() for key in keys: if isContainKey(predict, key): diff[key] = predict[key][0] - test[key] temp_y_hot += (predict[key][0] ** 2) else: diff[key] = abs(test[key]) temp_diff += (diff[key] ** 2) temp_y += (test[key] ** 2) n += 1.0 score -= math.sqrt(temp_diff / n) / (math.sqrt(temp_y / n) + math.sqrt(temp_y_hot / n)) return diff, score def computer_MC(CM_free): # 计算内存/CPU占比 M_C = CM_free[1] / CM_free[0] if M_C >= 4: M_C = 4.0 elif M_C >= 2: M_C = 2.0 else: M_C = 1.0 return M_C # def init_que(caseInfo): # vm_que=[] # for vm_type in caseInfo.vm_types: # # return vm_que def result_to_list(vm_size, vm, pm_size, pm, pm_name, pm_type_name): ''' 由预测和分配生成结果 vm:{vm_type:cot...} pm[{vm_type:cot,vm_type2:cot2...}...] ''' end_str = '' result = [] result.append(str(vm_size) + end_str) for index in vm.keys(): item = vm[index] tmp = index + ' ' + str(item) + end_str result.append(tmp) result.append(end_str) pm_datas = {} # 物理机信息处理 for i in range(len(pm)): # 虚拟机类型key name = pm_name[i] if isContainKey(pm_datas, name): # 添加数据 pm_datas[name].append(pm[i]) else: pm_datas[name] = [] pm_datas[name].append(pm[i]) end_str_sum = 2 for name in pm_type_name: # 如果当前类型物理机请求量为0 if not isContainKey(pm_datas, name): result.append(name + ' ' + str(0) + end_str) if end_str_sum > 0: result.append(end_str) end_str_sum -= 1 continue else: result.append(name + ' ' + str(len(pm_datas[name])) + end_str) # 每一种物理机 pm_data = pm_datas[name] for pm_id in range(len(pm_datas[name])): tmp = name + '-' + str(pm_id + 1) # 每一行物理机 pm_item = pm_data[pm_id] # 一个都没有 if len(pm_item.keys()) == 0: continue for index in pm_item.keys(): item = pm_item[index] tmp += ' ' + index + ' ' + str(item) tmp += end_str result.append(tmp) if end_str_sum > 0: result.append(end_str) end_str_sum -= 1 # result.append(end_str) # result.append(pm_type_name[1] + ' ' + str(0)) # result.append(end_str) # result.append(pm_type_name[2] + ' ' + str(0)) return result
import * as tf from '@tensorflow/tfjs'; const all_labels = ['CNV', 'DME', 'DRUSEN', 'NORMAL'] const MODEL_HELPERS = { model: { load_roctnet: async () => { const roctnet = await tf.loadLayersModel('http://[::]:8080/pre_trained/roctnet18/model.json'); return roctnet; }, diagnosisResult: (array) => { let result = {}; for(let i=0; i<all_labels.length; i++) { result[all_labels[i]] = parseFloat(array[i].toFixed(4)); } return result; }, } } export default MODEL_HELPERS;
import React from 'react'; import PropTypes from 'prop-types'; const IssueIcon = ({ className }) => ( <svg height="1em" width="0.875em" className={className}> <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); IssueIcon.propTypes = { className: PropTypes.string }; export default IssueIcon;
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import React from 'react'; import { SummaryStatus } from '../../summary_status'; import { ElasticsearchStatusIcon } from '../status_icon'; import { formatMetric } from '../../../lib/format_number'; import { i18n } from '@kbn/i18n'; export function ClusterStatus({ stats }) { const { dataSize, nodesCount, indicesCount, memUsed, memMax, totalShards, unassignedShards, documentCount, status } = stats; const metrics = [ { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.nodesLabel', { defaultMessage: 'Nodes' }), value: nodesCount, 'data-test-subj': 'nodesCount' }, { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.indicesLabel', { defaultMessage: 'Indices' }), value: indicesCount, 'data-test-subj': 'indicesCount' }, { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.memoryLabel', { defaultMessage: 'JVM Heap' }), value: formatMetric(memUsed, 'byte') + ' / ' + formatMetric(memMax, 'byte'), 'data-test-subj': 'memory' }, { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.totalShardsLabel', { defaultMessage: 'Total shards' }), value: totalShards, 'data-test-subj': 'totalShards' }, { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.unassignedShardsLabel', { defaultMessage: 'Unassigned shards' }), value: unassignedShards, 'data-test-subj': 'unassignedShards' }, { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.documentsLabel', { defaultMessage: 'Documents' }), value: formatMetric(documentCount, 'int_commas'), 'data-test-subj': 'documentCount' }, { label: i18n.translate('xpack.monitoring.elasticsearch.clusterStatus.dataLabel', { defaultMessage: 'Data' }), value: formatMetric(dataSize, 'byte'), 'data-test-subj': 'dataSize' } ]; const IconComponent = ({ status }) => ( <ElasticsearchStatusIcon status={status} /> ); return ( <SummaryStatus metrics={metrics} status={status} IconComponent={IconComponent} data-test-subj="elasticsearchClusterStatus" /> ); }
import React from 'react'; import {render, fireEvent} from '@testing-library/react'; import InputNumber from './index'; class TestInput extends React.Component { state = { value: "" }; handleChange = e => { this.setState({[e.target.name]: e.target.value}); } render() { return ( <InputNumber max={30} onChange={this.handleChange} name="value" value={this.state.value}/> ) } } const setup = () => { const {container} = render(<TestInput/>); const input = container.querySelector(`input.form-control[name='value']`); return { input } } test("Should able to change value", () => { const {input} = setup(); fireEvent.change(input, {target: {value: 23}}); expect(input.value).toBe("23"); }); test("Should not be able to change when react max value", () => { const {input} = setup(); fireEvent.change(input, {target: {value: 33}}); expect(input.value).toBe(""); });
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test rpc http basics # from test_framework.test_framework import GasbitTestFramework from test_framework.util import * import base64 try: import http.client as httplib except ImportError: import httplib try: import urllib.parse as urlparse except ImportError: import urlparse class HTTPBasicsTest (GasbitTestFramework): def setup_nodes(self): return start_nodes(4, self.options.tmpdir) def run_test(self): ################################################# # lowlevel check for http persistent connection # ################################################# url = urlparse.urlparse(self.nodes[0].url) authpair = url.username + ':' + url.password headers = {"Authorization": "Basic " + base64.b64encode(authpair)} conn = httplib.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert_equal('"error":null' in out1, True) assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out2 = conn.getresponse().read() assert_equal('"error":null' in out1, True) #must also response with a correct json-rpc message assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! conn.close() #same should be if we add keep-alive because this should be the std. behaviour headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection": "keep-alive"} conn = httplib.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert_equal('"error":null' in out1, True) assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out2 = conn.getresponse().read() assert_equal('"error":null' in out1, True) #must also response with a correct json-rpc message assert_equal(conn.sock!=None, True) #according to http/1.1 connection must still be open! conn.close() #now do the same with "Connection: close" headers = {"Authorization": "Basic " + base64.b64encode(authpair), "Connection":"close"} conn = httplib.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert_equal('"error":null' in out1, True) assert_equal(conn.sock!=None, False) #now the connection must be closed after the response #node1 (2nd node) is running with disabled keep-alive option urlNode1 = urlparse.urlparse(self.nodes[1].url) authpair = urlNode1.username + ':' + urlNode1.password headers = {"Authorization": "Basic " + base64.b64encode(authpair)} conn = httplib.HTTPConnection(urlNode1.hostname, urlNode1.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert_equal('"error":null' in out1, True) #node2 (third node) is running with standard keep-alive parameters which means keep-alive is on urlNode2 = urlparse.urlparse(self.nodes[2].url) authpair = urlNode2.username + ':' + urlNode2.password headers = {"Authorization": "Basic " + base64.b64encode(authpair)} conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert_equal('"error":null' in out1, True) assert_equal(conn.sock!=None, True) #connection must be closed because gasbitd should use keep-alive by default # Check excessive request size conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port) conn.connect() conn.request('GET', '/' + ('x'*1000), '', headers) out1 = conn.getresponse() assert_equal(out1.status, httplib.NOT_FOUND) conn = httplib.HTTPConnection(urlNode2.hostname, urlNode2.port) conn.connect() conn.request('GET', '/' + ('x'*10000), '', headers) out1 = conn.getresponse() assert_equal(out1.status, httplib.BAD_REQUEST) if __name__ == '__main__': HTTPBasicsTest ().main ()
define([ 'toolbars/toolbar', 'icons', 'modelviews/objecttree', ], function( Toolbar, icons, objectTree) { function stringifyVector(vec){ return '' + vec.x + ' ' + vec.y + ' ' + vec.z; } function stringifyVertex(vec){ return ' vertex ' + stringifyVector(vec) + '\n'; } function accumulateSTL(geometry){ var vertices = geometry.vertices; var faces = geometry.faces; var acc = ''; for(var i = 0, il = faces.length; i < il; i++) { var face = faces[i]; acc += ' facet normal ' + stringifyVector(face.normal) + ' \n'; acc += ' outer loop\n'; acc += stringifyVertex(vertices[face.a]); acc += stringifyVertex(vertices[face.b]); acc += stringifyVertex(vertices[face.c]); acc += ' endloop\n'; acc += ' endfacet\n'; if (face.d) { acc += ' facet normal ' + stringifyVector(face.normal) + ' \n'; acc += ' outer loop\n'; acc += stringifyVertex(vertices[face.a]); acc += stringifyVertex(vertices[face.c]); acc += stringifyVertex(vertices[face.d]); acc += ' endloop\n'; acc += ' endfacet\n'; } } return acc; } var Model = Toolbar.ItemModel.extend({ name: 'stl', initialize: function() { Toolbar.ItemModel.prototype.initialize.call(this); }, click: function() { var stl = 'solid ' + Shapesmith.design + '\n'; var topModels = objectTree.getTopLevelModels(); topModels.forEach(function(model) { var geometry = model.sceneView.sceneObject.children[0].geometry; stl += accumulateSTL(geometry); }); stl += 'endsolid'; // https://github.com/eligrey/FileSaver.js var blob = new Blob([stl], {type: 'text/plain;charset=utf-8'}); saveAs(blob, Shapesmith.design + '.stl'); }, icon: icons['stl'], }); return Model; });
import { StyleSheet } from 'react-native'; import { colors } from '../../styles'; export default StyleSheet.create({ container: { flex: 1, backgroundColor: colors.white, }, placeholder: {}, header: { alignItems: 'center', justifyContent: 'center', backgroundColor: colors.green, flex: 1, }, });
#!/usr/bin/env python3.8 # Released under the MIT License. See LICENSE for details. # """Functionality related to android builds.""" from __future__ import annotations import os import sys import subprocess from typing import TYPE_CHECKING import efrotools if TYPE_CHECKING: from typing import List, Optional, Set def androidaddr(archive_dir: str, arch: str, addr: str) -> None: """Print the source file location for an android program-counter. command line args: archive_dir architecture addr """ if not os.path.isdir(archive_dir): print('ERROR: invalid archive dir: "' + archive_dir + '"') sys.exit(255) archs = { 'x86': { 'prefix': 'x86-', 'libmain': 'libmain_x86.so' }, 'arm': { 'prefix': 'arm-', 'libmain': 'libmain_arm.so' }, 'arm64': { 'prefix': 'aarch64-', 'libmain': 'libmain_arm64.so' }, 'x86-64': { 'prefix': 'x86_64-', 'libmain': 'libmain_x86-64.so' } } if arch not in archs: print('ERROR: invalid arch "' + arch + '"; (choices are ' + ', '.join(archs.keys()) + ')') sys.exit(255) sdkutils = 'tools/android_sdk_utils' rootdir = '.' ndkpath = subprocess.check_output([sdkutils, 'get-ndk-path']).decode().strip() if not os.path.isdir(ndkpath): print("ERROR: ndk-path '" + ndkpath + '" does not exist') sys.exit(255) lines = subprocess.check_output( ['find', os.path.join(ndkpath, 'toolchains'), '-name', '*addr2line']).decode().strip().splitlines() # print('RAW LINES', lines) lines = [ line for line in lines if archs[arch]['prefix'] in line and '/llvm/' in line ] if len(lines) != 1: print(f"ERROR: can't find addr2line binary ({len(lines)} options).") sys.exit(255) addr2line = lines[0] efrotools.run('mkdir -p "' + os.path.join(rootdir, 'android_addr_tmp') + '"') try: efrotools.run('cd "' + os.path.join(rootdir, 'android_addr_tmp') + '" && tar -xf "' + os.path.join(archive_dir, 'unstripped_libs', archs[arch]['libmain'] + '.tgz') + '"') efrotools.run( addr2line + ' -e "' + os.path.join(rootdir, 'android_addr_tmp', archs[arch]['libmain']) + '" ' + addr) finally: os.system('rm -rf "' + os.path.join(rootdir, 'android_addr_tmp') + '"')
$(document).ready(function(){ $("#dd").click(function(){ $("#dd").removeAttr('style').html('You have not submitted an answer for any of the assignments,' + ' or if you have completed at least one assignment, you have not received a score yet. Please be patient!') }); });
var century, year, month, dayOfMonth, dayOfWeek, day; //Get input function getInput(){ century = parseInt(document.getElementById("century").value); year = parseInt(document.getElementById("year").value); month = parseInt(document.getElementById("month").value); dayOfMonth = parseInt(document.getElementById("monthday").value); form = document.getElementById('form') } //Calculate func function calculateDay(){ getInput(); dayOfWeek = ((((century/4) -2*century-1) + ((5*year/4) ) + ((26*(month+1)/10)) + dayOfMonth) % 7) -1; console.log(dayOfWeek); //Test the calculateDay function return (Math.floor(dayOfWeek)); } //main caller func function checkDayOfWeek(){ day = calculateDay(); checkGender(); console.log("The function runs");//Test chackDayOfWeek function } //arrays let daysOfWeek = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; let maleNames = ["Kwasi", "Kwadwo", "Kwabena", "Kwaku", "Yaw", "Kofi", "Kwame"]; let femaleNames =[" Akosua"," Adwoa","Abenaa","Akua","Yaa","Afua","Ama"] //get selected radio button function checkGender(){ var gen = document.getElementsByName("rads"); if(gen[0].checked == true && century !== "" && dayOfMonth !== "" && month !== "" && year !== "" && dayOfMonth > 0 && dayOfMonth <31 && month > 0 && month < 12 && year > 0 && year < 100){ var gender = "male"; document.getElementById("result").innerHTML = `You were born on a ${daysOfWeek[day]} and your Akan name is ${maleNames[day]}`; }else if(gen[1].checked == true && century !== "" && dayOfMonth !== "" && month !== "" && year !== "" && dayOfMonth > 0 && dayOfMonth <31 && month > 0 && month < 12 && year > 0 && year < 100){ var gender = "female"; document.getElementById("result").innerHTML = `You were born on a ${daysOfWeek[day]} and your Akan name is ${femaleNames[day]}`; }else if(gen[0].checked == false || gen[1].checked == false){ document.getElementById("result").innerHTML ='select gender' }else{ document.getElementById("result").innerHTML= `insert correct data`; } }
/********************************************************************************************************************** * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * * and limitations under the License. * *********************************************************************************************************************/ import { createAction } from "redux-actions"; import { either, isEmpty, isNil, lensPath, reject, view } from "ramda"; import { normalize } from "normalizr"; import { API, Storage, Auth } from "aws-amplify"; import uuid from "uuid/v4"; import { SUBMIT_DOCUMENTS, SUBMIT_DOCUMENT, FETCH_DOCUMENTS, FETCH_DOCUMENT, REDACT_DOCUMENT, HIGHLIGHT_DOCUMENT } from "../../../constants/action-types"; import { documentsSchema, documentSchema } from "./data"; const lensNextToken = lensPath(["data", "nextToken"]); const lensDocumentsTotal = lensPath(["data", "Total"]); const lensDocumentsData = lensPath(["data", "documents"]); const lensDocumentData = lensPath(["data"]); export const submitDocument = createAction( SUBMIT_DOCUMENT, async ({ sample, key }) => { const response = await API.post("TextractDemoTextractAPI", "document", { headers: { Authorization: `Bearer ${(await Auth.currentSession()) .getIdToken() .getJwtToken()}` }, response: true, body: { sample: !!sample, key } }); const data = view(lensDocumentData, response); return data; } ); export const submitDocuments = createAction( SUBMIT_DOCUMENTS, async ({ objects }) => { const response = await API.post("TextractDemoTextractAPI", "document", { headers: { Authorization: `Bearer ${(await Auth.currentSession()) .getIdToken() .getJwtToken()}` }, response: true, body: { objects } }); const data = view(lensDocumentData, response); return data; } ); /** * Get documents from TextractDemoTextractAPIs */ export const fetchDocuments = createAction( FETCH_DOCUMENTS, async ({ nextToken: nexttoken } = {}) => { const response = await API.get("TextractDemoTextractAPI", "documents", { headers: { Authorization: `Bearer ${(await Auth.currentSession()) .getIdToken() .getJwtToken()}` }, response: true, queryStringParameters: reject(either(isNil, isEmpty), { nexttoken, type: "user" }) }); const documentsNextToken = view(lensNextToken, response) || null; const documentsTotal = view(lensDocumentsTotal, response); const documents = view(lensDocumentsData, response).map(document => ({ ...document, documentName: document.objectName.replace(/^.*\//, "") })); const { entities } = normalize(documents, documentsSchema); const meta = reject(isNil, { documentsNextToken, documentsTotal }); return { ...entities, meta }; } ); export const fetchSingleDocument = createAction( FETCH_DOCUMENT, async documentid => { const response = await API.get("TextractDemoTextractAPI", "document", { headers: { Authorization: `Bearer ${(await Auth.currentSession()) .getIdToken() .getJwtToken()}` }, response: true, queryStringParameters: { documentid } }); const document = view(lensDocumentData, response); return normalize(document, documentSchema).entities; } ); /** * Get document from TextractDemoTextractAPI */ export const fetchDocument = createAction(FETCH_DOCUMENT, async documentid => { const response = await API.get("TextractDemoTextractAPI", "document", { headers: { Authorization: `Bearer ${(await Auth.currentSession()) .getIdToken() .getJwtToken()}` }, response: true, queryStringParameters: { documentid } }); const document = view(lensDocumentData, response); const { documentId, objectName, bucketName } = document; // Remove the last slash and everything before it const documentName = objectName.replace(/^.*\//, ""); const fileNameWithoutExtension = documentName.split(".")[0] // Amplify prepends public/ to the path, so we have to strip it const documentPublicSubPath = objectName.replace("public/", ""); const resultDirectory = `${documentId}/output`; const textractResponsePath = `${resultDirectory}/textract/response.json`; const comprehendMedicalResponsePath = `${resultDirectory}/comprehend/comprehendMedicalEntities.json` const comprehendResponsePath = `${resultDirectory}/comprehend/comprehendEntities.json` // Get a pre-signed URL for the original document upload const [documentData, searchablePdfData] = await Promise.all([ Storage.get(documentPublicSubPath, { bucket: bucketName, download: true }), Storage.get(`${resultDirectory}/${fileNameWithoutExtension}-searchable.pdf`, { download: true }) ]); const documentBlob = new Blob([documentData.Body], { type: documentData.contentType }); const searchablePdfBlob = new Blob([searchablePdfData.Body], { type: "application/pdf" }); // Get the raw textract response data from a json file on S3 const s3Response = await Storage.get(textractResponsePath, { download: true }); const s3ResponseText = await s3Response.Body?.text() const textractResponse = JSON.parse(s3ResponseText); // Get the raw comprehend medical response data from a json file on S3 const s3ComprehendMedicalResponse = await Storage.get(comprehendMedicalResponsePath, { download: true }); const s3ComprehendMedicalResponseText = await s3ComprehendMedicalResponse.Body?.text() const comprehendMedicalRespone = JSON.parse(s3ComprehendMedicalResponseText); // Get the raw comprehend response data from a json file on S3 const s3ComprehendResponse = await Storage.get(comprehendResponsePath, { download: true }); const s3ComprehendResponseText = await s3ComprehendResponse.Body?.text() const comprehendRespone = JSON.parse(s3ComprehendResponseText); return normalize( { ...document, documentURL: URL.createObjectURL(documentBlob), searchablePdfURL: URL.createObjectURL(searchablePdfBlob), documentName, textractResponse, textractFetchedAt: Date.now(), comprehendMedicalRespone, comprehendRespone, resultDirectory }, documentSchema ).entities; }); export const deleteDocument = createAction(FETCH_DOCUMENT, async documentid => { const response = await API.del("TextractDemoTextractAPI", "document", { headers: { Authorization: `Bearer ${(await Auth.currentSession()) .getIdToken() .getJwtToken()}` }, response: true, queryStringParameters: { documentid } }); return normalize( { documentId: documentid, deleted: true }, documentSchema ).entities; }); export const addRedactions = createAction( REDACT_DOCUMENT, (documentId, pageNumber, redactions) => { const keyedRedactions = redactions.reduce((acc, r) => { acc[uuid()] = r; return acc; }, {}); return normalize( { documentId, redactions: { [pageNumber]: keyedRedactions } }, documentSchema ).entities; } ); export const addHighlights = createAction( HIGHLIGHT_DOCUMENT, (documentId, pageNumber, highlights) => { const response = normalize( { documentId, highlights: highlights }, documentSchema ).entities return response; }); export const clearRedactions = createAction(REDACT_DOCUMENT, documentId => { return normalize( { documentId, redactions: false }, documentSchema ).entities; }); export const clearHighlights = createAction(HIGHLIGHT_DOCUMENT, documentId => { return normalize( { documentId, highlights: [] }, documentSchema ).entities; });
var merge = require('./merge'); var RollbarJSON = {}; var __initRollbarJSON = false; function setupJSON() { if (__initRollbarJSON) { return; } __initRollbarJSON = true; if (isDefined(JSON)) { if (isNativeFunction(JSON.stringify)) { RollbarJSON.stringify = JSON.stringify; } if (isNativeFunction(JSON.parse)) { RollbarJSON.parse = JSON.parse; } } if (!isFunction(RollbarJSON.stringify) || !isFunction(RollbarJSON.parse)) { var setupCustomJSON = require('../vendor/JSON-js/json3.js'); setupCustomJSON(RollbarJSON); } } setupJSON(); /* * isType - Given a Javascript value and a string, returns true if the type of the value matches the * given string. * * @param x - any value * @param t - a lowercase string containing one of the following type names: * - undefined * - null * - error * - number * - boolean * - string * - symbol * - function * - object * - array * @returns true if x is of type t, otherwise false */ function isType(x, t) { return t === typeName(x); } /* * typeName - Given a Javascript value, returns the type of the object as a string */ function typeName(x) { var name = typeof x; if (name !== 'object') { return name; } if (!x) { return 'null'; } if (x instanceof Error) { return 'error'; } return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); } /* isFunction - a convenience function for checking if a value is a function * * @param f - any value * @returns true if f is a function, otherwise false */ function isFunction(f) { return isType(f, 'function'); } /* isNativeFunction - a convenience function for checking if a value is a native JS function * * @param f - any value * @returns true if f is a native JS function, otherwise false */ function isNativeFunction(f) { var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var funcMatchString = Function.prototype.toString.call(Object.prototype.hasOwnProperty) .replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?'); var reIsNative = RegExp('^' + funcMatchString + '$'); return isObject(f) && reIsNative.test(f); } /* isObject - Checks if the argument is an object * * @param value - any value * @returns true is value is an object function is an object) */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /* * isDefined - a convenience function for checking if a value is not equal to undefined * * @param u - any value * @returns true if u is anything other than undefined */ function isDefined(u) { return !isType(u, 'undefined'); } /* * isIterable - convenience function for checking if a value can be iterated, essentially * whether it is an object or an array. * * @param i - any value * @returns true if i is an object or an array as determined by `typeName` */ function isIterable(i) { var type = typeName(i); return (type === 'object' || type === 'array'); } /* * isError - convenience function for checking if a value is of an error type * * @param e - any value * @returns true if e is an error */ function isError(e) { return isType(e, 'error'); } function traverse(obj, func, seen) { var k, v, i; var isObj = isType(obj, 'object'); var isArray = isType(obj, 'array'); var keys = []; if (isObj && seen.indexOf(obj) !== -1) { return obj; } seen.push(obj); if (isObj) { for (k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } } } else if (isArray) { for (i = 0; i < obj.length; ++i) { keys.push(i); } } var result = isObj ? {} : []; var same = true; for (i = 0; i < keys.length; ++i) { k = keys[i]; v = obj[k]; result[k] = func(k, v, seen); same = same && result[k] === obj[k]; } return (keys.length != 0 && !same) ? result : obj; } function redact() { return '********'; } // from http://stackoverflow.com/a/8809472/1138191 function uuid4() { var d = now(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); }); return uuid; } var LEVELS = { debug: 0, info: 1, warning: 2, error: 3, critical: 4 }; function sanitizeUrl(url) { var baseUrlParts = parseUri(url); if (!baseUrlParts) { return '(unknown)'; } // remove a trailing # if there is no anchor if (baseUrlParts.anchor === '') { baseUrlParts.source = baseUrlParts.source.replace('#', ''); } url = baseUrlParts.source.replace('?' + baseUrlParts.query, ''); return url; } var parseUriOptions = { strictMode: false, key: [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ], q: { name: 'queryKey', parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; function parseUri(str) { if (!isType(str, 'string')) { return undefined; } var o = parseUriOptions; var m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str); var uri = {}; var i = o.key.length; while (i--) { uri[o.key[i]] = m[i] || ''; } uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { if ($1) { uri[o.q.name][$1] = $2; } }); return uri; } function addParamsAndAccessTokenToPath(accessToken, options, params) { params = params || {}; params.access_token = accessToken; var paramsArray = []; var k; for (k in params) { if (Object.prototype.hasOwnProperty.call(params, k)) { paramsArray.push([k, params[k]].join('=')); } } var query = '?' + paramsArray.sort().join('&'); options = options || {}; options.path = options.path || ''; var qs = options.path.indexOf('?'); var h = options.path.indexOf('#'); var p; if (qs !== -1 && (h === -1 || h > qs)) { p = options.path; options.path = p.substring(0,qs) + query + '&' + p.substring(qs+1); } else { if (h !== -1) { p = options.path; options.path = p.substring(0,h) + query + p.substring(h); } else { options.path = options.path + query; } } } function formatUrl(u, protocol) { protocol = protocol || u.protocol; if (!protocol && u.port) { if (u.port === 80) { protocol = 'http:'; } else if (u.port === 443) { protocol = 'https:'; } } protocol = protocol || 'https:'; if (!u.hostname) { return null; } var result = protocol + '//' + u.hostname; if (u.port) { result = result + ':' + u.port; } if (u.path) { result = result + u.path; } return result; } function stringify(obj, backup) { var value, error; try { value = RollbarJSON.stringify(obj); } catch (jsonError) { if (backup && isFunction(backup)) { try { value = backup(obj); } catch (backupError) { error = backupError; } } else { error = jsonError; } } return {error: error, value: value}; } function jsonParse(s) { var value, error; try { value = RollbarJSON.parse(s); } catch (e) { error = e; } return {error: error, value: value}; } function makeUnhandledStackInfo( message, url, lineno, colno, error, mode, backupMessage, errorParser ) { var location = { url: url || '', line: lineno, column: colno }; location.func = errorParser.guessFunctionName(location.url, location.line); location.context = errorParser.gatherContext(location.url, location.line); var href = document && document.location && document.location.href; var useragent = window && window.navigator && window.navigator.userAgent; return { 'mode': mode, 'message': error ? String(error) : (message || backupMessage), 'url': href, 'stack': [location], 'useragent': useragent }; } function wrapCallback(logger, f) { return function(err, resp) { try { f(err, resp); } catch (e) { logger.error(e); } }; } function createItem(args, logger, notifier, requestKeys, lambdaContext) { var message, err, custom, callback, request; var arg; var extraArgs = []; for (var i = 0, l = args.length; i < l; ++i) { arg = args[i]; var typ = typeName(arg); switch (typ) { case 'undefined': break; case 'string': message ? extraArgs.push(arg) : message = arg; break; case 'function': callback = wrapCallback(logger, arg); break; case 'date': extraArgs.push(arg); break; case 'error': case 'domexception': err ? extraArgs.push(arg) : err = arg; break; case 'object': case 'array': if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) { err ? extraArgs.push(arg) : err = arg; break; } if (requestKeys && typ === 'object' && !request) { for (var j = 0, len = requestKeys.length; j < len; ++j) { if (arg[requestKeys[j]] !== undefined) { request = arg; break; } } if (request) { break; } } custom ? extraArgs.push(arg) : custom = arg; break; default: if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) { err ? extraArgs.push(arg) : err = arg; break; } extraArgs.push(arg); } } if (extraArgs.length > 0) { // if custom is an array this turns it into an object with integer keys custom = merge(custom); custom.extraArgs = extraArgs; } var item = { message: message, err: err, custom: custom, timestamp: now(), callback: callback, uuid: uuid4() }; if (custom && custom.level !== undefined) { item.level = custom.level; delete custom.level; } if (requestKeys && request) { item.request = request; } if (lambdaContext) { item.lambdaContext = lambdaContext; } item._originalArgs = args; return item; } /* * get - given an obj/array and a keypath, return the value at that keypath or * undefined if not possible. * * @param obj - an object or array * @param path - a string of keys separated by '.' such as 'plugin.jquery.0.message' * which would correspond to 42 in `{plugin: {jquery: [{message: 42}]}}` */ function get(obj, path) { if (!obj) { return undefined; } var keys = path.split('.'); var result = obj; try { for (var i = 0, len = keys.length; i < len; ++i) { result = result[keys[i]]; } } catch (e) { result = undefined; } return result; } function set(obj, path, value) { if (!obj) { return; } var keys = path.split('.'); var len = keys.length; if (len < 1) { return; } if (len === 1) { obj[keys[0]] = value; return; } try { var temp = obj[keys[0]] || {}; var replacement = temp; for (var i = 1; i < len-1; i++) { temp[keys[i]] = temp[keys[i]] || {}; temp = temp[keys[i]]; } temp[keys[len-1]] = value; obj[keys[0]] = replacement; } catch (e) { return; } } function scrub(data, scrubFields) { scrubFields = scrubFields || []; var paramRes = _getScrubFieldRegexs(scrubFields); var queryRes = _getScrubQueryParamRegexs(scrubFields); function redactQueryParam(dummy0, paramPart, dummy1, dummy2, dummy3, valPart) { return paramPart + redact(valPart); } function paramScrubber(v) { var i; if (isType(v, 'string')) { for (i = 0; i < queryRes.length; ++i) { v = v.replace(queryRes[i], redactQueryParam); } } return v; } function valScrubber(k, v) { var i; for (i = 0; i < paramRes.length; ++i) { if (paramRes[i].test(k)) { v = redact(v); break; } } return v; } function scrubber(k, v, seen) { var tmpV = valScrubber(k, v); if (tmpV === v) { if (isType(v, 'object') || isType(v, 'array')) { return traverse(v, scrubber, seen); } return paramScrubber(tmpV); } else { return tmpV; } } return traverse(data, scrubber, []); } function _getScrubFieldRegexs(scrubFields) { var ret = []; var pat; for (var i = 0; i < scrubFields.length; ++i) { pat = '^\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?$'; ret.push(new RegExp(pat, 'i')); } return ret; } function _getScrubQueryParamRegexs(scrubFields) { var ret = []; var pat; for (var i = 0; i < scrubFields.length; ++i) { pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?'; ret.push(new RegExp('(' + pat + '=)([^&\\n]+)', 'igm')); } return ret; } function formatArgsAsString(args) { var i, len, arg; var result = []; for (i = 0, len = args.length; i < len; i++) { arg = args[i]; switch (typeName(arg)) { case 'object': arg = stringify(arg); arg = arg.error || arg.value; if (arg.length > 500) { arg = arg.substr(0, 497) + '...'; } break; case 'null': arg = 'null'; break; case 'undefined': arg = 'undefined'; break; case 'symbol': arg = arg.toString(); break; } result.push(arg); } return result.join(' '); } function now() { if (Date.now) { return +Date.now(); } return +new Date(); } function filterIp(requestData, captureIp) { if (!requestData || !requestData['user_ip'] || captureIp === true) { return; } var newIp = requestData['user_ip']; if (!captureIp) { newIp = null; } else { try { var parts; if (newIp.indexOf('.') !== -1) { parts = newIp.split('.'); parts.pop(); parts.push('0'); newIp = parts.join('.'); } else if (newIp.indexOf(':') !== -1) { parts = newIp.split(':'); if (parts.length > 2) { var beginning = parts.slice(0, 3); var slashIdx = beginning[2].indexOf('/'); if (slashIdx !== -1) { beginning[2] = beginning[2].substring(0, slashIdx); } var terminal = '0000:0000:0000:0000:0000'; newIp = beginning.concat(terminal).join(':'); } } else { newIp = null; } } catch (e) { newIp = null; } } requestData['user_ip'] = newIp; } function handleOptions(current, input, payload) { var result = merge(current, input, payload); if (!input || input.overwriteScrubFields) { return result; } if (input.scrubFields) { result.scrubFields = (current.scrubFields || []).concat(input.scrubFields); } return result; } module.exports = { addParamsAndAccessTokenToPath: addParamsAndAccessTokenToPath, createItem: createItem, filterIp: filterIp, formatArgsAsString: formatArgsAsString, formatUrl: formatUrl, get: get, handleOptions: handleOptions, isError: isError, isFunction: isFunction, isIterable: isIterable, isNativeFunction: isNativeFunction, isType: isType, jsonParse: jsonParse, LEVELS: LEVELS, makeUnhandledStackInfo: makeUnhandledStackInfo, merge: merge, now: now, redact: redact, sanitizeUrl: sanitizeUrl, scrub: scrub, set: set, stringify: stringify, traverse: traverse, typeName: typeName, uuid4: uuid4 };
const { SlashCommandBuilder } = require('@discordjs/builders'); module.exports = { data: new SlashCommandBuilder() .setName('server') .setDescription('Replies with Server info'), async execute(interaction, nanako) { interaction.reply(`Server info: ${interaction.guild.name}\nTotal numbers: ${interaction.guild.memberCount}`); }, };
import numpy as np from pyriemann.estimation import (Covariances, ERPCovariances, XdawnCovariances, CospCovariances, HankelCovariances, Coherences, Shrinkage) import pytest def test_covariances(): """Test Covariances""" x = np.random.randn(2, 3, 100) cov = Covariances() cov.fit(x) cov.fit_transform(x) assert cov.get_params() == dict(estimator='scm') def test_hankel_covariances(): """Test Hankel Covariances""" x = np.random.randn(2, 3, 100) cov = HankelCovariances() cov.fit(x) cov.fit_transform(x) assert cov.get_params() == dict(estimator='scm', delays=4) cov = HankelCovariances(delays=[1, 2]) cov.fit(x) cov.fit_transform(x) def test_erp_covariances(): """Test fit ERPCovariances""" x = np.random.randn(10, 3, 100) labels = np.array([0, 1]).repeat(5) cov = ERPCovariances() cov.fit_transform(x, labels) cov = ERPCovariances(classes=[0]) cov.fit_transform(x, labels) # assert raise svd with pytest.raises(TypeError): ERPCovariances(svd='42') cov = ERPCovariances(svd=2) assert cov.get_params() == dict(classes=None, estimator='scm', svd=2) cov.fit_transform(x, labels) def test_xdawn_covariances(): """Test fit XdawnCovariances""" x = np.random.randn(10, 3, 100) labels = np.array([0, 1]).repeat(5) cov = XdawnCovariances() cov.fit_transform(x, labels) assert cov.get_params() == dict(nfilter=4, applyfilters=True, classes=None, estimator='scm', xdawn_estimator='scm', baseline_cov=None) def test_cosp_covariances(): """Test fit CospCovariances""" x = np.random.randn(2, 3, 1000) cov = CospCovariances() cov.fit(x) cov.fit_transform(x) assert cov.get_params() == dict(window=128, overlap=0.75, fmin=None, fmax=None, fs=None) def test_coherences(): """Test fit Coherences""" x = np.random.randn(2, 3, 1000) cov = Coherences() cov.fit(x) cov.fit_transform(x) assert cov.get_params() == dict(window=128, overlap=0.75, fmin=None, fmax=None, fs=None) def test_shrinkage(): """Test Shrinkage""" x = np.random.randn(2, 3, 100) cov = Covariances() covs = cov.fit_transform(x) sh = Shrinkage() sh.fit(covs) sh.transform(covs) assert sh.get_params() == dict(shrinkage=0.1)
"use strict"; const debug = require("debug"); const debugLog = debug("btcexp:router"); const express = require('express'); const csurf = require('csurf'); const router = express.Router(); const util = require('util'); const moment = require('moment'); const qrcode = require('qrcode'); const bitcoinjs = require('bitcoinjs-lib'); const sha256 = require("crypto-js/sha256"); const hexEnc = require("crypto-js/enc-hex"); const Decimal = require("decimal.js"); const asyncHandler = require("express-async-handler"); const markdown = require("markdown-it")(); const utils = require('./../app/utils.js'); const coins = require("./../app/coins.js"); const config = require("./../app/config.js"); const coreApi = require("./../app/api/coreApi.js"); const addressApi = require("./../app/api/addressApi.js"); const rpcApi = require("./../app/api/rpcApi.js"); const apiDocs = require("./../docs/api.js"); const btcQuotes = require("./../app/coins/btcQuotes.js"); const forceCsrf = csurf({ ignoreMethods: [] }); router.get("/docs", function(req, res, next) { res.locals.apiDocs = apiDocs; res.locals.route = req.query.route; res.locals.categories = []; apiDocs.routes.forEach(x => { let category = x.category; if (!res.locals.categories.find(y => (y.name == category))) { res.locals.categories.push({name:category, items:[]}); } res.locals.categories.find(x => (x.name == category)).items.push(x); }); res.render("api-docs"); next(); }); router.get("/changelog", function(req, res, next) { res.locals.changelogHtml = markdown.render(global.apiChangelogMarkdown); res.render("api-changelog"); next(); }); router.get("/version", function(req, res, next) { res.send(apiDocs.version); next(); }); /// BLOCKS router.get("/blocks/tip/height", asyncHandler(async (req, res, next) => { try { const blockcount = await rpcApi.getBlockCount(); res.send(blockcount.toString()); } catch (e) { utils.logError("a39gfoeuew", e); res.json({success: false}); } next(); })); router.get("/blocks/tip/hash", function(req, res, next) { coreApi.getBlockchainInfo().then(function(getblockchaininfo){ res.send(getblockchaininfo.bestblockhash.toString()); }).catch(next); }); router.get("/block/:hashOrHeight", asyncHandler(async (req, res, next) => { const hashOrHeight = req.params.hashOrHeight; let hash = (hashOrHeight.length == 64 ? hashOrHeight : null); try { if (hash == null) { hash = await coreApi.getBlockHashByHeight(parseInt(hashOrHeight)); } const block = await coreApi.getBlockByHash(hash); res.json(block); } catch (e) { utils.logError("w9fgeddsuos", e); res.json({success: false}); } next(); })); /// TRANSACTIONS router.get("/tx/:txid", function(req, res, next) { var txid = utils.asHash(req.params.txid); var promises = []; promises.push(coreApi.getRawTransactionsWithInputs([txid])); Promise.all(promises).then(function(results) { res.json(results[0].transactions[0]); next(); }).catch(function(err) { res.json({success:false, error:err}); next(); }); }); /// BLOCKCHAIN router.get("/blockchain/coins", function(req, res, next) { if (global.utxoSetSummary) { var supply = parseFloat(global.utxoSetSummary.total_amount).toString(); res.send(supply.toString()); next(); } else { // estimated supply coreApi.getBlockchainInfo().then(function(getblockchaininfo){ var estimatedSupply = utils.estimatedSupply(getblockchaininfo.blocks); res.send(estimatedSupply.toString()); }).catch(next); } }); /// MINING router.get("/mining/hashrate", asyncHandler(async (req, res, next) => { try { var decimals = 3; if (req.query.decimals) { decimals = parseInt(req.query.decimals); } var blocksPerDay = 24 * 60 * 60 / coinConfig.targetBlockTimeSeconds; var rates = []; var timePeriods = [ 1 * blocksPerDay, 7 * blocksPerDay, 30 * blocksPerDay, 90 * blocksPerDay, 365 * blocksPerDay, ]; var promises = []; for (var i = 0; i < timePeriods.length; i++) { const index = i; const x = timePeriods[i]; promises.push(new Promise(async (resolve, reject) => { try { const hashrate = await coreApi.getNetworkHashrate(x); var summary = utils.formatLargeNumber(hashrate, decimals); rates[index] = { val: parseFloat(summary[0]), unit: `${summary[1].name}hash`, unitAbbreviation: `${summary[1].abbreviation}H`, unitExponent: summary[1].exponent, unitMultiplier: summary[1].val, raw: summary[0] * summary[1].val, string1: `${summary[0]}x10^${summary[1].exponent}`, string2: `${summary[0]}e${summary[1].exponent}`, string3: `${(summary[0] * summary[1].val).toLocaleString()}` }; resolve(); } catch (ex) { utils.logError("8ehfwe8ehe", ex); resolve(); } })); } await Promise.all(promises); res.json({ "1Day": rates[0], "7Day": rates[1], "30Day": rates[2], "90day": rates[3], "365Day": rates[4] }); } catch (e) { utils.logError("23reuhd8uw92D", e); res.json({ error: typeof(e) == "string" ? e : utils.stringifySimple(e) }); } })); router.get("/mining/diff-adj-estimate", asyncHandler(async (req, res, next) => { var promises = []; const getblockchaininfo = await utils.timePromise("api_diffAdjEst_getBlockchainInfo", coreApi.getBlockchainInfo()); var currentBlock; var difficultyPeriod = parseInt(Math.floor(getblockchaininfo.blocks / coinConfig.difficultyAdjustmentBlockCount)); var difficultyPeriodFirstBlockHeader; promises.push(utils.safePromise("api_diffAdjEst_getBlockHeaderByHeight", async () => { currentBlock = await coreApi.getBlockHeaderByHeight(getblockchaininfo.blocks); })); promises.push(utils.safePromise("api_diffAdjEst_getBlockHeaderByHeight2", async () => { let h = coinConfig.difficultyAdjustmentBlockCount * difficultyPeriod; difficultyPeriodFirstBlockHeader = await coreApi.getBlockHeaderByHeight(h); })); await Promise.all(promises); var firstBlockHeader = difficultyPeriodFirstBlockHeader; var heightDiff = currentBlock.height - firstBlockHeader.height; var blockCount = heightDiff + 1; var timeDiff = currentBlock.mediantime - firstBlockHeader.mediantime; var timePerBlock = timeDiff / heightDiff; var dt = new Date().getTime() / 1000 - firstBlockHeader.time; var predictedBlockCount = dt / coinConfig.targetBlockTimeSeconds; var timePerBlock2 = dt / heightDiff; var blockRatioPercent = new Decimal(blockCount / predictedBlockCount).times(100); if (blockRatioPercent > 400) { blockRatioPercent = new Decimal(400); } if (blockRatioPercent < 25) { blockRatioPercent = new Decimal(25); } if (predictedBlockCount > blockCount) { var diffAdjPercent = new Decimal(100).minus(blockRatioPercent).times(-1); //diffAdjPercent = diffAdjPercent * -1; } else { var diffAdjPercent = blockRatioPercent.minus(new Decimal(100)); } res.send(diffAdjPercent.toFixed(2).toString()); })); /// MEMPOOL router.get("/mempool/count", function(req, res, next) { coreApi.getMempoolInfo().then(function(info){ res.send(info.size.toString()); }).catch(next); }); router.get("/mempool/fees", function(req, res, next) { var feeConfTargets = [1, 3, 6, 144]; coreApi.getSmartFeeEstimates("CONSERVATIVE", feeConfTargets).then(function(rawSmartFeeEstimates){ var smartFeeEstimates = {}; for (var i = 0; i < feeConfTargets.length; i++) { var rawSmartFeeEstimate = rawSmartFeeEstimates[i]; if (rawSmartFeeEstimate.errors) { smartFeeEstimates[feeConfTargets[i]] = "?"; } else { smartFeeEstimates[feeConfTargets[i]] = parseInt(new Decimal(rawSmartFeeEstimate.feerate).times(coinConfig.baseCurrencyUnit.multiplier).dividedBy(1000)); } } var results = { "nextBlock":smartFeeEstimates[1], "30min":smartFeeEstimates[3], "60min":smartFeeEstimates[6], "1day":smartFeeEstimates[144] }; res.json(results); }).catch(next); }); /// UTIL router.get("/util/xyzpub/:extendedPubkey", asyncHandler(async (req, res, next) => { try { const extendedPubkey = req.params.extendedPubkey; res.locals.extendedPubkey = extendedPubkey; let limit = 20; if (req.query.limit) { limit = parseInt(req.query.limit); } let offset = 0; if (req.query.offset) { offset = parseInt(req.query.offset); } let receiveAddresses = []; let changeAddresses = []; let relatedKeys = []; let outputType = "Unknown"; let outputTypeDesc = null; let bip32Path = "Unknown"; // if xpub/ypub/zpub convert to address under path m/0/0 if (extendedPubkey.match(/^(xpub|tpub).*$/)) { outputType = "P2PKH"; outputTypeDesc = "Pay to Public Key Hash"; bip32Path = "m/44'/0'"; const xpub_tpub = global.activeBlockchain == "main" ? "xpub" : "tpub"; const ypub_upub = global.activeBlockchain == "main" ? "ypub" : "upub"; const zpub_vpub = global.activeBlockchain == "main" ? "zpub" : "vpub"; let xpub = extendedPubkey; if (!extendedPubkey.startsWith(xpub_tpub)) { xpub = utils.xpubChangeVersionBytes(extendedPubkey, xpub_tpub); } receiveAddresses = utils.bip32Addresses(extendedPubkey, "p2pkh", 0, limit, offset); changeAddresses = utils.bip32Addresses(extendedPubkey, "p2pkh", 1, limit, offset); if (!extendedPubkey.startsWith(xpub_tpub)) { relatedKeys.push({ keyType: xpub_tpub, key: utils.xpubChangeVersionBytes(xpub, xpub_tpub), outputType: "P2PKH", firstAddress: utils.bip32Addresses(xpub, "p2pkh", 0, 1, 0)[0] }); } relatedKeys.push({ keyType: ypub_upub, key: utils.xpubChangeVersionBytes(xpub, ypub_upub), outputType: "P2WPKH in P2SH", firstAddress: utils.bip32Addresses(xpub, "p2sh(p2wpkh)", 0, 1, 0)[0] }); relatedKeys.push({ keyType: zpub_vpub, key: utils.xpubChangeVersionBytes(xpub, zpub_vpub), outputType: "P2WPKH", firstAddress: utils.bip32Addresses(xpub, "p2wpkh", 0, 1, 0)[0] }); } else if (extendedPubkey.match(/^(ypub|upub).*$/)) { outputType = "P2WPKH in P2SH"; outputTypeDesc = "Pay to Witness Public Key Hash (P2WPKH) wrapped inside Pay to Script Hash (P2SH), aka Wrapped Segwit"; bip32Path = "m/49'/0'"; const xpub_tpub = global.activeBlockchain == "main" ? "xpub" : "tpub"; const zpub_vpub = global.activeBlockchain == "main" ? "zpub" : "vpub"; const xpub = utils.xpubChangeVersionBytes(extendedPubkey, xpub_tpub); receiveAddresses = utils.bip32Addresses(xpub, "p2sh(p2wpkh)", 0, limit, offset); changeAddresses = utils.bip32Addresses(xpub, "p2sh(p2wpkh)", 1, limit, offset); relatedKeys.push({ keyType: xpub_tpub, key: xpub, outputType: "P2PKH", firstAddress: utils.bip32Addresses(xpub, "p2pkh", 0, 1, 0)[0] }); relatedKeys.push({ keyType: zpub_vpub, key: utils.xpubChangeVersionBytes(xpub, zpub_vpub), outputType: "P2WPKH", firstAddress: utils.bip32Addresses(xpub, "p2wpkh", 0, 1, 0)[0] }); } else if (extendedPubkey.match(/^(zpub|vpub).*$/)) { outputType = "P2WPKH"; outputTypeDesc = "Pay to Witness Public Key Hash, aka Native Segwit"; bip32Path = "m/84'/0'"; const xpub_tpub = global.activeBlockchain == "main" ? "xpub" : "tpub"; const ypub_upub = global.activeBlockchain == "main" ? "ypub" : "upub"; const xpub = utils.xpubChangeVersionBytes(extendedPubkey, xpub_tpub); receiveAddresses = utils.bip32Addresses(xpub, "p2wpkh", 0, limit, offset); changeAddresses = utils.bip32Addresses(xpub, "p2wpkh", 1, limit, offset); relatedKeys.push({ keyType: xpub_tpub, key: xpub, outputType: "P2PKH", firstAddress: utils.bip32Addresses(xpub, "p2pkh", 0, 1, 0)[0] }); relatedKeys.push({ keyType: ypub_upub, key: utils.xpubChangeVersionBytes(xpub, ypub_upub), outputType: "P2WPKH in P2SH", firstAddress: utils.bip32Addresses(xpub, "p2sh(p2wpkh)", 0, 1, 0)[0] }); } else if (extendedPubkey.startsWith("Ypub")) { outputType = "Multi-Sig P2WSH in P2SH"; bip32Path = "-"; } else if (extendedPubkey.startsWith("Zpub")) { outputType = "Multi-Sig P2WSH"; bip32Path = "-"; } res.json({ keyType: extendedPubkey.substring(0, 4), outputType: outputType, outputTypeDesc: outputTypeDesc, bip32Path: bip32Path, relatedKeys: relatedKeys, receiveAddresses: receiveAddresses, changeAddresses: changeAddresses }); next(); } catch (err) { res.locals.pageErrors.push(utils.logError("0923tygdusde", err)); next(); } })); /// PRICE router.get("/price/:currency/sats", function(req, res, next) { var result = 0; var amount = 1.0; var currency = req.params.currency.toLowerCase(); if (global.exchangeRates != null && global.exchangeRates[currency] != null) { var satsRateData = utils.satoshisPerUnitOfLocalCurrency(currency); result = satsRateData.amtRaw; } else if (currency == "xau" && global.exchangeRates != null && global.goldExchangeRates != null) { var dec = new Decimal(amount); dec = dec.times(global.exchangeRates.usd).dividedBy(global.goldExchangeRates.usd); var satCurrencyType = global.currencyTypes["sat"]; var one = new Decimal(1); dec = one.dividedBy(dec); dec = dec.times(satCurrencyType.multiplier); result = dec.toFixed(0); } res.send(result.toString()); next(); }); router.get("/price/:currency/marketcap", function(req, res, next) { var result = 0; coreApi.getBlockchainInfo().then(function(getblockchaininfo){ var estimatedSupply = utils.estimatedSupply(getblockchaininfo.blocks); var price = 0; var amount = 1.0; var currency = req.params.currency.toLowerCase(); if (global.exchangeRates != null && global.exchangeRates[currency] != null) { var formatData = utils.formatExchangedCurrency(amount, currency); price = parseFloat(formatData.valRaw).toFixed(2); } else if (currency == "xau" && global.exchangeRates != null && global.goldExchangeRates != null) { var dec = new Decimal(amount); dec = dec.times(global.exchangeRates.usd).dividedBy(global.goldExchangeRates.usd); var exchangedAmt = parseFloat(Math.round(dec * 100) / 100).toFixed(2); price = exchangedAmt; } result = estimatedSupply * price; res.send(result.toFixed(2).toString()); next(); }).catch(next); }); router.get("/price/:currency", function(req, res, next) { var result = 0; var amount = 1.0; var currency = req.params.currency.toLowerCase(); if (global.exchangeRates != null && global.exchangeRates[currency] != null) { var formatData = utils.formatExchangedCurrency(amount, currency); result = formatData.val; } else if (currency == "xau" && global.exchangeRates != null && global.goldExchangeRates != null) { var dec = new Decimal(amount); dec = dec.times(global.exchangeRates.usd).dividedBy(global.goldExchangeRates.usd); var exchangedAmt = parseFloat(Math.round(dec * 100) / 100).toFixed(2); result = utils.addThousandsSeparators(exchangedAmt); } res.send(result.toString()); next(); }); router.get("/price", function(req, res, next) { var amount = 1.0; var result = {}; ["usd", "eur", "gbp", "xau"].forEach(currency => { if (global.exchangeRates != null && global.exchangeRates[currency] != null) { var formatData = utils.formatExchangedCurrency(amount, currency); result[currency] = formatData.val; } else if (currency == "xau" && global.exchangeRates != null && global.goldExchangeRates != null) { var dec = new Decimal(amount); dec = dec.times(global.exchangeRates.usd).dividedBy(global.goldExchangeRates.usd); var exchangedAmt = parseFloat(Math.round(dec * 100) / 100).toFixed(2); result[currency] = utils.addThousandsSeparators(exchangedAmt); } }); res.json(result); next(); }); /// FUN router.get("/quotes/random", function(req, res, next) { var index = utils.randomInt(0, btcQuotes.items.length); res.json(btcQuotes.items[index]); next(); }); router.get("/quotes/:quoteIndex", function(req, res, next) { var index = parseInt(req.params.quoteIndex); res.json(btcQuotes.items[index]); next(); }); router.get("/quotes/all", function(req, res, next) { res.json(btcQuotes.items); next(); }); module.exports = router;
/*! * jQuery JavaScript Library v1.3rc1 * http://jquery.com/ * * Copyright (c) 2009 John Resig * Dual licensed under the MIT and GPL licenses. * http://docs.jquery.com/License * * Date: 2009-01-11 21:05:50 -0500 (Sun, 11 Jan 2009) * Revision: 6089 */ (function(){ var // Will speed up references to window, and allows munging its name. window = this, // Will speed up references to undefined, and allows munging its name. undefined, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery = window.jQuery = window.$ = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { // Make sure that a selection was provided selector = selector || document; // Handle $(DOMElement) if ( selector.nodeType ) { this[0] = selector; this.length = 1; this.context = selector; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? var match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) selector = jQuery.clean( [ match[1] ], context ); // HANDLE: $("#id") else { var elem = document.getElementById( match[3] ); // Make sure an element was located if ( elem ){ // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id != match[3] ) return jQuery().find( selector ); // Otherwise, we inject the element directly into the jQuery object var ret = jQuery( elem ); ret.context = document; ret.selector = selector; return ret; } selector = []; } // HANDLE: $(expr, [context]) // (which is just equivalent to: $(content).find(expr) } else return jQuery( context ).find( selector ); // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) return jQuery( document ).ready( selector ); // Make sure that old selector state is passed along if ( selector.selector && selector.context ) { this.selector = selector.selector; this.context = selector.context; } return this.setArray(jQuery.makeArray(selector)); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.3rc1", // The number of elements contained in the matched element set size: function() { return this.length; }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num === undefined ? // Return a 'clean' array jQuery.makeArray( this ) : // Return just the object this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery( elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) ret.selector = this.selector + (this.selector ? " " : "") + selector; else if ( name ) ret.selector = this.selector + "." + name + "(" + selector + ")"; // Return the newly-formed element set return ret; }, // Force the current matched set of elements to become // the specified array of elements (destroying the stack in the process) // You should use pushStack() in order to do this, but maintain the stack setArray: function( elems ) { // Resetting the length to 0, then using the native Array push // is a super-fast way to populate an object with array-like properties this.length = 0; Array.prototype.push.apply( this, elems ); return this; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem && elem.jquery ? elem[0] : elem , this ); }, attr: function( name, value, type ) { var options = name; // Look for the case where we're accessing a style value if ( typeof name === "string" ) if ( value === undefined ) return this[0] && jQuery[ type || "attr" ]( this[0], name ); else { options = {}; options[ name ] = value; } // Check to see if we're setting style values return this.each(function(i){ // Set all the styles for ( name in options ) jQuery.attr( type ? this.style : this, name, jQuery.prop( this, options[ name ], type, i, name ) ); }); }, css: function( key, value ) { // ignore negative width and height values if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 ) value = undefined; return this.attr( key, value, "curCSS" ); }, text: function( text ) { if ( typeof text !== "object" && text != null ) return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); var ret = ""; jQuery.each( text || this, function(){ jQuery.each( this.childNodes, function(){ if ( this.nodeType != 8 ) ret += this.nodeType != 1 ? this.nodeValue : jQuery.fn.text( [ this ] ); }); }); return ret; }, wrapAll: function( html ) { if ( this[0] ) // The elements to wrap the target around jQuery( html, this[0].ownerDocument ) .clone() .insertBefore( this[0] ) .map(function(){ var elem = this; while ( elem.firstChild ) elem = elem.firstChild; return elem; }) .append(this); return this; }, wrapInner: function( html ) { return this.each(function(){ jQuery( this ).contents().wrapAll( html ); }); }, wrap: function( html ) { return this.each(function(){ jQuery( this ).wrapAll( html ); }); }, append: function() { return this.domManip(arguments, true, function(elem){ if (this.nodeType == 1) this.appendChild( elem ); }); }, prepend: function() { return this.domManip(arguments, true, function(elem){ if (this.nodeType == 1) this.insertBefore( elem, this.firstChild ); }); }, before: function() { return this.domManip(arguments, false, function(elem){ this.parentNode.insertBefore( elem, this ); }); }, after: function() { return this.domManip(arguments, false, function(elem){ this.parentNode.insertBefore( elem, this.nextSibling ); }); }, end: function() { return this.prevObject || jQuery( [] ); }, // For internal use only. // Behaves like an Array's .push method, not like a jQuery method. push: [].push, find: function( selector ) { if ( this.length === 1 && !/,/.test(selector) ) { var ret = this.pushStack( [], "find", selector ); ret.length = 0; jQuery.find( selector, this[0], ret ); return ret; } else { var elems = jQuery.map(this, function(elem){ return jQuery.find( selector, elem ); }); return this.pushStack( /[^+>] [^+>]/.test( selector ) ? jQuery.unique( elems ) : elems, "find", selector ); } }, clone: function( events ) { // Do the clone var ret = this.map(function(){ if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var clone = this.cloneNode(true), container = document.createElement("div"); container.appendChild(clone); return jQuery.clean([container.innerHTML])[0]; } else return this.cloneNode(true); }); // Need to set the expando to null on the cloned set if it exists // removeData doesn't work here, IE removes it from the original as well // this is primarily for IE but the data expando shouldn't be copied over in any browser var clone = ret.find("*").andSelf().each(function(){ if ( this[ expando ] !== undefined ) this[ expando ] = null; }); // Copy the events from the original to the clone if ( events === true ) this.find("*").andSelf().each(function(i){ if (this.nodeType == 3) return; var events = jQuery.data( this, "events" ); for ( var type in events ) for ( var handler in events[ type ] ) jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data ); }); // Return the cloned set return ret; }, filter: function( selector ) { return this.pushStack( jQuery.isFunction( selector ) && jQuery.grep(this, function(elem, i){ return selector.call( elem, i ); }) || jQuery.multiFilter( selector, jQuery.grep(this, function(elem){ return elem.nodeType === 1; }) ), "filter", selector ); }, closest: function( selector ) { var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null; return this.map(function(){ var cur = this; while ( cur && cur.ownerDocument ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) return cur; cur = cur.parentNode; } }); }, not: function( selector ) { if ( typeof selector === "string" ) // test special case where just one selector is passed in if ( isSimple.test( selector ) ) return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector ); else selector = jQuery.multiFilter( selector, this ); var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType; return this.filter(function() { return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector; }); }, add: function( selector ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), typeof selector === "string" ? jQuery( selector ) : jQuery.makeArray( selector ) ))); }, is: function( selector ) { return !!selector && jQuery.multiFilter( selector, this ).length > 0; }, hasClass: function( selector ) { return !!selector && this.is( "." + selector ); }, val: function( value ) { if ( value === undefined ) { var elem = this[0]; if ( elem ) { if( jQuery.nodeName( elem, 'option' ) ) return (elem.attributes.value || {}).specified ? elem.value : elem.text; // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type == "select-one"; // Nothing was selected if ( index < 0 ) return null; // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) return value; // Multi-Selects return an array values.push( value ); } } return values; } // Everything else, we just grab the value return (elem.value || "").replace(/\r/g, ""); } return undefined; } if ( typeof value === "number" ) value += ''; return this.each(function(){ if ( this.nodeType != 1 ) return; if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) ) this.checked = (jQuery.inArray(this.value, value) >= 0 || jQuery.inArray(this.name, value) >= 0); else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(value); jQuery( "option", this ).each(function(){ this.selected = (jQuery.inArray( this.value, values ) >= 0 || jQuery.inArray( this.text, values ) >= 0); }); if ( !values.length ) this.selectedIndex = -1; } else this.value = value; }); }, html: function( value ) { return value === undefined ? (this[0] ? this[0].innerHTML : null) : this.empty().append( value ); }, replaceWith: function( value ) { return this.after( value ).remove(); }, eq: function( i ) { return this.slice( i, +i + 1 ); }, slice: function() { return this.pushStack( Array.prototype.slice.apply( this, arguments ), "slice", Array.prototype.slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function(elem, i){ return callback.call( elem, i, elem ); })); }, andSelf: function() { return this.add( this.prevObject ); }, domManip: function( args, table, callback ) { if ( this[0] ) { var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(), scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ), first = fragment.firstChild, extra = this.length > 1 ? fragment.cloneNode(true) : fragment; if ( first ) for ( var i = 0, l = this.length; i < l; i++ ) callback.call( root(this[i], first), i > 0 ? extra.cloneNode(true) : fragment ); if ( scripts ) jQuery.each( scripts, evalScript ); } return this; function root( elem, cur ) { return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; function evalScript( i, elem ) { if ( elem.src ) jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); else jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); if ( elem.parentNode ) elem.parentNode.removeChild( elem ); } function now(){ return +new Date; } jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) target = {}; // extend jQuery itself if only one argument is passed if ( length == i ) { target = this; --i; } for ( ; i < length; i++ ) // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) // Extend the base object for ( var name in options ) { var src = target[ name ], copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) continue; // Recurse if we're merging object values if ( deep && copy && typeof copy === "object" && !copy.nodeType ) target[ name ] = jQuery.extend( deep, // Never move original objects, clone them src || ( copy.length != null ? [ ] : { } ) , copy ); // Don't bring in undefined values else if ( copy !== undefined ) target[ name ] = copy; } // Return the modified object return target; }; // exclude the following css properties to add px var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, // cache defaultView defaultView = document.defaultView || {}, toString = Object.prototype.toString; jQuery.extend({ noConflict: function( deep ) { window.$ = _$; if ( deep ) window.jQuery = _jQuery; return jQuery; }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, // check if an element is in a (or is an) XML document isXMLDoc: function( elem ) { return elem.documentElement && !elem.body || elem.tagName && elem.ownerDocument && !elem.ownerDocument.body; }, // Evalulates a script in a global context globalEval: function( data ) { data = jQuery.trim( data ); if ( data ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) script.appendChild( document.createTextNode( data ) ); else script.text = data; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length; if ( args ) { if ( length === undefined ) { for ( name in object ) if ( callback.apply( object[ name ], args ) === false ) break; } else for ( ; i < length; ) if ( callback.apply( object[ i++ ], args ) === false ) break; // A special, fast, case for the most common use of each } else { if ( length === undefined ) { for ( name in object ) if ( callback.call( object[ name ], name, object[ name ] ) === false ) break; } else for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} } return object; }, prop: function( elem, value, type, i, name ) { // Handle executable functions if ( jQuery.isFunction( value ) ) value = value.call( elem, i ); // Handle passing in a number to a CSS property return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ? value + "px" : value; }, className: { // internal only, use addClass("class") add: function( elem, classNames ) { jQuery.each((classNames || "").split(/\s+/), function(i, className){ if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) ) elem.className += (elem.className ? " " : "") + className; }); }, // internal only, use removeClass("class") remove: function( elem, classNames ) { if (elem.nodeType == 1) elem.className = classNames !== undefined ? jQuery.grep(elem.className.split(/\s+/), function(className){ return !jQuery.className.has( classNames, className ); }).join(" ") : ""; }, // internal only, use hasClass("class") has: function( elem, className ) { return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1; } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) elem.style[ name ] = old[ name ]; }, css: function( elem, name, force ) { if ( name == "width" || name == "height" ) { var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ]; function getWH() { val = name == "width" ? elem.offsetWidth : elem.offsetHeight; var padding = 0, border = 0; jQuery.each( which, function() { padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; }); val -= Math.round(padding + border); } if ( jQuery(elem).is(":visible") ) getWH(); else jQuery.swap( elem, props, getWH ); return Math.max(0, val); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { var ret, style = elem.style; // We need to handle opacity special in IE if ( name == "opacity" && !jQuery.support.opacity ) { ret = jQuery.attr( style, "opacity" ); return ret == "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( name.match( /float/i ) ) name = styleFloat; if ( !force && style && style[ name ] ) ret = style[ name ]; else if ( defaultView.getComputedStyle ) { // Only "float" is needed here if ( name.match( /float/i ) ) name = "float"; name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase(); var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) ret = computedStyle.getPropertyValue( name ); // We should always get a number back from opacity if ( name == "opacity" && ret == "" ) ret = "1"; } else if ( elem.currentStyle ) { var camelCase = name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); }); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = ret || 0; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, clean: function( elems, context, fragment ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) context = context.ownerDocument || context[0] && context[0].ownerDocument || document; // If a single string is passed in and it's a single tag // just do a createElement and skip the rest if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) { var match = /^<(\w+)\s*\/?>$/.exec(elems[0]); if ( match ) return [ context.createElement( match[1] ) ]; } var ret = [], scripts = [], div = context.createElement("div"); jQuery.each(elems, function(i, elem){ if ( typeof elem === "number" ) elem += ''; if ( !elem ) return; // Convert html string into DOM nodes if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? all : front + "></" + tag + ">"; }); // Trim whitespace, otherwise indexOf won't work as expected var tags = jQuery.trim( elem ).toLowerCase(); var wrap = // option or optgroup !tags.indexOf("<opt") && [ 1, "<select multiple='multiple'>", "</select>" ] || !tags.indexOf("<leg") && [ 1, "<fieldset>", "</fieldset>" ] || tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && [ 1, "<table>", "</table>" ] || !tags.indexOf("<tr") && [ 2, "<table><tbody>", "</tbody></table>" ] || // <thead> matched above (!tags.indexOf("<td") || !tags.indexOf("<th")) && [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] || !tags.indexOf("<col") && [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] || // IE can't serialize <link> and <script> tags normally !jQuery.support.htmlSerialize && [ 1, "div<div>", "</div>" ] || [ 0, "", "" ]; // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( wrap[0]-- ) div = div.lastChild; // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) tbody[ j ].parentNode.removeChild( tbody[ j ] ); } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) ) div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild ); elem = jQuery.makeArray( div.childNodes ); } if ( elem.nodeType ) ret.push( elem ); else ret = jQuery.merge( ret, elem ); }); if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); fragment.appendChild( ret[i] ); } } return scripts; } return ret; }, attr: function( elem, name, value ) { // don't set attributes on text and comment nodes if (!elem || elem.nodeType == 3 || elem.nodeType == 8) return undefined; var notxml = !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) // IE elem.getAttribute passes even for style if ( elem.tagName ) { // These attributes require special treatment var special = /href|src|style/.test( name ); // Safari mis-reports the default selected property of a hidden option // Accessing the parent's selectedIndex property fixes it if ( name == "selected" ) elem.parentNode.selectedIndex; // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ){ // We can't allow the type property to be changed (since it causes problems in IE) if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode ) throw "type property can't be changed"; elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) return elem.getAttributeNode( name ).nodeValue; // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name == "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : elem.nodeName.match(/^(a|area|button|input|object|select|textarea)$/i) ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name == "style" ) return jQuery.attr( elem.style, "cssText", value ); if ( set ) // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); var attr = !jQuery.support.hrefNormalized && notxml && special // Some attributes require a special call on IE ? elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // IE uses filters for opacity if ( !jQuery.support.opacity && name == "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level elem.zoom = 1; // Set the alpha filter to set the opacity elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) + (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"); } return elem.filter && elem.filter.indexOf("opacity=") >= 0 ? (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '': ""; } name = name.replace(/-([a-z])/ig, function(all, letter){ return letter.toUpperCase(); }); if ( set ) elem[ name ] = value; return elem[ name ]; }, trim: function( text ) { return (text || "").replace( /^\s+|\s+$/g, "" ); }, makeArray: function( array ) { var ret = []; if( array != null ){ var i = array.length; // The window, strings (and functions) also have 'length' if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval ) ret[0] = array; else while( i ) ret[--i] = array[i]; } return ret; }, inArray: function( elem, array ) { for ( var i = 0, length = array.length; i < length; i++ ) // Use === because on IE, window == document if ( array[ i ] === elem ) return i; return -1; }, merge: function( first, second ) { // We have to loop this way because IE & Opera overwrite the length // expando of getElementsByTagName var i = 0, elem, pos = first.length; // Also, we need to make sure that the correct elements are being returned // (IE returns comment nodes in a '*' query) if ( !jQuery.support.getAll ) { while ( (elem = second[ i++ ]) != null ) if ( elem.nodeType != 8 ) first[ pos++ ] = elem; } else while ( (elem = second[ i++ ]) != null ) first[ pos++ ] = elem; return first; }, unique: function( array ) { var ret = [], done = {}; try { for ( var i = 0, length = array.length; i < length; i++ ) { var id = jQuery.data( array[ i ] ); if ( !done[ id ] ) { done[ id ] = true; ret.push( array[ i ] ); } } } catch( e ) { ret = array; } return ret; }, grep: function( elems, callback, inv ) { var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) if ( !inv != !callback( elems[ i ], i ) ) ret.push( elems[ i ] ); return ret; }, map: function( elems, callback ) { var ret = []; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { var value = callback( elems[ i ], i ); if ( value != null ) ret[ ret.length ] = value; } return ret.concat.apply( [], ret ); } }); // Use of jQuery.browser is deprecated. // It's included for backwards compatibility and plugins, // although they should work to migrate away. var userAgent = navigator.userAgent.toLowerCase(); // Figure out what browser is being used jQuery.browser = { version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1], safari: /webkit/.test( userAgent ), opera: /opera/.test( userAgent ), msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ), mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ) }; jQuery.each({ parent: function(elem){return elem.parentNode;}, parents: function(elem){return jQuery.dir(elem,"parentNode");}, next: function(elem){return jQuery.nth(elem,2,"nextSibling");}, prev: function(elem){return jQuery.nth(elem,2,"previousSibling");}, nextAll: function(elem){return jQuery.dir(elem,"nextSibling");}, prevAll: function(elem){return jQuery.dir(elem,"previousSibling");}, siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);}, children: function(elem){return jQuery.sibling(elem.firstChild);}, contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(name, original){ jQuery.fn[ name ] = function() { var args = arguments; return this.each(function(){ for ( var i = 0, length = args.length; i < length; i++ ) jQuery( args[ i ] )[ original ]( this ); }); }; }); jQuery.each({ removeAttr: function( name ) { jQuery.attr( this, name, "" ); if (this.nodeType == 1) this.removeAttribute( name ); }, addClass: function( classNames ) { jQuery.className.add( this, classNames ); }, removeClass: function( classNames ) { jQuery.className.remove( this, classNames ); }, toggleClass: function( classNames, state ) { if( typeof state !== "boolean" ) state = !jQuery.className.has( this, classNames ); jQuery.className[ state ? "add" : "remove" ]( this, classNames ); }, remove: function( selector ) { if ( !selector || jQuery.filter( selector, [ this ] ).length ) { // Prevent memory leaks jQuery( "*", this ).add([this]).each(function(){ jQuery.event.remove(this); jQuery.removeData(this); }); if (this.parentNode) this.parentNode.removeChild( this ); } }, empty: function() { // Remove element nodes and prevent memory leaks jQuery( ">*", this ).remove(); // Remove any remaining nodes while ( this.firstChild ) this.removeChild( this.firstChild ); } }, function(name, fn){ jQuery.fn[ name ] = function(){ return this.each( fn, arguments ); }; }); // Helper function used by the dimensions and offset modules function num(elem, prop) { return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0; } var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, data: function( elem, name, data ) { elem = elem == window ? windowData : elem; var id = elem[ expando ]; // Compute a unique ID for the element if ( !id ) id = elem[ expando ] = ++uuid; // Only generate the data cache if we're // trying to access or manipulate it if ( name && !jQuery.cache[ id ] ) jQuery.cache[ id ] = {}; // Prevent overriding the named cache with undefined values if ( data !== undefined ) jQuery.cache[ id ][ name ] = data; // Return the named cache data, or the ID for the element return name ? jQuery.cache[ id ][ name ] : id; }, removeData: function( elem, name ) { elem = elem == window ? windowData : elem; var id = elem[ expando ]; // If we want to remove a specific section of the element's data if ( name ) { if ( jQuery.cache[ id ] ) { // Remove the section of cache data delete jQuery.cache[ id ][ name ]; // If we've removed all the data, remove the element's cache name = ""; for ( name in jQuery.cache[ id ] ) break; if ( !name ) jQuery.removeData( elem ); } // Otherwise, we want to remove all of the element's data } else { // Clean up the element expando try { delete elem[ expando ]; } catch(e){ // IE has trouble directly removing the expando // but it's ok with using removeAttribute if ( elem.removeAttribute ) elem.removeAttribute( expando ); } // Completely remove the data cache delete jQuery.cache[ id ]; } }, queue: function( elem, type, data ) { if ( elem ){ type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); if ( !q || jQuery.isArray(data) ) q = jQuery.data( elem, type, jQuery.makeArray(data) ); else if( data ) q.push( data ); } return q; }, dequeue: function( elem, type ){ var queue = jQuery.queue( elem, type ), fn = queue.shift(); if( !type || type === "fx" ) fn = queue[0]; if( fn !== undefined ) fn.call(elem); } }); jQuery.fn.extend({ data: function( key, value ){ var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) data = jQuery.data( this[0], key ); return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){ jQuery.data( this, key, value ); }); }, removeData: function( key ){ return this.each(function(){ jQuery.removeData( this, key ); }); }, queue: function(type, data){ if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) return jQuery.queue( this[0], type ); return this.each(function(){ var queue = jQuery.queue( this, type, data ); if( type == "fx" && queue.length == 1 ) queue[0].call(this); }); }, dequeue: function(type){ return this.each(function(){ jQuery.dequeue( this, type ); }); } });/*! * Sizzle CSS Selector Engine - v0.9.1 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|[^[\]]+)+\]|\\.|[^ >+~,(\[]+)+|[>+~])(\s*,\s*)?/g, done = 0, toString = Object.prototype.toString; var Sizzle = function(selector, context, results, seed) { results = results || []; context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) return []; if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, check, mode, extra, prune = true; // Reset the position of the chunker regexp (start from head) chunker.lastIndex = 0; while ( (m = chunker.exec(selector)) !== null ) { parts.push( m[1] ); if ( m[2] ) { extra = RegExp.rightContext; break; } } if ( parts.length > 1 && Expr.match.POS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { var later = "", match; // Position selectors must be done after the filter while ( (match = Expr.match.POS.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.POS, "" ); } set = Sizzle.filter( later, Sizzle( selector, context ) ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { var tmpSet = []; selector = parts.shift(); if ( Expr.relative[ selector ] ) selector += parts.shift(); for ( var i = 0, l = set.length; i < l; i++ ) { Sizzle( selector, set[i], tmpSet ); } set = tmpSet; } } } else { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context ); set = Sizzle.filter( ret.expr, ret.set ); if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, isXML(context) ); } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { throw "Syntax error, unrecognized expression: " + (cur || selector); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, context, results, seed ); } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.match[ type ].exec( expr )) ) { var left = RegExp.leftContext; if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound; while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.match[ type ].exec( expr )) != null ) { var filter = Expr.filter[ type ], goodArray = null, goodPos = 0, found, item; anyFound = false; if ( curLoop == result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not ); if ( !match ) { anyFound = found = true; } else if ( match[0] === true ) { goodArray = []; var last = null, elem; for ( var i = 0; (elem = curLoop[i]) !== undefined; i++ ) { if ( elem && last !== elem ) { goodArray.push( elem ); last = elem; } } } } if ( match ) { for ( var i = 0; (item = curLoop[i]) !== undefined; i++ ) { if ( item ) { if ( goodArray && item != goodArray[goodPos] ) { goodPos++; } found = filter( item, match, goodPos, goodArray ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } expr = expr.replace(/\s*,\s*/, ""); // Improper expression if ( expr == old ) { if ( anyFound == null ) { throw "Syntax error, unrecognized expression: " + expr; } else { break; } } old = expr; } return curLoop; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/, ATTR: /\[((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ }, attrMap: { "class": "className", "for": "htmlFor" }, relative: { "+": function(checkSet, part){ for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var cur = elem.previousSibling; while ( cur && cur.nodeType !== 1 ) { cur = cur.previousSibling; } checkSet[i] = typeof part === "string" ? cur || false : cur === part; } } if ( typeof part === "string" ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part, isXML){ if ( typeof part === "string" && !/\W/.test(part) ) { part = isXML ? part : part.toUpperCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = typeof part === "string" ? elem.parentNode : elem.parentNode === part; } } if ( typeof part === "string" ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = "done" + (done++), checkFn = dirCheck; if ( !part.match(/\W/) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck); }, "~": function(checkSet, part, isXML){ var doneName = "done" + (done++), checkFn = dirCheck; if ( typeof part === "string" && !part.match(/\W/) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck); } }, find: { ID: function(match, context){ if ( context.getElementById ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context){ return context.getElementsByName ? context.getElementsByName(match[1]) : null; }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not){ match = " " + match[1].replace(/\\/g, "") + " "; for ( var i = 0; curLoop[i]; i++ ) { if ( not ^ (" " + curLoop[i].className + " ").indexOf(match) >= 0 ) { if ( !inplace ) result.push( curLoop[i] ); } else if ( inplace ) { curLoop[i] = false; } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ for ( var i = 0; !curLoop[i]; i++ ){} return isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); }, CHILD: function(match){ if ( match[1] == "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = "done" + (done++); return match; }, ATTR: function(match){ var name = match[1]; if ( Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( match[3].match(chunker).length > 1 ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 == i; }, eq: function(elem, i, match){ return match[3] - 0 == i; } }, filter: { CHILD: function(elem, match){ var type = match[1], parent = elem.parentNode; var doneName = match[0]; if ( parent && !parent[ doneName ] ) { var count = 1; for ( var node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType == 1 ) { node.nodeIndex = count++; } } parent[ doneName ] = count - 1; } if ( type == "first" ) { return elem.nodeIndex == 1; } else if ( type == "last" ) { return elem.nodeIndex == parent[ doneName ]; } else if ( type == "only" ) { return parent[ doneName ] == 1; } else if ( type == "nth" ) { var add = false, first = match[2], last = match[3]; if ( first == 1 && last == 0 ) { return true; } if ( first == 0 ) { if ( elem.nodeIndex == last ) { add = true; } } else if ( (elem.nodeIndex - last) % first == 0 && (elem.nodeIndex - last) / first >= 0 ) { add = true; } return add; } }, PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName === match; }, CLASS: function(elem, match){ return match.test( elem.className ); }, ATTR: function(elem, match){ var result = elem[ match[1] ] || elem.getAttribute( match[1] ), value = result + "", type = match[2], check = match[4]; return result == null ? false : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !match[4] ? result : type === "!=" ? value != check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; for ( var type in Expr.match ) { Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. try { Array.prototype.slice.call( document.documentElement.childNodes ); // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("form"), id = "script" + (new Date).getTime(); form.innerHTML = "<input name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( !!document.getElementById( id ) ) { Expr.find.ID = function(match, context){ if ( context.getElementById ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || m.getAttributeNode && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = elem.getAttributeNode && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); })(); // Check to see if the browser returns only elements // when doing getElementsByTagName("*") (function(){ // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } })(); if ( document.querySelectorAll ) (function(){ var oldSizzle = Sizzle; Sizzle = function(query, context, extra, seed){ context = context || document; if ( !seed && context.nodeType === 9 ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; Sizzle.find = oldSizzle.find; Sizzle.filter = oldSizzle.filter; Sizzle.selectors = oldSizzle.selectors; Sizzle.matches = oldSizzle.matches; })(); if ( document.documentElement.getElementsByClassName ) { Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context) { return context.getElementsByClassName(match[1]); }; } function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem && elem.nodeType ) { var done = elem[doneName]; if ( done ) { match = checkSet[ done ]; break; } if ( elem.nodeType === 1 ) elem[doneName] = i; if ( elem.nodeName === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem && elem.nodeType ) { if ( elem[doneName] ) { match = checkSet[ elem[doneName] ]; break; } if ( elem.nodeType === 1 ) { elem[doneName] = i; if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return a.compareDocumentPosition(b) & 16; } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ return elem.documentElement && !elem.body || elem.tagName && elem.ownerDocument && !elem.ownerDocument.body; }; // EXPOSE jQuery.find = Sizzle; jQuery.filter = Sizzle.filter; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; Sizzle.selectors.filters.hidden = function(elem){ return "hidden" === elem.type || jQuery.css(elem, "display") === "none" || jQuery.css(elem, "visibility") === "hidden"; }; Sizzle.selectors.filters.visible = function(elem){ return "hidden" !== elem.type && jQuery.css(elem, "display") !== "none" && jQuery.css(elem, "visibility") !== "hidden"; }; Sizzle.selectors.filters.animated = function(elem){ return jQuery.grep(jQuery.timers, function(fn){ return elem === fn.elem; }).length; }; jQuery.multiFilter = function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return Sizzle.matches(expr, elems); }; jQuery.dir = function( elem, dir ){ var matched = [], cur = elem[dir]; while ( cur && cur != document ) { if ( cur.nodeType == 1 ) matched.push( cur ); cur = cur[dir]; } return matched; }; jQuery.nth = function(cur, result, dir, elem){ result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) if ( cur.nodeType == 1 && ++num == result ) break; return cur; }; jQuery.sibling = function(n, elem){ var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType == 1 && n != elem ) r.push( n ); } return r; }; return; window.Sizzle = Sizzle; })(); /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function(elem, types, handler, data) { if ( elem.nodeType == 3 || elem.nodeType == 8 ) return; // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && elem != window ) elem = window; // Make sure that the function being executed has a unique ID if ( !handler.guid ) handler.guid = this.guid++; // if data is passed, bind to handler if ( data !== undefined ) { // Create temporary function pointer to original handler var fn = handler; // Create unique handler function, wrapped around original handler handler = this.proxy( fn ); // Store data in unique handler handler.data = data; } // Init the element's event structure var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}), handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){ // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply(arguments.callee.elem, arguments) : undefined; }); // Add elem as a property of the handle function // This is to prevent a memory leak with non-native // event in IE. handle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); jQuery.each(types.split(/\s+/), function(index, type) { // Namespaced event handlers var namespaces = type.split("."); type = namespaces.shift(); handler.type = namespaces.slice().sort().join("."); // Get the current list of functions bound to this event var handlers = events[type]; if ( jQuery.event.specialAll[type] ) jQuery.event.specialAll[type].setup.call(elem, data, namespaces); // Init the event handler queue if (!handlers) { handlers = events[type] = {}; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) { // Bind the global event handler to the element if (elem.addEventListener) elem.addEventListener(type, handle, false); else if (elem.attachEvent) elem.attachEvent("on" + type, handle); } } // Add the function to the element's handler list handlers[handler.guid] = handler; // Keep track of which events have been used, for global triggering jQuery.event.global[type] = true; }); // Nullify elem to prevent memory leaks in IE elem = null; }, guid: 1, global: {}, // Detach an event or set of events from an element remove: function(elem, types, handler) { // don't do events on text and comment nodes if ( elem.nodeType == 3 || elem.nodeType == 8 ) return; var events = jQuery.data(elem, "events"), ret, index; if ( events ) { // Unbind all events for the element if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") ) for ( var type in events ) this.remove( elem, type + (types || "") ); else { // types is actually an event object here if ( types.type ) { handler = types.handler; types = types.type; } // Handle multiple events seperated by a space // jQuery(...).unbind("mouseover mouseout", fn); jQuery.each(types.split(/\s+/), function(index, type){ // Namespaced event handlers var namespaces = type.split("."); type = namespaces.shift(); var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)"); if ( events[type] ) { // remove the given handler for the given type if ( handler ) delete events[type][handler.guid]; // remove all handlers for the given type else for ( var handle in events[type] ) // Handle the removal of namespaced events if ( namespace.test(events[type][handle].type) ) delete events[type][handle]; if ( jQuery.event.specialAll[type] ) jQuery.event.specialAll[type].teardown.call(elem, namespaces); // remove generic event handler if no more handlers exist for ( ret in events[type] ) break; if ( !ret ) { if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) { if (elem.removeEventListener) elem.removeEventListener(type, jQuery.data(elem, "handle"), false); else if (elem.detachEvent) elem.detachEvent("on" + type, jQuery.data(elem, "handle")); } ret = null; delete events[type]; } } }); } // Remove the expando if it's no longer used for ( ret in events ) break; if ( !ret ) { var handle = jQuery.data( elem, "handle" ); if ( handle ) handle.elem = null; jQuery.removeData( elem, "events" ); jQuery.removeData( elem, "handle" ); } } }, // bubbling is internal trigger: function( event, data, elem, bubbling ) { // Event object or event type var type = event.type || event; if( !bubbling ){ event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( this.global[type] ) jQuery.each( jQuery.cache, function(){ if ( this.events && this.events[type] ) jQuery.event.trigger( event, data, this.handle.elem ); }); } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 ) return undefined; // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray(data); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data(elem, "handle"); if ( handle ) handle.apply( elem, data ); // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links) if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false ) event.result = false; // Trigger the native events (except for clicks on links) if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) { this.triggered = true; try { elem[ type ](); // prevent IE from throwing an error for some hidden elements } catch (e) {} } this.triggered = false; if ( !event.isPropagationStopped() ) { var parent = elem.parentNode || elem.ownerDocument; if ( parent ) jQuery.event.trigger(event, data, parent, true); } }, handle: function(event) { // returned undefined or false var all, handlers; event = arguments[0] = jQuery.event.fix( event || window.event ); // Namespaced event handlers var namespaces = event.type.split("."); event.type = namespaces.shift(); // Cache this now, all = true means, any handler all = !namespaces.length && !event.exclusive; var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)"); handlers = ( jQuery.data(this, "events") || {} )[event.type]; for ( var j in handlers ) { var handler = handlers[j]; // Filter the functions by class if ( all || namespace.test(handler.type) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handler; event.data = handler.data; var ret = handler.apply(this, arguments); if( ret !== undefined ){ event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if( event.isImmediatePropagationStopped() ) break; } } }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function(event) { if ( event[expando] ) return event; // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ){ prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either // check if target is a textnode (safari) if ( event.target.nodeType == 3 ) event.target = event.target.parentNode; // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) event.which = event.charCode || event.keyCode; // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) event.metaKey = event.ctrlKey; // Add which for click: 1 == left; 2 == middle; 3 == right // Note: button is not normalized, so don't use it if ( !event.which && event.button ) event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); return event; }, proxy: function( fn, proxy ){ proxy = proxy || function(){ return fn.apply(this, arguments); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++; // So proxy can be declared as an argument return proxy; }, special: { ready: { // Make sure the ready event is setup setup: bindReady, teardown: function() {} } }, specialAll: { live: { setup: function( selector, namespaces ){ jQuery.event.add( this, namespaces[0], liveHandler ); }, teardown: function( namespaces ){ if ( namespaces.length ) { var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)"); jQuery.each( (jQuery.data(this, "events").live || {}), function(){ if ( name.test(this.type) ) remove++; }); if ( remove < 1 ) jQuery.event.remove( this, namespaces[0], liveHandler ); } } } } }; jQuery.Event = function( src ){ // Allow instantiation without the 'new' keyword if( !this.preventDefault ) return new jQuery.Event(src); // Event object if( src && src.type ){ this.originalEvent = src; this.type = src.type; this.timeStamp = src.timeStamp; // Event type }else this.type = src; if( !this.timeStamp ) this.timeStamp = now(); // Mark it as fixed this[expando] = true; }; function returnFalse(){ return false; } function returnTrue(){ return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if( !e ) return; // if preventDefault exists run it on the original event if (e.preventDefault) e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if( !e ) return; // if stopPropagation exists run it on the original event if (e.stopPropagation) e.stopPropagation(); // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation:function(){ this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function(event) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Traverse up the tree while ( parent && parent != this ) try { parent = parent.parentNode; } catch(e) { parent = this; } if( parent != this ){ // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } }; jQuery.each({ mouseover: 'mouseenter', mouseout: 'mouseleave' }, function( orig, fix ){ jQuery.event.special[ fix ] = { setup: function(){ jQuery.event.add( this, orig, withinElement, fix ); }, teardown: function(){ jQuery.event.remove( this, orig, withinElement ); } }; }); jQuery.fn.extend({ bind: function( type, data, fn ) { return type == "unload" ? this.one(type, data, fn) : this.each(function(){ jQuery.event.add( this, type, fn || data, fn && data ); }); }, one: function( type, data, fn ) { var one = jQuery.event.proxy( fn || data, function(event) { jQuery(this).unbind(event, one); return (fn || data).apply( this, arguments ); }); return this.each(function(){ jQuery.event.add( this, type, one, fn && data); }); }, unbind: function( type, fn ) { return this.each(function(){ jQuery.event.remove( this, type, fn ); }); }, trigger: function( type, data ) { return this.each(function(){ jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if( this[0] ){ var event = jQuery.Event(type); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while( i < args.length ) jQuery.event.proxy( fn, args[i++] ); return this.click( jQuery.event.proxy( fn, function(event) { // Figure out which function to execute this.lastToggle = ( this.lastToggle || 0 ) % i; // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ this.lastToggle++ ].apply( this, arguments ) || false; })); }, hover: function(fnOver, fnOut) { return this.mouseenter(fnOver).mouseleave(fnOut); }, ready: function(fn) { // Attach the listeners bindReady(); // If the DOM is already ready if ( jQuery.isReady ) // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later else // Add the function to the wait list jQuery.readyList.push( fn ); return this; }, live: function( type, fn ){ var proxy = jQuery.event.proxy( fn ); proxy.guid += this.selector + type; jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy ); return this; }, die: function( type, fn ){ jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null ); return this; } }); function liveHandler( event ){ var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"), stop = true, elems = []; jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){ if ( check.test(fn.type) ) { var elem = jQuery(event.target).closest(fn.data)[0]; if ( elem ) elems.push({ elem: elem, fn: fn }); } }); jQuery.each(elems, function(){ if ( !event.isImmediatePropagationStopped() && this.fn.call(this.elem, event, this.fn.data) === false ) stop = false; }); return stop; } function liveConvert(type, selector){ return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join("."); } jQuery.extend({ isReady: false, readyList: [], // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( jQuery.readyList ) { // Execute all of them jQuery.each( jQuery.readyList, function(){ this.call( document, jQuery ); }); // Reset the list of functions jQuery.readyList = null; } // Trigger any bound ready events jQuery(document).triggerHandler("ready"); } } }); var readyBound = false; function bindReady(){ if ( readyBound ) return; readyBound = true; // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", function(){ document.removeEventListener( "DOMContentLoaded", arguments.callee, false ); jQuery.ready(); }, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", function(){ if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", arguments.callee ); jQuery.ready(); } }); // If IE and not an iframe // continually check to see if the document is ready if ( document.documentElement.doScroll && !window.frameElement ) (function(){ if ( jQuery.isReady ) return; try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( arguments.callee, 0 ); return; } // and execute any waiting functions jQuery.ready(); })(); } // A fallback to window.onload, that will always work jQuery.event.add( window, "load", jQuery.ready ); } jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," + "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," + "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){ // Handle event binding jQuery.fn[name] = function(fn){ return fn ? this.bind(name, fn) : this.trigger(name); }; }); // Prevent memory leaks in IE // And prevent errors on refresh with events like mouseover in other browsers // Window isn't included so as not to unbind existing unload events jQuery( window ).bind( 'unload', function(){ for ( var id in jQuery.cache ) // Skip the window if ( id != 1 && jQuery.cache[ id ].handle ) jQuery.event.remove( jQuery.cache[ id ].handle.elem ); }); (function(){ jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + (new Date).getTime(); div.style.display = "none"; div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param></object>'; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType == 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that you can get all elements in an <object> element // IE 7 always returns no results objectAll: !!div.getElementsByTagName("object")[0] .getElementsByTagName("*").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) opacity: a.style.opacity === "0.5", // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Will be defined later scriptEval: false, noCloneEvent: true, boxModel: null }; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e){} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function(){ // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", arguments.callee); }); div.cloneNode(true).fireEvent("onclick"); } // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function(){ var div = document.createElement("div"); div.style.width = "1px"; div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; document.body.removeChild( div ); }); })(); var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat"; jQuery.props = { "for": "htmlFor", "class": "className", "float": styleFloat, cssFloat: styleFloat, styleFloat: styleFloat, readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", tabindex: "tabIndex" }; jQuery.fn.extend({ // Keep a copy of the old load _load: jQuery.fn.load, load: function( url, params, callback ) { if ( typeof url !== "string" ) return this._load( url ); var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if( typeof params === "object" ) { params = jQuery.param( params ); type = "POST"; } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function(res, status){ // If successful, inject the HTML into all the matched elements if ( status == "success" || status == "notmodified" ) // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div/>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); if( callback ) self.each( callback, [res.responseText, status, res] ); } }); return this; }, serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function(){ return this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type)); }) .map(function(i, elem){ var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function(val, i){ return {name: elem.name, value: val}; }) : {name: elem.name, value: val}; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){ jQuery.fn[o] = function(f){ return this.bind(o, f); }; }); var jsc = now(); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was ommited if ( jQuery.isFunction( data ) ) { callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { if ( jQuery.isFunction( data ) ) { callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr:function(){ return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, ajax: function( s ) { // Extend the settings, but re-extend 's' so that it can be // checked again later (in the test suite, specifically) s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s)); var jsonp, jsre = /=\?(&|$)/g, status, data, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) s.data = jQuery.param(s.data); // Handle JSONP Parameter Callbacks if ( s.dataType == "jsonp" ) { if ( type == "GET" ) { if ( !s.url.match(jsre) ) s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } else if ( !s.data || !s.data.match(jsre) ) s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) { jsonp = "jsonp" + jsc++; // Replace the =? sequence both in the query string and the data if ( s.data ) s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = function(tmp){ data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try{ delete window[ jsonp ]; } catch(e){} if ( head ) head.removeChild( script ); }; } if ( s.dataType == "script" && s.cache == null ) s.cache = false; if ( s.cache === false && type == "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type == "GET" ) { s.url += (s.url.match(/\?/) ? "&" : "?") + s.data; // IE likes to send both get and post data, prevent this s.data = null; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) jQuery.event.trigger( "ajaxStart" ); // Matches an absolute URL, and saves the domain var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url ); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType == "script" && type == "GET" && parts && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){ var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.src = s.url; if (s.scriptCharset) script.charset = s.scriptCharset; // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { done = true; success(); complete(); head.removeChild( script ); } }; } head.appendChild(script); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if( s.username ) xhr.open(type, s.url, s.async, s.username, s.password); else xhr.open(type, s.url, s.async); // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data ) xhr.setRequestHeader("Content-Type", s.contentType); // Set the If-Modified-Since header, if ifModified mode. if ( s.ifModified ) xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" ); // Set header so the called script knows that it's an XMLHttpRequest xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e){} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend(xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // close opended socket xhr.abort(); return false; } if ( s.global ) jQuery.event.trigger("ajaxSend", [xhr, s]); // Wait for a response to come back var onreadystatechange = function(isTimeout){ // The request was aborted, clear the interval and decrement jQuery.active if (xhr.readyState == 0) { if (ival) { // clear poll interval clearInterval(ival); ival = null; // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) { requestDone = true; // clear poll interval if (ival) { clearInterval(ival); ival = null; } status = isTimeout == "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; if ( status == "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(e) { status = "parsererror"; } } // Make sure that the request was successful or notmodified if ( status == "success" ) { // Cache Last-Modified header, if ifModified mode. var modRes; try { modRes = xhr.getResponseHeader("Last-Modified"); } catch(e) {} // swallow exception thrown by FF if header is not available if ( s.ifModified && modRes ) jQuery.lastModified[s.url] = modRes; // JSONP handles its own success callback if ( !jsonp ) success(); } else jQuery.handleError(s, xhr, status); // Fire the complete handlers complete(); // Stop memory leaks if ( s.async ) xhr = null; } }; if ( s.async ) { // don't attach the handler to the request, just poll it instead var ival = setInterval(onreadystatechange, 13); // Timeout checker if ( s.timeout > 0 ) setTimeout(function(){ // Check to see if the request is still happening if ( xhr ) { if( !requestDone ) onreadystatechange( "timeout" ); // Cancel the request if ( xhr ) xhr.abort(); } }, s.timeout); } // Send the data try { xhr.send(s.data); } catch(e) { jQuery.handleError(s, xhr, null, e); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) onreadystatechange(); function success(){ // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if ( s.global ) jQuery.event.trigger( "ajaxSuccess", [xhr, s] ); } function complete(){ // Process result if ( s.complete ) s.complete(xhr, status); // The request was completed if ( s.global ) jQuery.event.trigger( "ajaxComplete", [xhr, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) s.error( xhr, status, e ); // Fire the global callback if ( s.global ) jQuery.event.trigger( "ajaxError", [xhr, s, e] ); }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol == "file:" || ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223; } catch(e){} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { try { var xhrRes = xhr.getResponseHeader("Last-Modified"); // Firefox always returns 200. check Last-Modified date return xhr.status == 304 || xhrRes == jQuery.lastModified[url]; } catch(e){} return false; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type"), xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.tagName == "parsererror" ) throw "parsererror"; // Allow a pre-filtering function to sanitize the response // s != null is checked to keep backwards compatibility if( s && s.dataFilter ) data = s.dataFilter( data, type ); // The filter can actually parse the response if( typeof data === "string" ){ // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) data = window["eval"]("(" + data + ")"); } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a ) { var s = [ ]; function add( key, value ){ s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value); }; // If an array was passed in, assume that it is an array // of form elements if ( jQuery.isArray(a) || a.jquery ) // Serialize the form elements jQuery.each( a, function(){ add( this.name, this.value ); }); // Otherwise, assume that it's an object of key/value pairs else // Serialize the key/values for ( var j in a ) // If the value is an array then the key names need to be repeated if ( jQuery.isArray(a[j]) ) jQuery.each( a[j], function(){ add( j, this ); }); else add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] ); // Return the resulting serialization return s.join("&").replace(/%20/g, "+"); } }); var elemdisplay = {}, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; function genFx( type, num ){ var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){ obj[ this ] = type; }); return obj; } jQuery.fn.extend({ show: function(speed,callback){ if ( speed ) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ){ var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var tagName = this[i].tagName, display; if ( elemdisplay[ tagName ] ) { display = elemdisplay[ tagName ]; } else { var elem = jQuery("<" + tagName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) display = "block"; elem.remove(); elemdisplay[ tagName ] = display; } this[i].style.display = jQuery.data(this[i], "olddisplay", display); } } return this; } }, hide: function(speed,callback){ if ( speed ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ){ var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); this[i].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ){ var bool = typeof fn === "boolean"; return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ? this._toggle.apply( this, arguments ) : fn == null || bool ? this.each(function(){ var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }) : this.animate(genFx("toggle", 3), fn, fn2); }, fadeTo: function(speed,to,callback){ return this.animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); return this[ optall.queue === false ? "each" : "queue" ](function(){ var opt = jQuery.extend({}, optall), p, hidden = this.nodeType == 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden ) return opt.complete.call(this); if ( ( p == "height" || p == "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } } if ( opt.overflow != null ) this.style.overflow = "hidden"; opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function(name, val){ var e = new jQuery.fx( self, opt, name ); if ( /toggle|show|hide/.test(val) ) e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop ); else { var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat(parts[2]), unit = parts[3] || "px"; // We need to compute starting value if ( unit != "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) end = ((parts[1] == "-=" ? -1 : 1) * end) + start; e.custom( start, end, unit ); } else e.custom( start, val, "" ); } }); // For JS strict compliance return true; }); }, stop: function(clearQueue, gotoEnd){ var timers = jQuery.timers; if (clearQueue) this.queue([]); this.each(function(){ // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) if ( timers[i].elem == this ) { if (gotoEnd) // force the next step to be the last timers[i](true); timers.splice(i, 1); } }); // start the next in the queue if the last step wasn't forced if (!gotoEnd) this.dequeue(); return this; } }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" } }, function( name, props ){ jQuery.fn[ name ] = function( speed, callback ){ return this.animate( props, speed, callback ); }; }); jQuery.extend({ speed: function(speed, easing, fn) { var opt = typeof speed === "object" ? speed : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function(){ if ( opt.queue !== false ) jQuery(this).dequeue(); if ( jQuery.isFunction( opt.old ) ) opt.old.call( this ); }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], timerId: null, fx: function( elem, options, prop ){ this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) options.orig = {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function(){ if ( this.options.step ) this.options.step.call( this.elem, this.now, this ); (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style ) this.elem.style.display = "block"; }, // Get the current size cur: function(force){ if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) return this.elem[ this.prop ]; var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function(from, to, unit){ this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t(gotoEnd){ return self.step(gotoEnd); } t.elem = this.elem; jQuery.timers.push(t); if ( t() && jQuery.timerId == null ) { jQuery.timerId = setInterval(function(){ var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) if ( !timers[i]() ) timers.splice(i--, 1); if ( !timers.length ) { clearInterval( jQuery.timerId ); jQuery.timerId = null; } }, 13); } }, // Simple 'show' function show: function(){ // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery(this.elem).show(); }, // Simple 'hide' function hide: function(){ // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function(gotoEnd){ var t = now(); if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; var done = true; for ( var i in this.options.curAnim ) if ( this.options.curAnim[i] !== true ) done = false; if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display this.elem.style.display = this.options.display; if ( jQuery.css(this.elem, "display") == "none" ) this.elem.style.display = "block"; } // Hide the element if the "hide" operation was done if ( this.options.hide ) jQuery(this.elem).hide(); // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) for ( var p in this.options.curAnim ) jQuery.attr(this.elem.style, p, this.options.orig[p]); } if ( done ) // Execute the complete function this.options.complete.call( this.elem ); return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { speeds:{ slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function(fx){ jQuery.attr(fx.elem.style, "opacity", fx.now); }, _default: function(fx){ if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) fx.elem.style[ fx.prop ] = fx.now + fx.unit; else fx.elem[ fx.prop ] = fx.now; } } }); if ( document.documentElement["getBoundingClientRect"] ) jQuery.fn.offset = function() { if ( !this[0] ) return { top: 0, left: 0 }; if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] ); var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; else jQuery.fn.offset = function() { if ( !this[0] ) return { top: 0, left: 0 }; if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] ); jQuery.offset.initialized || jQuery.offset.initialize(); var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView.getComputedStyle(elem, null), top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { computedStyle = defaultView.getComputedStyle(elem, null); top -= elem.scrollTop, left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop, left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) ) top += parseInt( computedStyle.borderTopWidth, 10) || 0, left += parseInt( computedStyle.borderLeftWidth, 10) || 0; prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) top += parseInt( computedStyle.borderTopWidth, 10) || 0, left += parseInt( computedStyle.borderLeftWidth, 10) || 0; prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) top += body.offsetTop, left += body.offsetLeft; if ( prevComputedStyle.position === "fixed" ) top += Math.max(docElem.scrollTop, body.scrollTop), left += Math.max(docElem.scrollLeft, body.scrollLeft); return { top: top, left: left }; }; jQuery.offset = { initialize: function() { if ( this.initialized ) return; var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop, html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"cellpadding="0"cellspacing="0"><tr><td></td></tr></table>'; rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' }; for ( prop in rules ) container.style[prop] = rules[prop]; container.innerHTML = html; body.insertBefore(container, body.firstChild); innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative'; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); body.style.marginTop = '1px'; this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0); body.style.marginTop = bodyMarginTop; body.removeChild(container); this.initialized = true; }, bodyOffset: function(body) { jQuery.offset.initialized || jQuery.offset.initialize(); var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0, left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0; return { top: top, left: left }; } }; jQuery.fn.extend({ position: function() { var left = 0, top = 0, results; if ( this[0] ) { // Get *real* offsetParent var offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= num( this, 'marginTop' ); offset.left -= num( this, 'marginLeft' ); // Add offsetParent borders parentOffset.top += num( offsetParent, 'borderTopWidth' ); parentOffset.left += num( offsetParent, 'borderLeftWidth' ); // Subtract the two offsets results = { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; } return results; }, offsetParent: function() { var offsetParent = this[0].offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') ) offsetParent = offsetParent.offsetParent; return jQuery(offsetParent); } }); // Create scrollLeft and scrollTop methods jQuery.each( ['Left', 'Top'], function(i, name) { var method = 'scroll' + name; jQuery.fn[ method ] = function(val) { if (!this[0]) return null; return val !== undefined ? // Set the scroll offset this.each(function() { this == window || this == document ? window.scrollTo( !i ? val : jQuery(window).scrollLeft(), i ? val : jQuery(window).scrollTop() ) : this[ method ] = val; }) : // Return the scroll offset this[0] == window || this[0] == document ? self[ i ? 'pageYOffset' : 'pageXOffset' ] || jQuery.boxModel && document.documentElement[ method ] || document.body[ method ] : this[0][ method ]; }; }); // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function(i, name){ var tl = i ? "Left" : "Top", // top or left br = i ? "Right" : "Bottom"; // bottom or right // innerHeight and innerWidth jQuery.fn["inner" + name] = function(){ return this[ name.toLowerCase() ]() + num(this, "padding" + tl) + num(this, "padding" + br); }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function(margin) { return this["inner" + name]() + num(this, "border" + tl + "Width") + num(this, "border" + br + "Width") + (margin ? num(this, "margin" + tl) + num(this, "margin" + br) : 0); }; var type = name.toLowerCase(); jQuery.fn[ type ] = function( size ) { // Get window width or height return this[0] == window ? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] : // Get document width or height this[0] == document ? // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( document.documentElement["client" + name], document.body["scroll" + name], document.documentElement["scroll" + name], document.body["offset" + name], document.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element (this.length ? jQuery.css( this[0], type ) : null) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; });})();
export default { name: 'main-app', template: `<RouterView />` }
/** * EasyUI for jQuery 1.9.7 * * Copyright (c) 2009-2020 www.jeasyui.com. All rights reserved. * * Licensed under the freeware license: http://www.jeasyui.com/license_freeware.php * To use it on other terms please contact us: [email protected] * */ (function($){ function _1(_2){ var _3=$.data(_2,"treegrid"); var _4=_3.options; $(_2).datagrid($.extend({},_4,{url:null,data:null,loader:function(){ return false; },onBeforeLoad:function(){ return false; },onLoadSuccess:function(){ },onResizeColumn:function(_5,_6){ _16(_2); _4.onResizeColumn.call(_2,_5,_6); },onBeforeSortColumn:function(_7,_8){ if(_4.onBeforeSortColumn.call(_2,_7,_8)==false){ return false; } },onSortColumn:function(_9,_a){ _4.sortName=_9; _4.sortOrder=_a; if(_4.remoteSort){ _15(_2); }else{ var _b=$(_2).treegrid("getData"); _56(_2,null,_b); } _4.onSortColumn.call(_2,_9,_a); },onClickCell:function(_c,_d){ _4.onClickCell.call(_2,_d,_37(_2,_c)); },onDblClickCell:function(_e,_f){ _4.onDblClickCell.call(_2,_f,_37(_2,_e)); },onRowContextMenu:function(e,_10){ _4.onContextMenu.call(_2,e,_37(_2,_10)); }})); var _11=$.data(_2,"datagrid").options; _4.columns=_11.columns; _4.frozenColumns=_11.frozenColumns; _3.dc=$.data(_2,"datagrid").dc; if(_4.pagination){ var _12=$(_2).datagrid("getPager"); _12.pagination({total:0,pageNumber:_4.pageNumber,pageSize:_4.pageSize,pageList:_4.pageList,onSelectPage:function(_13,_14){ _4.pageNumber=_13||1; _4.pageSize=_14; _12.pagination("refresh",{pageNumber:_13,pageSize:_14}); _15(_2); }}); _4.pageSize=_12.pagination("options").pageSize; } }; function _16(_17,_18){ var _19=$.data(_17,"datagrid").options; var dc=$.data(_17,"datagrid").dc; if(!dc.body1.is(":empty")&&(!_19.nowrap||_19.autoRowHeight)){ if(_18!=undefined){ var _1a=_1b(_17,_18); for(var i=0;i<_1a.length;i++){ _1c(_1a[i][_19.idField]); } } } $(_17).datagrid("fixRowHeight",_18); function _1c(_1d){ var tr1=_19.finder.getTr(_17,_1d,"body",1); var tr2=_19.finder.getTr(_17,_1d,"body",2); tr1.css("height",""); tr2.css("height",""); var _1e=Math.max(tr1.height(),tr2.height()); tr1.css("height",_1e); tr2.css("height",_1e); }; }; function _1f(_20){ var dc=$.data(_20,"datagrid").dc; var _21=$.data(_20,"treegrid").options; if(!_21.rownumbers){ return; } dc.body1.find("div.datagrid-cell-rownumber").each(function(i){ $(this).html(i+1); }); }; function _22(_23){ return function(e){ $.fn.datagrid.defaults.rowEvents[_23?"mouseover":"mouseout"](e); var tt=$(e.target); var fn=_23?"addClass":"removeClass"; if(tt.hasClass("tree-hit")){ tt.hasClass("tree-expanded")?tt[fn]("tree-expanded-hover"):tt[fn]("tree-collapsed-hover"); } }; }; function _24(e){ var tt=$(e.target); var tr=tt.closest("tr.datagrid-row"); if(!tr.length||!tr.parent().length){ return; } var _25=tr.attr("node-id"); var _26=_27(tr); if(tt.hasClass("tree-hit")){ _28(_26,_25); }else{ if(tt.hasClass("tree-checkbox")){ _29(_26,_25); }else{ var _2a=$(_26).datagrid("options"); if(!tt.parent().hasClass("datagrid-cell-check")&&!_2a.singleSelect&&e.shiftKey){ var _2b=$(_26).treegrid("getChildren"); var _2c=$.easyui.indexOfArray(_2b,_2a.idField,_2a.lastSelectedIndex); var _2d=$.easyui.indexOfArray(_2b,_2a.idField,_25); var _2e=Math.min(Math.max(_2c,0),_2d); var to=Math.max(_2c,_2d); var row=_2b[_2d]; var td=tt.closest("td[field]",tr); if(td.length){ var _2f=td.attr("field"); _2a.onClickCell.call(_26,_25,_2f,row[_2f]); } $(_26).treegrid("clearSelections"); for(var i=_2e;i<=to;i++){ $(_26).treegrid("selectRow",_2b[i][_2a.idField]); } _2a.onClickRow.call(_26,row); }else{ $.fn.datagrid.defaults.rowEvents.click(e); } } } }; function _27(t){ return $(t).closest("div.datagrid-view").children(".datagrid-f")[0]; }; function _29(_30,_31,_32,_33){ var _34=$.data(_30,"treegrid"); var _35=_34.checkedRows; var _36=_34.options; if(!_36.checkbox){ return; } var row=_37(_30,_31); if(!row.checkState){ return; } var tr=_36.finder.getTr(_30,_31); var ck=tr.find(".tree-checkbox"); if(_32==undefined){ if(ck.hasClass("tree-checkbox1")){ _32=false; }else{ if(ck.hasClass("tree-checkbox0")){ _32=true; }else{ if(row._checked==undefined){ row._checked=ck.hasClass("tree-checkbox1"); } _32=!row._checked; } } } row._checked=_32; if(_32){ if(ck.hasClass("tree-checkbox1")){ return; } }else{ if(ck.hasClass("tree-checkbox0")){ return; } } if(!_33){ if(_36.onBeforeCheckNode.call(_30,row,_32)==false){ return; } } if(_36.cascadeCheck){ _38(_30,row,_32); _39(_30,row); }else{ _3a(_30,row,_32?"1":"0"); } if(!_33){ _36.onCheckNode.call(_30,row,_32); } }; function _3a(_3b,row,_3c){ var _3d=$.data(_3b,"treegrid"); var _3e=_3d.checkedRows; var _3f=_3d.options; if(!row.checkState||_3c==undefined){ return; } var tr=_3f.finder.getTr(_3b,row[_3f.idField]); var ck=tr.find(".tree-checkbox"); if(!ck.length){ return; } row.checkState=["unchecked","checked","indeterminate"][_3c]; row.checked=(row.checkState=="checked"); ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); ck.addClass("tree-checkbox"+_3c); if(_3c==0){ $.easyui.removeArrayItem(_3e,_3f.idField,row[_3f.idField]); }else{ $.easyui.addArrayItem(_3e,_3f.idField,row); } }; function _38(_40,row,_41){ var _42=_41?1:0; _3a(_40,row,_42); $.easyui.forEach(row.children||[],true,function(r){ _3a(_40,r,_42); }); }; function _39(_43,row){ var _44=$.data(_43,"treegrid").options; var _45=_46(_43,row[_44.idField]); if(_45){ _3a(_43,_45,_47(_45)); _39(_43,_45); } }; function _47(row){ var len=0; var c0=0; var c1=0; $.easyui.forEach(row.children||[],false,function(r){ if(r.checkState){ len++; if(r.checkState=="checked"){ c1++; }else{ if(r.checkState=="unchecked"){ c0++; } } } }); if(len==0){ return undefined; } var _48=0; if(c0==len){ _48=0; }else{ if(c1==len){ _48=1; }else{ _48=2; } } return _48; }; function _49(_4a,_4b){ var _4c=$.data(_4a,"treegrid").options; if(!_4c.checkbox){ return; } var row=_37(_4a,_4b); var tr=_4c.finder.getTr(_4a,_4b); var ck=tr.find(".tree-checkbox"); if(_4c.view.hasCheckbox(_4a,row)){ if(!ck.length){ row.checkState=row.checkState||"unchecked"; $("<span class=\"tree-checkbox\"></span>").insertBefore(tr.find(".tree-title")); } if(row.checkState=="checked"){ _29(_4a,_4b,true,true); }else{ if(row.checkState=="unchecked"){ _29(_4a,_4b,false,true); }else{ var _4d=_47(row); if(_4d===0){ _29(_4a,_4b,false,true); }else{ if(_4d===1){ _29(_4a,_4b,true,true); } } } } }else{ ck.remove(); row.checkState=undefined; row.checked=undefined; _39(_4a,row); } }; function _4e(_4f,_50){ var _51=$.data(_4f,"treegrid").options; var tr1=_51.finder.getTr(_4f,_50,"body",1); var tr2=_51.finder.getTr(_4f,_50,"body",2); var _52=$(_4f).datagrid("getColumnFields",true).length+(_51.rownumbers?1:0); var _53=$(_4f).datagrid("getColumnFields",false).length; _54(tr1,_52); _54(tr2,_53); function _54(tr,_55){ $("<tr class=\"treegrid-tr-tree\">"+"<td style=\"border:0px\" colspan=\""+_55+"\">"+"<div></div>"+"</td>"+"</tr>").insertAfter(tr); }; }; function _56(_57,_58,_59,_5a,_5b){ var _5c=$.data(_57,"treegrid"); var _5d=_5c.options; var dc=_5c.dc; _59=_5d.loadFilter.call(_57,_59,_58); var _5e=_37(_57,_58); if(_5e){ var _5f=_5d.finder.getTr(_57,_58,"body",1); var _60=_5d.finder.getTr(_57,_58,"body",2); var cc1=_5f.next("tr.treegrid-tr-tree").children("td").children("div"); var cc2=_60.next("tr.treegrid-tr-tree").children("td").children("div"); if(!_5a){ _5e.children=[]; } }else{ var cc1=dc.body1; var cc2=dc.body2; if(!_5a){ _5c.data=[]; } } if(!_5a){ cc1.empty(); cc2.empty(); } if(_5d.view.onBeforeRender){ _5d.view.onBeforeRender.call(_5d.view,_57,_58,_59); } _5d.view.render.call(_5d.view,_57,cc1,true); _5d.view.render.call(_5d.view,_57,cc2,false); if(_5d.showFooter){ _5d.view.renderFooter.call(_5d.view,_57,dc.footer1,true); _5d.view.renderFooter.call(_5d.view,_57,dc.footer2,false); } if(_5d.view.onAfterRender){ _5d.view.onAfterRender.call(_5d.view,_57); } if(!_58&&_5d.pagination){ var _61=$.data(_57,"treegrid").total; var _62=$(_57).datagrid("getPager"); var _63=_62.pagination("options"); if(_63.total!=_59.total){ _62.pagination("refresh",{pageNumber:_5d.pageNumber,total:_59.total}); if(_5d.pageNumber!=_63.pageNumber&&_63.pageNumber>0){ _5d.pageNumber=_63.pageNumber; _15(_57); } } } _16(_57); _1f(_57); $(_57).treegrid("showLines"); $(_57).treegrid("setSelectionState"); $(_57).treegrid("autoSizeColumn"); if(!_5b){ _5d.onLoadSuccess.call(_57,_5e,_59); } }; function _15(_64,_65,_66,_67,_68){ var _69=$.data(_64,"treegrid").options; var _6a=$(_64).datagrid("getPanel").find("div.datagrid-body"); if(_65==undefined&&_69.queryParams){ _69.queryParams.id=undefined; } if(_66){ _69.queryParams=_66; } var _6b=$.extend({},_69.queryParams); if(_69.pagination){ $.extend(_6b,{page:_69.pageNumber,rows:_69.pageSize}); } if(_69.sortName){ $.extend(_6b,{sort:_69.sortName,order:_69.sortOrder}); } var row=_37(_64,_65); if(_69.onBeforeLoad.call(_64,row,_6b)==false){ return; } var _6c=_6a.find("tr[node-id=\""+_65+"\"] span.tree-folder"); _6c.addClass("tree-loading"); $(_64).treegrid("loading"); var _6d=_69.loader.call(_64,_6b,function(_6e){ _6c.removeClass("tree-loading"); $(_64).treegrid("loaded"); _56(_64,_65,_6e,_67); if(_68){ _68(); } },function(){ _6c.removeClass("tree-loading"); $(_64).treegrid("loaded"); _69.onLoadError.apply(_64,arguments); if(_68){ _68(); } }); if(_6d==false){ _6c.removeClass("tree-loading"); $(_64).treegrid("loaded"); } }; function _6f(_70){ var _71=_72(_70); return _71.length?_71[0]:null; }; function _72(_73){ return $.data(_73,"treegrid").data; }; function _46(_74,_75){ var row=_37(_74,_75); if(row._parentId){ return _37(_74,row._parentId); }else{ return null; } }; function _1b(_76,_77){ var _78=$.data(_76,"treegrid").data; if(_77){ var _79=_37(_76,_77); _78=_79?(_79.children||[]):[]; } var _7a=[]; $.easyui.forEach(_78,true,function(_7b){ _7a.push(_7b); }); return _7a; }; function _7c(_7d,_7e){ var _7f=$.data(_7d,"treegrid").options; var tr=_7f.finder.getTr(_7d,_7e); var _80=tr.children("td[field=\""+_7f.treeField+"\"]"); return _80.find("span.tree-indent,span.tree-hit").length; }; function _37(_81,_82){ var _83=$.data(_81,"treegrid"); var _84=_83.options; var _85=null; $.easyui.forEach(_83.data,true,function(_86){ if(_86[_84.idField]==_82){ _85=_86; return false; } }); return _85; }; function _87(_88,_89){ var _8a=$.data(_88,"treegrid").options; var row=_37(_88,_89); var tr=_8a.finder.getTr(_88,_89); var hit=tr.find("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-collapsed")){ return; } if(_8a.onBeforeCollapse.call(_88,row)==false){ return; } hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); hit.next().removeClass("tree-folder-open"); row.state="closed"; tr=tr.next("tr.treegrid-tr-tree"); var cc=tr.children("td").children("div"); if(_8a.animate){ cc.slideUp("normal",function(){ $(_88).treegrid("autoSizeColumn"); _16(_88,_89); _8a.onCollapse.call(_88,row); }); }else{ cc.hide(); $(_88).treegrid("autoSizeColumn"); _16(_88,_89); _8a.onCollapse.call(_88,row); } }; function _8b(_8c,_8d){ var _8e=$.data(_8c,"treegrid").options; var tr=_8e.finder.getTr(_8c,_8d); var hit=tr.find("span.tree-hit"); var row=_37(_8c,_8d); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ return; } if(_8e.onBeforeExpand.call(_8c,row)==false){ return; } hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded"); hit.next().addClass("tree-folder-open"); var _8f=tr.next("tr.treegrid-tr-tree"); if(_8f.length){ var cc=_8f.children("td").children("div"); _90(cc); }else{ _4e(_8c,row[_8e.idField]); var _8f=tr.next("tr.treegrid-tr-tree"); var cc=_8f.children("td").children("div"); cc.hide(); var _91=$.extend({},_8e.queryParams||{}); _91.id=row[_8e.idField]; _15(_8c,row[_8e.idField],_91,true,function(){ if(cc.is(":empty")){ _8f.remove(); }else{ _90(cc); } }); } function _90(cc){ row.state="open"; if(_8e.animate){ cc.slideDown("normal",function(){ $(_8c).treegrid("autoSizeColumn"); _16(_8c,_8d); _8e.onExpand.call(_8c,row); }); }else{ cc.show(); $(_8c).treegrid("autoSizeColumn"); _16(_8c,_8d); _8e.onExpand.call(_8c,row); } }; }; function _28(_92,_93){ var _94=$.data(_92,"treegrid").options; var tr=_94.finder.getTr(_92,_93); var hit=tr.find("span.tree-hit"); if(hit.hasClass("tree-expanded")){ _87(_92,_93); }else{ _8b(_92,_93); } }; function _95(_96,_97){ var _98=$.data(_96,"treegrid").options; var _99=_1b(_96,_97); if(_97){ _99.unshift(_37(_96,_97)); } for(var i=0;i<_99.length;i++){ _87(_96,_99[i][_98.idField]); } }; function _9a(_9b,_9c){ var _9d=$.data(_9b,"treegrid").options; var _9e=_1b(_9b,_9c); if(_9c){ _9e.unshift(_37(_9b,_9c)); } for(var i=0;i<_9e.length;i++){ _8b(_9b,_9e[i][_9d.idField]); } }; function _9f(_a0,_a1){ var _a2=$.data(_a0,"treegrid").options; var ids=[]; var p=_46(_a0,_a1); while(p){ var id=p[_a2.idField]; ids.unshift(id); p=_46(_a0,id); } for(var i=0;i<ids.length;i++){ _8b(_a0,ids[i]); } }; function _a3(_a4,_a5){ var _a6=$.data(_a4,"treegrid"); var _a7=_a6.options; if(_a5.parent){ var tr=_a7.finder.getTr(_a4,_a5.parent); if(tr.next("tr.treegrid-tr-tree").length==0){ _4e(_a4,_a5.parent); } var _a8=tr.children("td[field=\""+_a7.treeField+"\"]").children("div.datagrid-cell"); var _a9=_a8.children("span.tree-icon"); if(_a9.hasClass("tree-file")){ _a9.removeClass("tree-file").addClass("tree-folder tree-folder-open"); var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_a9); if(hit.prev().length){ hit.prev().remove(); } } } _56(_a4,_a5.parent,_a5.data,_a6.data.length>0,true); }; function _aa(_ab,_ac){ var ref=_ac.before||_ac.after; var _ad=$.data(_ab,"treegrid").options; var _ae=_46(_ab,ref); _a3(_ab,{parent:(_ae?_ae[_ad.idField]:null),data:[_ac.data]}); var _af=_ae?_ae.children:$(_ab).treegrid("getRoots"); for(var i=0;i<_af.length;i++){ if(_af[i][_ad.idField]==ref){ var _b0=_af[_af.length-1]; _af.splice(_ac.before?i:(i+1),0,_b0); _af.splice(_af.length-1,1); break; } } _b1(true); _b1(false); _1f(_ab); $(_ab).treegrid("showLines"); function _b1(_b2){ var _b3=_b2?1:2; var tr=_ad.finder.getTr(_ab,_ac.data[_ad.idField],"body",_b3); var _b4=tr.closest("table.datagrid-btable"); tr=tr.parent().children(); var _b5=_ad.finder.getTr(_ab,ref,"body",_b3); if(_ac.before){ tr.insertBefore(_b5); }else{ var sub=_b5.next("tr.treegrid-tr-tree"); tr.insertAfter(sub.length?sub:_b5); } _b4.remove(); }; }; function _b6(_b7,_b8){ var _b9=$.data(_b7,"treegrid"); var _ba=_b9.options; var _bb=_46(_b7,_b8); $(_b7).datagrid("deleteRow",_b8); $.easyui.removeArrayItem(_b9.checkedRows,_ba.idField,_b8); _1f(_b7); if(_bb){ _49(_b7,_bb[_ba.idField]); } _b9.total-=1; $(_b7).datagrid("getPager").pagination("refresh",{total:_b9.total}); $(_b7).treegrid("showLines"); }; function _bc(_bd){ var t=$(_bd); var _be=t.treegrid("options"); if(_be.lines){ t.treegrid("getPanel").addClass("tree-lines"); }else{ t.treegrid("getPanel").removeClass("tree-lines"); return; } t.treegrid("getPanel").find("span.tree-indent").removeClass("tree-line tree-join tree-joinbottom"); t.treegrid("getPanel").find("div.datagrid-cell").removeClass("tree-node-last tree-root-first tree-root-one"); var _bf=t.treegrid("getRoots"); if(_bf.length>1){ _c0(_bf[0]).addClass("tree-root-first"); }else{ if(_bf.length==1){ _c0(_bf[0]).addClass("tree-root-one"); } } _c1(_bf); _c2(_bf); function _c1(_c3){ $.map(_c3,function(_c4){ if(_c4.children&&_c4.children.length){ _c1(_c4.children); }else{ var _c5=_c0(_c4); _c5.find(".tree-icon").prev().addClass("tree-join"); } }); if(_c3.length){ var _c6=_c0(_c3[_c3.length-1]); _c6.addClass("tree-node-last"); _c6.find(".tree-join").removeClass("tree-join").addClass("tree-joinbottom"); } }; function _c2(_c7){ $.map(_c7,function(_c8){ if(_c8.children&&_c8.children.length){ _c2(_c8.children); } }); for(var i=0;i<_c7.length-1;i++){ var _c9=_c7[i]; var _ca=t.treegrid("getLevel",_c9[_be.idField]); var tr=_be.finder.getTr(_bd,_c9[_be.idField]); var cc=tr.next().find("tr.datagrid-row td[field=\""+_be.treeField+"\"] div.datagrid-cell"); cc.find("span:eq("+(_ca-1)+")").addClass("tree-line"); } }; function _c0(_cb){ var tr=_be.finder.getTr(_bd,_cb[_be.idField]); var _cc=tr.find("td[field=\""+_be.treeField+"\"] div.datagrid-cell"); return _cc; }; }; $.fn.treegrid=function(_cd,_ce){ if(typeof _cd=="string"){ var _cf=$.fn.treegrid.methods[_cd]; if(_cf){ return _cf(this,_ce); }else{ return this.datagrid(_cd,_ce); } } _cd=_cd||{}; return this.each(function(){ var _d0=$.data(this,"treegrid"); if(_d0){ $.extend(_d0.options,_cd); }else{ _d0=$.data(this,"treegrid",{options:$.extend({},$.fn.treegrid.defaults,$.fn.treegrid.parseOptions(this),_cd),data:[],checkedRows:[],tmpIds:[]}); } _1(this); if(_d0.options.data){ $(this).treegrid("loadData",_d0.options.data); } _15(this); }); }; $.fn.treegrid.methods={options:function(jq){ return $.data(jq[0],"treegrid").options; },resize:function(jq,_d1){ return jq.each(function(){ $(this).datagrid("resize",_d1); }); },fixRowHeight:function(jq,_d2){ return jq.each(function(){ _16(this,_d2); }); },loadData:function(jq,_d3){ return jq.each(function(){ _56(this,_d3.parent,_d3); }); },load:function(jq,_d4){ return jq.each(function(){ $(this).treegrid("options").pageNumber=1; $(this).treegrid("getPager").pagination({pageNumber:1}); $(this).treegrid("reload",_d4); }); },reload:function(jq,id){ return jq.each(function(){ var _d5=$(this).treegrid("options"); var _d6={}; if(typeof id=="object"){ _d6=id; }else{ _d6=$.extend({},_d5.queryParams); _d6.id=id; } if(_d6.id){ var _d7=$(this).treegrid("find",_d6.id); if(_d7.children){ _d7.children.splice(0,_d7.children.length); } _d5.queryParams=_d6; var tr=_d5.finder.getTr(this,_d6.id); tr.next("tr.treegrid-tr-tree").remove(); tr.find("span.tree-hit").removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); _8b(this,_d6.id); }else{ _15(this,null,_d6); } }); },reloadFooter:function(jq,_d8){ return jq.each(function(){ var _d9=$.data(this,"treegrid").options; var dc=$.data(this,"datagrid").dc; if(_d8){ $.data(this,"treegrid").footer=_d8; } if(_d9.showFooter){ _d9.view.renderFooter.call(_d9.view,this,dc.footer1,true); _d9.view.renderFooter.call(_d9.view,this,dc.footer2,false); if(_d9.view.onAfterRender){ _d9.view.onAfterRender.call(_d9.view,this); } $(this).treegrid("fixRowHeight"); } }); },getData:function(jq){ return $.data(jq[0],"treegrid").data; },getFooterRows:function(jq){ return $.data(jq[0],"treegrid").footer; },getRoot:function(jq){ return _6f(jq[0]); },getRoots:function(jq){ return _72(jq[0]); },getParent:function(jq,id){ return _46(jq[0],id); },getChildren:function(jq,id){ return _1b(jq[0],id); },getLevel:function(jq,id){ return _7c(jq[0],id); },find:function(jq,id){ return _37(jq[0],id); },isLeaf:function(jq,id){ var _da=$.data(jq[0],"treegrid").options; var tr=_da.finder.getTr(jq[0],id); var hit=tr.find("span.tree-hit"); return hit.length==0; },select:function(jq,id){ return jq.each(function(){ $(this).datagrid("selectRow",id); }); },unselect:function(jq,id){ return jq.each(function(){ $(this).datagrid("unselectRow",id); }); },collapse:function(jq,id){ return jq.each(function(){ _87(this,id); }); },expand:function(jq,id){ return jq.each(function(){ _8b(this,id); }); },toggle:function(jq,id){ return jq.each(function(){ _28(this,id); }); },collapseAll:function(jq,id){ return jq.each(function(){ _95(this,id); }); },expandAll:function(jq,id){ return jq.each(function(){ _9a(this,id); }); },expandTo:function(jq,id){ return jq.each(function(){ _9f(this,id); }); },append:function(jq,_db){ return jq.each(function(){ _a3(this,_db); }); },insert:function(jq,_dc){ return jq.each(function(){ _aa(this,_dc); }); },remove:function(jq,id){ return jq.each(function(){ _b6(this,id); }); },pop:function(jq,id){ var row=jq.treegrid("find",id); jq.treegrid("remove",id); return row; },refresh:function(jq,id){ return jq.each(function(){ var _dd=$.data(this,"treegrid").options; _dd.view.refreshRow.call(_dd.view,this,id); }); },update:function(jq,_de){ return jq.each(function(){ var _df=$.data(this,"treegrid").options; var row=_de.row; _df.view.updateRow.call(_df.view,this,_de.id,row); if(row.checked!=undefined){ row=_37(this,_de.id); $.extend(row,{checkState:row.checked?"checked":(row.checked===false?"unchecked":undefined)}); _49(this,_de.id); } }); },beginEdit:function(jq,id){ return jq.each(function(){ $(this).datagrid("beginEdit",id); $(this).treegrid("fixRowHeight",id); }); },endEdit:function(jq,id){ return jq.each(function(){ $(this).datagrid("endEdit",id); }); },cancelEdit:function(jq,id){ return jq.each(function(){ $(this).datagrid("cancelEdit",id); }); },showLines:function(jq){ return jq.each(function(){ _bc(this); }); },setSelectionState:function(jq){ return jq.each(function(){ $(this).datagrid("setSelectionState"); var _e0=$(this).data("treegrid"); for(var i=0;i<_e0.tmpIds.length;i++){ _29(this,_e0.tmpIds[i],true,true); } _e0.tmpIds=[]; }); },getCheckedNodes:function(jq,_e1){ _e1=_e1||"checked"; var _e2=[]; $.easyui.forEach(jq.data("treegrid").checkedRows,false,function(row){ if(row.checkState==_e1){ _e2.push(row); } }); return _e2; },checkNode:function(jq,id){ return jq.each(function(){ _29(this,id,true); }); },uncheckNode:function(jq,id){ return jq.each(function(){ _29(this,id,false); }); },clearChecked:function(jq){ return jq.each(function(){ var _e3=this; var _e4=$(_e3).treegrid("options"); $(_e3).datagrid("clearChecked"); $.map($(_e3).treegrid("getCheckedNodes"),function(row){ _29(_e3,row[_e4.idField],false,true); }); }); }}; $.fn.treegrid.parseOptions=function(_e5){ return $.extend({},$.fn.datagrid.parseOptions(_e5),$.parser.parseOptions(_e5,["treeField",{checkbox:"boolean",cascadeCheck:"boolean",onlyLeafCheck:"boolean"},{animate:"boolean"}])); }; var _e6=$.extend({},$.fn.datagrid.defaults.view,{render:function(_e7,_e8,_e9){ var _ea=$.data(_e7,"treegrid").options; var _eb=$(_e7).datagrid("getColumnFields",_e9); var _ec=$.data(_e7,"datagrid").rowIdPrefix; if(_e9){ if(!(_ea.rownumbers||(_ea.frozenColumns&&_ea.frozenColumns.length))){ return; } } var _ed=this; if(this.treeNodes&&this.treeNodes.length){ var _ee=_ef.call(this,_e9,this.treeLevel,this.treeNodes); $(_e8).append(_ee.join("")); } function _ef(_f0,_f1,_f2){ var _f3=$(_e7).treegrid("getParent",_f2[0][_ea.idField]); var _f4=(_f3?_f3.children.length:$(_e7).treegrid("getRoots").length)-_f2.length; var _f5=["<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<_f2.length;i++){ var row=_f2[i]; if(row.state!="open"&&row.state!="closed"){ row.state="open"; } var css=_ea.rowStyler?_ea.rowStyler.call(_e7,row):""; var cs=this.getStyleValue(css); var cls="class=\"datagrid-row "+(_f4++%2&&_ea.striped?"datagrid-row-alt ":" ")+cs.c+"\""; var _f6=cs.s?"style=\""+cs.s+"\"":""; var _f7=_ec+"-"+(_f0?1:2)+"-"+row[_ea.idField]; _f5.push("<tr id=\""+_f7+"\" node-id=\""+row[_ea.idField]+"\" "+cls+" "+_f6+">"); _f5=_f5.concat(_ed.renderRow.call(_ed,_e7,_eb,_f0,_f1,row)); _f5.push("</tr>"); if(row.children&&row.children.length){ var tt=_ef.call(this,_f0,_f1+1,row.children); var v=row.state=="closed"?"none":"block"; _f5.push("<tr class=\"treegrid-tr-tree\"><td style=\"border:0px\" colspan="+(_eb.length+(_ea.rownumbers?1:0))+"><div style=\"display:"+v+"\">"); _f5=_f5.concat(tt); _f5.push("</div></td></tr>"); } } _f5.push("</tbody></table>"); return _f5; }; },renderFooter:function(_f8,_f9,_fa){ var _fb=$.data(_f8,"treegrid").options; var _fc=$.data(_f8,"treegrid").footer||[]; var _fd=$(_f8).datagrid("getColumnFields",_fa); var _fe=["<table class=\"datagrid-ftable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<_fc.length;i++){ var row=_fc[i]; row[_fb.idField]=row[_fb.idField]||("foot-row-id"+i); _fe.push("<tr class=\"datagrid-row\" node-id=\""+row[_fb.idField]+"\">"); _fe.push(this.renderRow.call(this,_f8,_fd,_fa,0,row)); _fe.push("</tr>"); } _fe.push("</tbody></table>"); $(_f9).html(_fe.join("")); },renderRow:function(_ff,_100,_101,_102,row){ var _103=$.data(_ff,"treegrid"); var opts=_103.options; var cc=[]; if(_101&&opts.rownumbers){ cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">0</div></td>"); } for(var i=0;i<_100.length;i++){ var _104=_100[i]; var col=$(_ff).datagrid("getColumnOption",_104); if(col){ var css=col.styler?(col.styler(row[_104],row)||""):""; var cs=this.getStyleValue(css); var cls=cs.c?"class=\""+cs.c+"\"":""; var _105=col.hidden?"style=\"display:none;"+cs.s+"\"":(cs.s?"style=\""+cs.s+"\"":""); cc.push("<td field=\""+_104+"\" "+cls+" "+_105+">"); var _105=""; if(!col.checkbox){ if(col.align){ _105+="text-align:"+col.align+";"; } if(!opts.nowrap){ _105+="white-space:normal;height:auto;"; }else{ if(opts.autoRowHeight){ _105+="height:auto;"; } } } cc.push("<div style=\""+_105+"\" "); if(col.checkbox){ cc.push("class=\"datagrid-cell-check "); }else{ cc.push("class=\"datagrid-cell "+col.cellClass); } if(_104==opts.treeField){ cc.push(" tree-node"); } cc.push("\">"); if(col.checkbox){ if(row.checked){ cc.push("<input type=\"checkbox\" checked=\"checked\""); }else{ cc.push("<input type=\"checkbox\""); } cc.push(" name=\""+_104+"\" value=\""+(row[_104]!=undefined?row[_104]:"")+"\">"); }else{ var val=null; if(col.formatter){ val=col.formatter(row[_104],row); }else{ val=row[_104]; } if(_104==opts.treeField){ for(var j=0;j<_102;j++){ cc.push("<span class=\"tree-indent\"></span>"); } if(row.state=="closed"){ cc.push("<span class=\"tree-hit tree-collapsed\"></span>"); cc.push("<span class=\"tree-icon tree-folder "+(row.iconCls?row.iconCls:"")+"\"></span>"); }else{ if(row.children&&row.children.length){ cc.push("<span class=\"tree-hit tree-expanded\"></span>"); cc.push("<span class=\"tree-icon tree-folder tree-folder-open "+(row.iconCls?row.iconCls:"")+"\"></span>"); }else{ cc.push("<span class=\"tree-indent\"></span>"); cc.push("<span class=\"tree-icon tree-file "+(row.iconCls?row.iconCls:"")+"\"></span>"); } } if(this.hasCheckbox(_ff,row)){ var flag=0; var crow=$.easyui.getArrayItem(_103.checkedRows,opts.idField,row[opts.idField]); if(crow){ flag=crow.checkState=="checked"?1:2; row.checkState=crow.checkState; row.checked=crow.checked; $.easyui.addArrayItem(_103.checkedRows,opts.idField,row); }else{ var prow=$.easyui.getArrayItem(_103.checkedRows,opts.idField,row._parentId); if(prow&&prow.checkState=="checked"&&opts.cascadeCheck){ flag=1; row.checked=true; $.easyui.addArrayItem(_103.checkedRows,opts.idField,row); }else{ if(row.checked){ $.easyui.addArrayItem(_103.tmpIds,row[opts.idField]); } } row.checkState=flag?"checked":"unchecked"; } cc.push("<span class=\"tree-checkbox tree-checkbox"+flag+"\"></span>"); }else{ row.checkState=undefined; row.checked=undefined; } cc.push("<span class=\"tree-title\">"+val+"</span>"); }else{ cc.push(val); } } cc.push("</div>"); cc.push("</td>"); } } return cc.join(""); },hasCheckbox:function(_106,row){ var opts=$.data(_106,"treegrid").options; if(opts.checkbox){ if($.isFunction(opts.checkbox)){ if(opts.checkbox.call(_106,row)){ return true; }else{ return false; } }else{ if(opts.onlyLeafCheck){ if(row.state=="open"&&!(row.children&&row.children.length)){ return true; } }else{ return true; } } } return false; },refreshRow:function(_107,id){ this.updateRow.call(this,_107,id,{}); },updateRow:function(_108,id,row){ var opts=$.data(_108,"treegrid").options; var _109=$(_108).treegrid("find",id); $.extend(_109,row); var _10a=$(_108).treegrid("getLevel",id)-1; var _10b=opts.rowStyler?opts.rowStyler.call(_108,_109):""; var _10c=$.data(_108,"datagrid").rowIdPrefix; var _10d=_109[opts.idField]; function _10e(_10f){ var _110=$(_108).treegrid("getColumnFields",_10f); var tr=opts.finder.getTr(_108,id,"body",(_10f?1:2)); var _111=tr.find("div.datagrid-cell-rownumber").html(); var _112=tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked"); tr.html(this.renderRow(_108,_110,_10f,_10a,_109)); tr.attr("style",_10b||""); tr.find("div.datagrid-cell-rownumber").html(_111); if(_112){ tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true); } if(_10d!=id){ tr.attr("id",_10c+"-"+(_10f?1:2)+"-"+_10d); tr.attr("node-id",_10d); } }; _10e.call(this,true); _10e.call(this,false); $(_108).treegrid("fixRowHeight",id); },deleteRow:function(_113,id){ var opts=$.data(_113,"treegrid").options; var tr=opts.finder.getTr(_113,id); tr.next("tr.treegrid-tr-tree").remove(); tr.remove(); var _114=del(id); if(_114){ if(_114.children.length==0){ tr=opts.finder.getTr(_113,_114[opts.idField]); tr.next("tr.treegrid-tr-tree").remove(); var cell=tr.children("td[field=\""+opts.treeField+"\"]").children("div.datagrid-cell"); cell.find(".tree-icon").removeClass("tree-folder").addClass("tree-file"); cell.find(".tree-hit").remove(); $("<span class=\"tree-indent\"></span>").prependTo(cell); } } this.setEmptyMsg(_113); function del(id){ var cc; var _115=$(_113).treegrid("getParent",id); if(_115){ cc=_115.children; }else{ cc=$(_113).treegrid("getData"); } for(var i=0;i<cc.length;i++){ if(cc[i][opts.idField]==id){ cc.splice(i,1); break; } } return _115; }; },onBeforeRender:function(_116,_117,data){ if($.isArray(_117)){ data={total:_117.length,rows:_117}; _117=null; } if(!data){ return false; } var _118=$.data(_116,"treegrid"); var opts=_118.options; if(data.length==undefined){ if(data.footer){ _118.footer=data.footer; } if(data.total){ _118.total=data.total; } data=this.transfer(_116,_117,data.rows); }else{ function _119(_11a,_11b){ for(var i=0;i<_11a.length;i++){ var row=_11a[i]; row._parentId=_11b; if(row.children&&row.children.length){ _119(row.children,row[opts.idField]); } } }; _119(data,_117); } this.sort(_116,data); this.treeNodes=data; this.treeLevel=$(_116).treegrid("getLevel",_117); var node=_37(_116,_117); if(node){ if(node.children){ node.children=node.children.concat(data); }else{ node.children=data; } }else{ _118.data=_118.data.concat(data); } },sort:function(_11c,data){ var opts=$.data(_11c,"treegrid").options; if(!opts.remoteSort&&opts.sortName){ var _11d=opts.sortName.split(","); var _11e=opts.sortOrder.split(","); _11f(data); } function _11f(rows){ rows.sort(function(r1,r2){ var r=0; for(var i=0;i<_11d.length;i++){ var sn=_11d[i]; var so=_11e[i]; var col=$(_11c).treegrid("getColumnOption",sn); var _120=col.sorter||function(a,b){ return a==b?0:(a>b?1:-1); }; r=_120(r1[sn],r2[sn])*(so=="asc"?1:-1); if(r!=0){ return r; } } return r; }); for(var i=0;i<rows.length;i++){ var _121=rows[i].children; if(_121&&_121.length){ _11f(_121); } } }; },transfer:function(_122,_123,data){ var opts=$.data(_122,"treegrid").options; var rows=$.extend([],data); var _124=_125(_123,rows); var toDo=$.extend([],_124); while(toDo.length){ var node=toDo.shift(); var _126=_125(node[opts.idField],rows); if(_126.length){ if(node.children){ node.children=node.children.concat(_126); }else{ node.children=_126; } toDo=toDo.concat(_126); } } return _124; function _125(_127,rows){ var rr=[]; for(var i=0;i<rows.length;i++){ var row=rows[i]; if(row._parentId==_127){ rr.push(row); rows.splice(i,1); i--; } } return rr; }; }}); $.fn.treegrid.defaults=$.extend({},$.fn.datagrid.defaults,{treeField:null,checkbox:false,cascadeCheck:true,onlyLeafCheck:false,lines:false,animate:false,singleSelect:true,view:_e6,rowEvents:$.extend({},$.fn.datagrid.defaults.rowEvents,{mouseover:_22(true),mouseout:_22(false),click:_24}),loader:function(_128,_129,_12a){ var opts=$(this).treegrid("options"); if(!opts.url){ return false; } $.ajax({type:opts.method,url:opts.url,data:_128,dataType:"json",success:function(data){ _129(data); },error:function(){ _12a.apply(this,arguments); }}); },loadFilter:function(data,_12b){ return data; },finder:{getTr:function(_12c,id,type,_12d){ type=type||"body"; _12d=_12d||0; var dc=$.data(_12c,"datagrid").dc; if(_12d==0){ var opts=$.data(_12c,"treegrid").options; var tr1=opts.finder.getTr(_12c,id,type,1); var tr2=opts.finder.getTr(_12c,id,type,2); return tr1.add(tr2); }else{ if(type=="body"){ var tr=$("#"+$.data(_12c,"datagrid").rowIdPrefix+"-"+_12d+"-"+id); if(!tr.length){ tr=(_12d==1?dc.body1:dc.body2).find("tr[node-id=\""+id+"\"]"); } return tr; }else{ if(type=="footer"){ return (_12d==1?dc.footer1:dc.footer2).find("tr[node-id=\""+id+"\"]"); }else{ if(type=="selected"){ return (_12d==1?dc.body1:dc.body2).find("tr.datagrid-row-selected"); }else{ if(type=="highlight"){ return (_12d==1?dc.body1:dc.body2).find("tr.datagrid-row-over"); }else{ if(type=="checked"){ return (_12d==1?dc.body1:dc.body2).find("tr.datagrid-row-checked"); }else{ if(type=="last"){ return (_12d==1?dc.body1:dc.body2).find("tr:last[node-id]"); }else{ if(type=="allbody"){ return (_12d==1?dc.body1:dc.body2).find("tr[node-id]"); }else{ if(type=="allfooter"){ return (_12d==1?dc.footer1:dc.footer2).find("tr[node-id]"); } } } } } } } } } },getRow:function(_12e,p){ var id=(typeof p=="object")?p.attr("node-id"):p; return $(_12e).treegrid("find",id); },getRows:function(_12f){ return $(_12f).treegrid("getChildren"); }},onBeforeLoad:function(row,_130){ },onLoadSuccess:function(row,data){ },onLoadError:function(){ },onBeforeCollapse:function(row){ },onCollapse:function(row){ },onBeforeExpand:function(row){ },onExpand:function(row){ },onClickRow:function(row){ },onDblClickRow:function(row){ },onClickCell:function(_131,row){ },onDblClickCell:function(_132,row){ },onContextMenu:function(e,row){ },onBeforeEdit:function(row){ },onAfterEdit:function(row,_133){ },onCancelEdit:function(row){ },onBeforeCheckNode:function(row,_134){ },onCheckNode:function(row,_135){ }}); })(jQuery);
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 9); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function(useSourceMap) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item, useSourceMap); if(item[2]) { return "@media " + item[2] + "{" + content + "}"; } else { return content; } }).join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; function cssWithMappingToString(item, useSourceMap) { var content = item[1] || ''; var cssMapping = item[3]; if (!cssMapping) { return content; } if (useSourceMap && typeof btoa === 'function') { var sourceMapping = toComment(cssMapping); var sourceURLs = cssMapping.sources.map(function (source) { return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */' }); return [content].concat(sourceURLs).concat([sourceMapping]).join('\n'); } return [content].join('\n'); } // Adapted from convert-source-map (MIT) function toComment(sourceMap) { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; return '/*# ' + data + ' */'; } /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (immutable) */ __webpack_exports__["default"] = addStylesClient; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__listToStyles__ = __webpack_require__(16); /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra Modified by Evan You @yyx990803 */ var hasDocument = typeof document !== 'undefined' if (typeof DEBUG !== 'undefined' && DEBUG) { if (!hasDocument) { throw new Error( 'vue-style-loader cannot be used in a non-browser environment. ' + "Use { target: 'node' } in your Webpack config to indicate a server-rendering environment." ) } } /* type StyleObject = { id: number; parts: Array<StyleObjectPart> } type StyleObjectPart = { css: string; media: string; sourceMap: ?string } */ var stylesInDom = {/* [id: number]: { id: number, refs: number, parts: Array<(obj?: StyleObjectPart) => void> } */} var head = hasDocument && (document.head || document.getElementsByTagName('head')[0]) var singletonElement = null var singletonCounter = 0 var isProduction = false var noop = function () {} var options = null var ssrIdKey = 'data-vue-ssr-id' // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page var isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\b/.test(navigator.userAgent.toLowerCase()) function addStylesClient (parentId, list, _isProduction, _options) { isProduction = _isProduction options = _options || {} var styles = Object(__WEBPACK_IMPORTED_MODULE_0__listToStyles__["a" /* default */])(parentId, list) addStylesToDom(styles) return function update (newList) { var mayRemove = [] for (var i = 0; i < styles.length; i++) { var item = styles[i] var domStyle = stylesInDom[item.id] domStyle.refs-- mayRemove.push(domStyle) } if (newList) { styles = Object(__WEBPACK_IMPORTED_MODULE_0__listToStyles__["a" /* default */])(parentId, newList) addStylesToDom(styles) } else { styles = [] } for (var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i] if (domStyle.refs === 0) { for (var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j]() } delete stylesInDom[domStyle.id] } } } } function addStylesToDom (styles /* Array<StyleObject> */) { for (var i = 0; i < styles.length; i++) { var item = styles[i] var domStyle = stylesInDom[item.id] if (domStyle) { domStyle.refs++ for (var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]) } for (; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j])) } if (domStyle.parts.length > item.parts.length) { domStyle.parts.length = item.parts.length } } else { var parts = [] for (var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j])) } stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts } } } } function createStyleElement () { var styleElement = document.createElement('style') styleElement.type = 'text/css' head.appendChild(styleElement) return styleElement } function addStyle (obj /* StyleObjectPart */) { var update, remove var styleElement = document.querySelector('style[' + ssrIdKey + '~="' + obj.id + '"]') if (styleElement) { if (isProduction) { // has SSR styles and in production mode. // simply do nothing. return noop } else { // has SSR styles but in dev mode. // for some reason Chrome can't handle source map in server-rendered // style tags - source maps in <style> only works if the style tag is // created and inserted dynamically. So we remove the server rendered // styles and inject new ones. styleElement.parentNode.removeChild(styleElement) } } if (isOldIE) { // use singleton mode for IE9. var styleIndex = singletonCounter++ styleElement = singletonElement || (singletonElement = createStyleElement()) update = applyToSingletonTag.bind(null, styleElement, styleIndex, false) remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true) } else { // use multi-style-tag mode in all other cases styleElement = createStyleElement() update = applyToTag.bind(null, styleElement) remove = function () { styleElement.parentNode.removeChild(styleElement) } } update(obj) return function updateStyle (newObj /* StyleObjectPart */) { if (newObj) { if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { return } update(obj = newObj) } else { remove() } } } var replaceText = (function () { var textStore = [] return function (index, replacement) { textStore[index] = replacement return textStore.filter(Boolean).join('\n') } })() function applyToSingletonTag (styleElement, index, remove, obj) { var css = remove ? '' : obj.css if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css) } else { var cssNode = document.createTextNode(css) var childNodes = styleElement.childNodes if (childNodes[index]) styleElement.removeChild(childNodes[index]) if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]) } else { styleElement.appendChild(cssNode) } } } function applyToTag (styleElement, obj) { var css = obj.css var media = obj.media var sourceMap = obj.sourceMap if (media) { styleElement.setAttribute('media', media) } if (options.ssrId) { styleElement.setAttribute(ssrIdKey, obj.id) } if (sourceMap) { // https://developer.chrome.com/devtools/docs/javascript-debugging // this makes source maps inside style tags work properly in Chrome css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */' // http://stackoverflow.com/a/26603875 css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */' } if (styleElement.styleSheet) { styleElement.styleSheet.cssText = css } else { while (styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild) } styleElement.appendChild(document.createTextNode(css)) } } /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = normalizeComponent; /* globals __VUE_SSR_CONTEXT__ */ // IMPORTANT: Do NOT use ES2015 features in this file (except for modules). // This module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle. function normalizeComponent ( scriptExports, render, staticRenderFns, functionalTemplate, injectStyles, scopeId, moduleIdentifier, /* server only */ shadowMode /* vue-cli only */ ) { scriptExports = scriptExports || {} // ES6 modules interop var type = typeof scriptExports.default if (type === 'object' || type === 'function') { scriptExports = scriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (render) { options.render = render options.staticRenderFns = staticRenderFns options._compiled = true } // functional template if (functionalTemplate) { options.functional = true } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = shadowMode ? function () { injectStyles.call(this, this.$root.$options.shadowRoot) } : injectStyles } if (hook) { if (options.functional) { // for template-only hot-reload because in that case the render fn doesn't // go through the normalizer options._injectStyles = hook // register for functioal component in vue file var originalRender = options.render options.render = function renderWithStyleInjection (h, context) { hook.call(context) return originalRender(h, context) } } else { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } } return { exports: scriptExports, options: options } } /***/ }), /* 3 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 4 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__header__ = __webpack_require__(17); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__pages_pullDown__ = __webpack_require__(21); // // // // // // // // // /* harmony default export */ __webpack_exports__["a"] = ({ name: "app", components: { TopHeader: __WEBPACK_IMPORTED_MODULE_0__header__["a" /* default */], PullDown: __WEBPACK_IMPORTED_MODULE_1__pages_pullDown__["a" /* default */] } }); /***/ }), /* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // // // // // // /* harmony default export */ __webpack_exports__["a"] = ({ name: "header" }); /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_pullToRefresh__ = __webpack_require__(24); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__service__ = __webpack_require__(28); // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["a"] = ({ mounted() { // this.$refs.list.triggerRefresh(); }, data() { return { articles: [], pageNumber: 1 } }, components: { PullToRefresh: __WEBPACK_IMPORTED_MODULE_0__src_pullToRefresh__["a" /* default */] }, methods: { shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }, refresh(finish) { this.pageNumber = 1; this.getNews(finish).then(res => { this.articles = this.shuffleArray(res.articles); finish(); }); }, getNews() { let requestPayload = { pageNumber: this.pageNumber, pageSize: 20 }; return __WEBPACK_IMPORTED_MODULE_1__service__["a" /* default */].getNews(requestPayload); }, infiniteScroll(finish) { this.pageNumber++; this.getNews(finish).then(res => { this.articles = this.articles.concat(res.articles); finish(); }); } } }); /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // // // // // // // // // // // // // // // // // // // // // // // // // // // // const STATES = { IDLE: 'IDLE', START: 'START', TRIGGERED: 'TRIGGERED' }; /* harmony default export */ __webpack_exports__["a"] = ({ props: { topSlidingHeight: { type: Number, default: 80 }, slidingThreshold: { type: Number, default: 2 }, triggerRefreshOnMounted: { type: Boolean, default: false } }, mounted() { if (this.triggerRefreshOnMounted) { this.triggerRefresh(); } }, computed: { spinnerClass() { if (this.state == STATES.IDLE) { return 'pull__spinner--animate'; } else if (this.state == STATES.TRIGGERED) { return 'pull__spinner--active'; } return ''; }, }, data() { return { startY: 0, endY: 0, transformYValue: 0, state: STATES.IDLE, isLoadMoreLoading: false } }, methods: { touchStart(e) { if (this.state != STATES.TRIGGERED && this.$refs.list.scrollTop == 0) { this.startY = e.touches[0].pageY; this.state = STATES.START; } }, touchMoving(e) { if (this.state == STATES.START && this.$refs.list.scrollTop == 0) { this.endY = e.touches[0].pageY; const diff = this.endY - this.startY; if ((diff / this.slidingThreshold) <= this.topSlidingHeight) { this.transformYValue = diff / this.slidingThreshold; } } }, touchEnd() { if (this.$refs.list.scrollTop == 0) { const diff = this.endY - this.startY; if (diff / this.slidingThreshold >= this.topSlidingHeight) { this.triggerRefresh(); } if (this.state == STATES.START) { this.finishLoading(); } } }, triggerRefresh() { this.state = STATES.TRIGGERED; this.$emit('refresh', this.finishLoading); this.transformYValue = this.topSlidingHeight; }, finishLoading() { this.transformYValue = 0; this.state = STATES.IDLE; }, scrolling() { if (!this.isLoadMoreLoading && this.$refs.list.offsetHeight + this.$refs.list.scrollTop == this.$refs.list.scrollHeight) { this.isLoadMoreLoading = true; this.$emit('triggerScroll', this.finishInfiniteScrollLoading); } }, finishInfiniteScrollLoading() { this.isLoadMoreLoading = false; }, } }); /***/ }), /* 9 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_vue__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__app__ = __webpack_require__(13); new __WEBPACK_IMPORTED_MODULE_0_vue__["a" /* default */]({ el: '#app', components: { App: __WEBPACK_IMPORTED_MODULE_1__app__["a" /* default */] }, template: '<App/>' // render: function () { // return createElement(App) // } }); /***/ }), /* 10 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/*! * Vue.js v2.5.16 * (c) 2014-2018 Evan You * Released under the MIT License. */ /* */ var emptyObject = Object.freeze({}); // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value e.g. [object Object] */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if a attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind polyfill for environments that do not support it... e.g. * PhantomJS 1.x. Technically we don't need this anymore since native bind is * now more performant in most browsers, but removing it would be breaking for * code that was able to run in PhantomJS 1.x, so this must be kept for * backwards compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/) */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }) /* */ /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm || {}; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.isCloned = true; return cloned } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; function toggleObserving (value) { shouldObserve = value; } /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive(obj, keys[i]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src, keys) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; if (!getter && arguments.length === 2) { val = obj[key]; } var setter = property && property.set; var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target)) ) { warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target)) ) { warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { process.env.NODE_ENV !== 'production' && assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } if (process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { validateComponentName(key); } } function validateComponentName (name) { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } if (isBuiltInTag(name) || config.isReservedTag(name)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + name ); } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else if (process.env.NODE_ENV !== 'production') { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else if (process.env.NODE_ENV !== 'production') { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // boolean casting var booleanIndex = getTypeIndex(Boolean, prop.type); if (booleanIndex > -1) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { // only cast empty string / same name to boolean if // boolean has higher priority var stringIndex = getTypeIndex(String, prop.type); if (stringIndex < 0 || booleanIndex < stringIndex) { value = true; } } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldObserve = shouldObserve; toggleObserving(true); observe(value); toggleObserving(prevShouldObserve); } if ( process.env.NODE_ENV !== 'production' && // skip validation for weex recycle-list child component props !(false && isObject(value) && ('@binding' in value)) ) { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (process.env.NODE_ENV !== 'production' && isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')) + ", got " + (toRawType(value)) + ".", vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isSameType (a, b) { return getType(a) === getType(b) } function getTypeIndex (type, expectedTypes) { if (!Array.isArray(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } for (var i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } return -1 } /* */ function handleError (err, vm, info) { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { logError(e, null, 'config.errorHandler'); } } logError(err, vm, info); } function logError (err, vm, info) { if (process.env.NODE_ENV !== 'production') { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ /* globals MessageChannel */ var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using both microtasks and (macro) tasks. // In < 2.4 we used microtasks everywhere, but there are some scenarios where // microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690) or even between bubbling of the same // event (#6566). However, using (macro) tasks everywhere also has subtle problems // when state is changed right before repaint (e.g. #6813, out-in transitions). // Here we use microtask by default, but expose a way to force (macro) task when // needed (e.g. in event handlers attached by v-on). var microTimerFunc; var macroTimerFunc; var useMacroTask = false; // Determine (macro) task defer implementation. // Technically setImmediate should be the ideal choice, but it's only available // in IE. The only polyfill that consistently queues the callback after all DOM // events triggered in the same loop is by using MessageChannel. /* istanbul ignore if */ if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { macroTimerFunc = function () { setImmediate(flushCallbacks); }; } else if (typeof MessageChannel !== 'undefined' && ( isNative(MessageChannel) || // PhantomJS MessageChannel.toString() === '[object MessageChannelConstructor]' )) { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = flushCallbacks; macroTimerFunc = function () { port.postMessage(1); }; } else { /* istanbul ignore next */ macroTimerFunc = function () { setTimeout(flushCallbacks, 0); }; } // Determine microtask defer implementation. /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); microTimerFunc = function () { p.then(flushCallbacks); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else { // fallback to macro microTimerFunc = macroTimerFunc; } /** * Wrap a function so that if any code inside triggers state change, * the changes are queued using a (macro) task instead of a microtask. */ function withMacroTask (fn) { return fn._withTask || (fn._withTask = function () { useMacroTask = true; var res = fn.apply(null, arguments); useMacroTask = false; return res }) } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; if (useMacroTask) { macroTimerFunc(); } else { microTimerFunc(); } } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ var mark; var measure; if (process.env.NODE_ENV !== 'production') { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); perf.clearMeasures(name); }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { cloned[i].apply(null, arguments$1); } } else { // return handler return value for single handlers return fns.apply(null, arguments) } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, def, cur, old, event; for (name in on) { def = cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); /* istanbul ignore if */ if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur); } add(event.name, cur, event.once, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); if (process.env.NODE_ENV !== 'production') { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor, context ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (isDef(factory.contexts)) { // already pending factory.contexts.push(context); } else { var contexts = factory.contexts = [context]; var sync = true; var forceRender = function () { for (var i = 0, l = contexts.length; i < l; i++) { contexts[i].$forceUpdate(); } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(); } }); var reject = once(function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(); } }); var res = factory(resolve, reject); if (isObject(res)) { if (typeof res.then === 'function') { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isDef(res.component) && typeof res.component.then === 'function') { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { setTimeout(function () { if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(); } }, res.delay || 200); } } if (isDef(res.timeout)) { setTimeout(function () { if (isUndef(factory.resolved)) { reject( process.env.NODE_ENV !== 'production' ? ("timeout (" + (res.timeout) + "ms)") : null ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn, once) { if (once) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$1 (event, fn) { target.$off(event, fn); } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, vm); target = undefined; } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var this$1 = this; var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var this$1 = this; var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$off(event[i], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (!fn) { vm._events[event] = null; return vm } if (fn) { // specific handler var cb; var i$1 = cbs.length; while (i$1--) { cb = cbs[i$1]; if (cb === fn || cb.fn === fn) { cbs.splice(i$1, 1); break } } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; if (process.env.NODE_ENV !== 'production') { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { try { cbs[i].apply(vm, args); } catch (e) { handleError(e, vm, ("event handler for \"" + event + "\"")); } } } return vm }; } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.fnContext === context) && data && data.slot != null ) { var name = data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children || []); } else { slot.push(child); } } else { (slots.default || (slots.default = [])).push(child); } } // ignore slots that contains only whitespace for (var name$1 in slots) { if (slots[name$1].every(isWhitespace)) { delete slots[name$1]; } } return slots } function isWhitespace (node) { return (node.isComment && !node.asyncFactory) || node.text === ' ' } function resolveScopedSlots ( fns, // see flow/vnode res ) { res = res || {}; for (var i = 0; i < fns.length; i++) { if (Array.isArray(fns[i])) { resolveScopedSlots(fns[i], res); } else { res[fns[i].key] = fns[i].fn; } } return res } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null; } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren var hasChildren = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots parentVnode.data.scopedSlots || // has new scoped slots vm.$scopedSlots !== emptyObject // has old scoped slots ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = parentVnode.data.attrs || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { toggleObserving(false); var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; var propOptions = vm.$options.props; // wtf flow? props[key] = validateProp(key, propOptions, propsData, vm); } toggleObserving(true); // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners listeners = listeners || emptyObject; var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { // #7573 disable dep collection when invoking lifecycle hooks pushTarget(); var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm); } catch (e) { handleError(e, vm, (hook + " hook")); } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } popTarget(); } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$1 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options, isRenderWatcher ) { this.vm = vm; if (isRenderWatcher) { vm._watcher = this; } vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$1; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''; // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted if (!isRoot) { toggleObserving(false); } var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive(props, key, value, function () { if (vm.$parent && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive(props, key, value); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); toggleObserving(true); } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; if (process.env.NODE_ENV !== 'production') { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { // #7573 disable dep collection when invoking data getters pushTarget(); try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } finally { popTarget(); } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { // $flow-disable-line var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (process.env.NODE_ENV !== 'production' && getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else if (process.env.NODE_ENV !== 'production') { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : userDef; sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : userDef.get : noop; sharedPropertyDefinition.set = userDef.set ? userDef.set : noop; } if (process.env.NODE_ENV !== 'production' && sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { if (process.env.NODE_ENV !== 'production') { if (methods[key] == null) { warn( "Method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = methods[key] == null ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, expOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(expOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { toggleObserving(false); Object.keys(result).forEach(function (key) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } else { defineReactive(vm, key, result[key]); } }); toggleObserving(true); } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject).filter(function (key) { /* istanbul ignore next */ return Object.getOwnPropertyDescriptor(inject, key).enumerable }) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && hasOwn(source._provided, provideKey)) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else if (process.env.NODE_ENV !== 'production') { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } if (isDef(ret)) { (ret)._isVList = true; } return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; var nodes; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } nodes = scopedSlotFn(props) || fallback; } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes) { if (process.env.NODE_ENV !== 'production' && slotNodes._rendered) { warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); } slotNodes._rendered = true; } nodes = slotNodes || fallback; } var target = props && props.slot; if (target) { return this.$createElement('template', { slot: target }, nodes) } else { return nodes } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ function isKeyNotMatch (expect, actual) { if (Array.isArray(expect)) { return expect.indexOf(actual) === -1 } else { return expect !== actual } } /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName ) { var mappedKeyCode = config.keyCodes[key] || builtInKeyCode; if (builtInKeyName && eventKeyName && !config.keyCodes[key]) { return isKeyNotMatch(builtInKeyName, eventKeyName) } else if (mappedKeyCode) { return isKeyNotMatch(mappedKeyCode, eventKeyCode) } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } if (!(key in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { var cached = this._staticTrees || (this._staticTrees = []); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree. if (tree && !isInFor) { return tree } // otherwise, render a fresh tree. tree = cached[index] = this.$options.staticRenderFns[index].call( this._renderProxy, null, this // for render fns generated for functional component templates ); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var options = Ctor.options; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm; if (hasOwn(parent, '_uid')) { contextVm = Object.create(parent); // $flow-disable-line contextVm._original = parent; } else { // the context vm passed in is a functional context as well. // in this case we want to make sure we are able to get a hold to the // real context instance. contextVm = parent; // $flow-disable-line parent = parent._original; } var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { return resolveSlots(children, parent); }; // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = data.scopedSlots || emptyObject; } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode && !Array.isArray(vnode)) { vnode.fnScopeId = options._scopeId; vnode.fnContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options) } else if (Array.isArray(vnode)) { var vnodes = normalizeChildren(vnode) || []; var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options); } return res } } function cloneAndMarkFunctionalResult (vnode, data, contextVm, options) { // #7817 clone node before setting fnContext, otherwise if the node is reused // (e.g. it was from a cached normal slot) the fnContext causes named slots // that should not be matched to match. var clone = cloneVNode(vnode); clone.fnContext = contextVm; clone.fnOptions = options; if (data.slot) { (clone.data || (clone.data = {})).slot = data.slot; } return clone } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ // Register the component hook to weex native render engine. // The hook will be triggered by native, not javascript. // Updates the state of the component to weex native render engine. /* */ // https://github.com/Hanks10100/weex-native-directive/tree/master/component // listening on native callback /* */ /* */ // inline hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init ( vnode, hydrating, parentElm, refElm ) { if ( vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } else { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // install component management hooks onto the placeholder node installComponentHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); // Weex specific: invoke recycle-list optimized @render function for // extracting cell-slot template. // https://github.com/Hanks10100/weex-native-directive/tree/master/component /* istanbul ignore if */ return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var options = { _isComponent: true, parent: parent, _parentVnode: vnode, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnode.componentOptions.Ctor(options) } function installComponentHooks (data) { var hooks = data.hook || (data.hook = {}); for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; hooks[key] = componentVNodeHooks[key]; } } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [data.model.callback].concat(on[event]); } else { on[event] = data.model.callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (Array.isArray(vnode)) { return vnode } else if (isDef(vnode)) { if (isDef(ns)) { applyNS(vnode, ns); } if (isDef(data)) { registerDeepBindings(data); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && ( isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) { applyNS(child, ns, force); } } } } // ref #5318 // necessary to ensure parent re-render when deep bindings like :style and // :class are used on slot nodes function registerDeepBindings (data) { if (isObject(data.style)) { traverse(data.style); } if (isObject(data.class)) { traverse(data.class); } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; // v-once cached trees var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } else { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true); } } function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; // reset _rendered flag on slots for duplicate slot check if (process.env.NODE_ENV !== 'production') { for (var key in vm.$slots) { // $flow-disable-line vm.$slots[key]._rendered = false; } } if (_parentVnode) { vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject; } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } else { vnode = vm._vnode; } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ var uid$3 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$3++; var startTag, endTag; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. var parentVnode = options._parentVnode; opts.parent = options.parent; opts._parentVnode = parentVnode; opts._parentElm = options._parentElm; opts._refElm = options._refElm; var vnodeComponentOptions = parentVnode.componentOptions; opts.propsData = vnodeComponentOptions.propsData; opts._parentListeners = vnodeComponentOptions.listeners; opts._renderChildren = vnodeComponentOptions.children; opts._componentTag = vnodeComponentOptions.tag; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var extended = Ctor.extendOptions; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = dedupe(latest[key], extended[key], sealed[key]); } } return modified } function dedupe (latest, extended, sealed) { // compare latest and sealed to ensure lifecycle hooks won't be duplicated // between merges if (Array.isArray(latest)) { var res = []; sealed = Array.isArray(sealed) ? sealed : [sealed]; extended = Array.isArray(extended) ? extended : [extended]; for (var i = 0; i < latest.length; i++) { // push original options and not sealed options to exclude duplicated options if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) { res.push(latest[i]); } } return res } else { return latest } } function Vue (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); renderMixin(Vue); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production' && name) { validateComponentName(name); } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && type === 'component') { validateComponentName(id); } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && (!current || cached$$1.tag !== current.tag)) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { var this$1 = this; for (var key in this$1.cache) { pruneCacheEntry(this$1.cache, key, this$1.keys); } }, mounted: function mounted () { var this$1 = this; this.$watch('include', function (val) { pruneCache(this$1, function (name) { return matches(val, name); }); }); this.$watch('exclude', function (val) { pruneCache(this$1, function (name) { return !matches(val, name); }); }); }, render: function render () { var slot = this.$slots.default; var vnode = getFirstComponentChild(slot); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); var ref = this; var include = ref.include; var exclude = ref.exclude; if ( // not included (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode } var ref$1 = this; var cache = ref$1.cache; var keys = ref$1.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode || (slot && slot[0]) } } var builtInComponents = { KeepAlive: KeepAlive } /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue); Object.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); // expose FunctionalRenderContext for ssr runtime helper installation Object.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext }); Vue.version = '2.5.16'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode && childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode && parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setStyleScope (node, scopeId) { node.setAttribute(scopeId, ''); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setStyleScope: setStyleScope }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } } function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!isDef(key)) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove () { if (--remove.listeners === 0) { removeNode(childElm); } } remove.listeners = listeners; return remove } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } function isUnknownElement$$1 (vnode, inVPre) { return ( !inVPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(vnode.tag) : ignore === vnode.tag }) ) && config.isUnknownElement(vnode.tag) ) } var creatingElmInVPre = 0; function createElm ( vnode, insertedVnodeQueue, parentElm, refElm, nested, ownerArray, index ) { if (isDef(vnode.elm) && isDef(ownerArray)) { // This vnode was used in a previous render! // now it's used as a new node, overwriting its elm would cause // potential patch errors down the road when it's used as an insertion // reference node. Instead, we clone the node on-demand before creating // associated DOM element for it. vnode = ownerArray[index] = cloneVNode(vnode); } vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { creatingElmInVPre++; } if (isUnknownElement$$1(vnode, creatingElmInVPre)) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { creatingElmInVPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (ref$$1.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { if (process.env.NODE_ENV !== 'production') { checkDuplicateKeys(children); } for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text))); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.fnScopeId)) { nodeOps.setStyleScope(vnode.elm, i); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setStyleScope(vnode.elm, i); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId) ) { nodeOps.setStyleScope(vnode.elm, i); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; if (process.env.NODE_ENV !== 'production') { checkDuplicateKeys(newCh); } while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } else { vnodeToMove = oldCh[idxInOld]; if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function checkDuplicateKeys (children) { var seenKeys = {}; for (var i = 0; i < children.length; i++) { var vnode = children[i]; var key = vnode.key; if (isDef(key)) { if (seenKeys[key]) { warn( ("Duplicate keys detected: '" + key + "'. This may cause an update error."), vnode.context ); } else { seenKeys[key] = true; } } } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var hydrationBailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization // Note: style is excluded because it relies on initial clone for future // deep updates (#7063). var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue, inVPre) { var i; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; inVPre = inVPre || (data && data.pre); vnode.elm = elm; if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.isAsyncPlaceholder = true; return true } // assert node match if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode, inVPre)) { return false } } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { var fullInvoke = false; for (var key in data) { if (!isRenderedModule(key)) { fullInvoke = true; invokeCreateHooks(vnode, insertedVnodeQueue); break } } if (!fullInvoke && data['class']) { // ensure collecting deps for deep class bindings for future updates traverse(data['class']); } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode, inVPre) { if (isDef(vnode.tag)) { return vnode.tag.indexOf('vue-component') === 0 || ( !isUnknownElement$$1(vnode, inVPre) && vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm$1 = nodeOps.parentNode(oldElm); // create new node createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); // update parent placeholder node element, recursively if (isDef(vnode.parent)) { var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } // destroy old node if (isDef(parentElm$1)) { removeVnodes(parentElm$1, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } } function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode, 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode, 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { // $flow-disable-line return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { // $flow-disable-line dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } // $flow-disable-line return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ] /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (el.tagName.indexOf('-') > -1) { baseSetAttr(el, key, value); } else if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { baseSetAttr(el, key, value); } } function baseSetAttr (el, key, value) { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // #7138: IE10 & 11 fires input event when setting placeholder on // <textarea>... block the first input event and remove the blocker // immediately. /* istanbul ignore if */ if ( isIE && !isIE9 && el.tagName === 'TEXTAREA' && key === 'placeholder' && !el.__ieph ) { var blocker = function (e) { e.stopImmediatePropagation(); el.removeEventListener('input', blocker); }; el.addEventListener('input', blocker); // $flow-disable-line el.__ieph = true; /* IE placeholder patched */ } el.setAttribute(key, value); } } var attrs = { create: updateAttrs, update: updateAttrs } /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass } /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + (args !== ')' ? ',' + args : args)) } } /* */ function baseWarn (msg) { console.error(("[Vue compiler]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); el.plain = false; } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); el.plain = false; } // add a raw attr (use this in preTransforms) function addRawAttr (el, name, value) { el.attrsMap[name] = value; el.attrsList.push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); el.plain = false; } function addHandler ( el, name, value, modifiers, important, warn ) { modifiers = modifiers || emptyObject; // warn prevent and passive modifier /* istanbul ignore if */ if ( process.env.NODE_ENV !== 'production' && warn && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers.passive) { delete modifiers.passive; name = '&' + name; // mark the event as passive } // normalize click.right and click.middle since they don't actually fire // this is technically browser-specific, but at least for now browsers are // the only target envs that have right/middle clicks. if (name === 'click') { if (modifiers.right) { name = 'contextmenu'; delete modifiers.right; } else if (modifiers.middle) { name = 'mouseup'; } } var events; if (modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value.trim() }; if (modifiers !== emptyObject) { newHandler.modifiers = modifiers; } var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } el.plain = false; } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: ("\"" + value + "\""), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; function parseModel (val) { // Fix https://github.com/vuejs/vue/pull/7730 // allow v-model="obj.val " (trailing whitespace) val = val.trim(); len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; if (process.env.NODE_ENV !== 'production') { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (process.env.NODE_ENV !== 'production') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.' ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + (genAssignmentCode(value, '$$a.concat([$$v])')) + ")}" + "else{$$i>-1&&(" + (genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')) + ")}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; // warn if v-bind:value conflicts with v-model // except for inputs with v-bind:type if (process.env.NODE_ENV !== 'production') { var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value']; var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (value$1 && !typeBinding) { var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'; warn$1( binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " + 'because the latter already expands to a value binding internally' ); } } var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function createOnceHandler (handler, event, capture) { var _target = target$1; // save current target element in closure return function onceHandler () { var res = handler.apply(null, arguments); if (res !== null) { remove$2(event, onceHandler, capture, _target); } } } function add$1 ( event, handler, once$$1, capture, passive ) { handler = withMacroTask(handler); if (once$$1) { handler = createOnceHandler(handler, event, capture); } target$1.addEventListener( event, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( event, handler, capture, _target ) { (_target || target$1).removeEventListener( event, handler._withTask || handler, capture ); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, vnode.context); target$1 = undefined; } var events = { create: updateDOMListeners, update: updateDOMListeners } /* */ function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (isUndef(props[key])) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isNotInFocusAndDirty(elm, checkVal) || isDirtyWithModifiers(elm, checkVal) )) } function isNotInFocusAndDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isDirtyWithModifiers (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers)) { if (modifiers.lazy) { // inputs with lazy should only be updated when not in focus return false } if (modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (modifiers.trim) { return value.trim() !== newVal.trim() } } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps } /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if ( childNode && childNode.data && (styleData = normalizeStyleData(childNode.data)) ) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle } /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def) { if (!def) { return } /* istanbul ignore else */ if (typeof def === 'object') { var res = {}; if (def.css !== false) { extend(res, autoCssTransition(def.name || 'v')); } extend(res, def); return res } else if (typeof def === 'string') { return autoCssTransition(def) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitionDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode, 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { removeTransitionClass(el, startClass); if (!cb.cancelled) { addTransitionClass(el, toClass); if (!userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data) || el.nodeType !== 1) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb)) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (process.env.NODE_ENV !== 'production' && isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { removeTransitionClass(el, leaveClass); if (!cb.cancelled) { addTransitionClass(el, leaveToClass); if (!userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {} var platformModules = [ attrs, klass, events, domProps, style, transition ] /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var directive = { inserted: function inserted (el, binding, vnode, oldVnode) { if (vnode.tag === 'select') { // #6903 if (oldVnode.elm && !oldVnode.elm._vOptions) { mergeVNodeHook(vnode, 'postpatch', function () { directive.componentUpdated(el, binding, vnode); }); } else { setSelected(el, binding, vnode.context); } el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (!value === !oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } } var platformDirectives = { model: directive, show: show } /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) && // #6687 component root is a comment node !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } } /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final desired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } } function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup } /* */ // install platform specific utils Vue.config.mustUseProp = mustUseProp; Vue.config.isReservedTag = isReservedTag; Vue.config.isReservedAttr = isReservedAttr; Vue.config.getTagNamespace = getTagNamespace; Vue.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue.options.directives, platformDirectives); extend(Vue.options.components, platformComponents); // install platform patch function Vue.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ if (inBrowser) { setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else if ( process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && isChrome ) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && config.productionTip !== false && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); } /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var rawTokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, tokenValue; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { rawTokens.push(tokenValue = text.slice(lastIndex, index)); tokens.push(JSON.stringify(tokenValue)); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); rawTokens.push({ '@binding': exp }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { rawTokens.push(tokenValue = text.slice(lastIndex)); tokens.push(JSON.stringify(tokenValue)); } return { expression: tokens.join('+'), tokens: rawTokens } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (process.env.NODE_ENV !== 'production' && staticClass) { var res = parseText(staticClass, options.delimiters); if (res) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData } /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var res = parseText(staticStyle, options.delimiters); if (res) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 } /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } } /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; // #7298: escape - to avoid being pased as HTML comment when inlined in page var comment = /^<!\--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', '&#9;': '\t' }; var encodedAttr = /&(?:lt|gt|quot|amp);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd)); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(lastTag, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298 .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (process.env.NODE_ENV !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag.") ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:/; var forAliasRE = /([^]*?)\s+(?:in|of)\s+([^]*)/; var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; var stripParensRE = /^\(|\)$/g; var argRE = /:(.*)$/; var bindRE = /^:|^v-bind:/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(he.decode); // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg) { if (!warned) { warned = true; warn$2(msg); } } function closeElement (element) { // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } // apply post-transforms for (var i = 0; i < postTransforms.length; i++) { postTransforms[i](element, options); } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref, shouldKeepComment: options.comments, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; process.env.NODE_ENV !== 'production' && warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.' ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); // element-scope stuff processElement(element, options); } function checkRootConstraints (el) { if (process.env.NODE_ENV !== 'production') { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.' ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.' ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if (process.env.NODE_ENV !== 'production') { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } else { closeElement(element); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; closeElement(element); }, chars: function chars (text) { if (!currentParent) { if (process.env.NODE_ENV !== 'production') { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var res; if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) { children.push({ type: 2, expression: res.expression, tokens: res.tokens, text: text }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text }); } } }, comment: function comment (text) { currentParent.children.push({ type: 3, text: text, isComment: true }); } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement (element, options) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !element.attrsList.length; processRef(element); processSlot(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if (process.env.NODE_ENV !== 'production' && el.tag === 'template') { warn$2("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var res = parseFor(exp); if (res) { extend(el, res); } else if (process.env.NODE_ENV !== 'production') { warn$2( ("Invalid v-for expression: " + exp) ); } } } function parseFor (exp) { var inMatch = exp.match(forAliasRE); if (!inMatch) { return } var res = {}; res.for = inMatch[2].trim(); var alias = inMatch[1].trim().replace(stripParensRE, ''); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { res.alias = alias.replace(forIteratorRE, ''); res.iterator1 = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.iterator2 = iteratorMatch[2].trim(); } } else { res.alias = alias; } return res } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else if (process.env.NODE_ENV !== 'production') { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored." ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (process.env.NODE_ENV !== 'production' && el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && el.attrsMap['v-for']) { warn$2( "Ambiguous combined usage of slot-scope and v-for on <" + (el.tag) + "> " + "(v-for takes higher priority). Use a wrapper <template> for the " + "scoped slot to make it clearer.", true ); } el.slotScope = slotScope; } var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (el.tag !== 'template' && !el.slotScope) { addAttr(el, 'slot', slotTarget); } } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } if (modifiers.sync) { addHandler( el, ("update:" + (camelize(name))), genAssignmentCode(value, "$event") ); } } if (isProp || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers, false, warn$2); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; if (arg) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if (process.env.NODE_ENV !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute if (process.env.NODE_ENV !== 'production') { var res = parseText(value, delimiters); if (res) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); // #6887 firefox doesn't update muted state if set via attribute // even immediately after element creation if (!el.component && name === 'muted' && platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, 'true'); } } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ /** * Expand input[v-model] with dyanmic type bindings into v-if-else chains * Turn this: * <input v-model="data[type]" :type="type"> * into this: * <input v-if="type === 'checkbox'" type="checkbox" v-model="data[type]"> * <input v-else-if="type === 'radio'" type="radio" v-model="data[type]"> * <input v-else :type="type" v-model="data[type]"> */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (!map['v-model']) { return } var typeBinding; if (map[':type'] || map['v-bind:type']) { typeBinding = getBindingAttr(el, 'type'); } if (!map.type && !typeBinding && map['v-bind']) { typeBinding = "(" + (map['v-bind']) + ").type"; } if (typeBinding) { var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; var hasElse = getAndRemoveAttr(el, 'v-else', true) != null; var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true); // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); if (hasElse) { branch0.else = true; } else if (elseIfCondition) { branch0.elseif = elseIfCondition; } return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } var model$2 = { preTransformNode: preTransformNode } var modules$1 = [ klass$1, style$1, model$2 ] /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model, text: text, html: html } /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // KeyboardEvent.keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // KeyboardEvent.key aliases var keyNames = { esc: 'Escape', tab: 'Tab', enter: 'Enter', space: ' ', // #7806: IE11 uses key names without `Arrow` prefix for arrow keys. up: ['Up', 'ArrowUp'], left: ['Left', 'ArrowLeft'], right: ['Right', 'ArrowRight'], down: ['Down', 'ArrowDown'], 'delete': ['Backspace', 'Delete'] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative, warn ) { var res = isNative ? 'nativeOn:{' : 'on:{'; for (var name in events) { res += "\"" + name + "\":" + (genHandler(name, events[name])) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); if (!handler.modifiers) { if (isMethodPath || isFunctionExpression) { return handler.value } /* istanbul ignore if */ return ("function($event){" + (handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? ("return " + (handler.value) + "($event)") : isFunctionExpression ? ("return (" + (handler.value) + ")($event)") : handler.value; /* istanbul ignore if */ return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var keyCode = keyCodes[key]; var keyName = keyNames[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(keyCode)) + "," + "$event.key," + "" + (JSON.stringify(keyName)) + ")" ) } /* */ function on (el, dir) { if (process.env.NODE_ENV !== 'production' && dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop } /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data = el.plain ? undefined : genData$2(el, state); var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state) { el.staticProcessed = true; state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { process.env.NODE_ENV !== 'production' && state.warn( "v-once can only be used inside v-for that is keyed. " ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (process.env.NODE_ENV !== 'production' && state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events, false, state.warn)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true, state.warn)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (process.env.NODE_ENV !== 'production' && ( el.children.length !== 1 || ast.type !== 1 )) { state.warn('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( slots, state ) { return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key], state) }).join(',')) + "])") } function genScopedSlot ( key, el, state ) { if (el.for && !el.forProcessed) { return genForScopedSlot(key, el, state) } var fn = "function(" + (String(el.slotScope)) + "){" + "return " + (el.tag === 'template' ? el.if ? ((el.if) + "?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; return ("{key:" + key + ",fn:" + fn + "}") } function genForScopedSlot ( key, el, state ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genScopedSlot(key, el, state)) + '})' } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { return (altGenElement || genElement)(el$1, state) } var normalizationType = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}"); var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; /* istanbul ignore if */ { res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkEvent (exp, text, errors) { var stipped = exp.replace(stripStringRE, ''); var keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { errors.push( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()) ); } checkExpression(exp, text, errors); } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier ( ident, type, text, errors ) { if (typeof ident === 'string') { try { new Function(("var " + ident + "=_")); } catch (e) { errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim()))); } } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()) ); } else { errors.push( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n" ); } } } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips if (process.env.NODE_ENV !== 'production') { if (compiled.errors && compiled.errors.length) { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } if (compiled.tips && compiled.tips.length) { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; finalOptions.warn = function (msg, tip) { (tip ? tips : errors).push(msg); }; if (options) { // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives || null), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } var compiled = baseCompile(template, finalOptions); if (process.env.NODE_ENV !== 'production') { errors.push.apply(errors, detectErrors(compiled.ast)); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); if (options.optimize !== false) { optimize(ast, options); } var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compileToFunctions = ref$1.compileToFunctions; /* */ // check whether current browser encodes a char inside attribute values var div; function getShouldDecode (href) { div = div || document.createElement('div'); div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>"; return div.innerHTML.indexOf('&#10;') > 0 } // #3663: IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false; // #6828: chrome encodes content in a[href] var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue.prototype.$mount; Vue.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { process.env.NODE_ENV !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { if (process.env.NODE_ENV !== 'production') { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { shouldDecodeNewlines: shouldDecodeNewlines, shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue.compile = compileToFunctions; /* harmony default export */ __webpack_exports__["a"] = (Vue); /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(4), __webpack_require__(3), __webpack_require__(11).setImmediate)) /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { if (timeout) { timeout.close(); } }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // setimmediate attaches itself to the global object __webpack_require__(12); // On some exotic environments, it's not clear which object `setimmeidate` was // able to install onto. Search each possibility in the same order as the // `setimmediate` library. exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || (typeof global !== "undefined" && global.setImmediate) || (this && this.setImmediate); exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || (typeof global !== "undefined" && global.clearImmediate) || (this && this.clearImmediate); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(4))) /***/ }), /* 13 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_app_vue__ = __webpack_require__(5); /* unused harmony namespace reexport */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_88f7d72e_hasScoped_false_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_app_vue__ = __webpack_require__(30); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__ = __webpack_require__(2); var disposed = false function injectStyle (context) { if (disposed) return __webpack_require__(14) } /* script */ /* template */ /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = Object(__WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__["a" /* default */])( __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_app_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_88f7d72e_hasScoped_false_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_app_vue__["a" /* render */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_88f7d72e_hasScoped_false_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_app_vue__["b" /* staticRenderFns */], __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "examples/app.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-88f7d72e", Component.options) } else { hotAPI.reload("data-v-88f7d72e", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["a"] = (Component.exports); /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(15); if(typeof content === 'string') content = [[module.i, content, '']]; if(content.locals) module.exports = content.locals; // add the styles to the DOM var add = __webpack_require__(1).default var update = add("6b105854", content, false, {}); // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../node_modules/css-loader/index.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"scoped\":false,\"sourceMap\":false}!../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./app.vue", function() { var newContent = require("!!../node_modules/css-loader/index.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"scoped\":false,\"sourceMap\":false}!../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./app.vue"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(0)(false); // imports // module exports.push([module.i, "\nbody {\n font-family: 'Roboto', sans-serif;\n background-color: #ECEFF1;\n padding: 0;\n margin: 0;\n}\n.container {\n padding: 16px;\n}\n* {\n box-sizing: border-box;\n}\n", ""]); // exports /***/ }), /* 16 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = listToStyles; /** * Translates the list format produced by css-loader into something * easier to manipulate. */ function listToStyles (parentId, list) { var styles = [] var newStyles = {} for (var i = 0; i < list.length; i++) { var item = list[i] var id = item[0] var css = item[1] var media = item[2] var sourceMap = item[3] var part = { id: parentId + ':' + i, css: css, media: media, sourceMap: sourceMap } if (!newStyles[id]) { styles.push(newStyles[id] = { id: id, parts: [part] }) } else { newStyles[id].parts.push(part) } } return styles } /***/ }), /* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_header_vue__ = __webpack_require__(6); /* unused harmony namespace reexport */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_99210f16_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__ = __webpack_require__(20); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__ = __webpack_require__(2); var disposed = false function injectStyle (context) { if (disposed) return __webpack_require__(18) } /* script */ /* template */ /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = "data-v-99210f16" /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = Object(__WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__["a" /* default */])( __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_header_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_99210f16_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__["a" /* render */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_99210f16_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__["b" /* staticRenderFns */], __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "examples/header.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-99210f16", Component.options) } else { hotAPI.reload("data-v-99210f16", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["a"] = (Component.exports); /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(19); if(typeof content === 'string') content = [[module.i, content, '']]; if(content.locals) module.exports = content.locals; // add the styles to the DOM var add = __webpack_require__(1).default var update = add("6983c86a", content, false, {}); // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../node_modules/css-loader/index.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"id\":\"data-v-99210f16\",\"scoped\":true,\"sourceMap\":false}!../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./header.vue", function() { var newContent = require("!!../node_modules/css-loader/index.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"id\":\"data-v-99210f16\",\"scoped\":true,\"sourceMap\":false}!../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./header.vue"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(0)(false); // imports // module exports.push([module.i, "\n.header[data-v-99210f16] {\n background-color: #01579B;\n overflow: hidden;\n height: 64px;\n box-shadow: 0px 3px 10px 2px #c3c3c3;\n position: fixed;\n width: 100%;\n z-index: 1;\n}\n.header .header__title[data-v-99210f16] {\n color: #FFFFFF;\n font-size: 18px;\n margin: 0;\n margin-top: 20px;\n margin-left: 16px;\n}\n", ""]); // exports /***/ }), /* 20 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _vm._m(0) } var staticRenderFns = [ function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c("div", { staticClass: "header" }, [ _c("h4", { staticClass: "header__title" }, [_vm._v("Pull to refresh")]) ]) } ] render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-99210f16", { render: render, staticRenderFns: staticRenderFns }) } } /***/ }), /* 21 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_pullDown_vue__ = __webpack_require__(7); /* unused harmony namespace reexport */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_55cdd5da_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_pullDown_vue__ = __webpack_require__(29); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__ = __webpack_require__(2); var disposed = false function injectStyle (context) { if (disposed) return __webpack_require__(22) } /* script */ /* template */ /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = "data-v-55cdd5da" /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = Object(__WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__["a" /* default */])( __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_pullDown_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_55cdd5da_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_pullDown_vue__["a" /* render */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_55cdd5da_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_pullDown_vue__["b" /* staticRenderFns */], __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "examples/pages/pullDown.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-55cdd5da", Component.options) } else { hotAPI.reload("data-v-55cdd5da", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["a"] = (Component.exports); /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(23); if(typeof content === 'string') content = [[module.i, content, '']]; if(content.locals) module.exports = content.locals; // add the styles to the DOM var add = __webpack_require__(1).default var update = add("0569e470", content, false, {}); // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../../node_modules/css-loader/index.js?{\"sourceMap\":false}!../../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"id\":\"data-v-55cdd5da\",\"scoped\":true,\"sourceMap\":false}!../../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./pullDown.vue", function() { var newContent = require("!!../../node_modules/css-loader/index.js?{\"sourceMap\":false}!../../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"id\":\"data-v-55cdd5da\",\"scoped\":true,\"sourceMap\":false}!../../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./pullDown.vue"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(0)(false); // imports // module exports.push([module.i, "\n.news__list[data-v-55cdd5da] {\n height: calc(100vh - 32px);\n overflow: scroll;\n padding-top: 62px;\n}\n.news[data-v-55cdd5da] {\n background-color: #FFF;\n overflow: hidden;\n padding: 16px;\n border-bottom: 1px solid #DDD;\n}\n.news .news__title[data-v-55cdd5da] {\n margin: 0;\n font-size: 14px;\n}\n.news .news__desc[data-v-55cdd5da] {\n font-size: 12px;\n}\n", ""]); // exports /***/ }), /* 24 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_pullToRefresh_vue__ = __webpack_require__(8); /* unused harmony namespace reexport */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_95a3fadc_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_pullToRefresh_vue__ = __webpack_require__(27); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__ = __webpack_require__(2); var disposed = false function injectStyle (context) { if (disposed) return __webpack_require__(25) } /* script */ /* template */ /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = "data-v-95a3fadc" /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = Object(__WEBPACK_IMPORTED_MODULE_2__node_modules_vue_loader_lib_runtime_component_normalizer__["a" /* default */])( __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_selector_type_script_index_0_pullToRefresh_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_95a3fadc_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_pullToRefresh_vue__["a" /* render */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_95a3fadc_hasScoped_true_optionsId_0_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_pullToRefresh_vue__["b" /* staticRenderFns */], __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "src/pullToRefresh.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-95a3fadc", Component.options) } else { hotAPI.reload("data-v-95a3fadc", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["a"] = (Component.exports); /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(26); if(typeof content === 'string') content = [[module.i, content, '']]; if(content.locals) module.exports = content.locals; // add the styles to the DOM var add = __webpack_require__(1).default var update = add("404c1deb", content, false, {}); // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../node_modules/css-loader/index.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"id\":\"data-v-95a3fadc\",\"scoped\":true,\"sourceMap\":false}!../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./pullToRefresh.vue", function() { var newContent = require("!!../node_modules/css-loader/index.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/style-compiler/index.js?{\"optionsId\":\"0\",\"vue\":true,\"id\":\"data-v-95a3fadc\",\"scoped\":true,\"sourceMap\":false}!../node_modules/sass-loader/lib/loader.js?{\"sourceMap\":false}!../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./pullToRefresh.vue"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(0)(false); // imports // module exports.push([module.i, "\n.pull__container[data-v-95a3fadc] {\n position: relative;\n overflow: hidden;\n height: 100%;\n}\n.pull__container .pull__list[data-v-95a3fadc] {\n overflow: scroll;\n height: 100%;\n}\n.pull__container .pull__list .loadMore[data-v-95a3fadc] {\n text-align: center;\n}\n.pull__container .pull__list .loadMore .loadMore__spinner[data-v-95a3fadc] {\n height: 30px;\n animation: rotator-data-v-95a3fadc 1.4s linear infinite;\n margin-top: 10px;\n}\n.pull__container .pull__list .loadMore .loadMore__spinner .path[data-v-95a3fadc] {\n stroke-dasharray: 187;\n stroke-dashoffset: 0;\n transform-origin: center;\n stroke: #01579B;\n animation: dash-data-v-95a3fadc 1.4s ease-in-out infinite;\n}\n.pull__container .pull__spinner_container[data-v-95a3fadc] {\n text-align: center;\n position: absolute;\n width: 100%;\n left: 0;\n top: -40px;\n}\n.pull__container .pull__spinner_container .pull__spinner[data-v-95a3fadc] {\n background-color: #FFFFFF;\n display: inline-block;\n border-radius: 50%;\n height: 34px;\n width: 34px;\n box-shadow: 0px 0px 6px 0px #b1b1b1;\n}\n.pull__container .pull__spinner_container .pull__spinner.pull__spinner--animate[data-v-95a3fadc] {\n transition-property: 0.01s;\n transition-duration: 0.35s;\n transition-timing-function: linear;\n transition-delay: 0s;\n}\n.pull__container .pull__spinner_container .pull__spinner .circle__idle[data-v-95a3fadc] {\n margin-top: 9px;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n display: inline-block;\n border: 8px #01579B;\n border-top: 0;\n border-right: 0;\n border-style: solid;\n position: relative;\n}\n.pull__container .pull__spinner_container .pull__spinner .circle__idle[data-v-95a3fadc]:before {\n content: \" \";\n height: 12px;\n width: 12px;\n background-color: #FFFFFF;\n position: absolute;\n top: 2px;\n border-radius: 50%;\n left: -6px;\n}\n.pull__container .pull__spinner_container .pull__spinner .circle__idle[data-v-95a3fadc]:after {\n content: \" \";\n background-color: #01579B;\n position: absolute;\n top: -2px;\n left: 0;\n border: 3px solid #FFF;\n border-left-color: #01579B;\n}\n.pull__container .pull__spinner_container .pull__spinner .circle__spinner[data-v-95a3fadc] {\n animation: rotator-data-v-95a3fadc 1.4s linear infinite;\n margin-top: 9px;\n height: 16px;\n display: none;\n}\n.pull__container .pull__spinner_container .pull__spinner .circle__spinner .path[data-v-95a3fadc] {\n stroke-dasharray: 187;\n stroke-dashoffset: 0;\n transform-origin: center;\n stroke: #01579B;\n animation: dash-data-v-95a3fadc 1.4s ease-in-out infinite;\n}\n.pull__container .pull__spinner_container .pull__spinner.pull__spinner--active .circle__spinner[data-v-95a3fadc] {\n display: inline-block;\n}\n.pull__container .pull__spinner_container .pull__spinner.pull__spinner--active .circle__idle[data-v-95a3fadc] {\n display: none;\n}\n@keyframes rotator-data-v-95a3fadc {\n0% {\n transform: rotate(0deg);\n}\n100% {\n transform: rotate(270deg);\n}\n}\n@keyframes dash-data-v-95a3fadc {\n0% {\n stroke-dashoffset: 187;\n}\n50% {\n stroke-dashoffset: 46.75;\n transform: rotate(135deg);\n}\n100% {\n stroke-dashoffset: 187;\n transform: rotate(450deg);\n}\n}\n", ""]); // exports /***/ }), /* 27 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "div", { staticClass: "pull__container", on: { touchstart: _vm.touchStart, touchmove: _vm.touchMoving, touchend: _vm.touchEnd } }, [ _vm._t( "top-scroll-container", [ _c("div", { staticClass: "pull__spinner_container" }, [ _c( "div", { staticClass: "pull__spinner", class: _vm.spinnerClass, style: { transform: "translateY(" + _vm.transformYValue + "px) rotate(" + _vm.transformYValue * 5 + "deg)" } }, [ _c("div", { staticClass: "circle__idle" }), _vm._v(" "), _c( "svg", { staticClass: "circle__spinner", attrs: { viewBox: "0 0 66 66", xmlns: "http://www.w3.org/2000/svg" } }, [ _c("circle", { staticClass: "path", attrs: { fill: "none", "stroke-width": "6", "stroke-linecap": "round", cx: "33", cy: "33", r: "30" } }) ] ) ] ) ]) ], { state: _vm.state } ), _vm._v(" "), _c( "div", { ref: "list", staticClass: "pull__list", on: { scroll: _vm.scrolling } }, [ _vm._t("default"), _vm._v(" "), _vm.isLoadMoreLoading ? _c("div", { staticClass: "loadMore" }, [ _c( "svg", { staticClass: "loadMore__spinner", attrs: { viewBox: "0 0 66 66", xmlns: "http://www.w3.org/2000/svg" } }, [ _c("circle", { staticClass: "path", attrs: { fill: "none", "stroke-width": "6", "stroke-linecap": "round", cx: "33", cy: "33", r: "30" } }) ] ) ]) : _vm._e() ], 2 ) ], 2 ) } var staticRenderFns = [] render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-95a3fadc", { render: render, staticRenderFns: staticRenderFns }) } } /***/ }), /* 28 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var url = 'https://newsapi.org/v2/everything?' + 'q=bollywood&' + 'apiKey=8f302ce5a8e9486dab884dd9071b971c'; /* harmony default export */ __webpack_exports__["a"] = ({ getNews(payload) { return fetch(new Request(`${url}&pageSize=${payload.pageSize}&page=${payload.pageNumber}`)) .then(function (response) { return response.json(); }) } }); /***/ }), /* 29 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "div", { staticClass: "news__list" }, [ _c( "pull-to-refresh", { ref: "list", attrs: { triggerRefreshOnMounted: true }, on: { refresh: _vm.refresh, triggerScroll: _vm.infiniteScroll } }, _vm._l(_vm.articles, function(article, key) { return _c("div", { key: key, staticClass: "news" }, [ _c("h4", { staticClass: "news__title" }, [ _vm._v(_vm._s(article.title)) ]), _vm._v(" "), _c("p", { staticClass: "news__desc" }, [ _vm._v(_vm._s(article.description)) ]) ]) }) ) ], 1 ) } var staticRenderFns = [] render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-55cdd5da", { render: render, staticRenderFns: staticRenderFns }) } } /***/ }), /* 30 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "div", [ _c("TopHeader"), _vm._v(" "), _c("div", { staticClass: "container" }, [_c("PullDown")], 1) ], 1 ) } var staticRenderFns = [] render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api") .rerender("data-v-88f7d72e", { render: render, staticRenderFns: staticRenderFns }) } } /***/ }) /******/ ]);
/* The MIT License (MIT) Copyright (C) 2017 Vsevolod Stakhov <[email protected]> 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. */ define(["jquery"], function ($) { "use strict"; var ui = {}; function cleanTextUpload(source) { $("#" + source + "TextSource").val(""); } // @upload text function uploadText(rspamd, data, source, headers) { var url = null; if (source === "spam") { url = "learnspam"; } else if (source === "ham") { url = "learnham"; } else if (source === "fuzzy") { url = "fuzzyadd"; } else if (source === "scan") { url = "checkv2"; } rspamd.query(url, { data: data, params: { processData: false, }, method: "POST", headers: headers, success: function (json, jqXHR) { cleanTextUpload(source); rspamd.alertMessage("alert-success", "Data successfully uploaded"); if (jqXHR.status !== 200) { rspamd.alertMessage("alert-info", jqXHR.statusText); } } }); } function columns_v2() { return [{ name: "id", title: "ID", style: { "font-size": "11px", "minWidth": 130, "overflow": "hidden", "textOverflow": "ellipsis", "wordBreak": "break-all", "whiteSpace": "normal" } }, { name: "action", title: "Action", style: { "font-size": "11px", "minwidth": 82 } }, { name: "score", title: "Score", style: { "font-size": "11px", "maxWidth": 110 }, sortValue: function (val) { return Number(val.options.sortValue); } }, { name: "symbols", title: "Symbols<br /><br />" + '<span style="font-weight:normal;">Sort by:</span><br />' + '<div class="btn-group btn-group-toggle btn-group-xs btn-sym-order-scan" data-toggle="buttons">' + '<label type="button" class="btn btn-outline-secondary btn-sym-scan-magnitude">' + '<input type="radio" value="magnitude">Magnitude</label>' + '<label type="button" class="btn btn-outline-secondary btn-sym-scan-score">' + '<input type="radio" value="score">Value</label>' + '<label type="button" class="btn btn-outline-secondary btn-sym-scan-name">' + '<input type="radio" value="name">Name</label>' + "</div>", breakpoints: "all", style: { "font-size": "11px", "width": 550, "maxWidth": 550 } }, { name: "time_real", title: "Scan time", breakpoints: "xs sm md", style: { "font-size": "11px", "maxWidth": 72 }, sortValue: function (val) { return Number(val); } }, { sorted: true, direction: "DESC", name: "time", title: "Time", style: { "font-size": "11px" }, sortValue: function (val) { return Number(val.options.sortValue); } }]; } // @upload text function scanText(rspamd, tables, data, server) { rspamd.query("checkv2", { data: data, params: { processData: false, }, method: "POST", success: function (neighbours_status) { var json = neighbours_status[0].data; if (json.action) { rspamd.alertMessage("alert-success", "Data successfully scanned"); var rows_total = $("#historyTable_scan > tbody > tr:not(.footable-detail-row)").length + 1; var o = rspamd.process_history_v2(rspamd, {rows:[json]}, "scan"); var items = o.items; rspamd.symbols.scan.push(o.symbols[0]); if (Object.prototype.hasOwnProperty.call(tables, "scan")) { tables.scan.rows.load(items, true); // Is there a way to get an event when all rows are loaded? rspamd.waitForRowsDisplayed("scan", rows_total, function () { rspamd.drawTooltips(); $("html, body").animate({ scrollTop: $("#scanResult").offset().top }, 1000); }); } else { rspamd.destroyTable("scan"); // Is there a way to get an event when the table is destroyed? setTimeout(function () { rspamd.initHistoryTable(rspamd, data, items, "scan", columns_v2(), true); rspamd.waitForRowsDisplayed("scan", rows_total, function () { $("html, body").animate({ scrollTop: $("#scanResult").offset().top }, 1000); }); }, 200); } } else { rspamd.alertMessage("alert-error", "Cannot scan data"); } }, errorMessage: "Cannot upload data", statusCode: { 404: function () { rspamd.alertMessage("alert-error", "Cannot upload data, no server found"); }, 500: function () { rspamd.alertMessage("alert-error", "Cannot tokenize message: no text data"); }, 503: function () { rspamd.alertMessage("alert-error", "Cannot tokenize message: no text data"); } }, server: server }); } ui.setup = function (rspamd, tables) { rspamd.set_page_size("scan", $("#scan_page_size").val()); rspamd.bindHistoryTableEventHandlers("scan", 3); $("#cleanScanHistory").off("click"); $("#cleanScanHistory").on("click", function (e) { e.preventDefault(); if (!confirm("Are you sure you want to clean scan history?")) { // eslint-disable-line no-alert return; } rspamd.destroyTable("scan"); rspamd.symbols.scan.length = 0; }); function enable_disable_scan_btn() { $("#scan button").prop("disabled", ($.trim($("textarea").val()).length === 0)); } enable_disable_scan_btn(); $("textarea").on("input", function () { enable_disable_scan_btn(); }); $("#scanClean").on("click", function () { $("#scan button").attr("disabled", true); $("#scanMsgSource").val(""); $("#scanResult").hide(); $("#scanOutput tbody").remove(); $("html, body").animate({scrollTop:0}, 1000); return false; }); // @init upload $("[data-upload]").on("click", function () { var source = $(this).data("upload"); var data = $("#scanMsgSource").val(); var headers = (source === "fuzzy") ? { flag: $("#fuzzyFlagText").val(), weight: $("#fuzzyWeightText").val() } : {}; if ($.trim(data).length > 0) { if (source === "scan") { var checked_server = rspamd.getSelector("selSrv"); var server = (checked_server === "All SERVERS") ? "local" : checked_server; scanText(rspamd, tables, data, server); } else { uploadText(rspamd, data, source, headers); } } else { rspamd.alertMessage("alert-error", "Message source field cannot be blank"); } return false; }); }; return ui; });
import React, { Component } from 'react'; import PageTitle from '../pageTitle'; // REDUX import { connect } from 'react-redux'; import * as actions from '../../actions'; import PaymentForm from './paymentForm'; class Payment extends Component { componentDidMount() { this.props.setHeaderLinks([]); this.props.setNavbarLinks([]); } onSubmit = (fields) => { console.log(fields); } render() { return ( <div className='payment'> <PageTitle className='payment__page-title' title='Payment Information' /> <PaymentForm onSubmit={this.onSubmit} className='payment__form' /> </div> ) } } Payment = connect(null, actions)(Payment); export default Payment;
var callbackArguments = []; var argument1 = function() { callbackArguments.push(arguments) return true; }; var argument2 = true; var argument3 = function() { callbackArguments.push(arguments) return "‹Œ"; }; var argument4 = [1.7976931348623157e+308,969,59,-1,213]; var argument5 = r_0; var argument6 = function() { callbackArguments.push(arguments) return -82; }; var argument7 = function() { callbackArguments.push(arguments) return "\u0015±kh\u0003\u001c\bn `"; }; var base_0 = ["[Kv","n","?t"] var r_0= undefined try { r_0 = base_0.reduceRight(argument1,argument2) } catch(e) { r_0= "Error" } var base_1 = ["[Kv","n","?t"] var r_1= undefined try { r_1 = base_1.reduceRight(argument3,argument4,argument5) } catch(e) { r_1= "Error" } var base_2 = ["[Kv","n","?t"] var r_2= undefined try { r_2 = base_2.reduceRight(argument6) } catch(e) { r_2= "Error" } var base_3 = ["[Kv","n","?t"] var r_3= undefined try { r_3 = base_3.reduceRight(argument7) } catch(e) { r_3= "Error" } function serialize(array){ return array.map(function(a){ if (a === null || a == undefined) return a; var name = a.constructor.name; if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String') return JSON.stringify(a); return name; }); } setTimeout(function(){ require("fs").writeFileSync("./experiments/reduceRight/reduceRightQC/test55.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments})) },300)
/** * HYPERLOOP GENERATED - DO NOT MODIFY * * This source code is Copyright (c) 2018 by Appcelerator, Inc. * All Rights Reserved. This code contains patents and/or patents pending. */ var $dispatch = Hyperloop.dispatch, $init, $imports; /** * CoreText//Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.3.sdk/System/Library/Frameworks/CoreText.framework/Headers/SFNTLayoutTypes.h * @class */ function KerxSimpleArrayHeader (pointer) { if (pointer) { var oldWrapper = Hyperloop.getWrapper(pointer); if (oldWrapper) return oldWrapper; } if (!(this instanceof KerxSimpleArrayHeader)) { throw new TypeError('Cannot instantiate a class by calling it as a function'); } if (!$init) { $initialize(); } if (!pointer) { pointer = Hyperloop.createPointer('{KerxSimpleArrayHeader=IIII[1I]}', 'CoreText', '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.3.sdk/System/Library/Frameworks/CoreText.framework/Headers/SFNTLayoutTypes'); } Object.defineProperty(this, '$native', { value: pointer, writable: false, enumerable: true, configurable: false }); Hyperloop.registerWrapper(this); } function $initialize () { $imports = {}; KerxSimpleArrayHeader._imports = $imports; // properties Object.defineProperties(KerxSimpleArrayHeader.prototype, { rowWidth: { get: function () { return $dispatch(this.$native, 'valueAtIndex:', 0); }, set: function (_rowWidth) { $dispatch(this.$native, 'setValue:atIndex:', [_rowWidth, 0]); }, enumerable: false }, leftOffsetTable: { get: function () { return $dispatch(this.$native, 'valueAtIndex:', 1); }, set: function (_leftOffsetTable) { $dispatch(this.$native, 'setValue:atIndex:', [_leftOffsetTable, 1]); }, enumerable: false }, rightOffsetTable: { get: function () { return $dispatch(this.$native, 'valueAtIndex:', 2); }, set: function (_rightOffsetTable) { $dispatch(this.$native, 'setValue:atIndex:', [_rightOffsetTable, 2]); }, enumerable: false }, theArray: { get: function () { return $dispatch(this.$native, 'valueAtIndex:', 3); }, set: function (_theArray) { $dispatch(this.$native, 'setValue:atIndex:', [_theArray, 3]); }, enumerable: false }, firstTable: { get: function () { return $dispatch(this.$native, 'valueAtIndex:', 4); }, set: function (_firstTable) { $dispatch(this.$native, 'setValue:atIndex:', [_firstTable, 4]); }, enumerable: false } }); $init = true; } module.exports = KerxSimpleArrayHeader;
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _default = (0, _createSvgIcon["default"])( /*#__PURE__*/React.createElement("path", { d: "M18 7c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm2 8c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-8 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM6 5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm12-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6 6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-6c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z" }), 'DialpadTwoTone'); exports["default"] = _default;
import React, { useEffect, useCallback, useState } from 'react'; import PropTypes from 'prop-types'; import { TeamItemContainer, TeamName, TeamResponsibility, TeamBio, TeamAvatar, PostItemLink, } from './styled'; import api from '../../services/api'; const PostItem = ({ link, avatar, name, responsibility }) => { const [dev, setDev] = useState({}); const loadDev = useCallback(async () => { const { data: { avatar_url, bio }, } = await api.get(`${avatar}`); setDev({ avatar: avatar_url, bio, }); }); useEffect(() => { loadDev(); console.log(dev); }, []); return ( <TeamItemContainer> <PostItemLink> <TeamAvatar src={dev.avatar} alt="Perfil" /> <TeamName>{name}</TeamName> </PostItemLink> <TeamResponsibility>{responsibility}</TeamResponsibility> <TeamBio>{dev.bio}</TeamBio> </TeamItemContainer> ); }; PostItem.propTypes = { link: PropTypes.string.isRequired, avatar: PropTypes.string.isRequired, name: PropTypes.string.isRequired, responsibility: PropTypes.string.isRequired, }; export default PostItem;
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ import { _ as _objectWithoutProperties, I as Icon, a as _extends } from '../Icon-63ed8f4f.js'; import '@carbon/icon-helpers'; import 'prop-types'; import React from 'react'; var _ref2 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M27.167 16.89L21.72 13 27.167 9.109 29.684 9.948 30.316 8.051 28 7.279 28 5 26 5 26 7.485 21 11.057 21 5.367 23.555 3.664 22.445 2 20 3.63 17.555 2 16.445 3.664 19 5.367 19 11.057 16 8.914 16 11.372 18.28 13 16 14.628 16 17.086 19 14.943 19 21.703 22.445 24 23.555 22.336 21 20.633 21 14.943 26 18.515 26 21 28 21 28 18.721 30.316 17.948 29.684 16.051 27.167 16.89zM12 23a3 3 0 01-6 0z" }); var _ref3 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M9,30A6.9931,6.9931,0,0,1,4,18.1108V7A5,5,0,0,1,14,7V18.1108A6.9931,6.9931,0,0,1,9,30ZM9,4A3.0033,3.0033,0,0,0,6,7V18.9834l-.332.2983a5,5,0,1,0,6.664,0L12,18.9834V7A3.0033,3.0033,0,0,0,9,4Z" }); var TemperatureFrigid32 = /*#__PURE__*/React.forwardRef(function TemperatureFrigid32(_ref, ref) { var children = _ref.children, rest = _objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React.createElement(Icon, _extends({ width: 32, height: 32, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _ref2, _ref3, children); }); export default TemperatureFrigid32;
/* * Copyright (c) 2015 Jonathan Perkin <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var binding = require('bindings')('rpio'); var fs = require('fs'); var util = require('util'); var EventEmitter = require('events').EventEmitter; /* * Event Emitter gloop. */ function rpio() { EventEmitter.call(this); } util.inherits(rpio, EventEmitter); module.exports = new rpio; /* * Constants. */ rpio.prototype.LOW = 0x0; rpio.prototype.HIGH = 0x1; /* * Supported function select modes. INPUT and OUTPUT match the bcm2835 * function select integers. PWM is handled specially. */ rpio.prototype.INPUT = 0x0; rpio.prototype.OUTPUT = 0x1; rpio.prototype.PWM = 0x2; /* * Configure builtin pullup/pulldown resistors. */ rpio.prototype.PULL_OFF = 0x0; rpio.prototype.PULL_DOWN = 0x1; rpio.prototype.PULL_UP = 0x2; /* * Pin edge detect events. Default to both. */ rpio.prototype.POLL_LOW = 0x1; /* Falling edge detect */ rpio.prototype.POLL_HIGH = 0x2; /* Rising edge detect */ rpio.prototype.POLL_BOTH = 0x3; /* POLL_LOW | POLL_HIGH */ /* * Reset pin status on close (default), or preserve current status. */ rpio.prototype.PIN_PRESERVE = 0x0; rpio.prototype.PIN_RESET = 0x1; /* * GPIO Pad Control */ rpio.prototype.PAD_GROUP_0_27 = 0x0; rpio.prototype.PAD_GROUP_28_45 = 0x1; rpio.prototype.PAD_GROUP_46_53 = 0x2; rpio.prototype.PAD_DRIVE_2mA = 0x00; rpio.prototype.PAD_DRIVE_4mA = 0x01; rpio.prototype.PAD_DRIVE_6mA = 0x02; rpio.prototype.PAD_DRIVE_8mA = 0x03; rpio.prototype.PAD_DRIVE_10mA = 0x04; rpio.prototype.PAD_DRIVE_12mA = 0x05; rpio.prototype.PAD_DRIVE_14mA = 0x06; rpio.prototype.PAD_DRIVE_16mA = 0x07; rpio.prototype.PAD_HYSTERESIS = 0x08; rpio.prototype.PAD_SLEW_UNLIMITED = 0x10; /* * Default pin mode is 'physical'. Other option is 'gpio' */ var rpio_inited = false; var rpio_options = { gpiomem: true, mapping: 'physical', mock: false, }; /* Default mock mode if hardware is unsupported. */ var defmock = 'raspi-3'; /* * Wrapper functions. */ function bindcall(bindfunc, optarg) { if (rpio_options.mock) return; return bindfunc(optarg); } function bindcall2(bindfunc, arg1, arg2) { if (rpio_options.mock) return; return bindfunc(arg1, arg2); } function bindcall3(bindfunc, arg1, arg2, arg3) { if (rpio_options.mock) return; return bindfunc(arg1, arg2, arg3); } function warn(msg) { console.error('WARNING: ' + msg); } /* * Map physical pin to BCM GPIOxx numbering. There are currently three * layouts: * * PINMAP_26_R1: 26-pin early original models A and B (PCB rev 1.0) * PINMAP_26: 26-pin standard models A and B (PCB rev 2.0) * PINMAP_40: 40-pin models * * A -1 indicates an unusable pin. Each table starts with a -1 so that we * can index into the array by pin number. */ var pincache = {}; var pinmap = null; var pinmaps = { /* * Original Raspberry Pi, PCB revision 1.0 */ PINMAP_26_R1: [ -1, -1, -1, /* P1 P2 */ 0, -1, /* P3 P4 */ 1, -1, /* P5 P6 */ 4, 14, /* P7 P8 */ -1, 15, /* P9 P10 */ 17, 18, /* P11 P12 */ 21, -1, /* P13 P14 */ 22, 23, /* P15 P16 */ -1, 24, /* P17 P18 */ 10, -1, /* P19 P20 */ 9, 25, /* P21 P22 */ 11, 8, /* P23 P24 */ -1, 7 /* P25 P26 */ ], /* * Original Raspberry Pi, PCB revision 2.0. * * Differs to R1 on pins 3, 5, and 13. * * XXX: no support yet for the P5 header pins. */ PINMAP_26: [ -1, -1, -1, /* P1 P2 */ 2, -1, /* P3 P4 */ 3, -1, /* P5 P6 */ 4, 14, /* P7 P8 */ -1, 15, /* P9 P10 */ 17, 18, /* P11 P12 */ 27, -1, /* P13 P14 */ 22, 23, /* P15 P16 */ -1, 24, /* P17 P18 */ 10, -1, /* P19 P20 */ 9, 25, /* P21 P22 */ 11, 8, /* P23 P24 */ -1, 7 /* P25 P26 */ ], /* * Raspberry Pi 40-pin models. * * First 26 pins are the same as PINMAP_26. */ PINMAP_40: [ -1, -1, -1, /* P1 P2 */ 2, -1, /* P3 P4 */ 3, -1, /* P5 P6 */ 4, 14, /* P7 P8 */ -1, 15, /* P9 P10 */ 17, 18, /* P11 P12 */ 27, -1, /* P13 P14 */ 22, 23, /* P15 P16 */ -1, 24, /* P17 P18 */ 10, -1, /* P19 P20 */ 9, 25, /* P21 P22 */ 11, 8, /* P23 P24 */ -1, 7, /* P25 P26 */ 0, 1, /* P27 P28 */ 5, -1, /* P29 P30 */ 6, 12, /* P31 P32 */ 13, -1, /* P33 P34 */ 19, 16, /* P35 P36 */ 26, 20, /* P37 P38 */ -1, 21 /* P39 P40 */ ] } /* * Pin event polling. We track which pins are being monitored, and create a * bitmask for efficient checks. The event_poll function is executed in a * setInterval() context whenever any pins are being monitored, and emits * events when their EDS bit is set. */ var event_pins = {}; var event_mask = 0x0; var event_running = false; function event_poll() { var active = bindcall(binding.gpio_event_poll, event_mask); for (gpiopin in event_pins) { if (active & (1 << gpiopin)) module.exports.emit('pin' + gpiopin); } } /* * Set up GPIO mapping based on board revision. */ function detect_pinmap() { var cpuinfo, boardrev, match; try { cpuinfo = fs.readFileSync('/proc/cpuinfo', 'ascii'); } catch (err) { return false; } if (!cpuinfo) return false; cpuinfo.toString().split(/\n/).forEach(function(line) { match = line.match(/^Revision.*(.{4})/); if (match) { boardrev = parseInt(match[1], 16); return; } }); switch (boardrev) { case 0x2: case 0x3: pinmap = 'PINMAP_26_R1'; break; case 0x4: case 0x5: case 0x6: case 0x7: case 0x8: case 0x9: case 0xd: case 0xe: case 0xf: pinmap = 'PINMAP_26'; break; case 0x10: case 0x12: case 0x13: case 0x15: case 0x92: case 0x93: case 0xc1: case 0x1041: case 0x2042: case 0x2082: case 0x20d3: pinmap = 'PINMAP_40'; break; default: return false; } return true; } function set_mock_pinmap() { switch (rpio_options.mock) { case 'raspi-b-r1': pinmap = 'PINMAP_26_R1'; break; case 'raspi-a': case 'raspi-b': pinmap = 'PINMAP_26'; break; case 'raspi-a+': case 'raspi-b+': case 'raspi-2': case 'raspi-3': case 'raspi-zero': case 'raspi-zero-w': pinmap = 'PINMAP_40'; break; default: return false; } return true; } function pin_to_gpio(pin) { if (pincache[pin]) return pincache[pin]; switch (rpio_options.mapping) { case 'physical': if (pinmaps[pinmap][pin] == -1 || pinmaps[pinmap][pin] == null) throw new Error('Invalid pin: ' + pin); pincache[pin] = pinmaps[pinmap][pin]; break; case 'gpio': if (pinmaps[pinmap].indexOf(pin) === -1) throw new Error('Invalid pin: ' + pin); pincache[pin] = pin; break; default: throw new Error('Unsupported GPIO mode'); } return pincache[pin]; } function check_sys_gpio(pin) { if (fs.existsSync('/sys/class/gpio/gpio' + pin)) throw new Error('GPIO' + pin + ' is currently in use by /sys/class/gpio'); } function get_pwm_function(pin) { var gpiopin = pin_to_gpio(pin); switch (gpiopin) { case 12: case 13: return 4; /* BCM2835_GPIO_FSEL_ALT0 */ case 18: case 19: return 2; /* BCM2835_GPIO_FSEL_ALT5 */ default: throw new Error('Pin ' + pin + ' does not support hardware PWM'); } } function get_pwm_channel(pin) { var gpiopin = pin_to_gpio(pin); switch (gpiopin) { case 12: case 18: return 0; case 13: case 19: return 1; default: throw new Error('Unknown PWM channel for pin ' + pin); } } function set_pin_pwm(pin) { var gpiopin = pin_to_gpio(pin); var channel, func; if (rpio_options.gpiomem) throw new Error('PWM not available in gpiomem mode'); check_sys_gpio(gpiopin); /* * PWM channels and alternate functions differ from pin to pin, set * them up appropriately based on selected pin. */ channel = get_pwm_channel(pin); func = get_pwm_function(pin); bindcall2(binding.gpio_function, gpiopin, func); /* * For now we assume mark-space mode, balanced is unsupported. */ bindcall3(binding.pwm_set_mode, channel, 1, 1); } /* * GPIO */ /* * Default warning handler, if the user registers their own then this one * is cancelled. */ function default_warn_handler(msg) { if (module.exports.listenerCount('warn') > 1) { module.exports.removeListener('warn', default_warn_handler); return; } warn(msg); } module.exports.on('warn', default_warn_handler); rpio.prototype.init = function(opts) { opts = opts || {}; for (var k in rpio_options) { if (k in opts) rpio_options[k] = opts[k]; } /* * Invalidate the pin cache and mapping as we may be in the process * of changing them. */ pincache = {}; pinmap = null; /* * Allow the user to specify a mock board to emulate, otherwise try * to autodetect the board, and fall back to mock mode if running on * an unsupported platform. */ if (rpio_options.mock) { if (!set_mock_pinmap()) throw new Error('Unsupported mock mode ' + rpio_options.mock); } else { if (!detect_pinmap()) { module.exports.emit('warn', 'Hardware auto-detect failed, running in ' + defmock + ' mock mode'); rpio_options.mock = defmock; set_mock_pinmap(); } } /* * Open the bcm2835 driver. */ bindcall(binding.rpio_init, Number(rpio_options.gpiomem)); rpio_inited = true; } rpio.prototype.open = function(pin, mode, init) { if (!rpio_inited) { /* PWM requires full /dev/mem */ if (mode === rpio.prototype.PWM) rpio_options.gpiomem = false; rpio.prototype.init(); } var gpiopin = pin_to_gpio(pin); check_sys_gpio(gpiopin); switch (mode) { case rpio.prototype.INPUT: if (init !== undefined) bindcall2(binding.gpio_pud, gpiopin, init); return bindcall2(binding.gpio_function, gpiopin, rpio.prototype.INPUT); case rpio.prototype.OUTPUT: if (init !== undefined) bindcall2(binding.gpio_write, gpiopin, init); return bindcall2(binding.gpio_function, gpiopin, rpio.prototype.OUTPUT); case rpio.prototype.PWM: return set_pin_pwm(pin); default: throw new Error('Unsupported mode ' + mode); } } rpio.prototype.mode = function(pin, mode) { var gpiopin = pin_to_gpio(pin); switch (mode) { case rpio.prototype.INPUT: return bindcall2(binding.gpio_function, gpiopin, rpio.prototype.INPUT); case rpio.prototype.OUTPUT: return bindcall2(binding.gpio_function, gpiopin, rpio.prototype.OUTPUT); case rpio.prototype.PWM: return set_pin_pwm(pin); default: throw new Error('Unsupported mode ' + mode); } } rpio.prototype.read = function(pin) { return bindcall(binding.gpio_read, pin_to_gpio(pin)); } rpio.prototype.readbuf = function(pin, buf, len) { if (len === undefined) len = buf.length; if (len > buf.length) throw new Error('Buffer not large enough to accommodate request'); return bindcall3(binding.gpio_readbuf, pin_to_gpio(pin), buf, len); } rpio.prototype.write = function(pin, value) { return bindcall2(binding.gpio_write, pin_to_gpio(pin), value); } rpio.prototype.writebuf = function(pin, buf, len) { if (len === undefined) len = buf.length; if (len > buf.length) throw new Error('Buffer not large enough to accommodate request'); return bindcall3(binding.gpio_writebuf, pin_to_gpio(pin), buf, len); } rpio.prototype.readpad = function(group) { if (rpio_options.gpiomem) throw new Error('Pad control not available in gpiomem mode'); return bindcall(binding.gpio_pad_read, group); } rpio.prototype.writepad = function(group, control) { if (rpio_options.gpiomem) throw new Error('Pad control not available in gpiomem mode'); bindcall2(binding.gpio_pad_write, group, control); } rpio.prototype.pud = function(pin, state) { bindcall2(binding.gpio_pud, pin_to_gpio(pin), state); } rpio.prototype.poll = function(pin, cb, direction) { var gpiopin = pin_to_gpio(pin); if (direction === undefined) direction = rpio.prototype.POLL_BOTH; /* * If callback is a function, set up pin for polling, otherwise * clear it. */ if (typeof(cb) === 'function') { if (gpiopin in event_pins) throw new Error('Pin ' + pin + ' is already listening for events.'); bindcall2(binding.gpio_event_set, gpiopin, direction); var pincb = function() { cb(pin); }; module.exports.on('pin' + gpiopin, pincb); event_pins[gpiopin] = pincb; event_mask |= (1 << gpiopin); if (!(event_running)) event_running = setInterval(event_poll, 1); } else { if (!(gpiopin in event_pins)) throw new Error('Pin ' + pin + ' is not listening for events.'); bindcall(binding.gpio_event_clear, gpiopin); rpio.prototype.removeListener('pin' + gpiopin, event_pins[gpiopin]); delete event_pins[gpiopin]; event_mask &= ~(1 << gpiopin); if (Object.keys(event_pins).length === 0) { clearInterval(event_running); event_running = false; } } } rpio.prototype.close = function(pin, reset) { var gpiopin = pin_to_gpio(pin); if (reset === undefined) reset = rpio.prototype.PIN_RESET; if (gpiopin in event_pins) rpio.prototype.poll(pin, null); if (reset) { if (!rpio_options.gpiomem) rpio.prototype.pud(pin, rpio.prototype.PULL_OFF); rpio.prototype.mode(pin, rpio.prototype.INPUT); } } /* * PWM */ rpio.prototype.pwmSetClockDivider = function(divider) { if (divider !== 0 && (divider & (divider - 1)) !== 0) throw new Error('Clock divider must be zero or power of two'); return bindcall(binding.pwm_set_clock, divider); } rpio.prototype.pwmSetRange = function(pin, range) { var channel = get_pwm_channel(pin); return bindcall2(binding.pwm_set_range, channel, range); } rpio.prototype.pwmSetData = function(pin, data) { var channel = get_pwm_channel(pin); return bindcall2(binding.pwm_set_data, channel, data); } /* * i2c */ rpio.prototype.i2cBegin = function() { if (!rpio_inited) { /* i2c requires full /dev/mem */ rpio_options.gpiomem = false; rpio.prototype.init(); } if (rpio_options.gpiomem) throw new Error('i2c not available in gpiomem mode'); bindcall(binding.i2c_begin); } rpio.prototype.i2cSetSlaveAddress = function(addr) { return bindcall(binding.i2c_set_slave_address, addr); } rpio.prototype.i2cSetClockDivider = function(divider) { if ((divider % 2) !== 0) throw new Error('Clock divider must be an even number'); return bindcall(binding.i2c_set_clock_divider, divider); } rpio.prototype.i2cSetBaudRate = function(baud) { return bindcall(binding.i2c_set_baudrate, baud); } rpio.prototype.i2cRead = function(buf, len) { if (len === undefined) len = buf.length; if (len > buf.length) throw new Error('Buffer not large enough to accommodate request'); return bindcall2(binding.i2c_read, buf, len); } rpio.prototype.i2cWrite = function(buf, len) { if (len === undefined) len = buf.length; if (len > buf.length) throw new Error('Buffer not large enough to accommodate request'); return bindcall2(binding.i2c_write, buf, len); } rpio.prototype.i2cEnd = function() { bindcall(binding.i2c_end); } /* * SPI */ rpio.prototype.spiBegin = function() { if (!rpio_inited) { /* SPI requires full /dev/mem */ rpio_options.gpiomem = false; rpio.prototype.init(); } if (rpio_options.gpiomem) throw new Error('SPI not available in gpiomem mode'); bindcall(binding.spi_begin); } rpio.prototype.spiChipSelect = function(cs) { return bindcall(binding.spi_chip_select, cs); } rpio.prototype.spiSetCSPolarity = function(cs, active) { return bindcall2(binding.spi_set_cs_polarity, cs, active); } rpio.prototype.spiSetClockDivider = function(divider) { if ((divider % 2) !== 0 || divider < 0 || divider > 65536) throw new Error('Clock divider must be an even number between 0 and 65536'); return bindcall(binding.spi_set_clock_divider, divider); } rpio.prototype.spiSetDataMode = function(mode) { return bindcall(binding.spi_set_data_mode, mode); } rpio.prototype.spiTransfer = function(txbuf, rxbuf, len) { return bindcall3(binding.spi_transfer, txbuf, rxbuf, len); } rpio.prototype.spiWrite = function(buf, len) { return bindcall2(binding.spi_write, buf, len); } rpio.prototype.spiEnd = function() { bindcall(binding.spi_end); } /* * Misc functions. */ rpio.prototype.sleep = function(secs) { bindcall(binding.rpio_usleep, secs * 1000000); } rpio.prototype.msleep = function(msecs) { bindcall(binding.rpio_usleep, msecs * 1000); } rpio.prototype.usleep = function(usecs) { bindcall(binding.rpio_usleep, usecs); } process.on('exit', function(code) { bindcall(binding.rpio_close); });
/** * Eco Compiler v1.1.0-rc-3 * http://github.com/sstephenson/eco * * Copyright (c) 2011 Sam Stephenson * Released under the MIT License */ this.eco=function(e){return function t(n){var r,i={id:n,exports:{}};if(r=e[n])return r(i,t,i.exports),i.exports;throw"Cannot find module '"+n+"'"}}({eco:function(e,t,n){(function(){var n,r,i,s,o;o=t("./compiler"),n=o.compile,i=o.precompile,s=t("./preprocessor").preprocess,e.exports=r=function(e){var t,i;return r.cache?(i=(t=r.cache)[e])!=null?i:t[e]=n(e):n(e)},r.cache={},r.preprocess=s,r.precompile=i,r.compile=n,r.render=function(e,t){return r(e)(t)},t.extensions&&(t.extensions[".eco"]=function(e,n){var r;return r=t("fs").readFileSync(n,"utf-8"),e._compile("module.exports = "+i(r),n)})}).call(this)},"./compiler":function(e,t,n){(function(){var e,r,i,s;e=t("coffee-script"),s=t("./preprocessor").preprocess,r=t("./util").indent,n.precompile=i=function(t){var n;return n=e.compile(s(t),{noWrap:!0}),"eco(\n function(__out, __capture, __sanitize, __safe, __objSafe, __escape){\n"+r(n,4)+"\n }\n)"},n.compile=function(e){return(new Function("return "+i(e)))()}}).call(this)},"./preprocessor":function(e,t,n){(function(){var n,r,i;r=t("./scanner"),i=t("./util"),e.exports=n=function(){function e(e){this.scanner=new r(e),this.output="",this.level=0,this.options={},this.captures=[]}return e.preprocess=function(t){var n;return n=new e(t),n.preprocess()},e.prototype.preprocess=function(){var e=this;while(!this.scanner.done)this.scanner.scan(function(t){return e[t[0]].apply(e,t.slice(1))});return this.output},e.prototype.record=function(e){return this.output+=i.repeat(" ",this.level),this.output+=e+"\n"},e.prototype.printString=function(e){if(e.length)return this.record("__out.push "+i.inspectString(e))},e.prototype.beginCode=function(e){return this.options=e},e.prototype.recordCode=function(e){if(e!=="end")return this.options.print?this.options.safe?this.record("__out.push "+e):this.record("__out.push __sanitize "+e):this.record(e)},e.prototype.indent=function(e){this.level++;if(e)return this.record("__capture "+e),this.captures.unshift(this.level),this.indent()},e.prototype.dedent=function(){this.level--,this.level<0&&this.fail("unexpected dedent");if(this.captures[0]===this.level)return this.captures.shift(),this.dedent()},e.prototype.fail=function(e){throw"Parse error on line "+this.scanner.lineNo+": "+e},e}()}).call(this)},"./scanner":function(e,t,n){(function(){var n,r,i;r=t("strscan").StringScanner,i=t("./util").trim,e.exports=n=function(){function e(e){this.source=e.replace(/\r\n?/g,"\n"),this.scanner=new r(this.source),this.mode="data",this.buffer="",this.lineNo=1,this.done=!1}return e.modePatterns={data:/(.*?)(<%%|<%\s*(\#)|<%(([=-])?)|\n|$)/,code:/(.*?)((((:|(->|=>))\s*))?%>|\n|$)/,comment:/(.*?)(%>|\n|$)/},e.dedentablePattern=/^(end|when|else|catch|finally)(?:\W|$)/,e.scan=function(t){var n,r;r=[],n=new e(t);while(!n.done)n.scan(function(e){return r.push(e)});return r},e.prototype.scan=function(e){if(this.done)return e();if(this.scanner.hasTerminated()){this.done=!0;switch(this.mode){case"data":return e(["printString",this.flush()]);case"code":return e(["fail","unexpected end of template"])}}else{this.advance();switch(this.mode){case"data":return this.scanData(e);case"code":return this.scanCode(e);case"comment":return this.scanComment(e)}}},e.prototype.advance=function(){return this.scanner.scanUntil(e.modePatterns[this.mode]),this.buffer+=this.scanner.getCapture(0),this.tail=this.scanner.getCapture(1),this.comment=this.scanner.getCapture(2),this.directive=this.scanner.getCapture(4),this.arrow=this.scanner.getCapture(5)},e.prototype.scanData=function(e){if(this.tail==="<%%")return this.buffer+="<%",this.scan(e);if(this.tail==="\n")return this.buffer+=this.tail,this.lineNo++,this.scan(e);if(this.tail)return e(["printString",this.flush()]),this.comment?this.mode="comment":(this.mode="code",e(["beginCode",{print:this.directive!=null,safe:this.directive==="-"}]))},e.prototype.scanCode=function(e){var t;if(this.tail==="\n")return e(["fail","unexpected newline in code block"]);if(this.tail){this.mode="data",t=i(this.flush()),this.arrow&&(t+=" "+this.arrow),this.isDedentable(t)&&e(["dedent"]),e(["recordCode",t]);if(this.directive)return e(["indent",this.arrow])}},e.prototype.scanComment=function(e){if(this.tail==="\n")return e(["fail","unexpected newline in code block"]);if(this.tail)return this.mode="data",this.buffer=""},e.prototype.flush=function(){var e;return e=this.buffer,this.buffer="",e},e.prototype.isDedentable=function(t){return t.match(e.dedentablePattern)},e}()}).call(this)},"./util":function(e,t,n){(function(){var e,t;n.repeat=e=function(e,t){return Array(t+1).join(e)},n.indent=function(t,n){var r,i,s;return s=e(" ",n),i=function(){var e,n,i,o;i=t.split("\n"),o=[];for(e=0,n=i.length;e<n;e++)r=i[e],o.push(s+r);return o}(),i.join("\n")},n.trim=function(e){return e.replace(/^\s+/,"").replace(/\s+$/,"")},t={"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},n.inspectString=function(e){var n;return n=e.replace(/[\x00-\x1f\\]/g,function(e){var n;return e in t?t[e]:(n=e.charCodeAt(0).toString(16),n.length===1&&(n="0"+n),"\\u00"+n)}),"'"+n.replace(/'/g,"\\'")+"'"}}).call(this)},strscan:function(e,t,n){(function(){var e;(typeof n!="undefined"&&n!==null?n:this).StringScanner=function(){return e=function(e){return this.source=e.toString(),this.reset(),this},e.prototype.scan=function(e){var t;return(t=e.exec(this.getRemainder()))&&t.index===0?this.setState(t,{head:this.head+t[0].length,last:this.head}):this.setState([])},e.prototype.scanUntil=function(e){var t;return(t=e.exec(this.getRemainder()))?(this.setState(t,{head:this.head+t.index+t[0].length,last:this.head}),this.source.slice(this.last,this.head)):this.setState([])},e.prototype.scanChar=function(){return this.scan(/[\s\S]/)},e.prototype.skip=function(e){if(this.scan(e))return this.match.length},e.prototype.skipUntil=function(e){if(this.scanUntil(e))return this.head-this.last},e.prototype.check=function(e){var t;return(t=e.exec(this.getRemainder()))&&t.index===0?this.setState(t):this.setState([])},e.prototype.checkUntil=function(e){var t;return(t=e.exec(this.getRemainder()))?(this.setState(t),this.source.slice(this.head,this.head+t.index+t[0].length)):this.setState([])},e.prototype.peek=function(e){return this.source.substr(this.head,typeof e!="undefined"&&e!==null?e:1)},e.prototype.getSource=function(){return this.source},e.prototype.getRemainder=function(){return this.source.slice(this.head)},e.prototype.getPosition=function(){return this.head},e.prototype.hasTerminated=function(){return this.head===this.source.length},e.prototype.getPreMatch=function(){if(this.match)return this.source.slice(0,this.head-this.match.length)},e.prototype.getMatch=function(){return this.match},e.prototype.getPostMatch=function(){if(this.match)return this.source.slice(this.head)},e.prototype.getCapture=function(e){return this.captures[e]},e.prototype.reset=function(){return this.setState([],{head:0,last:0})},e.prototype.terminate=function(){return this.setState([],{head:this.source.length,last:this.head})},e.prototype.concat=function(e){return this.source+=e},e.prototype.unscan=function(){if(this.match)return this.setState([],{head:this.last,last:0});throw"nothing to unscan"},e.prototype.setState=function(e,t){var n,r;return this.head=typeof (n=typeof t=="undefined"||t===null?undefined:t.head)!="undefined"&&n!==null?n:this.head,this.last=typeof (r=typeof t=="undefined"||t===null?undefined:t.last)!="undefined"&&r!==null?r:this.last,this.captures=e.slice(1),this.match=e[0]},e}()})()},"coffee-script":function(e,t,n){if(typeof CoffeeScript=="undefined"||CoffeeScript==null)throw"Cannot require '"+e.id+"': CoffeeScript not found";e.exports=CoffeeScript}})("eco")
# Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from . import save_embedding, utils
/*! * CustomWiggle 3.0.0 * https://greensock.com * * @license Copyright 2008-2019, GreenSock. All rights reserved. * Subject to the terms at https://greensock.com/standard-license or for * Club GreenSock members, the agreement issued with that membership. * @author: Jack Doyle, [email protected] */ /* eslint-disable */ var gsap, _coreInitted, createCustomEase, _getGSAP = function _getGSAP() { return gsap || typeof window !== "undefined" && (gsap = window.gsap) && gsap.registerPlugin && gsap; }, _eases = { easeOut: "M0,1,C0.7,1,0.6,0,1,0", easeInOut: "M0,0,C0.1,0,0.24,1,0.444,1,0.644,1,0.6,0,1,0", anticipate: "M0,0,C0,0.222,0.024,0.386,0,0.4,0.18,0.455,0.65,0.646,0.7,0.67,0.9,0.76,1,0.846,1,1", uniform: "M0,0,C0,0.95,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0" }, _linearEase = function _linearEase(p) { return p; }, _initCore = function _initCore(required) { if (!_coreInitted) { gsap = _getGSAP(); createCustomEase = gsap && gsap.parseEase("_CE"); if (createCustomEase) { for (var p in _eases) { _eases[p] = createCustomEase("", _eases[p]); } _coreInitted = 1; _create("wiggle").config = function (vars) { return typeof vars === "object" ? _create("", vars) : _create("wiggle(" + vars + ")", { wiggles: +vars }); }; } else { required && console.warn("Please gsap.registerPlugin(CustomEase, CustomWiggle)"); } } }, _parseEase = function _parseEase(ease, invertNonCustomEases) { if (typeof ease !== "function") { ease = gsap.parseEase(ease) || createCustomEase("", ease); } return ease.custom || !invertNonCustomEases ? ease : function (p) { return 1 - ease(p); }; }, _bonusValidated = 1, //<name>CustomWiggle</name> _create = function _create(id, vars) { if (!_coreInitted) { _initCore(1); } vars = vars || {}; var wiggles = (vars.wiggles || 10) | 0, inc = 1 / wiggles, x = inc / 2, anticipate = vars.type === "anticipate", yEase = _eases[vars.type] || _eases.easeOut, xEase = _linearEase, rnd = 1000, nextX, nextY, angle, handleX, handleY, easedX, y, path, i; if (_bonusValidated) { if (anticipate) { //the anticipate ease is actually applied on the x-axis (timing) and uses easeOut for amplitude. xEase = yEase; yEase = _eases.easeOut; } if (vars.timingEase) { xEase = _parseEase(vars.timingEase); } if (vars.amplitudeEase) { yEase = _parseEase(vars.amplitudeEase, true); } easedX = xEase(x); y = anticipate ? -yEase(x) : yEase(x); path = [0, 0, easedX / 4, 0, easedX / 2, y, easedX, y]; if (vars.type === "random") { //if we just select random values on the y-axis and plug them into the "normal" algorithm, since the control points are always straight horizontal, it creates a bit of a slowdown at each anchor which just didn't seem as desirable, so we switched to an algorithm that bends the control points to be more in line with their context. path.length = 4; nextX = xEase(inc); nextY = Math.random() * 2 - 1; for (i = 2; i < wiggles; i++) { x = nextX; y = nextY; nextX = xEase(inc * i); nextY = Math.random() * 2 - 1; angle = Math.atan2(nextY - path[path.length - 3], nextX - path[path.length - 4]); handleX = Math.cos(angle) * inc; handleY = Math.sin(angle) * inc; path.push(x - handleX, y - handleY, x, y, x + handleX, y + handleY); } path.push(nextX, 0, 1, 0); } else { for (i = 1; i < wiggles; i++) { path.push(xEase(x + inc / 2), y); x += inc; y = (y > 0 ? -1 : 1) * yEase(i * inc); easedX = xEase(x); path.push(xEase(x - inc / 2), y, easedX, y); } path.push(xEase(x + inc / 4), y, xEase(x + inc / 4), 0, 1, 0); } i = path.length; while (--i > -1) { path[i] = ~~(path[i] * rnd) / rnd; //round values to avoid odd strings for super tiny values } path[2] = "C" + path[2]; return createCustomEase(id, "M" + path.join(",")); } }; export var CustomWiggle = /*#__PURE__*/ function () { function CustomWiggle(id, vars) { this.ease = _create(id, vars); } CustomWiggle.create = function create(id, vars) { return _create(id, vars); }; CustomWiggle.register = function register(core) { gsap = core; _initCore(); }; return CustomWiggle; }(); _getGSAP() && gsap.registerPlugin(CustomWiggle); CustomWiggle.version = "3.0.0"; export { CustomWiggle as default };
$(function(e){ //______summernote $('.summernote').summernote({ placeholder: '', tabsize: 1, height: 200, toolbar: [ ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['color', ['color']], ['para', ['ul', 'ol']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview']], ] }); //______summernote $('.editsummernote').summernote({ placeholder: ' Lorem ipsum dolor sit amet, quis Neque porro quisquam est, nostrud exercitation ullamco laboris commodo consequat.', tabsize: 1, height: 200, toolbar: [ ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['color', ['color']], ['para', ['ul', 'ol']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview']], ] }); // ______________ Attach Remove $(document).on('click', '[data-toggle="remove"]', function(e) { let $a = $(this).closest(".attach-supportfiles"); $a.remove(); e.preventDefault(); return false; }); // ______________Edit Summernote $(document).on("click", '.supportnote-icon', function () { if(document) { $('body').toggleClass('add-supportnote'); localStorage.setItem("add-supportnote", "True"); } else { $('body').removeClass('add-supportnote'); localStorage.setItem("add-supportnote", "false"); } }); $(document).on("click", '.dismiss-btn', function () { $('body').removeClass('add-supportnote'); }); // ______________Edit Summernote $(document).on("click", '.reopen-button', function () { if(document) { $('body').toggleClass('add-reopencard'); localStorage.setItem("add-reopencard", "True"); } else { $('body').removeClass('add-reopencard'); localStorage.setItem("add-reopencard", "false"); } }); });
// This file configures the development web server // which supports hot reloading and synchronized testing. // Require Browsersync along with webpack and middleware for it import browserSync from 'browser-sync'; // Required for react-router browserHistory // see https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643 import historyApiFallback from 'connect-history-api-fallback'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import webpackConfigBuilder from '../webpack.config'; const webpackConfig = webpackConfigBuilder('development'); const bundler = webpack(webpackConfig); // Run Browsersync and use middleware for Hot Module Replacement browserSync({ server: { baseDir: 'src', middleware: [ webpackDevMiddleware(bundler, { // Dev middleware can't access config, so we provide publicPath publicPath: webpackConfig.output.publicPath, // pretty colored output stats: { colors: true }, // Set to false to display a list of each file that is being bundled. noInfo: true // for other settings see // http://webpack.github.io/docs/webpack-dev-middleware.html }), // bundler should be the same as above webpackHotMiddleware(bundler), historyApiFallback() ] }, // no need to watch '*.js' here, webpack will take care of it for us, // including full page reloads if HMR won't work files: [ 'src/*.html' ] });
const Item = require("../models"); exports.itemsByCategory = (req, res) => { Item.find({ category: req.params.category }).exec((err, items) => { if (err || !items) { return res.status(400).json({ error: "No items found for category", }); } res.json({ items }); }); }; exports.createItem = (req, res) => { const newItem = new Item(req.body); newItem.save((err, item) => { if (err) { return res.status(400).json({ error: err, }); } res.json({ item }); }); }; exports.deleteItem = (req, res) => { Item.deleteOne({ _id: req.params.id }).exec((err, item) => { if (err || !item) { return res.status(400).json({ error: "No item found for that id", }); } res.json({ deleted: item }); }); };
import sourcemaps from 'rollup-plugin-sourcemaps'; import license from 'rollup-plugin-license'; const path = require('path'); export default { output: { format: 'es', sourcemap: true }, plugins: [ sourcemaps(), license({ sourceMap: true, banner: { file: path.join(__dirname, 'license-banner.txt'), encoding: 'utf-8', } }) ], onwarn: () => { return } }
# coding=utf8 from __future__ import unicode_literals, absolute_import, division, print_function """ This is the SpiceBot events system. We utilize the Sopel code for event numbers and self-trigger the bot into performing actions """ import sopel import functools import threading import time import inspect # TODO from .logs import logs # full_message = ':{} PRIVMSG {} :{}'.format(hostmask, sender, msg) class BotEvents(object): """A dynamic listing of all the notable Bot numeric events. Events will be assigned a 4-digit number above 1000. This allows you to do, ``@module.event(events.BOT_WELCOME)```` Triggers handled by this module will be processed immediately. Others will be placed into a queue. Triggers will be logged by ID and content """ def __init__(self): self.lock = threading.Lock() self.RPL_WELCOME = '001' # This is a defined IRC event self.RPL_MYINFO = '004' # This is a defined IRC event self.RPL_ISUPPORT = '005' # This is a defined IRC event self.RPL_WHOREPLY = '352' # This is a defined IRC event self.RPL_NAMREPLY = '353' # This is a defined IRC event self.RPL_WHOISREGNICK = '307' # this is an unrealircd event self.BOT_UPTIME = time.time() self.BOT_WELCOME = '1001' self.BOT_READY = '1002' self.BOT_CONNECTED = '1003' self.BOT_LOADED = '1004' self.BOT_RECONNECTED = '1005' self.defaultevents = [self.BOT_WELCOME, self.BOT_READY, self.BOT_CONNECTED, self.BOT_LOADED, self.BOT_RECONNECTED] self.dict = { "assigned_IDs": {1000: "BOT_UPTIME", 1001: "BOT_WELCOME", 1002: "BOT_READY", 1003: "BOT_CONNECTED", 1004: "BOT_LOADED", 1005: "BOT_RECONNECTED"}, "triggers_recieved": {}, "trigger_queue": [], "startup_required": [self.BOT_WELCOME, self.BOT_READY, self.BOT_CONNECTED], "RPL_WELCOME_Count": 0 } def __getattr__(self, name): ''' will only get called for undefined attributes ''' self.lock.acquire() eventnumber = max(list(self.dict["assigned_IDs"].keys())) + 1 self.dict["assigned_IDs"][eventnumber] = str(name) setattr(self, name, str(eventnumber)) self.lock.release() return str(eventnumber) def trigger(self, bot, number, message="SpiceBot_Events"): pretriggerdict = {"number": str(number), "message": message} if number in self.defaultevents: self.dispatch(bot, pretriggerdict) else: self.dict["trigger_queue"].append(pretriggerdict) def dispatch(self, bot, pretriggerdict): number = pretriggerdict["number"] message = pretriggerdict["message"] pretrigger = sopel.trigger.PreTrigger( bot.nick, ":SpiceBot_Events " + str(number) + " " + str(bot.nick) + " :" + message ) bot.dispatch(pretrigger) self.recieved({"number": number, "message": message}) def recieved(self, trigger): self.lock.acquire() if isinstance(trigger, dict): eventnumber = str(trigger["number"]) message = str(trigger["message"]) else: eventnumber = str(trigger.event) message = trigger.args[1] logs.log('SpiceBot_Events', str(eventnumber) + " " + str(message)) if eventnumber not in self.dict["triggers_recieved"]: self.dict["triggers_recieved"][eventnumber] = [] self.dict["triggers_recieved"][eventnumber].append(message) self.lock.release() def check(self, checklist): if not isinstance(checklist, list): checklist = [str(checklist)] for number in checklist: if str(number) not in list(self.dict["triggers_recieved"].keys()): return False return True def startup_add(self, startlist): self.lock.acquire() if not isinstance(startlist, list): startlist = [str(startlist)] for eventitem in startlist: if eventitem not in self.dict["startup_required"]: self.dict["startup_required"].append(eventitem) self.lock.release() def startup_check(self): for number in self.dict["startup_required"]: if str(number) not in list(self.dict["triggers_recieved"].keys()): return False return True def startup_debug(self): not_done = [] for number in self.dict["startup_required"]: if str(number) not in list(self.dict["triggers_recieved"].keys()): not_done.append(int(number)) reference_not_done = [] for item in not_done: reference_not_done.append(str(self.dict["assigned_IDs"][item])) return reference_not_done def check_ready(self, checklist): def actual_decorator(function): @functools.wraps(function) def _nop(*args, **kwargs): while not self.check(checklist): pass return function(*args, **kwargs) return _nop return actual_decorator def startup_check_ready(self): def actual_decorator(function): @functools.wraps(function) def _nop(*args, **kwargs): while not self.startup_check(): pass return function(*args, **kwargs) return _nop return actual_decorator events = BotEvents() """ Other """ def lineno(): """Returns the current line number in our program.""" linenum = inspect.currentframe().f_back.f_lineno frameinfo = inspect.getframeinfo(inspect.currentframe()) filename = frameinfo.filename return str("File: " + str(filename) + " Line: " + str(linenum))
from .base import CustomUserPopulateCommand class Command(CustomUserPopulateCommand): def handle_custom_user(self, from_app_label, from_model_name, to_app_label, to_model_name): self.create_populate_migration(from_app_label, from_model_name, to_app_label, to_model_name, reverse=False)
import {EventActions} from "@drizzle/store"; import { toast } from 'react-toastify' // Due to an issue with metamask we get several fires for teh same event: // https://github.com/MetaMask/metamask-extension/issues/6668 // To avoid that we just make sure that we do not retrigger let processed_events = new Set(); const EventNotifier = store => next => action => { if (action.type === EventActions.EVENT_FIRED && !processed_events.has(action.event.transactionHash)) { console.log(action); const contract = action.name const contractEvent = action.event.event const message = action.event.returnValues._message const display = `${contract}(${contractEvent}): ${message}` console.log(display); toast.success(display, { position: toast.POSITION.TOP_RIGHT }) processed_events.add(action.event.transactionHash); } return next(action); } export default EventNotifier;
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import os import stat import sys # find the import for catkin's python package - either from source space or from an installed underlay if os.path.exists(os.path.join('/opt/ros/melodic/share/catkin/cmake', 'catkinConfig.cmake.in')): sys.path.insert(0, os.path.join('/opt/ros/melodic/share/catkin/cmake', '..', 'python')) try: from catkin.environment_cache import generate_environment_script except ImportError: # search for catkin package in all workspaces and prepend to path for workspace in "/home/caster/ros_ws/caster/devel;/opt/ros/melodic".split(';'): python_path = os.path.join(workspace, 'lib/python2.7/dist-packages') if os.path.isdir(os.path.join(python_path, 'catkin')): sys.path.insert(0, python_path) break from catkin.environment_cache import generate_environment_script code = generate_environment_script('/home/caster/ros_ws/caster/devel/.private/ros_sharp/env.sh') output_filename = '/home/caster/ros_ws/caster/build/ros_sharp/catkin_generated/setup_cached.sh' with open(output_filename, 'w') as f: #print('Generate script for cached setup "%s"' % output_filename) f.write('\n'.join(code)) mode = os.stat(output_filename).st_mode os.chmod(output_filename, mode | stat.S_IXUSR)
import pytest import pint.formatting as fmt @pytest.mark.filterwarnings("ignore::DeprecationWarning:pint*") @pytest.mark.parametrize( ["format", "default", "flag", "expected"], ( pytest.param(".02fD", ".3fP", True, (".02f", "D"), id="both-both-separate"), pytest.param(".02fD", ".3fP", False, (".02f", "D"), id="both-both-combine"), pytest.param(".02fD", ".3fP", None, (".02f", "D"), id="both-both-default"), pytest.param("D", ".3fP", True, (".3f", "D"), id="unit-both-separate"), pytest.param("D", ".3fP", False, ("", "D"), id="unit-both-combine"), pytest.param("D", ".3fP", None, ("", "D"), id="unit-both-default"), pytest.param(".02f", ".3fP", True, (".02f", "P"), id="magnitude-both-separate"), pytest.param(".02f", ".3fP", False, (".02f", ""), id="magnitude-both-combine"), pytest.param(".02f", ".3fP", None, (".02f", ""), id="magnitude-both-default"), pytest.param("D", "P", True, ("", "D"), id="unit-unit-separate"), pytest.param("D", "P", False, ("", "D"), id="unit-unit-combine"), pytest.param("D", "P", None, ("", "D"), id="unit-unit-default"), pytest.param( ".02f", ".3f", True, (".02f", ""), id="magnitude-magnitude-separate" ), pytest.param( ".02f", ".3f", False, (".02f", ""), id="magnitude-magnitude-combine" ), pytest.param( ".02f", ".3f", None, (".02f", ""), id="magnitude-magnitude-default" ), pytest.param("D", ".3f", True, (".3f", "D"), id="unit-magnitude-separate"), pytest.param("D", ".3f", False, ("", "D"), id="unit-magnitude-combine"), pytest.param("D", ".3f", None, ("", "D"), id="unit-magnitude-default"), pytest.param(".02f", "P", True, (".02f", "P"), id="magnitude-unit-separate"), pytest.param(".02f", "P", False, (".02f", ""), id="magnitude-unit-combine"), pytest.param(".02f", "P", None, (".02f", ""), id="magnitude-unit-default"), pytest.param("", ".3fP", True, (".3f", "P"), id="none-both-separate"), pytest.param("", ".3fP", False, (".3f", "P"), id="none-both-combine"), pytest.param("", ".3fP", None, (".3f", "P"), id="none-both-default"), pytest.param("", "P", True, ("", "P"), id="none-unit-separate"), pytest.param("", "P", False, ("", "P"), id="none-unit-combine"), pytest.param("", "P", None, ("", "P"), id="none-unit-default"), pytest.param("", ".3f", True, (".3f", ""), id="none-magnitude-separate"), pytest.param("", ".3f", False, (".3f", ""), id="none-magnitude-combine"), pytest.param("", ".3f", None, (".3f", ""), id="none-magnitude-default"), pytest.param("", "", True, ("", ""), id="none-none-separate"), pytest.param("", "", False, ("", ""), id="none-none-combine"), pytest.param("", "", None, ("", ""), id="none-none-default"), ), ) def test_split_format(format, default, flag, expected): result = fmt.split_format(format, default, flag) assert result == expected
/*! * jquery-resource v0.0.0 - Support for RESTful. * Copyright 2015 Hironobu Igawa * license MIT */ var resource; (function (resource) { 'use strict'; /** * @class Http HTTP通信 */ var Http = (function () { function Http() { } /** * @function execute 通信処理を行う。 * @param {{}} params * @returns {JQueryPromise} */ Http.execute = function (params) { var options = $.extend({}, params); var promise = $.Deferred().resolve(options).promise(); for (var i = 0; i < Http.interceptors.length; i++) promise = promise.then(Http.interceptors[i].request, Http.interceptors[i].requestError); promise = promise.then(function (options) { options.dataType = 'json'; options.type = options.method; delete options.method; return $.ajax(options); }); for (var j = Http.interceptors.length - 1; j >= 0; j--) promise = promise.then(Http.interceptors[j].response, Http.interceptors[j].responseError); return promise; }; Http.interceptors = []; return Http; }()); resource.Http = Http; })(resource || (resource = {})); var resource; (function (resource_1) { 'use strict'; /** * @class Resource リソース */ var Resource = (function () { /** * @constructor * @param {IModelClass<T>} modelClass * @param {string} url * @param {IActions} actions */ function Resource(modelClass, url, actions) { this.url = url; this.modelClass = function Model(params) { var _this = this; modelClass.call(this, params); if (!params) return; Object.keys(params).forEach(function (key) { if (!params.hasOwnProperty(key)) return; _this[key] = params[key]; }); }; this.modelClass.prototype = Object.create(modelClass.prototype); this.actions = $.extend({}, Resource.defaultActions, actions); } /** * @method static init リソースの初期化を行う。 * @param {IModelClass<IModel>} modelClass * @param {string} url * @param {IActions} actions */ Resource.init = function (modelClass, url, actions) { var resource = new Resource(modelClass, url, actions); resource.initConstructor(); resource.initActions(); resource.initToJSON(); return resource.modelClass; }; /** * @method initConstructor コンストラクタを初期化する。 */ Resource.prototype.initConstructor = function () { var _this = this; Object.defineProperty(this.modelClass, 'constructor', { value: function (params) { return _this.generateModel(params); }, enumerable: false, writable: true, configurable: true }); }; /** * @method setActions アクションを初期化する。 */ Resource.prototype.initActions = function () { var _this = this; var prototype = this.modelClass.prototype; $.each(this.actions, function (actionName) { var action = _this.generateAction(actionName); _this.modelClass[actionName] = function (p) { return action(null, p); }; prototype[actionName] = function (p) { return action(this, p); }; }); }; /** * @method initToJSON JSON変換関数の初期化を行う。 */ Resource.prototype.initToJSON = function () { var prototype = this.modelClass.prototype; prototype.toJSON = prototype.defaultToJSON || Resource.defaultToJSON; }; /** * @method static copy オブジェクトの値をモデルにコピーする。 * モデルが指定されていない場合、新しくモデルを生成して返却する。 * @param {{}} src * @param {T} dest * @returns {T} */ Resource.prototype.copy = function (src, dest) { if (dest) { $.each(dest, function (key) { if (!dest.hasOwnProperty(key)) return; if (key === 'promise' || key === 'resolved') return; delete dest[key]; }); } var model = dest || this.generateModel(); $.each(src, function (k, v) { return model[k] = v; }); return model; }; /** * @method static generateAction アクションを生成する。 * @param {string} actionName * @returns {(data?: T, params?: any) => T|IModelArray<T>|JQueryPromise<T|IModelArray<T>>} */ Resource.prototype.generateAction = function (actionName) { var _this = this; var action = this.actions[actionName]; return function (model, params) { var instanceCallFlg = !!model; var val = instanceCallFlg ? model : (action.arrayFlg ? [] : _this.generateModel()); var promise = resource_1.Http.execute(_this.generateHttpConfig(action, model, params)) .done(function (data) { if (action.arrayFlg) { data.forEach(function (v) { return val.push(_this.generateModel(v)); }); } else { _this.copy(data, val); } }) .always(function () { if (!instanceCallFlg) val.resolved = true; }) .then(function () { return val; }); if (!instanceCallFlg) { val.promise = promise; val.resolved = false; return val; } return promise; }; }; /** * @method generateHttpConfig HTTP設定を生成して返却する。 * @param {IAction} action * @param {T} model * @param {{}} params * @returns {Object} */ Resource.prototype.generateHttpConfig = function (action, model, params) { var httpConfig = {}; $.each(action, function (key, value) { if (key === 'url' || key === 'arrayFlg') return; httpConfig[key] = value; }); var templateURL = action.url || this.url; var data = $.extend({}, action.params, model && model.toJSON(), params); var paramKeys = resource_1.Router.getURLParamKeys(templateURL); httpConfig.url = resource_1.Router.generateURL(templateURL, paramKeys, data); httpConfig.data = this.excludeParams(data, paramKeys); return httpConfig; }; /** * @method excludeParams パラメータから指定のキーを除外して返却する。 * @param {{}} params * @param {string[]} paramKeys * @returns {{}} result */ Resource.prototype.excludeParams = function (params, paramKeys) { var result = $.extend({}, params); paramKeys.forEach(function (k) { return delete result[k]; }); return result; }; /** * @method generateModel モデルを生成して返却する。 * @param {{}} params * @returns {T} */ Resource.prototype.generateModel = function (params) { return new this.modelClass(params); }; Resource.defaultActions = { "get": { method: "GET" }, "query": { method: "GET", arrayFlg: true }, "create": { method: "POST" }, "update": { method: "PUT" }, "destroy": { method: "DELETE" } }; Resource.defaultToJSON = function () { var _this = this; var keys = []; // Corresponding to the getter/setter. for (var key in this) keys.push(key); return keys.reduce(function (json, key) { if (key === 'promise' || key === 'resolved') return json; if (_this[key] instanceof Function) return json; json[key] = _this[key]; return json; }, {}); }; return Resource; }()); resource_1.Resource = Resource; })(resource || (resource = {})); /// <reference path="Resource.ts" /> /// <reference path="Http.ts" /> (function ($) { $.resource = { init: resource.Resource.init, http: resource.Http }; Object.defineProperty($.resource, 'defaultActions', { get: function () { return resource.Resource.defaultActions; }, set: function (actions) { return resource.Resource.defaultActions = actions; }, enumerable: true, configurable: true }); Object.defineProperty($.resource, 'defaultToJSON', { get: function () { return resource.Resource.defaultToJSON; }, set: function (defaultToJSON) { return resource.Resource.defaultToJSON = defaultToJSON; }, enumerable: true, configurable: true }); })(jQuery); var resource; (function (resource) { /** * @class Router ルータ */ var Router = (function () { function Router() { } /** * @method getUrlParams URLパラメータキーを返却する。 * @param {string} template * @returns {string[]} */ Router.getURLParamKeys = function (template) { return template.split(/\W/) .filter(function (p) { return !new RegExp("^\\d+$").test(p); }) .filter(function (p) { return !!p; }) .filter(function (p) { return new RegExp("(^|[^\\\\]):" + p + "(\\W|$)").test(template); }); }; /** * @method generateURL URLを生成して返却する。 * (例1) * template = "/users/:userId", paramKeys = ['userId'], params = {userId: "1"}の場合、 * "/users/1"を返却する。 * (例2) * template = "/users/:userId", paramKeys = ['userId'], params = {}の場合、 * "/users"を返却する。 * (例3) * template = "/users/:userId.json", paramKeys = ['userId'], params = {}の場合、 * "/users.json"を返却する。 * @param {string} template * @param {string[]} paramKeys * @param {{}} params * @returns {string} */ Router.generateURL = function (template, paramKeys, params) { if (!paramKeys.length) { return template; } var url = paramKeys.reduce(function (u, k) { return params[k] ? Router.replace(u, k, params[k]) : Router.exclude(u, k); }, template); return url.replace(/\/\.json$/, '.json'); }; /** * @method replace 対象キーを置換して返却する。 * (例) * template = "/users/:userId", key = "userId", val = "1"の場合、 * "/users/1"を返却する。 * @param {string} template * @param {string} key * @param {any} val * @returns {string} */ Router.replace = function (template, key, val) { return template.replace(new RegExp(":" + key + "(\\W|$)", "g"), function (m, p1) { return Router.encodeURI(val) + p1; }); }; /** * @method exclude 対象キーをURLから除外して返却する。 * (例) * template = "/users/:userId", key = "userId"の場合、 * "/users/"を返却する。 * (例2) * template = "/users/:userId/name", key = "userId"の場合、 * "/users/name"を返却する。 * (例3) * template = "/users/:userId:name", key = "userId"の場合、 * "/users/:name"を返却する。 * @param {string} template * @param {string} key * @returns {string} */ Router.exclude = function (template, key) { return template.replace(new RegExp("(\/?):" + key + "(\\W|$)", "g"), function (match, leadingSlashes, tail) { return tail.charAt(0) === '/' ? tail : leadingSlashes + tail; }); }; /** * @method encodeURI URLエンコードして返却する。 * @param {string} val * @returns {string} */ Router.encodeURI = function (val) { return encodeURIComponent(val) .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/gi, '$') .replace(/%2C/gi, ',') .replace(/%26/gi, '&') .replace(/%3D/gi, '=') .replace(/%2B/gi, '+'); }; return Router; }()); resource.Router = Router; })(resource || (resource = {}));
import React from 'react' import { render } from 'react-dom' import Root from './routes/Root' import {store, persistor} from './configStore' import './styles/all.css' render( <Root store={store} persistor={persistor} />, document.getElementById('root') )
import { useState } from 'react' import styled from 'styled-components' import Modal from 'react-modal' import PokedexAbilitiesModal from './PokedexAbilitiesModal' const PokedexAbilitiesItemStyle = styled.div` width: 100%; height: 50px; border-bottom: 0.5px solid #bbb; position: relative; &:hover { background-color: #eee; } `; const PokedexAbilitiesItemNumber = styled.span` font-size: 14px; top: 18px; left: 18px; display: inline-block; position: absolute; `; const PokedexAbilitiesItemName = styled.span` top: 17px; left: 50px; display; inline-block; position: absolute; `; const PokedexAbilitiesItemUsage = styled.span` font-size: 14px; top: 18px; right: 18px; display: inline-block; position: absolute; `; const PokedexAbilitiesItem = (props) => { const [showModal, setShowModal] = useState(false); const openModal = (e) => { setShowModal(true); } const closeModal = (e) => { e.stopPropagation(); setShowModal(false); } const modalStyleMobile = { content: { width: '90%', height: '90%', top: '0', left: '0', }, overlay: { zIndex: '4' } } return ( <PokedexAbilitiesItemStyle onClick={openModal}> {props.abilitydata ? <div><Modal isOpen={showModal} style={props.width < 500 ? modalStyleMobile : {}} ariaHideApp={false}> <PokedexAbilitiesModal pokemonData={props.pokemonData} abilitydata={props.abilitydata} season={props.season} ruleset={props.ruleset} onbuttonclick={closeModal} width={props.width} /> </Modal> <PokedexAbilitiesItemNumber>#{props.number}</PokedexAbilitiesItemNumber> <PokedexAbilitiesItemName>{props.abilitydata.name_ko}</PokedexAbilitiesItemName> <PokedexAbilitiesItemUsage>{props.usage}%</PokedexAbilitiesItemUsage></div> : null} </PokedexAbilitiesItemStyle> ); } export default PokedexAbilitiesItem;
'use strict' module.exports = nix nix.displayName = 'nix' nix.aliases = [] function nix(Prism) { Prism.languages.nix = { comment: /\/\*[\s\S]*?\*\/|#.*/, string: { pattern: /"(?:[^"\\]|\\[\s\S])*"|''(?:(?!'')[\s\S]|''(?:'|\\|\$\{))*''/, greedy: true, inside: { interpolation: { // The lookbehind ensures the ${} is not preceded by \ or '' pattern: /(^|(?:^|(?!'').)[^\\])\$\{(?:[^{}]|\{[^}]*\})*\}/, lookbehind: true, inside: { antiquotation: { pattern: /^\$(?=\{)/, alias: 'variable' } // See rest below } } } }, url: [ /\b(?:[a-z]{3,7}:\/\/)[\w\-+%~\/.:#=?&]+/, { pattern: /([^\/])(?:[\w\-+%~.:#=?&]*(?!\/\/)[\w\-+%~\/.:#=?&])?(?!\/\/)\/[\w\-+%~\/.:#=?&]*/, lookbehind: true } ], antiquotation: { pattern: /\$(?=\{)/, alias: 'variable' }, number: /\b\d+\b/, keyword: /\b(?:assert|builtins|else|if|in|inherit|let|null|or|then|with)\b/, function: /\b(?:abort|add|all|any|attrNames|attrValues|baseNameOf|compareVersions|concatLists|currentSystem|deepSeq|derivation|dirOf|div|elem(?:At)?|fetch(?:url|Tarball)|filter(?:Source)?|fromJSON|genList|getAttr|getEnv|hasAttr|hashString|head|import|intersectAttrs|is(?:Attrs|Bool|Function|Int|List|Null|String)|length|lessThan|listToAttrs|map|mul|parseDrvName|pathExists|read(?:Dir|File)|removeAttrs|replaceStrings|seq|sort|stringLength|sub(?:string)?|tail|throw|to(?:File|JSON|Path|String|XML)|trace|typeOf)\b|\bfoldl'\B/, boolean: /\b(?:true|false)\b/, operator: /[=!<>]=?|\+\+?|\|\||&&|\/\/|->?|[?@]/, punctuation: /[{}()[\].,:;]/ } Prism.languages.nix.string.inside.interpolation.inside.rest = Prism.languages.nix }
/** * @license Highcharts JS v5.0.0 (2016-09-29) * Exporting module * * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ (function(factory) { if (typeof module === 'object' && module.exports) { module.exports = factory; } else { factory(Highcharts); } }(function(Highcharts) { (function(H) { /** * Exporting module * * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ /* eslint indent:0 */ 'use strict'; // create shortcuts var defaultOptions = H.defaultOptions, doc = H.doc, Chart = H.Chart, addEvent = H.addEvent, removeEvent = H.removeEvent, fireEvent = H.fireEvent, createElement = H.createElement, discardElement = H.discardElement, css = H.css, merge = H.merge, pick = H.pick, each = H.each, extend = H.extend, splat = H.splat, isTouchDevice = H.isTouchDevice, win = H.win, SVGRenderer = H.SVGRenderer; var symbols = H.Renderer.prototype.symbols; // Add language extend(defaultOptions.lang, { printChart: 'Print chart', downloadPNG: 'Download PNG image', downloadJPEG: 'Download JPEG image', downloadPDF: 'Download PDF document', downloadSVG: 'Download SVG vector image', contextButtonTitle: 'Chart context menu' }); // Buttons and menus are collected in a separate config option set called 'navigation'. // This can be extended later to add control buttons like zoom and pan right click menus. defaultOptions.navigation = { buttonOptions: { theme: {}, symbolSize: 14, symbolX: 12.5, symbolY: 10.5, align: 'right', buttonSpacing: 3, height: 22, // text: null, verticalAlign: 'top', width: 24 } }; // Presentational attributes merge(true, defaultOptions.navigation, { menuStyle: { border: '1px solid #999999', background: '#ffffff', padding: '5px 0' }, menuItemStyle: { padding: '0.5em 1em', background: 'none', color: '#333333', fontSize: isTouchDevice ? '14px' : '11px', transition: 'background 250ms, color 250ms' }, menuItemHoverStyle: { background: '#335cad', color: '#ffffff' }, buttonOptions: { symbolFill: '#666666', symbolStroke: '#666666', symbolStrokeWidth: 3, theme: { fill: '#ffffff', // capture hover stroke: 'none', padding: 5 } } }); // Add the export related options defaultOptions.exporting = { //enabled: true, //filename: 'chart', type: 'image/png', url: 'https://export.highcharts.com/', //width: undefined, printMaxWidth: 780, scale: 2, buttons: { contextButton: { className: 'highcharts-contextbutton', menuClassName: 'highcharts-contextmenu', //x: -10, symbol: 'menu', _titleKey: 'contextButtonTitle', menuItems: [{ textKey: 'printChart', onclick: function() { this.print(); } }, { separator: true }, { textKey: 'downloadPNG', onclick: function() { this.exportChart(); } }, { textKey: 'downloadJPEG', onclick: function() { this.exportChart({ type: 'image/jpeg' }); } }, { textKey: 'downloadPDF', onclick: function() { this.exportChart({ type: 'application/pdf' }); } }, { textKey: 'downloadSVG', onclick: function() { this.exportChart({ type: 'image/svg+xml' }); } } // Enable this block to add "View SVG" to the dropdown menu /* ,{ text: 'View SVG', onclick: function () { var svg = this.getSVG() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); doc.body.innerHTML = '<pre>' + svg + '</pre>'; } } // */ ] } } }; // Add the H.post utility H.post = function(url, data, formAttributes) { var name, form; // create the form form = createElement('form', merge({ method: 'post', action: url, enctype: 'multipart/form-data' }, formAttributes), { display: 'none' }, doc.body); // add the data for (name in data) { createElement('input', { type: 'hidden', name: name, value: data[name] }, null, form); } // submit form.submit(); // clean up discardElement(form); }; extend(Chart.prototype, { /** * A collection of regex fixes on the produces SVG to account for expando properties, * browser bugs, VML problems and other. Returns a cleaned SVG. */ sanitizeSVG: function(svg) { svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/isShadow="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/url\(("|&quot;)(\S+)("|&quot;)\)/g, 'url($2)') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ (NS[0-9]+\:)?href=/g, ' xlink:href=') // #3567 .replace(/\n/, ' ') // Any HTML added to the container after the SVG (#894) .replace(/<\/svg>.*?$/, '</svg>') // Batik doesn't support rgba fills and strokes (#3095) .replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, '$1="rgb($2)" $1-opacity="$3"') /* This fails in IE < 8 .replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight return s2 +'.'+ s3[0]; })*/ // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD'); // soft hyphen // IE specific svg = svg .replace(/<IMG /g, '<image ') .replace(/<(\/?)TITLE>/g, '<$1title>') .replace(/height=([^" ]+)/g, 'height="$1"') .replace(/width=([^" ]+)/g, 'width="$1"') .replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>') .replace(/ id=([^" >]+)/g, ' id="$1"') // #4003 .replace(/class=([^" >]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function(s) { return s.toLowerCase(); }); return svg; }, /** * Return innerHTML of chart. Used as hook for plugins. */ getChartHTML: function() { return this.container.innerHTML; }, /** * Return an SVG representation of the chart * * @param additionalOptions {Object} Additional chart options for the generated SVG representation */ getSVG: function(additionalOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, sourceWidth, sourceHeight, cssWidth, cssHeight, html, options = merge(chart.options, additionalOptions), // copy the options and add extra options allowHTML = options.exporting.allowHTML; // IE compatibility hack for generating SVG content that it doesn't really understand if (!doc.createElementNS) { doc.createElementNS = function(ns, tagName) { return doc.createElement(tagName); }; } // create a sandbox where a new chart will be generated sandbox = createElement('div', null, { position: 'absolute', top: '-9999em', width: chart.chartWidth + 'px', height: chart.chartHeight + 'px' }, doc.body); // get the source size cssWidth = chart.renderTo.style.width; cssHeight = chart.renderTo.style.height; sourceWidth = options.exporting.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || 600; sourceHeight = options.exporting.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, renderer: 'SVGRenderer', width: sourceWidth, height: sourceHeight }); options.exporting.enabled = false; // hide buttons in print delete options.data; // #3004 // prepare for replicating the chart options.series = []; each(chart.series, function(serie) { seriesOptions = merge(serie.userOptions, { // #4912 animation: false, // turn off animation enableMouseTracking: false, showCheckbox: false, visible: serie.visible }); if (!seriesOptions.isInternal) { // used for the navigator series that has its own option set options.series.push(seriesOptions); } }); // Axis options must be merged in one by one, since it may be an array or an object (#2022, #3900) if (additionalOptions) { each(['xAxis', 'yAxis'], function(axisType) { each(splat(additionalOptions[axisType]), function(axisOptions, i) { options[axisType][i] = merge(options[axisType][i], axisOptions); }); }); } // generate the chart copy chartCopy = new H.Chart(options, chart.callback); // reflect axis extremes in the export each(['xAxis', 'yAxis'], function(axisType) { each(chart[axisType], function(axis, i) { var axisCopy = chartCopy[axisType][i], extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (axisCopy && (userMin !== undefined || userMax !== undefined)) { axisCopy.setExtremes(userMin, userMax, true, false); } }); }); // get the SVG from the container's innerHTML svg = chartCopy.getChartHTML(); // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); // Move HTML into a foreignObject if (allowHTML) { html = svg.match(/<\/svg>(.*?$)/); if (html) { html = '<foreignObject x="0" y="0" width="200" height="200">' + '<body xmlns="http://www.w3.org/1999/xhtml">' + html[1] + '</body>' + '</foreignObject>'; svg = svg.replace('</svg>', html + '</svg>'); } } // sanitize svg = this.sanitizeSVG(svg); // IE9 beta bugs with innerHTML. Test again with final IE9. svg = svg.replace(/(url\(#highcharts-[0-9]+)&quot;/g, '$1') .replace(/&quot;/g, '\''); return svg; }, getSVGForExport: function(options, chartOptions) { var chartExportingOptions = this.options.exporting; return this.getSVG(merge({ chart: { borderRadius: 0 } }, chartExportingOptions.chartOptions, chartOptions, { exporting: { sourceWidth: (options && options.sourceWidth) || chartExportingOptions.sourceWidth, sourceHeight: (options && options.sourceHeight) || chartExportingOptions.sourceHeight } } )); }, /** * Submit the SVG representation of the chart to the server * @param {Object} options Exporting options. Possible members are url, type, width and formAttributes. * @param {Object} chartOptions Additional chart options for the SVG representation of the chart */ exportChart: function(options, chartOptions) { var svg = this.getSVGForExport(options, chartOptions); // merge the options options = merge(this.options.exporting, options); // do the post H.post(options.url, { filename: options.filename || 'chart', type: options.type, width: options.width || 0, // IE8 fails to post undefined correctly, so use 0 scale: options.scale, svg: svg }, options.formAttributes); }, /** * Print the chart */ print: function() { var chart = this, container = chart.container, origDisplay = [], origParent = container.parentNode, body = doc.body, childNodes = body.childNodes, printMaxWidth = chart.options.exporting.printMaxWidth, resetParams, handleMaxWidth; if (chart.isPrinting) { // block the button while in printing mode return; } chart.isPrinting = true; chart.pointer.reset(null, 0); fireEvent(chart, 'beforePrint'); // Handle printMaxWidth handleMaxWidth = printMaxWidth && chart.chartWidth > printMaxWidth; if (handleMaxWidth) { resetParams = [chart.options.chart.width, undefined, false]; chart.setSize(printMaxWidth, undefined, false); } // hide all body content each(childNodes, function(node, i) { if (node.nodeType === 1) { origDisplay[i] = node.style.display; node.style.display = 'none'; } }); // pull out the chart body.appendChild(container); // print win.focus(); // #1510 win.print(); // allow the browser to prepare before reverting setTimeout(function() { // put the chart back in origParent.appendChild(container); // restore all body content each(childNodes, function(node, i) { if (node.nodeType === 1) { node.style.display = origDisplay[i]; } }); chart.isPrinting = false; // Reset printMaxWidth if (handleMaxWidth) { chart.setSize.apply(chart, resetParams); } fireEvent(chart, 'afterPrint'); }, 1000); }, /** * Display a popup menu for choosing the export type * * @param {String} className An identifier for the menu * @param {Array} items A collection with text and onclicks for the items * @param {Number} x The x position of the opener button * @param {Number} y The y position of the opener button * @param {Number} width The width of the opener button * @param {Number} height The height of the opener button */ contextMenu: function(className, items, x, y, width, height, button) { var chart = this, navOptions = chart.options.navigation, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + className, menu = chart[cacheName], menuPadding = Math.max(width, height), // for mouse leave detection innerMenu, hide, hideTimer, menuStyle, docMouseUpHandler = function(e) { if (!chart.pointer.inClass(e.target, className)) { hide(); } }; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart[cacheName] = menu = createElement('div', { className: className }, { position: 'absolute', zIndex: 1000, padding: menuPadding + 'px' }, chart.container); innerMenu = createElement('div', { className: 'highcharts-menu' }, null, menu); // Presentational CSS css(innerMenu, extend({ MozBoxShadow: '3px 3px 10px #888', WebkitBoxShadow: '3px 3px 10px #888', boxShadow: '3px 3px 10px #888' }, navOptions.menuStyle)); // hide on mouse out hide = function() { css(menu, { display: 'none' }); if (button) { button.setState(0); } chart.openMenu = false; }; // Hide the menu some time after mouse leave (#1357) addEvent(menu, 'mouseleave', function() { hideTimer = setTimeout(hide, 500); }); addEvent(menu, 'mouseenter', function() { clearTimeout(hideTimer); }); // Hide it on clicking or touching outside the menu (#2258, #2335, #2407) addEvent(doc, 'mouseup', docMouseUpHandler); addEvent(chart, 'destroy', function() { removeEvent(doc, 'mouseup', docMouseUpHandler); }); // create the items each(items, function(item) { if (item) { var element; if (item.separator) { element = createElement('hr', null, null, innerMenu); } else { element = createElement('div', { className: 'highcharts-menu-item', onclick: function(e) { if (e) { // IE7 e.stopPropagation(); } hide(); if (item.onclick) { item.onclick.apply(chart, arguments); } }, innerHTML: item.text || chart.options.lang[item.textKey] }, null, innerMenu); element.onmouseover = function() { css(this, navOptions.menuItemHoverStyle); }; element.onmouseout = function() { css(this, navOptions.menuItemStyle); }; css(element, extend({ cursor: 'pointer' }, navOptions.menuItemStyle)); } // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + 'px'; } else { menuStyle.left = (x - menuPadding) + 'px'; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight && button.alignOptions.verticalAlign !== 'top') { menuStyle.bottom = (chartHeight - y - menuPadding) + 'px'; } else { menuStyle.top = (y + height - menuPadding) + 'px'; } css(menu, menuStyle); chart.openMenu = true; }, /** * Add the export button to the chart */ addButton: function(options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbol, button, symbolSize = btnOptions.symbolSize || 12; if (!chart.btnCount) { chart.btnCount = 0; } // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } var attr = btnOptions.theme, states = attr.states, hover = states && states.hover, select = states && states.select, callback; delete attr.states; if (onclick) { callback = function(e) { e.stopPropagation(); onclick.call(chart, e); }; } else if (menuItems) { callback = function() { chart.contextMenu( button.menuClassName, menuItems, button.translateX, button.translateY, button.width, button.height, button ); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { attr.paddingLeft = pick(attr.paddingLeft, 25); } else if (!btnOptions.text) { extend(attr, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } button = renderer.button(btnOptions.text, 0, 0, callback, attr, hover, select) .addClass(options.className) .attr({ 'stroke-linecap': 'round', title: chart.options.lang[btnOptions._titleKey], zIndex: 3 // #4955 }); button.menuClassName = options.menuClassName || 'highcharts-menu-' + chart.btnCount++; if (btnOptions.symbol) { symbol = renderer.symbol( btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize ) .addClass('highcharts-button-symbol') .attr({ zIndex: 1 }).add(button); symbol.attr({ stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill, 'stroke-width': btnOptions.symbolStrokeWidth || 1 }); } button.add() .align(extend(btnOptions, { width: button.width, x: pick(btnOptions.x, chart.buttonOffset) // #1654 }), true, 'spacingBox'); chart.buttonOffset += (button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1); chart.exportSVGElements.push(button, symbol); }, /** * Destroy the buttons. */ destroyExport: function(e) { var chart = e ? e.target : this, exportSVGElements = chart.exportSVGElements, exportDivElements = chart.exportDivElements; // Destroy the extra buttons added if (exportSVGElements) { each(exportSVGElements, function(elem, i) { // Destroy and null the svg/vml elements if (elem) { // #1822 elem.onclick = elem.ontouchstart = null; chart.exportSVGElements[i] = elem.destroy(); } }); exportSVGElements.length = 0; } // Destroy the divs for the menu if (exportDivElements) { each(exportDivElements, function(elem, i) { // Remove the event handler removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); }); exportDivElements.length = 0; } } }); symbols.menu = function(x, y, width, height) { var arr = [ 'M', x, y + 2.5, 'L', x + width, y + 2.5, 'M', x, y + height / 2 + 0.5, 'L', x + width, y + height / 2 + 0.5, 'M', x, y + height - 1.5, 'L', x + width, y + height - 1.5 ]; return arr; }; // Add the buttons on chart load Chart.prototype.renderExporting = function() { var n, exportingOptions = this.options.exporting, buttons = exportingOptions.buttons, isDirty = this.isDirtyExporting || !this.exportSVGElements; this.buttonOffset = 0; if (this.isDirtyExporting) { this.destroyExport(); } if (isDirty && exportingOptions.enabled !== false) { for (n in buttons) { this.addButton(buttons[n]); } this.isDirtyExporting = false; } // Destroy the export elements at chart destroy addEvent(this, 'destroy', this.destroyExport); }; Chart.prototype.callbacks.push(function(chart) { function update(prop, options, redraw) { chart.isDirtyExporting = true; merge(true, chart.options[prop], options); if (pick(redraw, true)) { chart.redraw(); } } chart.renderExporting(); addEvent(chart, 'redraw', chart.renderExporting); // Add update methods to handle chart.update and chart.exporting.update // and chart.navigation.update. each(['exporting', 'navigation'], function(prop) { chart[prop] = { update: function(options, redraw) { update(prop, options, redraw); } }; }); }); }(Highcharts)); }));
export { default as Switch } from './switch';
import argparse import datetime import sys import torch from dataset import LuxorDataset from model import Net parser = argparse.ArgumentParser() parser.add_argument('--test_dataset_path', type=str, default="../l/l2", dest='test_dataset_path') parser.add_argument('--model_state_dict_path', type=str, default="statedict", dest='model_state_dict_path') args = parser.parse_args() test_dataset = LuxorDataset(args.test_dataset_path, 1, 801) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=6, shuffle=False) if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") model = Net() model.to(device) model.load_state_dict(torch.load(args.model_state_dict_path)) model.eval() start_time = datetime.datetime.now() with torch.no_grad(): for i_batch, sample_batched in enumerate(test_loader): features = sample_batched["x"].to(device=device) outputs = model(features) indices = outputs.argmax(1) letters = [chr(ord('a') + i) for i in indices] print(''.join(letters)) end_time = datetime.datetime.now() sys.stderr.write("Solving time (sec): %f\n" % (end_time - start_time).total_seconds())
from indicators.SingleValueIndicator import SingleValueIndicator class WMA(SingleValueIndicator): def __init__(self, period, timeSeries = None): super(WMA, self).__init__() self.period = int(period) self.denomSum = period * (period + 1) / 2.0 self.initialize(timeSeries) def _calculate(self): if len(self.timeSeries) < self.period: return else: s = 0.0 for i in range(self.period, 0, -1): index = len(self.timeSeries) - self.period + i - 1 # decreases from end of array with increasing i s += self.timeSeries[index] * i self.values.append(s / self.denomSum)
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _inlineStylePrefixer = require('inline-style-prefixer'); var _inlineStylePrefixer2 = _interopRequireDefault(_inlineStylePrefixer); var _reactStyleProptype = require('react-style-proptype'); var _reactStyleProptype2 = _interopRequireDefault(_reactStyleProptype); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Safari/537.2'; var Pane = function (_Component) { _inherits(Pane, _Component); function Pane() { var _ref; _classCallCheck(this, Pane); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _this = _possibleConstructorReturn(this, (_ref = Pane.__proto__ || Object.getPrototypeOf(Pane)).call.apply(_ref, [this].concat(args))); _this.state = { size: _this.props.size }; return _this; } _createClass(Pane, [{ key: 'render', value: function render() { var split = this.props.split; var classes = ['Pane', split, this.props.className]; var style = _extends({}, this.props.style || {}, { flex: 1, position: 'relative', outline: 'none' }); if (this.state.size !== undefined) { if (split === 'vertical') { style.width = this.state.size; } else { style.height = this.state.size; style.display = 'flex'; } style.flex = 'none'; } return _react2.default.createElement( 'div', { className: classes.join(' '), style: this.props.prefixer.prefix(style) }, this.props.children ); } }]); return Pane; }(_react.Component); Pane.propTypes = { split: _react.PropTypes.oneOf(['vertical', 'horizontal']), className: _react.PropTypes.string.isRequired, children: _react.PropTypes.node.isRequired, prefixer: _react.PropTypes.instanceOf(_inlineStylePrefixer2.default).isRequired, style: _reactStyleProptype2.default, size: _react.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.number]) }; Pane.defaultProps = { prefixer: new _inlineStylePrefixer2.default({ userAgent: USER_AGENT }) }; exports.default = Pane; module.exports = exports['default'];
pbjsChunk([257],{ /***/ 126: /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(127); /***/ }), /***/ 127: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spec", function() { return spec; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_utils__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_adapters_bidderFactory__ = __webpack_require__(1); var BIDDER_CODE = 'adocean'; function buildEndpointUrl(emiter, payload) { var payloadString = ''; __WEBPACK_IMPORTED_MODULE_0__src_utils__["_each"](payload, function (v, k) { if (payloadString.length) { payloadString += '&'; } payloadString += k + '=' + encodeURIComponent(v); }); return 'https://' + emiter + '/ad.json?' + payloadString; } function buildRequest(masterBidRequests, masterId, gdprConsent) { var emiter; var payload = { id: masterId }; if (gdprConsent) { payload.gdpr_consent = gdprConsent.consentString || undefined; payload.gdpr = gdprConsent.gdprApplies ? 1 : 0; } var bidIdMap = {}; __WEBPACK_IMPORTED_MODULE_0__src_utils__["_each"](masterBidRequests, function (bid, slaveId) { if (!emiter) { emiter = bid.params.emiter; } bidIdMap[slaveId] = bid.bidId; }); return { method: 'GET', url: buildEndpointUrl(emiter, payload), data: {}, bidIdMap: bidIdMap }; } function assignToMaster(bidRequest, bidRequestsByMaster) { var masterId = bidRequest.params.masterId; var slaveId = bidRequest.params.slaveId; var masterBidRequests = bidRequestsByMaster[masterId] = bidRequestsByMaster[masterId] || [{}]; var i = 0; while (masterBidRequests[i] && masterBidRequests[i][slaveId]) { i++; } if (!masterBidRequests[i]) { masterBidRequests[i] = {}; } masterBidRequests[i][slaveId] = bidRequest; } function _interpretResponse(placementResponse, bidRequest, bids) { if (!placementResponse.error) { var adCode = '<script type="application/javascript">(function(){var wu="' + (placementResponse.winUrl || '') + '",su="' + (placementResponse.statsUrl || '') + '".replace(/\\[TIMESTAMP\\]/,(new Date()).getTime());'; adCode += 'if(navigator.sendBeacon){if(wu){navigator.sendBeacon(wu)||((new Image(1,1)).src=wu)};if(su){navigator.sendBeacon(su)||((new Image(1,1)).src=su)}}'; adCode += 'else{if(wu){(new Image(1,1)).src=wu;}if(su){(new Image(1,1)).src=su;}}'; adCode += '})();<\/script>'; adCode += decodeURIComponent(placementResponse.code); var bid = { ad: adCode, cpm: parseFloat(placementResponse.price), currency: placementResponse.currency, height: parseInt(placementResponse.height, 10), requestId: bidRequest.bidIdMap[placementResponse.id], width: parseInt(placementResponse.width, 10), netRevenue: false, ttl: parseInt(placementResponse.ttl), creativeId: placementResponse.crid }; bids.push(bid); } } var spec = { code: BIDDER_CODE, isBidRequestValid: function isBidRequestValid(bid) { return !!(bid.params.slaveId && bid.params.masterId && bid.params.emiter); }, buildRequests: function buildRequests(validBidRequests, bidderRequest) { var bidRequestsByMaster = {}; var requests = []; __WEBPACK_IMPORTED_MODULE_0__src_utils__["_each"](validBidRequests, function (bidRequest) { assignToMaster(bidRequest, bidRequestsByMaster); }); __WEBPACK_IMPORTED_MODULE_0__src_utils__["_each"](bidRequestsByMaster, function (masterRequests, masterId) { __WEBPACK_IMPORTED_MODULE_0__src_utils__["_each"](masterRequests, function (instanceRequests) { requests.push(buildRequest(instanceRequests, masterId, bidderRequest.gdprConsent)); }); }); return requests; }, interpretResponse: function interpretResponse(serverResponse, bidRequest) { var bids = []; if (__WEBPACK_IMPORTED_MODULE_0__src_utils__["isArray"](serverResponse.body)) { __WEBPACK_IMPORTED_MODULE_0__src_utils__["_each"](serverResponse.body, function (placementResponse) { _interpretResponse(placementResponse, bidRequest, bids); }); } return bids; } }; Object(__WEBPACK_IMPORTED_MODULE_1__src_adapters_bidderFactory__["registerBidder"])(spec); /***/ }) },[126]);
const { omit } = require('lodash') const config = { presets: [ [ require.resolve('@babel/preset-env'), { targets: { electron: '6.0', }, loose: true, }, ], require.resolve('@babel/preset-react'), require.resolve('@babel/preset-typescript'), ], plugins: [ require.resolve('babel-plugin-styled-components'), [require.resolve('@babel/plugin-proposal-decorators'), { legacy: true }], [require.resolve('@babel/plugin-proposal-class-properties'), { loose: true }], [require.resolve('@babel/plugin-proposal-pipeline-operator'), { proposal: 'minimal' }], ].concat( [ '@babel/plugin-proposal-do-expressions', '@babel/plugin-proposal-export-default-from', '@babel/plugin-proposal-export-namespace-from', '@babel/plugin-proposal-function-bind', '@babel/plugin-proposal-function-sent', '@babel/plugin-proposal-json-strings', '@babel/plugin-proposal-logical-assignment-operators', '@babel/plugin-proposal-nullish-coalescing-operator', '@babel/plugin-proposal-numeric-separator', '@babel/plugin-proposal-optional-chaining', '@babel/plugin-proposal-throw-expressions', '@babel/plugin-syntax-dynamic-import', '@babel/plugin-syntax-import-meta', 'babel-plugin-add-module-exports', 'babel-plugin-dynamic-import-node', ].map(plugin => require.resolve(plugin)), ), ignore: [], only: [/\.(es|ts|tsx)$/], babelrc: false, extensions: ['.es', '.ts', '.tsx'], cache: false, } module.exports = config // babel-jest does not support extra config options if (process.env.NODE_ENV === 'test') { module.exports = omit(config, ['extensions', 'cache']) }
def score(input): if (input[12]) >= (9.72500038): if (input[12]) >= (19.8299999): var0 = 1.1551429 else: var0 = 1.8613131 else: if (input[5]) >= (6.94099998): var0 = 3.75848508 else: var0 = 2.48056006 if (input[12]) >= (7.68499994): if (input[12]) >= (15): var1 = 1.24537706 else: var1 = 1.92129695 else: if (input[5]) >= (7.43700027): var1 = 3.96021533 else: var1 = 2.51493931 return ((0.5) + (var0)) + (var1)
# 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 numpy as np from scipy.interpolate import interp1d import matplotlib.cbook as cbook import matplotlib.pyplot as plt import matplotlib from matplotlib.colors import ListedColormap from mpl_toolkits.mplot3d import Axes3D # no not remove, used for 3d plots import pickle import sys import os np.set_printoptions(threshold=sys.maxsize) np.set_printoptions(suppress=True) class Numpy_Visualizer(object): def __init__(self, filename, **kwargs): self.filename = filename self.name = filename self.x_plots = kwargs.get('x_plots' , 10) self.y_plots = kwargs.get('y_plots' , 10) self.w = kwargs.get('width' , 28) self.h = kwargs.get('height' , 28) self.c = kwargs.get('channels' , 1) self.D = kwargs.get('dimensionality' , 784) self.plot_only = kwargs.get('plot_only' , True) self.store_only_output = kwargs.get('store_only_output', True) self.data = np.load(filename) # for mu in self.data: # print(mu.reshape(32,32)) print('self.data.shape', self.data.shape) self.data = np.squeeze(self.data) # print(self.data) self.K = self.x_plots * self.y_plots self.fig, axes = plt.subplots(self.y_plots, self.x_plots) empty = np.zeros([self.K, self.D]) empty[:, 0] = 1 empty[:, -1] = 1 self.all_ax_img = list() # 3d plot variables self.bar = None self.cbar = None self.ax = None shape = (self.h, self.w) if self.c == 1 else (self.h, self.w, self.c) if type(axes) == np.ndarray: # multiple images axes = axes.ravel() for data, ax_ in zip(empty, axes): ax_img = ax_.imshow(data.reshape(shape), cmap='gray') self.all_ax_img.append(ax_img) for ax_ in axes: ax_.tick_params( # disable labels and ticks axis = 'both', which = 'both', bottom = False , top = False , left = False , right = False , labelbottom = False , labelleft = False , ) else: # only one image empty = np.eye(self.w, self.h) ax_img = axes.imshow(empty) self.all_ax_img.append(ax_img) axes.tick_params( # disable labels and ticks axis = 'both', which = 'both', bottom = False , top = False , left = False , right = False , labelbottom = False , labelleft = False , ) plt.gcf().canvas.set_window_title(f'Visualization: {self.name}') self.fig.canvas.draw() self.fig.canvas.flush_events() plt.ion() plt.draw() plt.show() def visualize(self): data = self.data min_ = np.min(data) max_ = np.max(data) print('min, max', min_, max_) images = interp1d([min_, max_], [0., 1.])(data) shape = (self.h, self.w) if self.c == 1 else (self.h, self.w, self.c) print('shape', shape) for i, ax_img in enumerate(self.all_ax_img): if len(images.shape) != 1: image = images[i].reshape(shape) else : image = images.reshape(shape) ax_img._A = cbook.safe_masked_invalid(image, copy=False) if self.plot_only: plt.pause(0.00000000000000001) self.fig.canvas.draw() self.fig.canvas.flush_events() self.fig.savefig(f'{self.filename}.pdf') if __name__ == '__main__': if False: # D5-5 Numpy_Visualizer('../../1_samples.npy').visualize() Numpy_Visualizer('../../2_samples.npy').visualize() Numpy_Visualizer('../../0_xs_samples.npy').visualize() Numpy_Visualizer('../../1_xs_samples.npy').visualize() if True: # D2-2-2-2-2 Numpy_Visualizer('../../1_samples.npy').visualize() Numpy_Visualizer('../../2_samples.npy').visualize() Numpy_Visualizer('../../3_samples.npy').visualize() Numpy_Visualizer('../../4_samples.npy').visualize() Numpy_Visualizer('../../5_samples.npy').visualize() Numpy_Visualizer('../../0_xs_samples.npy').visualize() Numpy_Visualizer('../../1_xs_samples.npy').visualize() Numpy_Visualizer('../../2_xs_samples.npy').visualize() Numpy_Visualizer('../../3_xs_samples.npy').visualize() Numpy_Visualizer('../../4_xs_samples.npy').visualize() if False: # D1-1-1-1-1-1-1-1-1-1 Numpy_Visualizer('../../1_samples.npy').visualize() Numpy_Visualizer('../../2_samples.npy').visualize() Numpy_Visualizer('../../3_samples.npy').visualize() Numpy_Visualizer('../../4_samples.npy').visualize() Numpy_Visualizer('../../5_samples.npy').visualize() Numpy_Visualizer('../../6_samples.npy').visualize() Numpy_Visualizer('../../7_samples.npy').visualize() Numpy_Visualizer('../../8_samples.npy').visualize() Numpy_Visualizer('../../9_samples.npy').visualize() Numpy_Visualizer('../../10_samples.npy').visualize() Numpy_Visualizer('../../0_xs_samples.npy').visualize() Numpy_Visualizer('../../1_xs_samples.npy').visualize() Numpy_Visualizer('../../2_xs_samples.npy').visualize() Numpy_Visualizer('../../3_xs_samples.npy').visualize() Numpy_Visualizer('../../4_xs_samples.npy').visualize() Numpy_Visualizer('../../5_xs_samples.npy').visualize() Numpy_Visualizer('../../6_xs_samples.npy').visualize() Numpy_Visualizer('../../7_xs_samples.npy').visualize() Numpy_Visualizer('../../8_xs_samples.npy').visualize() Numpy_Visualizer('../../9_xs_samples.npy').visualize()
// In seconds export const ONE_DAY = 86400; export const ONE_WEEK = 604800; export const TWO_WEEKS = 1209600;
# Generated by gen_torchvision_benchmark.py import torch import torch.optim as optim import torchvision.models as models class Model: def __init__(self, device="cpu", jit=False): self.device = device self.jit = jit self.model = models.squeezenet1_1() if self.jit: self.model = torch.jit.script(self.model) self.example_inputs = (torch.randn((32, 3, 224, 224)),) def get_module(self): return self.model, self.example_inputs def train(self, niter=3): optimizer = optim.Adam(self.model.parameters()) loss = torch.nn.CrossEntropyLoss() for _ in range(niter): optimizer.zero_grad() pred = self.model(*self.example_inputs) y = torch.empty(pred.shape[0], dtype=torch.long).random_(pred.shape[1]) loss(pred, y).backward() optimizer.step() def eval(self, niter=1): model, example_inputs = self.get_module() example_inputs = example_inputs[0][0].unsqueeze(0) for i in range(niter): model(example_inputs) if __name__ == "__main__": m = Model(device="cuda", jit=True) module, example_inputs = m.get_module() module(*example_inputs) m.train(niter=1) m.eval(niter=1)
// const installExtensions = async () => { // if (isDev) { // const installer = require('electron-devtools-installer'); // eslint-disable-line global-require // const extensions = [ // 'REACT_DEVELOPER_TOOLS', // 'REDUX_DEVTOOLS' // ]; // const forceDownload = !!process.env.UPGRADE_EXTENSIONS; // for (const name of extensions) { // eslint-disable-line // try { // await installer.default(installer[name], forceDownload); // } catch (e) {} // eslint-disable-line // } // } // }; const installDevTools = (mainWindow) => { if (process.env.NODE_ENV === 'development') { require('electron-debug')(); // eslint-disable-line global-require mainWindow.openDevTools(); } }; module.exports = { installDevTools, };
importScripts("../dist/localforage.js"); self.addEventListener('message', function(e) { var data = e.data; function handleError(e) { data.value = e.message; self.postMessage({ error: JSON.stringify(e), body: data, fail: true }); } localforage.setDriver(data.driver) .then(function () { data.value += ' with ' + localforage.driver(); return localforage.setItem(data.key, data); }, handleError) .then(function () { return localforage.getItem(data.key); }, handleError) .then(function (data) { self.postMessage({ body: data }); }, handleError) .catch(handleError); }, false);
import React, { Component, Fragment } from 'react'; import DateBox from 'devextreme-react/date-box'; import './date-time.scss'; class DateTime extends Component { constructor(props) { super(props); // this.now = new Date(); this.value = this.props.value; //add check url this.state = { fromURL: '' }; this.onValueChanged = this.onValueChanged.bind(this); } componentDidMount() { let prvUrl = document.referrer; //console.log(prvUrl); let paraString = prvUrl.substring(prvUrl.indexOf("/")+1).split("/"); console.log(paraString); let nowEnv = paraString[2]; console.log(nowEnv); this.setState({fromURL: nowEnv}); } onValueChanged(e) { this.setState({ value: e.value }); } render() { return ( <Fragment> <div className="dx-field-datetime"> <DateBox // defaultValue={this.value} type="datetime" /> <p>{this.state.fromURL}</p> </div> </Fragment> ); } } export default DateTime;
""" This script defines an example automated tron client that will avoid walls if it's about to crash into one. This is meant to be an example of how to implement a basic matchmaking agent. """ import argparse from random import choice, randint from colosseumrl.envs.tron.rllib import SimpleAvoidAgent from colosseumrl.matchmaking import request_game, GameResponse from colosseumrl.RLApp import create_rl_agent from colosseumrl.envs.tron import TronGridClientEnvironment from colosseumrl.envs.tron import TronGridEnvironment from colosseumrl.rl_logging import get_logger logger = get_logger() def tron_client(env: TronGridClientEnvironment, username: str): """ Our client function for the random tron client. Parameters ---------- env : TronGridClientEnvironment The client environment that we will interact with for this agent. username : str Our desired username. """ # Connect to the game server and wait for the game to begin. # We run env.connect once we have initialized ourselves and we are ready to join the game. player_num = env.connect(username) logger.debug("Player number: {}".format(player_num)) # Next we run env.wait_for_turn() to wait for our first real observation env.wait_for_turn() logger.info("Game started...") # Keep executing moves until the game is over terminal = False agent = SimpleAvoidAgent() while not terminal: # See if there is a wall in front of us, if there is, then we will turn in a random direction. action = agent(env.server_environment, env.observation) # We use env.step in order to execute an action and wait until it is our turn again. # This function will block while the action is executed and will return the next observation that belongs to us new_obs, reward, terminal, winners = env.step(action) print("Took step with action {}, got: {}".format(action, (new_obs, reward, terminal, winners))) # Once the game is over, we print out the results and close the agent. logger.info("Game is over. Players {} won".format(winners)) logger.info("Final observation: {}".format(new_obs)) if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--host", "-s", type=str, default="localhost", help="Hostname of the matchmaking server.") parser.add_argument("--port", "-p", type=int, default=50051, help="Port the matchmaking server is running on.") parser.add_argument("--username", "-u", type=str, default="", help="Desired username to use for your connection. By default it will generate a random one.") logger.debug("Connecting to matchmaking server. Waiting for a game to be created.") args = parser.parse_args() if args.username == "": username = "Tester_{}".format(randint(0, 1000)) else: username = args.username # We use request game to connect to the matchmaking server and await a game assigment. game: GameResponse = request_game(args.host, args.port, username) logger.debug("Game has been created. Playing as {}".format(username)) logger.debug("Current Ranking: {}".format(game.ranking)) # Once we have been assigned a game server, we launch an RLApp agent and begin our computation agent = create_rl_agent(agent_fn=tron_client, host=game.host, port=game.port, auth_key=game.token, client_environment=TronGridClientEnvironment, server_environment=TronGridEnvironment) agent(username)
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ (function() { function u() { return !1; } function x(a, b) { var c, d = []; a.filterChildren(b); for (c = a.children.length - 1; 0 <= c; c--) d.unshift(a.children[c]), a.children[c].remove(); c = a.attributes; var e = a, g = !0, h; for (h in c) if (g) g = !1; else { var l = new CKEDITOR.htmlParser.element(a.name); l.attributes[h] = c[h]; e.add(l); e = l; delete c[h]; } for (c = 0; c < d.length; c++) e.add(d[c]); } var f, k, t, p, m = CKEDITOR.tools, y = ['o:p', 'xml', 'script', 'meta', 'link'], z = 'v:arc v:curve v:line v:oval v:polyline v:rect v:roundrect v:group'.split( ' ', ), w = {}, v = 0; CKEDITOR.plugins.pastefromword = {}; CKEDITOR.cleanWord = function(a, b) { function c(a) { (a.attributes['o:gfxdata'] || 'v:group' === a.parent.name) && e.push(a.attributes.id); } var d = Boolean(a.match(/mso-list:\s*l\d+\s+level\d+\s+lfo\d+/)), e = []; CKEDITOR.plugins.clipboard.isCustomDataTypesSupported && (a = CKEDITOR.plugins.pastefromword.styles.inliner .inline(a) .getBody() .getHtml()); a = a.replace(/<!\[/g, '\x3c!--[').replace(/\]>/g, ']--\x3e'); var g = CKEDITOR.htmlParser.fragment.fromHtml(a), h = { root: function(a) { a.filterChildren(p); CKEDITOR.plugins.pastefromword.lists.cleanup(f.createLists(a)); }, elementNames: [ [/^\?xml:namespace$/, ''], [/^v:shapetype/, ''], [new RegExp(y.join('|')), ''], ], elements: { a: function(a) { if (a.attributes.name) { if ('_GoBack' == a.attributes.name) { delete a.name; return; } if (a.attributes.name.match(/^OLE_LINK\d+$/)) { delete a.name; return; } } if (a.attributes.href && a.attributes.href.match(/#.+$/)) { var b = a.attributes.href.match(/#(.+)$/)[1]; w[b] = a; } a.attributes.name && w[a.attributes.name] && ((a = w[a.attributes.name]), (a.attributes.href = a.attributes.href.replace( /.*#(.*)$/, '#$1', ))); }, div: function(a) { k.createStyleStack(a, p, b); }, img: function(a) { if (a.parent && a.parent.attributes) { var b = a.parent.attributes; (b = b.style || b.STYLE) && b.match(/mso\-list:\s?Ignore/) && (a.attributes['cke-ignored'] = !0); } k.mapStyles(a, { width: function(b) { k.setStyle(a, 'width', b + 'px'); }, height: function(b) { k.setStyle(a, 'height', b + 'px'); }, }); a.attributes.src && a.attributes.src.match(/^file:\/\//) && a.attributes.alt && a.attributes.alt.match(/^https?:\/\//) && (a.attributes.src = a.attributes.alt); var b = a.attributes['v:shapes'] ? a.attributes['v:shapes'].split(' ') : [], c = CKEDITOR.tools.array.every(b, function(a) { return -1 < e.indexOf(a); }); if (b.length && c) return !1; }, p: function(a) { a.filterChildren(p); if ( a.attributes.style && a.attributes.style.match(/display:\s*none/i) ) return !1; if (f.thisIsAListItem(b, a)) t.isEdgeListItem(b, a) && t.cleanupEdgeListItem(a), f.convertToFakeListItem(b, a), m.array.reduce( a.children, function(a, b) { 'p' === b.name && (0 < a && new CKEDITOR.htmlParser.element('br').insertBefore(b), b.replaceWithChildren(), (a += 1)); return a; }, 0, ); else { var c = a.getAscendant(function(a) { return 'ul' == a.name || 'ol' == a.name; }), d = m.parseCssText(a.attributes.style); c && !c.attributes['cke-list-level'] && d['mso-list'] && d['mso-list'].match(/level/) && (c.attributes['cke-list-level'] = d['mso-list'].match( /level(\d+)/, )[1]); b.config.enterMode == CKEDITOR.ENTER_BR && (delete a.name, a.add(new CKEDITOR.htmlParser.element('br'))); } k.createStyleStack(a, p, b); }, pre: function(a) { f.thisIsAListItem(b, a) && f.convertToFakeListItem(b, a); k.createStyleStack(a, p, b); }, h1(a){f.thisIsAListItem(b,a)&&f.convertToFakeListItem(b,a);k.createStyleStack(a,p,b)},h2(a){f.thisIsAListItem(b,a)&&f.convertToFakeListItem(b,a);k.createStyleStack(a,p,b)},h3(a){f.thisIsAListItem(b,a)&&f.convertToFakeListItem(b,a);k.createStyleStack(a,p,b)},h4(a){f.thisIsAListItem(b,a)&&f.convertToFakeListItem(b,a);k.createStyleStack(a,p,b)},h5(a){f.thisIsAListItem(b,a)&&f.convertToFakeListItem(b,a);k.createStyleStack(a,p,b)},h6(a){f.thisIsAListItem(b, a)&&f.convertToFakeListItem(b,a);k.createStyleStack(a,p,b)},font(a){if(a.getHtml().match(/^\s*$/))return(new CKEDITOR.htmlParser.text(" ")).insertAfter(a),!1;b&&!0===b.config.pasteFromWordRemoveFontStyles&&a.attributes.size&&delete a.attributes.size;CKEDITOR.dtd.tr[a.parent.name]&&CKEDITOR.tools.arrayCompare(CKEDITOR.tools.objectKeys(a.attributes),["class","style"])?k.createStyleStack(a,p,b):x(a,p)},ul(a){if(d)return"li"==a.parent.name&&0===m.indexOf(a.parent.children,a)&&k.setStyle(a.parent, "list-style-type","none"),f.dissolveList(a),!1},li(a){t.correctLevelShift(a);d&&(a.attributes.style=k.normalizedStyles(a,b),k.pushStylesLower(a))},ol(a){if(d)return"li"==a.parent.name&&0===m.indexOf(a.parent.children,a)&&k.setStyle(a.parent,"list-style-type","none"),f.dissolveList(a),!1},span(a){a.filterChildren(p);a.attributes.style=k.normalizedStyles(a,b);if(!a.attributes.style||a.attributes.style.match(/^mso\-bookmark:OLE_LINK\d+$/)||a.getHtml().match(/^(\s|&nbsp;)+$/)){for(var c= a.children.length-1;0<=c;c--)a.children[c].insertAfter(a);return!1}a.attributes.style.match(/FONT-FAMILY:\s*Symbol/i)&&a.forEach(function(a){a.value=a.value.replace(/&nbsp;/g,"")},CKEDITOR.NODE_TEXT,!0);k.createStyleStack(a,p,b)},table(a){a._tdBorders={};a.filterChildren(p);var b,c=0,d;for(d in a._tdBorders)a._tdBorders[d]>c&&(c=a._tdBorders[d],b=d);k.setStyle(a,"border",b);c=(b=a.parent)&&b.parent;if(b.name&&"div"===b.name&&b.attributes.align&&1===m.objectKeys(b.attributes).length&&1=== b.children.length){a.attributes.align=b.attributes.align;d=b.children.splice(0);a.remove();for(a=d.length-1;0<=a;a--)c.add(d[a],b.getIndex());b.remove()}},td(a){var c=a.getAscendant("table"),d=c._tdBorders,e=["border","border-top","border-right","border-bottom","border-left"],c=m.parseCssText(c.attributes.style),g=c.background||c.BACKGROUND;g&&k.setStyle(a,"background",g,!0);(c=c["background-color"]||c["BACKGROUND-COLOR"])&&k.setStyle(a,"background-color",c,!0);var c=m.parseCssText(a.attributes.style), h;for(h in c)g=c[h],delete c[h],c[h.toLowerCase()]=g;for(h=0;h<e.length;h++)c[e[h]]&&(g=c[e[h]],d[g]=d[g]?d[g]+1:1);k.createStyleStack(a,p,b,/margin|text\-align|padding|list\-style\-type|width|height|border|white\-space|vertical\-align|background/i)},"v:imagedata":u,"v:shape":function(a){let b=!1;if(a.getFirst("v:imagedata")===null)c(a);else{a.parent.find((c) => {"img"==c.name&&c.attributes&&c.attributes["v:shapes"]==a.attributes.id&&(b=!0)},!0);if(b)return!1;let d="";a.parent.name==="v:group"? ? c(a) : (a.forEach( function(a) { a.attributes && a.attributes.src && (d = a.attributes.src); }, CKEDITOR.NODE_ELEMENT, !0, ), a.filterChildren(p), (a.name = 'img'), (a.attributes.src = a.attributes.src || d), delete a.attributes.type); } }, style: function() { return !1; }, object: function(a) { return !(!a.attributes || !a.attributes.data); }, }, attributes: { style: function(a, c) { return k.normalizedStyles(c, b) || !1; }, class: function(a) { a = a.replace( /(el\d+)|(font\d+)|msonormal|msolistparagraph\w*/gi, '', ); return '' === a ? !1 : a; }, cellspacing: u, cellpadding: u, border: u, 'v:shapes': u, 'o:spid': u, }, comment: function(a) { a.match(/\[if.* supportFields.*\]/) && v++; '[endif]' == a && (v = 0 < v ? v - 1 : 0); return !1; }, text: function(a, b) { if (v) return ''; var c = b.parent && b.parent.parent; return c && c.attributes && c.attributes.style && c.attributes.style.match(/mso-list:\s*ignore/i) ? a.replace(/&nbsp;/g, ' ') : a; }, }; CKEDITOR.tools.array.forEach(z, function(a) { h.elements[a] = c; }); p = new CKEDITOR.htmlParser.filter(h); var l = new CKEDITOR.htmlParser.basicWriter(); p.applyTo(g); g.writeHtml(l); return l.getHtml(); }; CKEDITOR.plugins.pastefromword.styles = { setStyle: function(a, b, c, d) { var e = m.parseCssText(a.attributes.style); (d && e[b]) || ('' === c ? delete e[b] : (e[b] = c), (a.attributes.style = CKEDITOR.tools.writeCssText(e))); }, mapStyles: function(a, b) { for (var c in b) if (a.attributes[c]) { if ('function' === typeof b[c]) b[c](a.attributes[c]); else k.setStyle(a, b[c], a.attributes[c]); delete a.attributes[c]; } }, normalizedStyles: function(a, b) { var c = 'background-color:transparent border-image:none color:windowtext direction:ltr mso- text-indent visibility:visible div:border:none'.split( ' ', ), d = 'font-family font font-size color background-color line-height text-decoration'.split( ' ', ), e = function() { for (var a = [], b = 0; b < arguments.length; b++) arguments[b] && a.push(arguments[b]); return -1 !== m.indexOf(c, a.join(':')); }, g = b && !0 === b.config.pasteFromWordRemoveFontStyles, h = m.parseCssText(a.attributes.style); 'cke:li' == a.name && h['TEXT-INDENT'] && h.MARGIN && ((a.attributes['cke-indentation'] = f.getElementIndentation(a)), (h.MARGIN = h.MARGIN.replace( /(([\w\.]+ ){3,3})[\d\.]+(\w+$)/, '$10$3', ))); for (var l = m.objectKeys(h), q = 0; q < l.length; q++) { var n = l[q].toLowerCase(), r = h[l[q]], k = CKEDITOR.tools.indexOf; ((g && -1 !== k(d, n.toLowerCase())) || e(null, n, r) || e(null, n.replace(/\-.*$/, '-')) || e(null, n) || e(a.name, n, r) || e(a.name, n.replace(/\-.*$/, '-')) || e(a.name, n) || e(r)) && delete h[l[q]]; } return CKEDITOR.tools.writeCssText(h); }, createStyleStack: function(a, b, c, d) { var e = []; a.filterChildren(b); for (b = a.children.length - 1; 0 <= b; b--) e.unshift(a.children[b]), a.children[b].remove(); k.sortStyles(a); b = m.parseCssText(k.normalizedStyles(a, c)); c = a; var g = 'span' === a.name, h; for (h in b) if (!h.match(d || /margin|text\-align|width|border|padding/i)) if (g) g = !1; else { var l = new CKEDITOR.htmlParser.element('span'); l.attributes.style = h + ':' + b[h]; c.add(l); c = l; delete b[h]; } CKEDITOR.tools.isEmpty(b) ? delete a.attributes.style : (a.attributes.style = CKEDITOR.tools.writeCssText(b)); for (b = 0; b < e.length; b++) c.add(e[b]); }, sortStyles: function(a) { for ( var b = ['border', 'border-bottom', 'font-size', 'background'], c = m.parseCssText(a.attributes.style), d = m.objectKeys(c), e = [], g = [], h = 0; h < d.length; h++ ) -1 !== m.indexOf(b, d[h].toLowerCase()) ? e.push(d[h]) : g.push(d[h]); e.sort(function(a, c) { var d = m.indexOf(b, a.toLowerCase()), e = m.indexOf(b, c.toLowerCase()); return d - e; }); d = [].concat(e, g); e = {}; for (h = 0; h < d.length; h++) e[d[h]] = c[d[h]]; a.attributes.style = CKEDITOR.tools.writeCssText(e); }, pushStylesLower: function(a, b, c) { if (!a.attributes.style || 0 === a.children.length) return !1; b = b || {}; var d = { 'list-style-type': !0, width: !0, height: !0, border: !0, 'border-': !0, }, e = m.parseCssText(a.attributes.style), g; for (g in e) if ( !( g.toLowerCase() in d || d[g.toLowerCase().replace(/\-.*$/, '-')] || g.toLowerCase() in b ) ) { for (var h = !1, l = 0; l < a.children.length; l++) { var f = a.children[l]; if (f.type === CKEDITOR.NODE_TEXT && c) { var n = new CKEDITOR.htmlParser.element('span'); n.setHtml(f.value); f.replaceWith(n); f = n; } f.type === CKEDITOR.NODE_ELEMENT && ((h = !0), k.setStyle(f, g, e[g])); } h && delete e[g]; } a.attributes.style = CKEDITOR.tools.writeCssText(e); return !0; }, inliner: { filtered: 'break-before break-after break-inside page-break page-break-before page-break-after page-break-inside'.split( ' ', ), parse(a){function b(a){var b=new CKEDITOR.dom.element("style"),c=new CKEDITOR.dom.element("iframe");c.hide();CKEDITOR.document.getBody().append(c);c.$.contentDocument.documentElement.appendChild(b.$);b.$.textContent=a;c.remove();return b.$.sheet}function c(a){var b=a.indexOf("{"),c=a.indexOf("}");return d(a.substring(b+1,c),!0)}var d=CKEDITOR.tools.parseCssText,e=CKEDITOR.plugins.pastefromword.styles.inliner.filter,g=a.is?a.$.sheet:b(a);a=[];var h;if(g)for(g=g.cssRules,h=0;h<g.length;h++)g[h].type=== window.CSSRule.STYLE_RULE&&a.push({selector:g[h].selectorText,styles:e(c(g[h].cssText))});return a},filter(a){var b=CKEDITOR.plugins.pastefromword.styles.inliner.filtered,c=m.array.indexOf,d={},e;for(e in a)-1===c(b,e)&&(d[e]=a[e]);return d},sort(a){return a.sort(function(a){var c=CKEDITOR.tools.array.map(a,function(a){return a.selector});return function(a,b){var g=-1!==(""+a.selector).indexOf(".")?1:0,g=(-1!==(""+b.selector).indexOf(".")?1:0)-g;return 0!==g?g:c.indexOf(b.selector)- c.indexOf(a.selector)}}(a))},inline(a){var b=CKEDITOR.plugins.pastefromword.styles.inliner.parse,c=CKEDITOR.plugins.pastefromword.styles.inliner.sort,d=function(a){a=(new DOMParser).parseFromString(a,"text/html");return new CKEDITOR.dom.document(a)}(a);a=d.find("style");c=c(function(a){var c=[],d;for(d=0;d<a.count();d++)c=c.concat(b(a.getItem(d)));return c}(a));CKEDITOR.tools.array.forEach(c,function(a){var b=a.styles;a=d.find(a.selector);var c,f,q;for(q=0;q<a.count();q++)c=a.getItem(q), f=CKEDITOR.tools.parseCssText(c.getAttribute("style")),f=CKEDITOR.tools.extend({},f,b),c.setAttribute("style",CKEDITOR.tools.writeCssText(f))});return d}}};k=CKEDITOR.plugins.pastefromword.styles;CKEDITOR.plugins.pastefromword.lists={thisIsAListItem(a,b){return t.isEdgeListItem(a,b)||b.attributes.style&&b.attributes.style.match(/mso\-list:\s?l\d/)&&"li"!==b.parent.name||b.attributes["cke-dissolved"]||b.getHtml().match(/<!\-\-\[if !supportLists]\-\->/)?!0:!1},convertToFakeListItem(a, b){t.isDegenerateListItem(a,b)&&t.assignListLevels(a,b);this.getListItemInfo(b);if(!b.attributes["cke-dissolved"]){var c;b.forEach(function(a){!c&&"img"==a.name&&a.attributes["cke-ignored"]&&"*"==a.attributes.alt&&(c="·",a.remove())},CKEDITOR.NODE_ELEMENT);b.forEach(function(a){c||a.value.match(/^ /)||(c=a.value)},CKEDITOR.NODE_TEXT);if("undefined"==typeof c)return;b.attributes["cke-symbol"]=c.replace(/(?: |&nbsp;).*$/,"");f.removeSymbolText(b)}if(b.attributes.style){var d=m.parseCssText(b.attributes.style); d["margin-left"]&&(delete d["margin-left"],b.attributes.style=CKEDITOR.tools.writeCssText(d))}b.name="cke:li"},convertToRealListItems(a){var b=[];a.forEach(function(a){"cke:li"==a.name&&(a.name="li",b.push(a))},CKEDITOR.NODE_ELEMENT,!1);return b},removeSymbolText(a){var b,c=a.attributes["cke-symbol"];a.forEach(function(d){!b&&-1<d.value.indexOf(c)&&(d.value=d.value.replace(c,""),d.parent.getHtml().match(/^(\s|&nbsp;)*$/)&&(b=d.parent!==a?d.parent:null))},CKEDITOR.NODE_TEXT);b&&b.remove()}, setListSymbol(a,b,c){c=c||1;var d=m.parseCssText(a.attributes.style);if("ol"==a.name){if(a.attributes.type||d["list-style-type"])return;var e={"[ivx]":"lower-roman","[IVX]":"upper-roman","[a-z]":"lower-alpha","[A-Z]":"upper-alpha","\\d":"decimal"},g;for(g in e)if(f.getSubsectionSymbol(b).match(new RegExp(g))){d["list-style-type"]=e[g];break}a.attributes["cke-list-style-type"]=d["list-style-type"]}else e={"·":"disc",o:"circle","§":"square"},!d["list-style-type"]&&e[b]&&(d["list-style-type"]= e[b]);f.setListSymbol.removeRedundancies(d,c);(a.attributes.style=CKEDITOR.tools.writeCssText(d))||delete a.attributes.style},setListStart(a){for(var b=[],c=0,d=0;d<a.children.length;d++)b.push(a.children[d].attributes["cke-symbol"]||"");b[0]||c++;switch(a.attributes["cke-list-style-type"]){case "lower-roman":case "upper-roman":a.attributes.start=f.toArabic(f.getSubsectionSymbol(b[c]))-c;break;case "lower-alpha":case "upper-alpha":a.attributes.start=f.getSubsectionSymbol(b[c]).replace(/\W/g, "").toLowerCase().charCodeAt(0)-96-c;break;case "decimal":a.attributes.start=parseInt(f.getSubsectionSymbol(b[c]),10)-c||1}"1"==a.attributes.start&&delete a.attributes.start;delete a.attributes["cke-list-style-type"]},numbering:{toNumber(a,b){function c(a){a=a.toUpperCase();for(var b=1,c=1;0<a.length;c*=26)b+="ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(a.charAt(a.length-1))*c,a=a.substr(0,a.length-1);return b}function d(a){var b=[[1E3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50, "L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]];a=a.toUpperCase();for(var c=b.length,d=0,f=0;f<c;++f)for(var n=b[f],r=n[1].length;a.substr(0,r)==n[1];a=a.substr(r))d+=n[0];return d}return"decimal"==b?Number(a):"upper-roman"==b||"lower-roman"==b?d(a.toUpperCase()):"lower-alpha"==b||"upper-alpha"==b?c(a):1},getStyle(a){a=a.slice(0,1);var b={i:"lower-roman",v:"lower-roman",x:"lower-roman",l:"lower-roman",m:"lower-roman",I:"upper-roman",V:"upper-roman",X:"upper-roman",L:"upper-roman", M:"upper-roman"}[a];b||(b="decimal",a.match(/[a-z]/)&&(b="lower-alpha"),a.match(/[A-Z]/)&&(b="upper-alpha"));return b}},getSubsectionSymbol(a){return(a.match(/([\da-zA-Z]+).?$/)||["placeholder","1"])[1]},setListDir(a){var b=0,c=0;a.forEach(function(a){"li"==a.name&&("rtl"==(a.attributes.dir||a.attributes.DIR||"").toLowerCase()?c++:b++)},CKEDITOR.ELEMENT_NODE);c>b&&(a.attributes.dir="rtl")},createList(a){return(a.attributes["cke-symbol"].match(/([\da-np-zA-NP-Z]).?/)||[])[1]? new CKEDITOR.htmlParser.element("ol"):new CKEDITOR.htmlParser.element("ul")},createLists(a){var b,c,d,e=f.convertToRealListItems(a);if(0===e.length)return[];var g=f.groupLists(e);for(a=0;a<g.length;a++){var h=g[a],l=h[0];for(d=0;d<h.length;d++)if(1==h[d].attributes["cke-list-level"]){l=h[d];break}var l=[f.createList(l)],k=l[0],n=[l[0]];k.insertBefore(h[0]);for(d=0;d<h.length;d++){b=h[d];for(c=b.attributes["cke-list-level"];c>l.length;){var r=f.createList(b),m=k.children;0<m.length?m[m.length- 1].add(r):(m=new CKEDITOR.htmlParser.element("li",{style:"list-style-type:none"}),m.add(r),k.add(m));l.push(r);n.push(r);k=r;c==l.length&&f.setListSymbol(r,b.attributes["cke-symbol"],c)}for(;c<l.length;)l.pop(),k=l[l.length-1],c==l.length&&f.setListSymbol(k,b.attributes["cke-symbol"],c);b.remove();k.add(b)}l[0].children.length&&(d=l[0].children[0].attributes["cke-symbol"],!d&&1<l[0].children.length&&(d=l[0].children[1].attributes["cke-symbol"]),d&&f.setListSymbol(l[0],d));for(d=0;d<n.length;d++)f.setListStart(n[d]); for(d=0;d<h.length;d++)this.determineListItemValue(h[d])}return e},cleanup(a){var b=["cke-list-level","cke-symbol","cke-list-id","cke-indentation","cke-dissolved"],c,d;for(c=0;c<a.length;c++)for(d=0;d<b.length;d++)delete a[c].attributes[b[d]]},determineListItemValue(a){if("ol"===a.parent.name){var b=this.calculateValue(a),c=a.attributes["cke-symbol"].match(/[a-z0-9]+/gi),d;c&&(c=c[c.length-1],d=a.parent.attributes["cke-list-style-type"]||this.numbering.getStyle(c),c=this.numbering.toNumber(c, d),c!==b&&(a.attributes.value=c))}},calculateValue(a){if(!a.parent)return 1;var b=a.parent;a=a.getIndex();var c=null,d,e,g;for(g=a;0<=g&&null===c;g--)e=b.children[g],e.attributes&&void 0!==e.attributes.value&&(d=g,c=parseInt(e.attributes.value,10));null===c&&(c=void 0!==b.attributes.start?parseInt(b.attributes.start,10):1,d=0);return c+(a-d)},dissolveList(a){function b(a){return 50<=a?"l"+b(a-50):40<=a?"xl"+b(a-40):10<=a?"x"+b(a-10):9==a?"ix":5<=a?"v"+b(a-5):4==a?"iv":1<=a?"i"+b(a- 1):""}function c(a,b){function c(b,d){return b&&b.parent?a(b.parent)?c(b.parent,d+1):c(b.parent,d):d}return c(b,0)}var d=function(a){return function(b){return b.name==a}},e=function(a){return d("ul")(a)||d("ol")(a)},g=CKEDITOR.tools.array,h=[],f,q;a.forEach(function(a){h.push(a)},CKEDITOR.NODE_ELEMENT,!1);f=g.filter(h,d("li"));var n=g.filter(h,e);g.forEach(n,function(a){var h=a.attributes.type,f=parseInt(a.attributes.start,10)||1,l=c(e,a)+1;h||(h=m.parseCssText(a.attributes.style)["list-style-type"]); g.forEach(g.filter(a.children,d("li")),function(c,d){var e;switch(h){case "disc":e="·";break;case "circle":e="o";break;case "square":e="§";break;case "1":case "decimal":e=f+d+".";break;case "a":case "lower-alpha":e=String.fromCharCode(97+f-1+d)+".";break;case "A":case "upper-alpha":e=String.fromCharCode(65+f-1+d)+".";break;case "i":case "lower-roman":e=b(f+d)+".";break;case "I":case "upper-roman":e=b(f+d).toUpperCase()+".";break;default:e="ul"==a.name?"·":f+d+"."}c.attributes["cke-symbol"]=e;c.attributes["cke-list-level"]= l})});f=g.reduce(f,function(a,b){var c=b.children[0];if(c&&c.name&&c.attributes.style&&c.attributes.style.match(/mso-list:/i)){k.pushStylesLower(b,{"list-style-type":!0,display:!0});var d=m.parseCssText(c.attributes.style,!0);k.setStyle(b,"mso-list",d["mso-list"],!0);k.setStyle(c,"mso-list","");delete b["cke-list-level"];(c=d.display?"display":d.DISPLAY?"DISPLAY":"")&&k.setStyle(b,"display",d[c],!0)}if(1===b.children.length&&e(b.children[0]))return a;b.name="p";b.attributes["cke-dissolved"]=!0;a.push(b); return a},[]);for(q=f.length-1;0<=q;q--)f[q].insertAfter(a);for(q=n.length-1;0<=q;q--)delete n[q].name},groupLists(a){var b,c,d=[[a[0]]],e=d[0];c=a[0];c.attributes["cke-indentation"]=c.attributes["cke-indentation"]||f.getElementIndentation(c);for(b=1;b<a.length;b++){c=a[b];var g=a[b-1];c.attributes["cke-indentation"]=c.attributes["cke-indentation"]||f.getElementIndentation(c);c.previous!==g&&(f.chopDiscontinuousLists(e,d),d.push(e=[]));e.push(c)}f.chopDiscontinuousLists(e,d);return d},chopDiscontinuousLists(a, b){for(var c={},d=[[]],e,g=0;g<a.length;g++){var h=c[a[g].attributes["cke-list-level"]],l=this.getListItemInfo(a[g]),k,n;h?(n=h.type.match(/alpha/)&&7==h.index?"alpha":n,n="o"==a[g].attributes["cke-symbol"]&&14==h.index?"alpha":n,k=f.getSymbolInfo(a[g].attributes["cke-symbol"],n),l=this.getListItemInfo(a[g]),(h.type!=k.type||e&&l.id!=e.id&&!this.isAListContinuation(a[g]))&&d.push([])):k=f.getSymbolInfo(a[g].attributes["cke-symbol"]);for(e=parseInt(a[g].attributes["cke-list-level"],10)+1;20>e;e++)c[e]&& delete c[e];c[a[g].attributes["cke-list-level"]]=k;d[d.length-1].push(a[g]);e=l}[].splice.apply(b,[].concat([m.indexOf(b,a),1],d))},isAListContinuation(a){var b=a;do if((b=b.previous)&&b.type===CKEDITOR.NODE_ELEMENT){if(void 0===b.attributes["cke-list-level"])break;if(b.attributes["cke-list-level"]===a.attributes["cke-list-level"])return b.attributes["cke-list-id"]===a.attributes["cke-list-id"]}while(b);return!1},getElementIndentation(a){a=m.parseCssText(a.attributes.style);if(a.margin|| a.MARGIN){a.margin=a.margin||a.MARGIN;var b={styles:{margin:a.margin}};CKEDITOR.filter.transformationsTools.splitMarginShorthand(b);a["margin-left"]=b.styles["margin-left"]}return parseInt(m.convertToPx(a["margin-left"]||"0px"),10)},toArabic(a){return a.match(/[ivxl]/i)?a.match(/^l/i)?50+f.toArabic(a.slice(1)):a.match(/^lx/i)?40+f.toArabic(a.slice(1)):a.match(/^x/i)?10+f.toArabic(a.slice(1)):a.match(/^ix/i)?9+f.toArabic(a.slice(2)):a.match(/^v/i)?5+f.toArabic(a.slice(1)):a.match(/^iv/i)? 4+f.toArabic(a.slice(2)):a.match(/^i/i)?1+f.toArabic(a.slice(1)):f.toArabic(a.slice(1)):0},getSymbolInfo(a,b){var c=a.toUpperCase()==a?"upper-":"lower-",d={"·":["disc",-1],o:["circle",-2],"§":["square",-3]};if(a in d||b&&b.match(/(disc|circle|square)/))return{index:d[a][1],type:d[a][0]};if(a.match(/\d/))return{index:a?parseInt(f.getSubsectionSymbol(a),10):0,type:"decimal"};a=a.replace(/\W/g,"").toLowerCase();return!b&&a.match(/[ivxl]+/i)||b&&"alpha"!=b||"roman"==b?{index:f.toArabic(a),type:c+ "roman"}:a.match(/[a-z]/i)?{index:a.charCodeAt(0)-97,type:c+"alpha"}:{index:-1,type:"disc"}},getListItemInfo(a){if(void 0!==a.attributes["cke-list-id"])return{id:a.attributes["cke-list-id"],level:a.attributes["cke-list-level"]};var b=m.parseCssText(a.attributes.style)["mso-list"],c={id:"0",level:"1"};b&&(b+=" ",c.level=b.match(/level(.+?)\s+/)[1],c.id=b.match(/l(\d+?)\s+/)[1]);a.attributes["cke-list-level"]=void 0!==a.attributes["cke-list-level"]?a.attributes["cke-list-level"]:c.level;a.attributes["cke-list-id"]= c.id;return c}};f=CKEDITOR.plugins.pastefromword.lists;CKEDITOR.plugins.pastefromword.images={extractFromRtf(a){var b=[],c=/\{\\pict[\s\S]+?\\bliptag\-?\d+(\\blipupi\-?\d+)?(\{\\\*\\blipuid\s?[\da-fA-F]+)?[\s\}]*?/,d;a=a.match(new RegExp("(?:("+c.source+"))([\\da-fA-F\\s]+)\\}","g"));if(!a)return b;for(var e=0;e<a.length;e++)if(c.test(a[e])){if(-1!==a[e].indexOf("\\pngblip"))d="image/png";else if(-1!==a[e].indexOf("\\jpegblip"))d="image/jpeg";else continue;b.push({hex:d?a[e].replace(c,"").replace(/[^\da-fA-F]/g, ""):null,type:d})}return b},extractTagsFromHtml(a){for(var b=/<img[^>]+src="([^"]+)[^>]+/g,c=[],d;d=b.exec(a);)c.push(d[1]);return c}};CKEDITOR.plugins.pastefromword.heuristics={isEdgeListItem(a,b){if(!CKEDITOR.env.edge||!a.config.pasteFromWord_heuristicsEdgeList)return!1;var c="";b.forEach&&b.forEach(function(a){c+=a.value},CKEDITOR.NODE_TEXT);return c.match(/^(?: |&nbsp;)*\(?[a-zA-Z0-9]+?[\.\)](?: |&nbsp;){2,}/)?!0:t.isDegenerateListItem(a,b)},cleanupEdgeListItem(a){var b= !1;a.forEach(function(a){b||(a.value=a.value.replace(/^(?:&nbsp;|[\s])+/,""),a.value.length&&(b=!0))},CKEDITOR.NODE_TEXT)},isDegenerateListItem(a,b){return!!b.attributes["cke-list-level"]||b.attributes.style&&!b.attributes.style.match(/mso\-list/)&&!!b.find(function(a){if(a.type==CKEDITOR.NODE_ELEMENT&&b.name.match(/h\d/i)&&a.getHtml().match(/^[a-zA-Z0-9]+?[\.\)]$/))return!0;var d=m.parseCssText(a.attributes&&a.attributes.style,!0);if(!d)return!1;var e=d["font-family"]||"";return(d.font|| d["font-size"]||"").match(/7pt/i)&&!!a.previous||e.match(/symbol/i)},!0).length},assignListLevels(a,b){if(!b.attributes||void 0===b.attributes["cke-list-level"]){for(var c=[f.getElementIndentation(b)],d=[b],e=[],g=CKEDITOR.tools.array,h=g.map;b.next&&b.next.attributes&&!b.next.attributes["cke-list-level"]&&t.isDegenerateListItem(a,b.next);)b=b.next,c.push(f.getElementIndentation(b)),d.push(b);var k=h(c,function(a,b){return 0===b?0:a-c[b-1]}),m=this.guessIndentationStep(g.filter(c,function(a){return 0!== a})),e=h(c,function(a){return Math.round(a/m)});-1!==g.indexOf(e,0)&&(e=h(e,function(a){return a+1}));g.forEach(d,function(a,b){a.attributes["cke-list-level"]=e[b]});return{indents:c,levels:e,diffs:k}}},guessIndentationStep(a){return a.length?Math.min.apply(null,a):null},correctLevelShift(a){if(this.isShifted(a)){var b=CKEDITOR.tools.array.filter(a.children,function(a){return"ul"==a.name||"ol"==a.name}),c=CKEDITOR.tools.array.reduce(b,function(a,b){return(b.children&&1==b.children.length&& t.isShifted(b.children[0])?[b]:b.children).concat(a)},[]);CKEDITOR.tools.array.forEach(b,function(a){a.remove()});CKEDITOR.tools.array.forEach(c,function(b){a.add(b)});delete a.name}},isShifted(a){return"li"!==a.name?!1:0===CKEDITOR.tools.array.filter(a.children,function(a){return a.name&&("ul"==a.name||"ol"==a.name||"p"==a.name&&0===a.children.length)?!1:!0}).length}};t=CKEDITOR.plugins.pastefromword.heuristics;f.setListSymbol.removeRedundancies=function(a,b){(b===1&&a["list-style-type"]==="disc"|| a["list-style-type"]==="decimal")&&delete a["list-style-type"]};CKEDITOR.plugins.pastefromword.createAttributeStack=x;CKEDITOR.config.pasteFromWord_heuristicsEdgeList=!0})();
(function() { // Initialize the FirebaseUI Widget using Firebase. var ui = new firebaseui.auth.AuthUI(firebase.auth()); var uiConfig = { callbacks: { signInSuccessWithAuthResult: function(authResult, redirectUrl) { firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) { console.log(idToken) }).catch(function(error) { console.error(error); }); // User successfully signed in. // Return type determines whether we continue the redirect automatically // or whether we leave that to developer to handle. return true; }, uiShown: function() { // The widget is rendered. // Hide the loader. document.getElementById('loader').style.display = 'none'; } }, // Will use popup for IDP Providers sign-in flow instead of the default, redirect. signInFlow: 'popup', signInSuccessUrl: 'main.html', signInOptions: [ // Leave the lines as is for the providers you want to offer your users. firebase.auth.EmailAuthProvider.PROVIDER_ID, firebase.auth.GoogleAuthProvider.PROVIDER_ID, // firebase.auth.FacebookAuthProvider.PROVIDER_ID, // firebase.auth.TwitterAuthProvider.PROVIDER_ID, // firebase.auth.GithubAuthProvider.PROVIDER_ID, // firebase.auth.PhoneAuthProvider.PROVIDER_ID ], // Terms of service url. tosUrl: 'main.html', // Privacy policy url. privacyPolicyUrl: '<your-privacy-policy-url>' }; // The start method will wait until the DOM is loaded. ui.start('#firebaseui-auth-container', uiConfig); firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL) })()
import React, { Component } from "react"; import { Row, Form, Button, Col, Card, Alert } from "react-bootstrap"; import { useHistory } from "react-router-dom"; import '../App.css'; import { baseUrl } from "../config/cons"; class login extends Component { constructor(props) { super(props); this.state = { email: '', error: false } this.emailChange = this.emailChange.bind(this); this.passwordChange = this.passwordChange.bind(this); this.loginRequest = this.loginRequest.bind(this); } componentDidMount() { } loginRequest() { const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.state.email, password: this.state.password }) }; fetch(baseUrl + "/login", requestOptions) .then(res => { if(!res.ok){ throw new Error(res) } return res.json() }) .then( (result) => { console.log(result); if(result.token){ localStorage.setItem('token', result.token); this.props.history.push("/") } }, (error) => { this.setState({ error: true }); } ) .catch(err => { console.log(err); }); } emailChange(event) { this.setState({ email: event.target.value }) } passwordChange(event) { this.setState({ password: event.target.value }) } render() { let styles = { marginRight: '0px', marginLeft: '0px', }; return ( <Row style={styles} className="justify-content-center h-100 align-items-center" > <Col md={4}> <Card> <Card.Header> <Card.Title mt={2}> <h4>Log in</h4> </Card.Title> </Card.Header> <Card.Body> <Form> { this.state.error ? <AlertDismissibleExample /> : null } <Form.Group> <Form.Label>Username or Email</Form.Label> <Form.Control className="field-config" onChange={evt => this.emailChange(evt)} type="email" placeholder="Enter email" /> </Form.Group> <Form.Group> <Form.Label>Password</Form.Label> <Form.Control onChange={evt => this.passwordChange(evt)} type="password" placeholder="Password" /> </Form.Group> <Form.Group> </Form.Group> <div className="form-group"> <Button variant="outline-info" onClick={() => this.loginRequest()}>Log in</Button>{ } </div> </Form> </Card.Body> <Card.Body className="my-border-top text-center"> Don't have an account? <a href="/register" style={{ color: "#ffc68a" }}>Sign up</a> </Card.Body> </Card> </Col> </Row> ); } } const AlertDismissibleExample = () => { return ( <Alert variant="danger"> Incorrect username/email or passowrd. </Alert> ); } export default login;
var app = getApp() Page({ data: { hasUserInfo: false }, getUserInfo() { my.getAuthCode({ scopes: 'auth_user', fail: (error) => { console.error('getAuthCode', error); }, success: () => { // do login... // then my.getAuthUserInfo({ fail: (error) => { console.error('getAuthUserInfo', error); }, success: (userInfo) => { console.log(`userInfo:`, userInfo); this.setData({ userInfo, hasUserInfo: true, }); abridge.alert({ title: JSON.stringify(userInfo), // alert 框的标题 }); } }); } }); }, clear() { this.setData({ hasUserInfo: false, userInfo: {} }) } })
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import pytest from .common import CASSANDRA_E2E_METRICS @pytest.mark.e2e def test(dd_agent_check): instance = {} aggregator = dd_agent_check(instance, rate=True) for metric in CASSANDRA_E2E_METRICS: aggregator.assert_metric(metric) aggregator.assert_all_metrics_covered()
// Copyright (C) 2022 Igalia S.L. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-temporal.calendar.prototype.month description: > RangeError thrown if an invalid ISO string (or syntactically valid ISO string that is not supported) is used as a PlainDate features: [Temporal, arrow-function] ---*/ const invalidStrings = [ // invalid ISO strings: "", "invalid iso8601", "2020-01-00", "2020-01-32", "2020-02-30", "2021-02-29", "2020-00-01", "2020-13-01", "2020-01-01T", "2020-01-01T25:00:00", "2020-01-01T01:60:00", "2020-01-01T01:60:61", "2020-01-01junk", "2020-01-01T00:00:00junk", "2020-01-01T00:00:00+00:00junk", "2020-01-01T00:00:00+00:00[UTC]junk", "2020-01-01T00:00:00+00:00[UTC][u-ca=iso8601]junk", "02020-01-01", "2020-001-01", "2020-01-001", "2020-01-01T001", "2020-01-01T01:001", "2020-01-01T01:01:001", // valid, but forms not supported in Temporal: "2020-W01-1", "2020-001", "+0002020-01-01", // valid, but this calendar must not exist: "2020-01-01[u-ca=notexist]", // may be valid in other contexts, but insufficient information for PlainDate: "2020-01", "+002020-01", "01-01", "2020-W01", "P1Y", "-P12Y", // valid, but outside the supported range: "-999999-01-01", "+999999-01-01", ]; const instance = new Temporal.Calendar("iso8601"); for (const arg of invalidStrings) { assert.throws( RangeError, () => instance.month(arg), `"${arg}" should not be a valid ISO string for a PlainDate` ); }
from fastapi_mvc.cli.cli import cli def test_root(cli_runner): result = cli_runner.invoke(cli) assert result.exit_code == 0 def test_root_options(cli_runner): result = cli_runner.invoke(cli, ["--verbose", "new", "--help"]) assert result.exit_code == 0 result = cli_runner.invoke(cli, ["new", "--help"]) assert result.exit_code == 0 def test_root_help(cli_runner): result = cli_runner.invoke(cli, ["--help"]) assert result.exit_code == 0 def test_root_invalid_option(cli_runner): result = cli_runner.invoke(cli, ["--not_exists"]) assert result.exit_code == 2
const pump = require('pump'); const revall = require('gulp-rev-all'); const del = require('gulp-rev-delete-original'); const { dest, src } = require('gulp'); const { basename, extname } = require('path'); const completeTask = require('@parameter1/base-cms-cli-utils/task-callback'); module.exports = cwd => (cb) => { pump([ src('dist/css/*', { cwd }), revall.revision({ fileNameManifest: 'manifest.json', includeFilesInManifest: ['.css'], transformFilename: (file, hash) => { const base = basename(file.path); const mapname = basename(file.path, '.map'); const prefix = base === mapname ? basename(mapname, extname(file.path)) : basename(mapname, extname(mapname)); const suffix = base.replace(prefix, ''); return `${prefix}.${hash.substr(0, 8)}${suffix}`; }, }), del(), dest('dist/css', { cwd }), revall.manifestFile(), dest('dist/css', { cwd }), ], e => completeTask(e, cb)); };
var Module=typeof Module!=="undefined"?Module:{};try{this["Module"]=Module;Module.test}catch(e){this["Module"]=Module={}}if(typeof process==="object"){if(typeof FS==="object"){Module["preRun"]=Module["preRun"]||[];Module["preRun"].push(function(){FS.init();FS.mkdir("/test-data");FS.mount(NODEFS,{root:"."},"/test-data")})}}else{Module["print"]=function(x){var event=new Event("test-output");event.data=x;window.dispatchEvent(event)}}var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){var ret=tryParseAsDataURI(filename);if(ret){return binary?ret:ret.toString()}if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){var data=tryParseAsDataURI(f);if(data){return intArrayToString(data)}return read(f)}}readBinary=function readBinary(f){var data;data=tryParseAsDataURI(f);if(data){return data}if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText}catch(err){var data=tryParseAsDataURI(url);if(data){return intArrayToString(data)}throw err}};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}catch(err){var data=tryParseAsDataURI(url);if(data){return data}throw err}}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}var data=tryParseAsDataURI(url);if(data){onload(data.buffer);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(typeof WebAssembly!=="object"){err("no native wasm support detected")}var wasmMemory;var wasmTable=new WebAssembly.Table({"initial":6,"maximum":6+8,"element":"anyfunc"});var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}var WASM_PAGE_SIZE=65536;var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var DYNAMIC_BASE=5247552,DYNAMICTOP_PTR=4512;var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{wasmMemory=new WebAssembly.Memory({"initial":INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE,"maximum":2147483648/WASM_PAGE_SIZE})}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";out(what);err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";throw new WebAssembly.RuntimeError(what)}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="data:application/octet-stream;base64,AGFzbQEAAAABaRBgAABgA39/fwF/YAN/f38AYAF/AX9gAn9/AX9gAX8AYAJ/fwBgAAF/YAR/f39/AX9gBH9+f38Bf2ACfn8Bf2AFf39/f38AYAZ/f35/fn8Bf2AGf3x/f39/AX9gA35/fwF/YAN/fn8BfgI7BwFhAWEAAQFhAWIACAFhAWMAAQFhAWQAAwFhAWUAAAFhBm1lbW9yeQIBgAKAgAIBYQV0YWJsZQFwAAYDLy4EBgsCAwYCCAEFAgIDBAMDBQcABwAHAAUKDgoGBAQEBQIFDwMEAQcMCQIAAAAABgkBfwFBwKTAAgsHDQMBZgAyAWcAKQFoACsJCwEAQQELBS0sKConCuBBLgcAIAAgAXcLCQAgACABNgAAC2gBAX8jAEGAAmsiBSQAIARBgMAEcSACIANMckUEQCAFIAEgAiADayICQYACIAJBgAJJIgEbEA8gAUUEQANAIAAgBUGAAhAIIAJBgH5qIgJB/wFLDQALCyAAIAUgAhAICyAFQYACaiQACxcAIAAtAABBIHFFBEAgASACIAAQDRoLCwoAIABBUGpBCkkLNQEBfyMAQRBrIgIgADYCDCABBEBBACEAA0AgAigCDCAAakEAOgAAIABBAWoiACABRw0ACwsLCgAgACABIAIQLguqEQIQfwF+IwBB0ABrIgUkACAFQYAINgJMIAVBN2ohEyAFQThqIRACQAJAA0ACQCANQQBIDQAgBEH/////ByANa0oEQEHQFkE9NgIAQX8hDQwBCyAEIA1qIQ0LIAUoAkwiCSEEAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkAgCS0AACIHBEADQAJAAkACQCAHQf8BcSIGRQRAIAQhBwwBCyAGQSVHDQEgBCEHA0AgBC0AAUElRw0BIAUgBEECaiIGNgJMIAdBAWohByAELQACIQogBiEEIApBJUYNAAsLIAcgCWshBCAABEAgACAJIAQQCAsgBA0RQX8hD0EBIQcgBSgCTCwAARAJIQYgBSgCTCEEAkAgBkUNACAELQACQSRHDQAgBCwAAUFQaiEPQQEhEUEDIQcLIAUgBCAHaiIENgJMQQAhBwJAIAQsAAAiDkFgaiIKQR9LBEAgBCEGDAELIAQhBkEBIAp0IgpBidEEcUUNAANAIAUgBEEBaiIGNgJMIAcgCnIhByAELAABIg5BYGoiCkEfSw0BIAYhBEEBIAp0IgpBidEEcQ0ACwsCQCAOQSpGBEAgBQJ/AkAgBiwAARAJRQ0AIAUoAkwiBC0AAkEkRw0AIAQsAAFBAnQgA2pBwH5qQQo2AgAgBCwAAUEDdCACakGAfWooAgAhC0EBIREgBEEDagwBCyARDRVBACERQQAhCyAABEAgASABKAIAIgRBBGo2AgAgBCgCACELCyAFKAJMQQFqCyIENgJMIAtBf0oNAUEAIAtrIQsgB0GAwAByIQcMAQsgBUHMAGoQESILQQBIDRMgBSgCTCEEC0F/IQgCQCAELQAAQS5HDQAgBC0AAUEqRgRAAkAgBCwAAhAJRQ0AIAUoAkwiBC0AA0EkRw0AIAQsAAJBAnQgA2pBwH5qQQo2AgAgBCwAAkEDdCACakGAfWooAgAhCCAFIARBBGoiBDYCTAwCCyARDRQgAAR/IAEgASgCACIEQQRqNgIAIAQoAgAFQQALIQggBSAFKAJMQQJqIgQ2AkwMAQsgBSAEQQFqNgJMIAVBzABqEBEhCCAFKAJMIQQLQQAhBgNAIAYhEkF/IQwgBCwAAEG/f2pBOUsNFCAFIARBAWoiDjYCTCAELAAAIQYgDiEEIAYgEkE6bGpB7w1qLQAAIgZBf2pBCEkNAAsgBkUNEwJAAkACQCAGQRNGBEAgD0F/TA0BDBcLIA9BAEgNASADIA9BAnRqIAY2AgAgBSACIA9BA3RqKQMANwNAC0EAIQQgAEUNEwwBCyAARQ0RIAVBQGsgBiABEBAgBSgCTCEOCyAHQf//e3EiCiAHIAdBgMAAcRshB0EAIQxBlA4hDyAQIQYgDkF/aiwAACIEQV9xIAQgBEEPcUEDRhsgBCASGyIEQah/aiIOQSBNDQECQAJ/AkACQCAEQb9/aiIKQQZLBEAgBEHTAEcNFCAIRQ0BIAUoAkAMAwsgCkEBaw4DEwETCAtBACEEIABBICALQQAgBxAHDAILIAVBADYCDCAFIAUpA0A+AgggBSAFQQhqNgJAQX8hCCAFQQhqCyEGQQAhBAJAA0AgBigCACIJRQ0BIAVBBGogCRASIglBAEgiCiAJIAggBGtLckUEQCAGQQRqIQYgCCAEIAlqIgRLDQEMAgsLQX8hDCAKDRULIABBICALIAQgBxAHIARFBEBBACEEDAELQQAhCiAFKAJAIQYDQCAGKAIAIglFDQEgBUEEaiAJEBIiCSAKaiIKIARKDQEgACAFQQRqIAkQCCAGQQRqIQYgCiAESQ0ACwsgAEEgIAsgBCAHQYDAAHMQByALIAQgCyAEShshBAwRCyAFIARBAWoiBjYCTCAELQABIQcgBiEEDAELCyAOQQFrDh8MDAwMDAwMDAEMAwQBAQEMBAwMDAwIBQYMDAIMCQwMBwsgDSEMIAANDyARRQ0MQQEhBANAIAMgBEECdGooAgAiAARAIAIgBEEDdGogACABEBBBASEMIARBAWoiBEEKRw0BDBELC0EBIQwgBEEJSw0PA0AgBCIAQQFqIgRBCkcEQCADIARBAnRqKAIARQ0BCwtBf0EBIABBCUkbIQwMDwsgACAFKwNAIAsgCCAHIARBABENACEEDAwLIAUoAkAiBEGeDiAEGyIJIAgQIiIEIAggCWogBBshBiAKIQcgBCAJayAIIAQbIQgMCQsgBSAFKQNAPAA3QQEhCCATIQkgCiEHDAgLIAUpA0AiFEJ/VwRAIAVCACAUfSIUNwNAQQEhDEGUDgwGCyAHQYAQcQRAQQEhDEGVDgwGC0GWDkGUDiAHQQFxIgwbDAULIAUpA0AgEBAfIQkgB0EIcUUNBSAIIBAgCWsiBEEBaiAIIARKGyEIDAULIAhBCCAIQQhLGyEIIAdBCHIhB0H4ACEECyAFKQNAIBAgBEEgcRAeIQkgB0EIcUUNAyAFKQNAUA0DIARBBHZBlA5qIQ9BAiEMDAMLQQAhBCASQf8BcSIGQQdLDQUCQAJAAkACQAJAAkACQCAGQQFrDgcBAgMEDAUGAAsgBSgCQCANNgIADAsLIAUoAkAgDTYCAAwKCyAFKAJAIA2sNwMADAkLIAUoAkAgDTsBAAwICyAFKAJAIA06AAAMBwsgBSgCQCANNgIADAYLIAUoAkAgDaw3AwAMBQsgBSkDQCEUQZQOCyEPIBQgEBAdIQkLIAdB//97cSAHIAhBf0obIQcCfyAIIAUpA0AiFFBFckUEQCAQIQlBAAwBCyAIIBRQIBAgCWtqIgQgCCAEShsLIQgLIABBICAMIAYgCWsiCiAIIAggCkgbIg5qIgYgCyALIAZIGyIEIAYgBxAHIAAgDyAMEAggAEEwIAQgBiAHQYCABHMQByAAQTAgDiAKQQAQByAAIAkgChAIIABBICAEIAYgB0GAwABzEAcMAQsLQQAhDAwBC0F/IQwLIAVB0ABqJAAgDAu1AQEEfwJAIAIoAhAiAwR/IAMFIAIQEw0BIAIoAhALIAIoAhQiBWsgAUkEQCACIAAgASACKAIkEQEADwsCQCACLABLQQBIDQAgASEEA0AgBCIDRQ0BIAAgA0F/aiIEai0AAEEKRw0ACyACIAAgAyACKAIkEQEAIgQgA0kNASABIANrIQEgACADaiEAIAIoAhQhBSADIQYLIAUgACABECUgAiACKAIUIAFqNgIUIAEgBmohBAsgBAt+AQN/IwBBEGsiASQAIAFBCjoADwJAIAAoAhAiAkUEQCAAEBMNASAAKAIQIQILAkAgACgCFCIDIAJPDQAgACwAS0EKRg0AIAAgA0EBajYCFCADQQo6AAAMAQsgACABQQ9qQQEgACgCJBEBAEEBRw0AIAEtAA8aCyABQRBqJAAL8QICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgA2AgAgAyACIARrQXxxIgJqIgFBfGogADYCACACQQlJDQAgAyAANgIIIAMgADYCBCABQXhqIAA2AgAgAUF0aiAANgIAIAJBGUkNACADIAA2AhggAyAANgIUIAMgADYCECADIAA2AgwgAUFwaiAANgIAIAFBbGogADYCACABQWhqIAA2AgAgAUFkaiAANgIAIAIgA0EEcUEYciIBayICQSBJDQAgAK0iBUIghiAFhCEFIAEgA2ohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCwujAgACQAJAIAFBFEsNACABQXdqIgFBCUsNAAJAAkACQAJAAkACQAJAAkAgAUEBaw4JAQIJAwQFBgkHAAsgAiACKAIAIgFBBGo2AgAgACABKAIANgIADwsgAiACKAIAIgFBBGo2AgAgACABNAIANwMADwsgAiACKAIAIgFBBGo2AgAgACABNQIANwMADwsgAiACKAIAIgFBBGo2AgAgACABMgEANwMADwsgAiACKAIAIgFBBGo2AgAgACABMwEANwMADwsgAiACKAIAIgFBBGo2AgAgACABMAAANwMADwsgAiACKAIAIgFBBGo2AgAgACABMQAANwMADwsgACACQQARBgALDwsgAiACKAIAQQdqQXhxIgFBCGo2AgAgACABKQMANwMAC0IBA38gACgCACwAABAJBEADQCAAKAIAIgIsAAAhAyAAIAJBAWo2AgAgAyABQQpsakFQaiEBIAIsAAEQCQ0ACwsgAQsRACAARQRAQQAPCyAAIAEQIwtZAQF/IAAgAC0ASiIBQX9qIAFyOgBKIAAoAgAiAUEIcQRAIAAgAUEgcjYCAEF/DwsgAEIANwIEIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhBBAAsVACAARQRAQQAPC0HQFiAANgIAQX8LEAAgAEIANwIAIABCADcCCAsuAEGAFigCAAR/QQEFQYwWQQA2AgAQMEGIFkEBNgIAEBcQL0GAFkEBNgIAQQALCygBAX8jAEEQayIAJAAgAEEAOgAPQb4IIABBD2pBABAAGiAAQRBqJAALKwECfyMAQRBrIgAkACAAQQA6AA9BmAggAEEPakEAEAAhASAAQRBqJAAgAQsyAQF/IwBBIGsiACQAIAAQJEHgFUIgQaASIABB1BIoAgARCQAaIABBIBAKIABBIGokAAtgAQN/QYgIIQEDQCABIgBBBGohASAAKAIAIgJBf3MgAkH//ft3anFBgIGChHhxRQ0ACyACQf8BcUUEQCAAQYgIaw8LA0AgAC0AASECIABBAWoiASEAIAINAAsgAUGICGsLZgECf0GQDigCACIAKAJMQQBOBH9BAQUgAQsaAkBBf0EAEBoiASAAECEgAUcbQQBIDQACQCAALQBLQQpGDQAgACgCFCIBIAAoAhBPDQAgACABQQFqNgIUIAFBCjoAAAwBCyAAEA4LCyUBAX8jAEEQayIBJAAgASAANgIMQZAOKAIAIAAQICABQRBqJAALgwECA38BfgJAIABCgICAgBBUBEAgACEFDAELA0AgAUF/aiIBIAAgAEIKgCIFQgp+fadBMHI6AAAgAEL/////nwFWIQIgBSEAIAINAAsLIAWnIgIEQANAIAFBf2oiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEEIAMhAiAEDQALCyABCzQAIABQRQRAA0AgAUF/aiIBIACnQQ9xQYASai0AACACcjoAACAAQgSIIgBCAFINAAsLIAELLQAgAFBFBEADQCABQX9qIgEgAKdBB3FBMHI6AAAgAEIDiCIAQgBSDQALCyABC8UCAQN/IwBB0AFrIgIkACACIAE2AswBQQAhASACQaABakEAQSgQDyACIAIoAswBNgLIAQJAQQAgAkHIAWogAkHQAGogAkGgAWoQDEEASA0AIAAoAkxBAE4EQEEBIQELIAAoAgAhAyAALABKQQBMBEAgACADQV9xNgIACyADQSBxIQQCfyAAKAIwBEAgACACQcgBaiACQdAAaiACQaABahAMDAELIABB0AA2AjAgACACQdAAajYCECAAIAI2AhwgACACNgIUIAAoAiwhAyAAIAI2AiwgACACQcgBaiACQdAAaiACQaABahAMIANFDQAaIABBAEEAIAAoAiQRAQAaIABBADYCMCAAIAM2AiwgAEEANgIcIABBADYCECAAKAIUGiAAQQA2AhRBAAsaIAAgACgCACAEcjYCACABRQ0ACyACQdABaiQACzcBAX8gACECIAICfyABKAJMQX9MBEBBiAggAiABEA0MAQtBiAggAiABEA0LIgFGBEAgAA8LIAELvAEBAX8gAUEARyECAkACQAJAAkAgAUUgAEEDcUVyDQADQCAALQAARQ0CIABBAWohACABQX9qIgFBAEchAiABRQ0BIABBA3ENAAsLIAJFDQELIAAtAABFDQECQCABQQRPBEADQCAAKAIAIgJBf3MgAkH//ft3anFBgIGChHhxDQIgAEEEaiEAIAFBfGoiAUEDSw0ACwsgAUUNAQsDQCAALQAARQ0CIABBAWohACABQX9qIgENAAsLQQAPCyAAC4kCAAJAIAAEfyABQf8ATQ0BAkBBoBUoAgAoAgBFBEAgAUGAf3FBgL8DRg0DDAELIAFB/w9NBEAgACABQT9xQYABcjoAASAAIAFBBnZBwAFyOgAAQQIPCyABQYCwA09BACABQYBAcUGAwANHG0UEQCAAIAFBP3FBgAFyOgACIAAgAUEMdkHgAXI6AAAgACABQQZ2QT9xQYABcjoAAUEDDwsgAUGAgHxqQf//P00EQCAAIAFBP3FBgAFyOgADIAAgAUESdkHwAXI6AAAgACABQQZ2QT9xQYABcjoAAiAAIAFBDHZBP3FBgAFyOgABQQQPCwtB0BZBGTYCAEF/BUEBCw8LIAAgAToAAEEBC/oEARZ/QbLaiMsHIQJB7siBmQMhA0Hl8MGLBiEEQfTKgdkGIQVBFCEQQbASKAAAIQlBtBIoAAAhCkG4EigAACESQbwSKAAAIQtBwBIoAAAhDEHEEigAACEGQcgSKAAAIQ1BzBIoAAAhDkGQEigAACEBQZQSKAAAIQdBmBIoAAAhCEGcEigAACEPA0AgBCAGakEHEAUgC3MiCyAEakEJEAUgCHMiCCALakENEAUgBnMiESAIakESEAUhEyADIAlqQQcQBSAPcyIGIANqQQkQBSANcyINIAZqQQ0QBSAJcyIJIA1qQRIQBSEPIAEgAmpBBxAFIA5zIg4gAmpBCRAFIApzIgogDmpBDRAFIAFzIhQgCmpBEhAFIRUgBSAMakEHEAUgEnMiASAFakEJEAUgB3MiByABakENEAUgDHMiDCAHakESEAUhFiABIAQgE3MiBGpBBxAFIAlzIgkgBGpBCRAFIApzIgogCWpBDRAFIAFzIhIgCmpBEhAFIARzIQQgAyAPcyIDIAtqQQcQBSAUcyIBIANqQQkQBSAHcyIHIAFqQQ0QBSALcyILIAdqQRIQBSADcyEDIAIgFXMiAiAGakEHEAUgDHMiDCACakEJEAUgCHMiCCAMakENEAUgBnMiDyAIakESEAUgAnMhAiAFIBZzIgUgDmpBBxAFIBFzIgYgBWpBCRAFIA1zIg0gBmpBDRAFIA5zIg4gDWpBEhAFIAVzIQUgEEECSyERIBBBfmohECARDQALIAAgBBAGIABBBGogAxAGIABBCGogAhAGIABBDGogBRAGIABBEGogARAGIABBFGogBxAGIABBGGogCBAGIABBHGogDxAGC/4DAQJ/IAJBgARPBEAgACABIAIQAhoPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIAQcAASQ0AIAIgAEFAaiIESw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBE0NAAsLIAIgAE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIABJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsLeAEBfyAAKAJMQQBIBEACQCAALABLQQpGDQAgACgCFCIBIAAoAhBPDQAgACABQQFqNgIUIAFBCjoAAA8LIAAQDg8LAkACQCAALABLQQpGDQAgACgCFCIBIAAoAhBPDQAgACABQQFqNgIUIAFBCjoAAAwBCyAAEA4LCwQAQgALBABBAAsRABAWBH9B4wAFEDEQG0EACwvHAgEGfyMAQSBrIgMkACADIAAoAhwiBDYCECAAKAIUIQUgAyACNgIcIAMgATYCGCADIAUgBGsiATYCFCABIAJqIQRBAiEGIANBEGohAQJ/AkACQCAAKAI8IANBEGpBAiADQQxqEAEQFEUEQANAIAQgAygCDCIFRg0CIAVBf0wNAyABQQhqIAEgBSABKAIEIgdLIggbIgEgBSAHQQAgCBtrIgcgASgCAGo2AgAgASABKAIEIAdrNgIEIAQgBWshBCAAKAI8IAEgBiAIayIGIANBDGoQARAURQ0ACwsgA0F/NgIMIARBf0cNAQsgACAAKAIsIgE2AhwgACABNgIUIAAgASAAKAIwajYCECACDAELIABBADYCHCAAQgA3AxAgACAAKAIAQSByNgIAQQAgBkECRg0AGiACIAEoAgRrCyEEIANBIGokACAECwUAQdAWC/ECAQJ/IwBB8ABrIgckACACUEUEQCAHIAUpABg3AxggByAFKQAQNwMQIAcgBSkAADcDAEEIIQYgByAFKQAINwMIIAcgAykAADcDYANAIAdB4ABqIAZqIAQ8AAAgBEIIiCEEIAZBAWoiBkEQRw0ACyACQj9WBEADQEEAIQYgB0EgaiAHQeAAaiAHEAsDQCAAIAZqIAdBIGogBmotAAAgASAGai0AAHM6AABBASEFIAZBAWoiBkHAAEcNAAtBCCEGA0AgB0HgAGogBmoiAyAFIAMtAABqIgM6AAAgA0EIdiEFIAZBAWoiBkEQRw0ACyABQUBrIQEgAEFAayEAIAJCQHwiAkI/Vg0ACwsCQCACUA0AQQAhBiAHQSBqIAdB4ABqIAcQCyACpyIDRQ0AA0AgACAGaiAHQSBqIAZqLQAAIAEgBmotAABzOgAAIAZBAWoiBiADRw0ACwsgB0EgakHAABAKIAdBIBAKCyAHQfAAaiQAQQALlAICAn8BfiMAQfAAayIEJAAgAVBFBEAgBCADKQAYNwMYIAQgAykAEDcDECAEIAMpAAA3AwAgBCADKQAINwMIIAIpAAAhBiAEQgA3A2ggBCAGNwNgAkAgAULAAFoEQANAIAAgBEHgAGogBBALQQghA0EBIQIDQCAEQeAAaiADaiIFIAIgBS0AAGoiAjoAACACQQh2IQIgA0EBaiIDQRBHDQALIABBQGshACABQkB8IgFCP1YNAAsgAVANAQtBACEDIARBIGogBEHgAGogBBALIAGnIgJFDQADQCAAIANqIARBIGogA2otAAA6AAAgA0EBaiIDIAJHDQALCyAEQSBqQcAAEAogBEEgEAoLIARB8ABqJABBAAuUBgEifyACKAAAIREgAigABCESIAIoAAghEyACKAAMIRQgAigAECEVIAIoABghFiACKAAcIRcgAigAFCIZIQIgFiEGIBchB0H0yoHZBiEEIBUhA0Gy2ojLByEFIAEoAAwhGCABKAAIIhohCCABKAAEIhshDyABKAAAIhwhAUHuyIGZAyENIBQhCSATIRAgEiEKIBEhC0Hl8MGLBiEOIBghDANAIAIgDmpBBxAFIAlzIgkgDmpBCRAFIAhzIgggCWpBDRAFIAJzIh0gCGpBEhAFIR4gCyANakEHEAUgDHMiAiANakEJEAUgBnMiBiACakENEAUgC3MiCyAGakESEAUhHyABIAVqQQcQBSAHcyIHIAVqQQkQBSAKcyIKIAdqQQ0QBSABcyIgIApqQRIQBSEhIAMgBGpBBxAFIBBzIgEgBGpBCRAFIA9zIgwgAWpBDRAFIANzIiIgDGpBEhAFISMgASAOIB5zIgNqQQcQBSALcyILIANqQQkQBSAKcyIKIAtqQQ0QBSABcyIQIApqQRIQBSADcyEOIA0gH3MiAyAJakEHEAUgIHMiASADakEJEAUgDHMiDyABakENEAUgCXMiCSAPakESEAUgA3MhDSAFICFzIgUgAmpBBxAFICJzIgMgBWpBCRAFIAhzIgggA2pBDRAFIAJzIgwgCGpBEhAFIAVzIQUgBCAjcyIEIAdqQQcQBSAdcyICIARqQQkQBSAGcyIGIAJqQQ0QBSAHcyIHIAZqQRIQBSAEcyEEICRBAmoiJEEUSA0ACyAAIA5B5fDBiwZqEAYgAEEEaiALIBFqEAYgAEEIaiAKIBJqEAYgAEEMaiAQIBNqEAYgAEEQaiAJIBRqEAYgAEEUaiANQe7IgZkDahAGIABBGGogASAcahAGIABBHGogDyAbahAGIABBIGogCCAaahAGIABBJGogDCAYahAGIABBKGogBUGy2ojLB2oQBiAAQSxqIAMgFWoQBiAAQTBqIAIgGWoQBiAAQTRqIAYgFmoQBiAAQThqIAcgF2oQBiAAQTxqIARB9MqB2QZqEAYLXgEBfwJAQR4QAyIAQQFOBEBB0BIgADYCAAwBC0HQEigCACEACyAAQQ9NBEBBhBYoAgAiAARAIAARAAALEAQAC0EAIQADQCAAQcAWahAYOgAAIABBAWoiAEEQRw0ACwstAQF/IwBBEGsiACQAIAAQFSAAKAIABEAgABAVQZAWQQBBKBAPCyAAQRBqJAALSgECfyMAQRBrIgAkABAZA0AgACABQeAVai0AADYCACAAEBwgAUEHcUEHRgRAQZAOKAIAECYLIAFBAWoiAUEgRw0ACyAAQRBqJAALAwABCwv/CRQAQYAIC6QGLDB4JTAyeAAtLS0gU1VDQ0VTUyAtLS0AInsgcmV0dXJuIE1vZHVsZS5nZXRSYW5kb21WYWx1ZSgpOyB9IgB7IGlmIChNb2R1bGUuZ2V0UmFuZG9tVmFsdWUgPT09IHVuZGVmaW5lZCkgeyB0cnkgeyB2YXIgd2luZG93XyA9ICdvYmplY3QnID09PSB0eXBlb2Ygd2luZG93ID8gd2luZG93IDogc2VsZjsgdmFyIGNyeXB0b18gPSB0eXBlb2Ygd2luZG93Xy5jcnlwdG8gIT09ICd1bmRlZmluZWQnID8gd2luZG93Xy5jcnlwdG8gOiB3aW5kb3dfLm1zQ3J5cHRvOyB2YXIgcmFuZG9tVmFsdWVzU3RhbmRhcmQgPSBmdW5jdGlvbigpIHsgdmFyIGJ1ZiA9IG5ldyBVaW50MzJBcnJheSgxKTsgY3J5cHRvXy5nZXRSYW5kb21WYWx1ZXMoYnVmKTsgcmV0dXJuIGJ1ZlswXSA+Pj4gMDsgfTsgcmFuZG9tVmFsdWVzU3RhbmRhcmQoKTsgTW9kdWxlLmdldFJhbmRvbVZhbHVlID0gcmFuZG9tVmFsdWVzU3RhbmRhcmQ7IH0gY2F0Y2ggKGUpIHsgdHJ5IHsgdmFyIGNyeXB0byA9IHJlcXVpcmUoJ2NyeXB0bycpOyB2YXIgcmFuZG9tVmFsdWVOb2RlSlMgPSBmdW5jdGlvbigpIHsgdmFyIGJ1ZiA9IGNyeXB0b1sncmFuZG9tQnl0ZXMnXSg0KTsgcmV0dXJuIChidWZbMF0gPDwgMjQgfCBidWZbMV0gPDwgMTYgfCBidWZbMl0gPDwgOCB8IGJ1ZlszXSkgPj4+IDA7IH07IHJhbmRvbVZhbHVlTm9kZUpTKCk7IE1vZHVsZS5nZXRSYW5kb21WYWx1ZSA9IHJhbmRvbVZhbHVlTm9kZUpTOyB9IGNhdGNoIChlKSB7IHRocm93ICdObyBzZWN1cmUgcmFuZG9tIG51bWJlciBnZW5lcmF0b3IgZm91bmQnOyB9IH0gfSB9AGAJAAAtKyAgIDBYMHgAKG51bGwpAEGwDgtBEQAKABEREQAAAAAFAAAAAAAACQAAAAALAAAAAAAAAAARAA8KERERAwoHAAETCQsLAAAJBgsAAAsABhEAAAAREREAQYEPCyELAAAAAAAAAAARAAoKERERAAoAAAIACQsAAAAJAAsAAAsAQbsPCwEMAEHHDwsVDAAAAAAMAAAAAAkMAAAAAAAMAAAMAEH1DwsBDgBBgRALFQ0AAAAEDQAAAAAJDgAAAAAADgAADgBBrxALARAAQbsQCx4PAAAAAA8AAAAACRAAAAAAABAAABAAABIAAAASEhIAQfIQCw4SAAAAEhISAAAAAAAACQBBoxELAQsAQa8RCxUKAAAAAAoAAAAACQsAAAAAAAsAAAsAQd0RCwEMAEHpEQsnDAAAAAAMAAAAAAkMAAAAAAAMAAAMAAAwMTIzNDU2Nzg5QUJDREVGAEGQEgtRaWlu6VW2K3PNYr2odfxz1oIZ4ANregs3AAAAAAAAAAAbJ1Vkc+mF1GLNURl6mkbHYAlUnqxkdPIGxO4IRPaDiQBAAAABAAAAAgAAAAAAAAAFAEHsEgsBAwBBhBMLDgQAAAAFAAAAaAsAAAAEAEGcEwsBAQBBqxMLBQr/////AEGgFQsCgBE=";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}var binary=tryParseAsDataURI(wasmBinaryFile);if(binary){return binary}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return new Promise(function(resolve,reject){resolve(getBinary())})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}var ASM_CONSTS={1048:function(){return Module.getRandomValue()},1086:function(){if(Module.getRandomValue===undefined){try{var window_="object"===typeof window?window:self;var crypto_=typeof window_.crypto!=="undefined"?window_.crypto:window_.msCrypto;var randomValuesStandard=function(){var buf=new Uint32Array(1);crypto_.getRandomValues(buf);return buf[0]>>>0};randomValuesStandard();Module.getRandomValue=randomValuesStandard}catch(e){try{var crypto=require("crypto");var randomValueNodeJS=function(){var buf=crypto["randomBytes"](4);return(buf[0]<<24|buf[1]<<16|buf[2]<<8|buf[3])>>>0};randomValueNodeJS();Module.getRandomValue=randomValueNodeJS}catch(e){throw"No secure random number generator found"}}}}};function _emscripten_asm_const_iii(code,sigPtr,argbuf){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}__ATINIT__.push({func:function(){___wasm_call_ctors()}});function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j<len;j++){SYSCALLS.printChar(fd,HEAPU8[ptr+j])}num+=len}HEAP32[pnum>>2]=num;return 0}function setErrNo(value){HEAP32[___errno_location()>>2]=value;return value}function _sysconf(name){switch(name){case 30:return 16384;case 85:var maxHeapSize=2147483648;return maxHeapSize/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:case 79:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:{if(typeof navigator==="object")return navigator["hardwareConcurrency"]||1;return 1}}setErrNo(28);return-1}function readAsmConstArgs(sigPtr,buf){if(!readAsmConstArgs.array){readAsmConstArgs.array=[]}var args=readAsmConstArgs.array;args.length=0;var ch;while(ch=HEAPU8[sigPtr++]){if(ch===100||ch===102){buf=buf+7&~7;args.push(HEAPF64[buf>>3]);buf+=8}else{buf=buf+3&~3;args.push(HEAP32[buf>>2]);buf+=4}}return args}var ASSERTIONS=false;function intArrayToString(array){var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>255){if(ASSERTIONS){assert(false,"Character code "+chr+" ("+String.fromCharCode(chr)+") at offset "+i+" not in 0x00-0xFF.")}chr&=255}ret.push(String.fromCharCode(chr))}return ret.join("")}var decodeBase64=typeof atob==="function"?atob:function(input){var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=enc1<<2|enc2>>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!==64){output=output+String.fromCharCode(chr2)}if(enc4!==64){output=output+String.fromCharCode(chr3)}}while(i<input.length);return output};function intArrayFromBase64(s){if(typeof ENVIRONMENT_IS_NODE==="boolean"&&ENVIRONMENT_IS_NODE){var buf;try{buf=Buffer.from(s,"base64")}catch(_){buf=new Buffer(s,"base64")}return new Uint8Array(buf["buffer"],buf["byteOffset"],buf["byteLength"])}try{var decoded=decodeBase64(s);var bytes=new Uint8Array(decoded.length);for(var i=0;i<decoded.length;++i){bytes[i]=decoded.charCodeAt(i)}return bytes}catch(_){throw new Error("Converting base64 string to bytes failed.")}}function tryParseAsDataURI(filename){if(!isDataURI(filename)){return}return intArrayFromBase64(filename.slice(dataURIPrefix.length))}var asmLibraryArg={"e":_abort,"a":_emscripten_asm_const_iii,"c":_emscripten_memcpy_big,"b":_fd_write,"memory":wasmMemory,"d":_sysconf,"table":wasmTable};var asm=createWasm();Module["asm"]=asm;var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["f"]).apply(null,arguments)};var _main=Module["_main"]=function(){return(_main=Module["_main"]=Module["asm"]["g"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["h"]).apply(null,arguments)};Module["asm"]=asm;var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}var calledMain=false;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args){var entryFunction=Module["_main"];var argc=0;var argv=0;try{var ret=entryFunction(argc,argv);exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="unwind"){noExitRuntime=true;return}else{var toLog=e;if(e&&typeof e==="object"&&e.stack){toLog=[e,e.stack]}err("exception thrown: "+toLog);quit_(1,e)}}finally{calledMain=true}}function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(shouldRunNow)callMain(args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;function exit(status,implicit){if(implicit&&noExitRuntime&&status===0){return}if(noExitRuntime){}else{ABORT=true;EXITSTATUS=status;exitRuntime();if(Module["onExit"])Module["onExit"](status)}quit_(status,new ExitStatus(status))}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"])shouldRunNow=false;noExitRuntime=true;run();
import*as Common from'../common/common.js';export class ContrastInfo extends Common.ObjectWrapper.ObjectWrapper{constructor(contrastInfo){super();this._isNull=true;this._contrastRatio=null;this._contrastRatioThresholds=null;this._fgColor=null;this._bgColor=null;if(!contrastInfo){return;} if(!contrastInfo.computedFontSize||!contrastInfo.computedFontWeight||!contrastInfo.backgroundColors||contrastInfo.backgroundColors.length!==1){return;} this._isNull=false;const isLargeFont=ContrastInfo.computeIsLargeFont(contrastInfo.computedFontSize,contrastInfo.computedFontWeight);this._contrastRatioThresholds=_ContrastThresholds[(isLargeFont?'largeFont':'normalFont')];const bgColorText=contrastInfo.backgroundColors[0];const bgColor=Common.Color.Color.parse(bgColorText);if(bgColor){this._setBgColorInternal(bgColor);}} isNull(){return this._isNull;} setColor(fgColor){this._fgColor=fgColor;this._updateContrastRatio();this.dispatchEventToListeners(Events.ContrastInfoUpdated);} color(){return this._fgColor;} contrastRatio(){return this._contrastRatio;} setBgColor(bgColor){this._setBgColorInternal(bgColor);this.dispatchEventToListeners(Events.ContrastInfoUpdated);} _setBgColorInternal(bgColor){this._bgColor=bgColor;if(!this._fgColor){return;} const fgRGBA=this._fgColor.rgba();if(bgColor.hasAlpha()){const blendedRGBA=[];Common.Color.Color.blendColors(bgColor.rgba(),fgRGBA,blendedRGBA);this._bgColor=new Common.Color.Color(blendedRGBA,Common.Color.Format.RGBA);} this._contrastRatio=Common.Color.Color.calculateContrastRatio(fgRGBA,this._bgColor.rgba());} bgColor(){return this._bgColor;} _updateContrastRatio(){if(!this._bgColor||!this._fgColor){return;} this._contrastRatio=Common.Color.Color.calculateContrastRatio(this._fgColor.rgba(),this._bgColor.rgba());} contrastRatioThreshold(level){if(!this._contrastRatioThresholds){return null;} return this._contrastRatioThresholds[level];} static computeIsLargeFont(fontSize,fontWeight){const boldWeights=['bold','bolder','600','700','800','900'];const fontSizePx=parseFloat(fontSize.replace('px',''));const isBold=(boldWeights.indexOf(fontWeight)!==-1);const fontSizePt=fontSizePx*72/96;if(isBold){return fontSizePt>=14;} return fontSizePt>=18;}} export const Events={ContrastInfoUpdated:Symbol('ContrastInfoUpdated')};const _ContrastThresholds={largeFont:{aa:3.0,aaa:4.5},normalFont:{aa:4.5,aaa:7.0}};export let ContrastInfoType;
import Input from "@hig/input"; import React from "react"; import { withInfo } from "@storybook/addon-info"; import { storiesOf } from "@storybook/react"; import Spacer from "@hig/spacer"; import getKnobs from "./getKnobs"; import Label from "../index"; import infoOptions from "./infoOptions"; import withThemeProvider from "./withThemeProvider"; const storybook = storiesOf("Forms|Label", module); storybook.add( "default", withInfo(infoOptions)(() => { const props = { children: "Email" }; const { children, theme, ...otherProps } = getKnobs(props); return withThemeProvider(<Label {...otherProps}>{children}</Label>); }) ); storybook.add( "top label", withInfo(infoOptions)(() => { const props = { children: "Input Field" }; const { children, theme, ...otherProps } = getKnobs(props); return withThemeProvider( <form id="a_form"> <Label form="a_form" htmlFor="an_input" variant="top" {...otherProps}> {children} </Label> <Spacer spacing="s" /> <Input id="an_input" variant="box" /> </form> ); }) ); storybook.add( "side label", withInfo(infoOptions)(() => { const props = { children: "Input Field" }; const { children, theme, ...otherProps } = getKnobs(props); return withThemeProvider( <form id="a_form" style={{ display: "flex", alignItems: "center" }}> <Label form="a_form" htmlFor="an_input" variant="side" {...otherProps}> {children} </Label> <Spacer spacing="s" /> <Input id="an_input" variant="box" /> </form> ); }) );
'use strict'; const { App } = require('jovo-framework'); const { Alexa } = require('jovo-platform-alexa'); const { GoogleAssistant } = require('jovo-platform-googleassistant'); const { Bixby } = require('jovo-platform-bixby'); const { JovoDebugger } = require('jovo-plugin-debugger'); const { FileDb } = require('jovo-db-filedb'); // ------------------------------------------------------------------ // APP INITIALIZATION // ------------------------------------------------------------------ const app = new App(); app.use( new Alexa(), new GoogleAssistant(), new Bixby(), new JovoDebugger(), new FileDb(), ); // ------------------------------------------------------------------ // APP LOGIC // ------------------------------------------------------------------ app.setHandler({ LAUNCH() { return this.toIntent('HelloWorldIntent'); }, HelloWorldIntent() { this.ask("Hello World! What's your name?", 'Please tell me your name.'); }, MyNameIsIntent() { this.tell('Hey ' + this.$inputs.name.value + ', nice to meet you!'); }, PlayAudioIntent() { this.$bixbyCapsule.$audioPlayer.play({ title: 'Example Audio', stream: { url: 'https://s3.amazonaws.com/jovo-songs/song1.mp3' }, }); }, AUDIOPLAYER: { 'BixbyCapsule.AudioPlaying'() { console.log('BixbyCapsule.AudioPlaying'); this.tell('Playing audio.'); }, }, }); module.exports = { app };
/** * Blend textures into a target */ import shader from 'gl-shader'; import { mapList } from '../../../fp/map'; import Screen from '../'; import vert from '../index.vert'; import frag from './index.frag'; export const defaults = () => ({ shader: [vert, frag], views: [], alphas: [], resolution: [1, 1] }); export class Blend { constructor(gl, options) { this.gl = gl; const params = Object.assign(defaults(), options); this.shader = ((Array.isArray(params.shader))? shader(this.gl, ...params.shader) : params.shader); this.screen = new Screen(gl); this.views = params.views; this.alphas = params.alphas; this.resolution = params.resolution; this.uniforms = {}; } draw(target, resolution = (target && target.shape), clear = true) { if(target) { target.bind(); } if(resolution) { this.gl.viewport(0, 0, resolution[0], resolution[1]); this.resolution = resolution; } if(clear) { this.gl.clear(this.gl.COLOR_BUFFER_BIT); } this.shader.bind(); Object.assign(this.shader.uniforms, this.uniforms, { views: mapList((view, v) => ((view.color)? view.color[0] : view).bind(v), this.views, this.uniforms.views), alphas: this.alphas, resolution: this.resolution }); this.screen.render(); if(target) { this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); } } } export default Blend;
import { action } from 'easy-peasy'; export const baseStore = { sidebar: false, setSidebar: action((state,payload) => state.sidebar = payload) }
const aliases = (prefix = `src`) => ({ 'react': `../node_modules/react`, }); module.exports = aliases;
var building = function(object) { this.object = object; this.points = []; this.points.push(new uno.Point(70, 70)); this.points.push(new uno.Point(150, 10)); this.points.push(new uno.Point(230, 70)); this.points.push(new uno.Point(70, 70)); this.alpha = 1; this.speed = 0.1; }; building.id = 'building'; building.prototype.render = function(render, deltaTime) { if (!this.object.transform) return; this.alpha -= 1 / deltaTime * this.speed; if (this.alpha < 0 || this.alpha > 1) this.speed *= -1; render.alpha = this.alpha; render.transform = this.object.transform.matrix; render.style(null, 0x00D025, 10); render.line(0, 200, 300, 200); render.style(0xA35B00, 0xDFA700, 5); render.rect(90, 70, 125, 125); render.style(0xFF0000, 0x0038DF); render.poly(this.points); render.style(uno.Color.GREEN, uno.Color.RED, 10); render.blend = uno.Render.BLEND_ADD; render.ellipse(150, 130, 50, 70); render.style(0xFFE51E, null, 0); render.blend = uno.Render.BLEND_NORMAL; render.circle(50, 0, 30); render.style(uno.Color.TRANSPARENT, uno.Color.BLUE, 30); render.blend = uno.Render.BLEND_ADD; render.arc(150, 200, 200, 0, uno.Math.PI, true); }; function create(render1, render2) { var stage = uno.Object.create(resize); var obj = uno.Object.create(uno.Transform, building, drag); obj.transform.position.set(100, 100); stage.addChild(obj); if (render1) render1.root = stage; if (render2) render2.root = stage; } function init() { createRenders(true, true); }
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(e);function n(e,t){return e(t={exports:{}},t.exports),t.exports /** @license React v16.13.1 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */}var o="function"==typeof Symbol&&Symbol.for,a=o?Symbol.for("react.element"):60103,i=o?Symbol.for("react.portal"):60106,c=o?Symbol.for("react.fragment"):60107,s=o?Symbol.for("react.strict_mode"):60108,u=o?Symbol.for("react.profiler"):60114,f=o?Symbol.for("react.provider"):60109,l=o?Symbol.for("react.context"):60110,p=o?Symbol.for("react.async_mode"):60111,d=o?Symbol.for("react.concurrent_mode"):60111,y=o?Symbol.for("react.forward_ref"):60112,m=o?Symbol.for("react.suspense"):60113,b=o?Symbol.for("react.suspense_list"):60120,v=o?Symbol.for("react.memo"):60115,g=o?Symbol.for("react.lazy"):60116,h=o?Symbol.for("react.block"):60121,x=o?Symbol.for("react.fundamental"):60117,S=o?Symbol.for("react.responder"):60118,w=o?Symbol.for("react.scope"):60119;function O(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case a:switch(e=e.type){case p:case d:case c:case u:case s:case m:return e;default:switch(e=e&&e.$$typeof){case l:case y:case g:case v:case f:return e;default:return t}}case i:return t}}}function E(e){return O(e)===d}var $={AsyncMode:p,ConcurrentMode:d,ContextConsumer:l,ContextProvider:f,Element:a,ForwardRef:y,Fragment:c,Lazy:g,Memo:v,Portal:i,Profiler:u,StrictMode:s,Suspense:m,isAsyncMode:function(e){return E(e)||O(e)===p},isConcurrentMode:E,isContextConsumer:function(e){return O(e)===l},isContextProvider:function(e){return O(e)===f},isElement:function(e){return"object"==typeof e&&null!==e&&e.$$typeof===a},isForwardRef:function(e){return O(e)===y},isFragment:function(e){return O(e)===c},isLazy:function(e){return O(e)===g},isMemo:function(e){return O(e)===v},isPortal:function(e){return O(e)===i},isProfiler:function(e){return O(e)===u},isStrictMode:function(e){return O(e)===s},isSuspense:function(e){return O(e)===m},isValidElementType:function(e){return"string"==typeof e||"function"==typeof e||e===c||e===d||e===u||e===s||e===m||e===b||"object"==typeof e&&null!==e&&(e.$$typeof===g||e.$$typeof===v||e.$$typeof===f||e.$$typeof===l||e.$$typeof===y||e.$$typeof===x||e.$$typeof===S||e.$$typeof===w||e.$$typeof===h)},typeOf:O},T=n((function(e,t){"production"!==process.env.NODE_ENV&&function(){var e="function"==typeof Symbol&&Symbol.for,r=e?Symbol.for("react.element"):60103,n=e?Symbol.for("react.portal"):60106,o=e?Symbol.for("react.fragment"):60107,a=e?Symbol.for("react.strict_mode"):60108,i=e?Symbol.for("react.profiler"):60114,c=e?Symbol.for("react.provider"):60109,s=e?Symbol.for("react.context"):60110,u=e?Symbol.for("react.async_mode"):60111,f=e?Symbol.for("react.concurrent_mode"):60111,l=e?Symbol.for("react.forward_ref"):60112,p=e?Symbol.for("react.suspense"):60113,d=e?Symbol.for("react.suspense_list"):60120,y=e?Symbol.for("react.memo"):60115,m=e?Symbol.for("react.lazy"):60116,b=e?Symbol.for("react.block"):60121,v=e?Symbol.for("react.fundamental"):60117,g=e?Symbol.for("react.responder"):60118,h=e?Symbol.for("react.scope"):60119;function x(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case r:var d=e.type;switch(d){case u:case f:case o:case i:case a:case p:return d;default:var b=d&&d.$$typeof;switch(b){case s:case l:case m:case y:case c:return b;default:return t}}case n:return t}}}var S=u,w=f,O=s,E=c,$=r,T=l,j=o,C=m,P=y,N=n,I=i,k=a,A=p,_=!1;function R(e){return x(e)===f}t.AsyncMode=S,t.ConcurrentMode=w,t.ContextConsumer=O,t.ContextProvider=E,t.Element=$,t.ForwardRef=T,t.Fragment=j,t.Lazy=C,t.Memo=P,t.Portal=N,t.Profiler=I,t.StrictMode=k,t.Suspense=A,t.isAsyncMode=function(e){return _||(_=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),R(e)||x(e)===u},t.isConcurrentMode=R,t.isContextConsumer=function(e){return x(e)===s},t.isContextProvider=function(e){return x(e)===c},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===r},t.isForwardRef=function(e){return x(e)===l},t.isFragment=function(e){return x(e)===o},t.isLazy=function(e){return x(e)===m},t.isMemo=function(e){return x(e)===y},t.isPortal=function(e){return x(e)===n},t.isProfiler=function(e){return x(e)===i},t.isStrictMode=function(e){return x(e)===a},t.isSuspense=function(e){return x(e)===p},t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===o||e===f||e===i||e===a||e===p||e===d||"object"==typeof e&&null!==e&&(e.$$typeof===m||e.$$typeof===y||e.$$typeof===c||e.$$typeof===s||e.$$typeof===l||e.$$typeof===v||e.$$typeof===g||e.$$typeof===h||e.$$typeof===b)},t.typeOf=x}()}));T.AsyncMode,T.ConcurrentMode,T.ContextConsumer,T.ContextProvider,T.Element,T.ForwardRef,T.Fragment,T.Lazy,T.Memo,T.Portal,T.Profiler,T.StrictMode,T.Suspense,T.isAsyncMode,T.isConcurrentMode,T.isContextConsumer,T.isContextProvider,T.isElement,T.isForwardRef,T.isFragment,T.isLazy,T.isMemo,T.isPortal,T.isProfiler,T.isStrictMode,T.isSuspense,T.isValidElementType,T.typeOf;var j=n((function(e){"production"===process.env.NODE_ENV?e.exports=$:e.exports=T})),C=Object.getOwnPropertySymbols,P=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable; /* object-assign (c) Sindre Sorhus @license MIT */function I(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}var k=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(t).map((function(e){return t[e]}));if("0123456789"!==n.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach((function(e){o[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,n,o=I(e),a=1;a<arguments.length;a++){for(var i in r=Object(arguments[a]))P.call(r,i)&&(o[i]=r[i]);if(C){n=C(r);for(var c=0;c<n.length;c++)N.call(r,n[c])&&(o[n[c]]=r[n[c]])}}return o},A=Function.call.bind(Object.prototype.hasOwnProperty),_="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",R=A,M=function(){};if("production"!==process.env.NODE_ENV){var F=_,z={},D=R;M=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(e){}}}function V(e,t,r,n,o){if("production"!==process.env.NODE_ENV)for(var a in e)if(D(e,a)){var i;try{if("function"!=typeof e[a]){var c=Error((n||"React class")+": "+r+" type `"+a+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[a]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw c.name="Invariant Violation",c}i=e[a](t,a,n,r,null,F)}catch(e){i=e}if(!i||i instanceof Error||M((n||"React class")+": type specification of "+r+" `"+a+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof i+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),i instanceof Error&&!(i.message in z)){z[i.message]=!0;var s=o?o():"";M("Failed "+r+" type: "+i.message+(null!=s?s:""))}}}V.resetWarningCache=function(){"production"!==process.env.NODE_ENV&&(z={})};var q=V,L=function(){};function W(){return null}"production"!==process.env.NODE_ENV&&(L=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(e){}});function Y(){}function B(){}B.resetWarningCache=Y;var U=function(e,t){var r="function"==typeof Symbol&&Symbol.iterator;var n="<<anonymous>>",o={array:s("array"),bigint:s("bigint"),bool:s("boolean"),func:s("function"),number:s("number"),object:s("object"),string:s("string"),symbol:s("symbol"),any:c(W),arrayOf:function(e){return c((function(t,r,n,o,a){if("function"!=typeof e)return new i("Property `"+a+"` of component `"+n+"` has invalid PropType notation inside arrayOf.");var c=t[r];if(!Array.isArray(c))return new i("Invalid "+o+" `"+a+"` of type `"+l(c)+"` supplied to `"+n+"`, expected an array.");for(var s=0;s<c.length;s++){var u=e(c,s,n,o,a+"["+s+"]",_);if(u instanceof Error)return u}return null}))},element:c((function(t,r,n,o,a){var c=t[r];return e(c)?null:new i("Invalid "+o+" `"+a+"` of type `"+l(c)+"` supplied to `"+n+"`, expected a single ReactElement.")})),elementType:c((function(e,t,r,n,o){var a=e[t];return j.isValidElementType(a)?null:new i("Invalid "+n+" `"+o+"` of type `"+l(a)+"` supplied to `"+r+"`, expected a single ReactElement type.")})),instanceOf:function(e){return c((function(t,r,o,a,c){if(!(t[r]instanceof e)){var s=e.name||n;return new i("Invalid "+a+" `"+c+"` of type `"+(((u=t[r]).constructor&&u.constructor.name?u.constructor.name:n)+"` supplied to `")+o+"`, expected instance of `"+s+"`.")}var u;return null}))},node:c((function(e,t,r,n,o){return f(e[t])?null:new i("Invalid "+n+" `"+o+"` supplied to `"+r+"`, expected a ReactNode.")})),objectOf:function(e){return c((function(t,r,n,o,a){if("function"!=typeof e)return new i("Property `"+a+"` of component `"+n+"` has invalid PropType notation inside objectOf.");var c=t[r],s=l(c);if("object"!==s)return new i("Invalid "+o+" `"+a+"` of type `"+s+"` supplied to `"+n+"`, expected an object.");for(var u in c)if(R(c,u)){var f=e(c,u,n,o,a+"."+u,_);if(f instanceof Error)return f}return null}))},oneOf:function(e){if(!Array.isArray(e))return"production"!==process.env.NODE_ENV&&L(arguments.length>1?"Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).":"Invalid argument supplied to oneOf, expected an array."),W;function t(t,r,n,o,c){for(var s=t[r],u=0;u<e.length;u++)if(a(s,e[u]))return null;var f=JSON.stringify(e,(function(e,t){return"symbol"===p(t)?String(t):t}));return new i("Invalid "+o+" `"+c+"` of value `"+String(s)+"` supplied to `"+n+"`, expected one of "+f+".")}return c(t)},oneOfType:function(e){if(!Array.isArray(e))return"production"!==process.env.NODE_ENV&&L("Invalid argument supplied to oneOfType, expected an instance of array."),W;for(var t=0;t<e.length;t++){var r=e[t];if("function"!=typeof r)return L("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+d(r)+" at index "+t+"."),W}return c((function(t,r,n,o,a){for(var c=[],s=0;s<e.length;s++){var u=(0,e[s])(t,r,n,o,a,_);if(null==u)return null;u.data&&R(u.data,"expectedType")&&c.push(u.data.expectedType)}return new i("Invalid "+o+" `"+a+"` supplied to `"+n+"`"+(c.length>0?", expected one of type ["+c.join(", ")+"]":"")+".")}))},shape:function(e){return c((function(t,r,n,o,a){var c=t[r],s=l(c);if("object"!==s)return new i("Invalid "+o+" `"+a+"` of type `"+s+"` supplied to `"+n+"`, expected `object`.");for(var f in e){var d=e[f];if("function"!=typeof d)return u(n,o,a,f,p(d));var y=d(c,f,n,o,a+"."+f,_);if(y)return y}return null}))},exact:function(e){return c((function(t,r,n,o,a){var c=t[r],s=l(c);if("object"!==s)return new i("Invalid "+o+" `"+a+"` of type `"+s+"` supplied to `"+n+"`, expected `object`.");var f=k({},t[r],e);for(var d in f){var y=e[d];if(R(e,d)&&"function"!=typeof y)return u(n,o,a,d,p(y));if(!y)return new i("Invalid "+o+" `"+a+"` key `"+d+"` supplied to `"+n+"`.\nBad object: "+JSON.stringify(t[r],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(e),null," "));var m=y(c,d,n,o,a+"."+d,_);if(m)return m}return null}))}};function a(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}function i(e,t){this.message=e,this.data=t&&"object"==typeof t?t:{},this.stack=""}function c(e){if("production"!==process.env.NODE_ENV)var r={},o=0;function a(a,c,s,u,f,l,p){if(u=u||n,l=l||s,p!==_){if(t){var d=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw d.name="Invariant Violation",d}if("production"!==process.env.NODE_ENV&&"undefined"!=typeof console){var y=u+":"+s;!r[y]&&o<3&&(L("You are manually calling a React.PropTypes validation function for the `"+l+"` prop on `"+u+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),r[y]=!0,o++)}}return null==c[s]?a?null===c[s]?new i("The "+f+" `"+l+"` is marked as required in `"+u+"`, but its value is `null`."):new i("The "+f+" `"+l+"` is marked as required in `"+u+"`, but its value is `undefined`."):null:e(c,s,u,f,l)}var c=a.bind(null,!1);return c.isRequired=a.bind(null,!0),c}function s(e){return c((function(t,r,n,o,a,c){var s=t[r];return l(s)!==e?new i("Invalid "+o+" `"+a+"` of type `"+p(s)+"` supplied to `"+n+"`, expected `"+e+"`.",{expectedType:e}):null}))}function u(e,t,r,n,o){return new i((e||"React class")+": "+t+" type `"+r+"."+n+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+o+"`.")}function f(t){switch(typeof t){case"number":case"string":case"undefined":return!0;case"boolean":return!t;case"object":if(Array.isArray(t))return t.every(f);if(null===t||e(t))return!0;var n=function(e){var t=e&&(r&&e[r]||e["@@iterator"]);if("function"==typeof t)return t}(t);if(!n)return!1;var o,a=n.call(t);if(n!==t.entries){for(;!(o=a.next()).done;)if(!f(o.value))return!1}else for(;!(o=a.next()).done;){var i=o.value;if(i&&!f(i[1]))return!1}return!0;default:return!1}}function l(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":function(e,t){return"symbol"===e||!!t&&("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}(t,e)?"symbol":t}function p(e){if(null==e)return""+e;var t=l(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function d(e){var t=p(e);switch(t){case"array":case"object":return"an "+t;case"boolean":case"date":case"regexp":return"a "+t;default:return t}}return i.prototype=Error.prototype,o.checkPropTypes=q,o.resetWarningCache=q.resetWarningCache,o.PropTypes=o,o},J=function(){function e(e,t,r,n,o,a){if(a!==_){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}function t(){return e}e.isRequired=e;var r={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:B,resetWarningCache:Y};return r.PropTypes=r,r},H=n((function(e){if("production"!==process.env.NODE_ENV){var t=j;e.exports=U(t.isElement,!0)}else e.exports=J()}));function G(e,t){void 0===t&&(t={});var r=t.insertAt;if(e&&"undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css","top"===r&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}G(".dateInput::selection{background-color:#f74b73;color:#f5f5f5}.dateInput::-moz-selection{background-color:#f74b73;color:#f5f5f5}");const K=({size:t="md",className:n=""})=>{const[o,a]=e.useState(),i=e.useRef();let c;"xs"===t?c=190:"sm"===t?c=260:"md"===t?c=350:"lg"===t&&(c=520);const s={backgroundColor:"#F2F2F2",textAlign:"center",width:`${c}px`,height:"20px",paddingTop:"12px",paddingBottom:"12px",borderRadius:"40px",fontFamily:"Cabin",fontSize:"15px",color:"#A7A7A7",border:"none",outline:"none"},u=()=>{const e=i.current.value.replace(/\D/g,"").match(/(\d{0,2})(\d{0,2})(\d{0,4})/);i.current.value=e[2]?`${e[1]}.${e[2]}${""+(e[3]?`.${e[3]}`:"")}${""+(e[4]?`.${e[4]}`:"")}`:e[1];const t=i.current.value.replace(/(\D)/g,"");a(t)};return e.useEffect((()=>{u()}),[o]),r.default.createElement("input",{type:"text",ref:i,onChange:u,style:s,placeholder:"DD.MM.YYYY",className:`dateInput ${n}`})};K.propTypes={size:H.oneOf(["xs","sm","md","lg"]),className:H.string};G(".passwordInput::selection{background-color:#f74b73;color:#f5f5f5}.passwordInput::-moz-selection{background-color:#f74b73;color:#f5f5f5}");const Q=({size:e="md",className:t="",visible:n=!1,placeholder:o="•••••••••••••••••"})=>{let a;"xs"===e?a=190:"sm"===e?a=260:"md"===e?a=350:"lg"===e&&(a=520);const i={backgroundColor:"#F2F2F2",textAlign:"center",width:`${a}px`,height:"20px",paddingTop:"12px",paddingBottom:"12px",borderRadius:"40px",fontFamily:"Cabin",fontSize:""+(n?"15px":"18px"),overflow:"hidden",color:"#A7A7A7",border:"none",outline:"none"};return r.default.createElement("input",{type:n?"text":"password",placeholder:o,style:i,className:`passwordInput ${t}`})};Q.prototypes={size:H.oneOf(["xs","sm","md","lg"]),className:H.string,visible:H.bool,placeholder:H.string};G(".textInput::selection{background-color:#f74b73;color:#f5f5f5}.textInput::-moz-selection{background-color:#f74b73;color:#f5f5f5}");const X=({placeholder:e,size:t="md",className:n=""})=>{let o;"xs"===t?o=190:"sm"===t?o=260:"md"===t?o=350:"lg"===t&&(o=520);const a={backgroundColor:"#F2F2F2",textAlign:"center",width:`${o}px`,height:"20px",paddingTop:"12px",paddingBottom:"12px",borderRadius:"40px",fontFamily:"Cabin",fontSize:"15px",color:"#A7A7A7",border:"none",outline:"none"};return r.default.createElement("input",{type:"text",placeholder:e,style:a,className:`textInput ${n}`})};X.propTypes={placeholder:H.string.isRequired,size:H.oneOf(["xs","sm","md","lg"]),className:H.string},exports.DateInput=K,exports.PasswordInput=Q,exports.TextInput=X;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Update; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _update = require('lodash/update'); var _update2 = _interopRequireDefault(_update); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Update(props) { return props.children((0, _update2.default)(props.object, props.path, props.updater)); } Update.defaultProps = { children: function children(value) { return value; } };
import os import sys import re from time import sleep import time import random from microMolder import LambdaMolder from microFront import CloudFrontMolder from microGateway import ApiGatewayMolder from microDynamo import DynamoMolder from microUtils import loadConfig, roleCleaner from MMAnsibleDeployAll import deployStart from main_Deployer import TemporalDeployer import awsconnect from awsconnect import awsConnect # sudo ansible-playbook -i windows-servers CR-Admin-Users.yml -vvvv dir_path = os.path.dirname(__file__) # directory='/Users/bgarner/CR/Ansible_Deployer/ansible' directory = os.path.join(dir_path, '../../ansible') # EXECUTE AGAINST DEFINITIONS # # # PRODUCE RESULTS PASS/FAIL # python microMolder.py -L xx-LambdaName true ENVR.yaml '/path/to/Ansible_Deployer/ansible/roles/xx-LambdaName' API_Name true # python Main_DEPLOYER.py -DY dev "test,stage" xx_tablename ENVR.yaml '/path/to/Ansible_Deployer/ansible/roles/xx-LambdaName' API_Name true #. OR # python Main_DEPLOYER.py "xx-stage,xx-test" xx_tablename ENVR.yaml # python Main_Deployer.py "xx-test" xx_tablename ENVR.yaml if __name__ == "__main__": SkipDefinition = False start_time = time.time() config = "ENVR.yaml" fullpath = "%s/%s" % (dir_path, config) origin, global_accts = loadConfig(fullpath) triggers = origin['triggers'] if triggers is None: raise ValueError("[E] config file [ %s ] did not load correctly.. PLEASE check / fix and try again" % (fullpath)) td = TemporalDeployer() targetAPI = fullUpdate = target_environments = None # environments="party3d" # environments="test" # environments="final" environments = "test,stage,prod,final" ############################################################## ######### don't forget to update ENVR.yaml############# ############################################################## # target2Define -->must update the EID, name and target_environments = environments.split(",") type_in = "-DY" # -DY #-G -L targetAPI = "API_Name" fullUpdate = True # root="/Users/bgarner/CR/Ansible_Deployer/ansible/roles" root = os.path.join(dir_path, "../../ansible/roles") for role in dynamo: ready = None # role = roleCleaner(role) roleString = roleCleaner(role) sendto = "%s/%s" % (root, roleString) if not SkipDefinition: acctID, target, acctTitle, ready = td.Define(type_in, role, origin, global_accts, sendto, config, triggers, targetAPI, fullUpdate) print("-[DEFINED]-- %s seconds ---" % (time.time() - start_time)) if ready or SkipDefinition: print("###########################################################") print("######### Ansible DEPLOYMENT START [%s] ##################%s" % (type_in, roleString)) print("###########################################################") results = deployStart(global_accts, target_environments, roleString) for k, v in results.items(): msg = "%s Account: %s, %s" % (v['name'], k, v['value']) print(msg) print("-[DEPLOYED]-- %s seconds ---" % (time.time() - start_time)) # print(global_accts) #print (target_environments) #//logger.info("Finished") print("--[FIN]- %s seconds ---" % (time.time() - start_time))
$(function () { getTasksResultSinceLastMinute(); getTasksResultSinceLastHour(); getTasksResultSinceLastWeek(); getJobType(); getJobExecutionType(); getStatictisJobs(); getRunningJobAndTaskSincelastWeek(); getRegisteredJobs(); }); function getTasksResultSinceLastMinute() { var url = '/api/job/statistics/tasks/results/lastMinute', chartName = '#total_jobs_lastMinute', colorsArray = ['rgb(144,237,125)','red'], jobData = getChartData(url); var jobResult = [['成功', jobData.successCount],['失败', jobData.failedCount]]; producePieChart(chartName,'一分钟作业情况',colorsArray,jobResult); } function getTasksResultSinceLastHour() { var url = '/api/job/statistics/tasks/results/lastHour', chartName = '#total_jobs_lastHour', colorsArray = ['rgb(144,237,125)','red'], jobData = getChartData(url); var jobResult = [['成功', jobData.successCount],['失败', jobData.failedCount]]; producePieChart(chartName,'一小时作业情况',colorsArray,jobResult); } function getTasksResultSinceLastWeek() { var url = '/api/job/statistics/tasks/results/lastWeek', chartName = '#total_jobs_weekly', colorsArray = ['rgb(144,237,125)','red'], jobData = getChartData(url); var jobResult = [['成功', jobData.successCount],['失败', jobData.failedCount]]; producePieChart(chartName,'一周作业情况',colorsArray,jobResult); } function getJobType() { var url = '/api/job/statistics/jobs/type', chartName = '#job_type', colorsArray = ['rgb(144, 237, 125)','rgb(247, 163, 92)','rgb(67, 67, 72)'], jobData = getChartData(url); var jobResult = [['DATAFLOW', jobData.dataflowJobCount],['SIMPLE', jobData.simpleJobCount],['SCRIPT',jobData.scriptJobCount]]; producePieChart(chartName,'作业类型',colorsArray,jobResult); } function getJobExecutionType() { var url = '/api/job/statistics/jobs/executionType', chartName = '#job_execution_type', colorsArray = ['rgb(144, 237, 125)','rgb(124, 181, 236)'], jobData = getChartData(url); var jobResult = [['TRANSIENT', jobData.transientJobCount],['DAEMON', jobData.daemonJobCount]]; producePieChart(chartName,'作业执行类型',colorsArray,jobResult); } function getStatictisJobs(){ var url = '/api/job/statistics/tasks/results?since=last24hours', chartName = '#statictis_jobs', jobData = getChartData(url); var succData = [],failData = []; for(var i=0;i<jobData.length;i++){ var dateTime = new Date(jobData[i].statisticsTime).getTime() + 1000*60*60*8; succData.push([dateTime,jobData[i].successCount]); failData.push([dateTime,jobData[i].failedCount]) } resultData = [{type: 'spline',name: '作业成功数',data: succData}, {type: 'spline',name: '作业失败数',data: failData}]; produceLineChart(chartName,'作业成功/失败数',resultData); } function getRunningJobAndTaskSincelastWeek(){ var urlJob = '/api/job/statistics/jobs/running?since=lastWeek', urlTask = '/api/job/statistics/tasks/running?since=lastWeek', chartName = '#run_jobs', jobData = getChartData(urlJob), taskData = getChartData(urlTask), jobRunningData = [], taskRunningData = []; for(var i=0;i<jobData.length;i++){ var dateTime = new Date(jobData[i].statisticsTime).getTime() + 1000*60*60*8; jobRunningData.push([dateTime,jobData[i].runningCount]); } for(var i=0;i<taskData.length;i++){ var dateTime = new Date(taskData[i].statisticsTime).getTime() + 1000*60*60*8; taskRunningData.push([dateTime,taskData[i].runningCount]); } resultData = [{type: 'spline',name: '任务运行数',data: taskRunningData}, {type: 'spline',name: '作业运行数',data: jobRunningData}]; produceLineChart(chartName,'作业/任务运行数',resultData); } function getRegisteredJobs(){ var url = '/api/job/statistics/jobs/register', chartName = '#import_jobs', jobData = getChartData(url); var registerData = []; for(var i=0;i<jobData.length;i++){ var dateTime = new Date(jobData[i].statisticsTime).getTime() + 1000*60*60*8; registerData.push([dateTime,jobData[i].registeredCount]); } resultData = [{ type: 'spline',name: '接入作业数',data: registerData}]; produceLineChart(chartName,'接入平台作业数',resultData); } function getChartData(url){ var result = []; $.ajax({ url: url, async: false, dataType: 'json', success: function (data) { if(null != data){ result = data; } } }); return result; } function producePieChart(chartName,title,colorsArray,jobData){ $(chartName).highcharts({ chart: { backgroundColor: 'rgba(255, 255, 255, 0)', }, title: { text: title }, plotOptions: { pie: { size: '60%', allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>:<br> {point.percentage:.1f} %', distance: 5 } } }, colors: colorsArray, series: [{ type: 'pie', name: '作业', data: jobData }], credits: { enabled: false } }); } function produceLineChart(chartName,title,jobData){ Highcharts.setOptions({ lang: { resetZoom: '重置', resetZoomTitle: '重置缩放比例' } }); $(chartName).highcharts({ chart: { zoomType: 'x', resetZoomButton: { position:{ align: 'right', verticalAlign: 'top', x: 0, y: -50 } }, backgroundColor: 'rgba(255, 255, 255, 0)' }, credits:{ enabled:false }, title: { text: title }, subtitle: { text: document.ontouchstart === undefined ? '鼠标拖动可以进行缩放' : '手势操作进行缩放' }, tooltip:{ shared:true, crosshairs:true, dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%Y-%m-%d %H:%M:%S', minute: '%Y-%m-%d %H:%M', hour: '%Y-%m-%d %H:%M', day: '%Y-%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } }, xAxis: { type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } }, yAxis: { title: { text: '' }, labels: { align: 'left', x: -10, y: 0 } }, series: jobData }); }
import React from 'react'; import Icon from '../Icon'; /* eslint-disable react/jsx-props-no-spreading */ export default function IconHeart(props) { return ( <Icon {...props}> <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" /> </Icon> ); }
'use strict'; const _ = require('lodash') const votes = require('../../db_seed').VOTES module.exports = { up: function (queryInterface, Sequelize) { let prods = _(votes) .map((value) => _.extend(value, {createdAt: new Date(), updatedAt: new Date()})) .value() return queryInterface.bulkInsert('Votes', prods, {}) }, down: function (queryInterface, Sequelize) { return queryInterface.bulkDelete('Votes', null, {}) } };
# main.py # Demonstration code to use the ML-experiment framework import sys sys.path.append("./src") from reporter import Reporter import experiment as exp import configparser from util import Util def main(config_file): # load one configuration per experiment config = configparser.ConfigParser() config.read(config_file) util = Util() # create a new experiment expr = exp.Experiment(config) print(f'running {expr.name}') # load the experiment # expr.load(f'{util.get_exp_name()}.pkl') reporter = Reporter([], []) reporter.make_conf_animation('test.gif') print('DONE') if __name__ == "__main__": main(sys.argv[1])