code
stringlengths
2
1.05M
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array'), require('d3-axis'), require('d3-collection'), require('d3-dispatch'), require('d3-format'), require('d3-scale'), require('d3-selection'), require('d3-shape'), require('d3-time-format')) : typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-axis', 'd3-collection', 'd3-dispatch', 'd3-format', 'd3-scale', 'd3-selection', 'd3-shape', 'd3-time-format'], factory) : (factory((global.ldd3 = global.ldd3 || {}),global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3)); }(this, (function (exports,d3,d3$1,d3$2,d3$3,d3$4,d3$5,d3$6,d3$7,d3$8) { 'use strict'; //# sourceMappingURL=d3-bundle.js.map var BottomCategoricalAxis = (function () { /** * Create a new BottomCategoricalAxis. * @param container - the svg element to which the axis will be appended. * @param _width - the width of the container. * @param _height - the height of the container. */ function BottomCategoricalAxis(container, _width, _height) { this._width = _width; this._height = _height; this._group = container.append('g') .classed('axis', true) .attr('transform', "translate(" + 0 + "," + _height + ")"); this._scale = d3$5.scaleBand() .range([0, _width]); this._axis = d3$1.axisBottom(this._scale); } /** * Get the group in which the axis is drawn. */ BottomCategoricalAxis.prototype.group = function () { return this._group; }; BottomCategoricalAxis.prototype.domain = function (value) { if (arguments.length) { this._scale.domain(value); this._group.call(this._axis); return this; } else { return this._scale.domain(); } }; BottomCategoricalAxis.prototype.padding = function (value) { this._scale.padding(value); return this; }; BottomCategoricalAxis.prototype.scale = function (value) { return this._scale(value); }; BottomCategoricalAxis.prototype.bandWidth = function () { return this._scale.bandwidth(); }; return BottomCategoricalAxis; }()); //# sourceMappingURL=BottomCategoricalAxis.js.map var BottomLinearAxis = (function () { function BottomLinearAxis(container, _width, _height) { this._width = _width; this._height = _height; var xScale = d3$5.scaleLinear() .range([0, this._width]); var fmt = d3$4.format('0'); var xAxis = d3$1.axisBottom(xScale) .tickFormat(function (d) { return fmt(d); }); var xAxisGroup = container.append('g') .classed('horizontal axis', true) .attr('transform', "translate(" + 0 + "," + this._height + ")"); this._scale = xScale; this._group = xAxisGroup; this._axis = xAxis; } BottomLinearAxis.prototype.domain = function (value) { this._scale.domain(value); this._group.call(this._axis); return this; }; BottomLinearAxis.prototype.format = function (value) { this._axis.tickFormat(d3$4.format(value)); return this; }; BottomLinearAxis.prototype.scale = function (value) { return this._scale(value); }; return BottomLinearAxis; }()); //# sourceMappingURL=BottomLinearAxis.js.map var BottomTimeAxis = (function () { function BottomTimeAxis(container, _width, _height) { this._width = _width; this._height = _height; var xScale = d3$5.scaleTime() .range([0, this._width]); var xAxis = d3$1.axisBottom(xScale); var xAxisGroup = container.append('g') .classed('horizontal axis', true) .attr('transform', "translate(" + 0 + "," + this._height + ")"); this._scale = xScale; this._group = xAxisGroup; this._axis = xAxis; } BottomTimeAxis.prototype.format = function (value) { this._axis.tickFormat(d3$8.timeFormat(value)); return this; }; BottomTimeAxis.prototype.domain = function (value) { this._scale.domain(value); this._group.call(this._axis); return this; }; BottomTimeAxis.prototype.scale = function (value) { return this._scale(value); }; return BottomTimeAxis; }()); //# sourceMappingURL=BottomTimeAxis.js.map var LeftCategoricalAxis = (function () { function LeftCategoricalAxis(container, _width, _height) { this._width = _width; this._height = _height; this._group = container.append('g') .classed('axis', true) .attr('transform', "translate(" + 0 + "," + 0 + ")"); this._scale = d3$5.scaleBand() .range([0, _height]); this._axis = d3$1.axisLeft(this._scale); } LeftCategoricalAxis.prototype.group = function () { return this._group; }; LeftCategoricalAxis.prototype.domain = function (value) { if (arguments.length) { this._scale.domain(value); this._group.call(this._axis); return this; } else { return this._scale.domain(); } }; LeftCategoricalAxis.prototype.scale = function (value) { return this._scale(value); }; LeftCategoricalAxis.prototype.bandWidth = function () { return this._scale.bandwidth(); }; LeftCategoricalAxis.prototype.padding = function (value) { if (arguments.length) { this._scale.padding(value); return this; } else { return this._scale.padding(); } }; return LeftCategoricalAxis; }()); //# sourceMappingURL=LeftCategoricalAxis.js.map var LeftLinearAxis = (function () { function LeftLinearAxis(container, _width, _height) { this._width = _width; this._height = _height; this._group = container.append('g') .classed('axis', true); this._scale = d3$5.scaleLinear() .range([_height, 0]); this._axis = d3$1.axisLeft(this._scale); } LeftLinearAxis.prototype.group = function () { return this._group; }; LeftLinearAxis.prototype.domain = function (value) { if (arguments.length) { this._scale.domain(value).nice(); this._group.call(this._axis); return this; } else { return this._scale.domain(); } }; LeftLinearAxis.prototype.format = function (specifier) { this._axis.tickFormat(d3$4.format(specifier)); return this; }; LeftLinearAxis.prototype.scale = function (value) { return this._scale(value); }; LeftLinearAxis.prototype.ticks = function () { return this._scale.ticks(); }; return LeftLinearAxis; }()); //# sourceMappingURL=LeftLinearAxis.js.map var TopLinearAxis = (function () { function TopLinearAxis(container, _width, _height) { this._width = _width; this._height = _height; var xScale = d3$5.scaleLinear() .range([0, this._width]); var fmt = d3$4.format('0'); var xAxis = d3$1.axisTop(xScale) .tickFormat(function (d) { return fmt(d); }); var xAxisGroup = container.append('g') .classed('horizontal axis', true) .attr('transform', "translate(" + 0 + "," + 0 + ")"); this._scale = xScale; this._group = xAxisGroup; this._axis = xAxis; } TopLinearAxis.prototype.domain = function (value) { this._scale.domain(value).nice(); this._group.call(this._axis); return this; }; TopLinearAxis.prototype.scale = function (value) { return this._scale(value); }; return TopLinearAxis; }()); //# sourceMappingURL=TopLinearAxis.js.map // import BottomCategoricalAxis ; //# sourceMappingURL=Axes.js.map var ChartContainer = (function () { function ChartContainer(container, width, height, margins) { this._parent = container; var chartContainerMargins = margins; var chartContainerGroup = container.append('g') .attr('transform', "translate(" + chartContainerMargins.left + "," + chartContainerMargins.top + ")"); var chartContainerWidth = width - chartContainerMargins.left - chartContainerMargins.right; var chartContainerHeight = height - chartContainerMargins.top - chartContainerMargins.bottom; this._chartContainerWidth = chartContainerWidth; this._chartContainerHeight = chartContainerHeight; this._group = chartContainerGroup; } ChartContainer.prototype.parent = function () { return this._parent; }; ChartContainer.prototype.group = function () { return this._group; }; ChartContainer.prototype.width = function () { return this._chartContainerWidth; }; ChartContainer.prototype.height = function () { return this._chartContainerHeight; }; return ChartContainer; }()); //# sourceMappingURL=ChartContainer.js.map function GetContainer(selector, width, height, margins) { var svg = d3$6.select(selector) .append('svg') .attr('width', width) .attr('height', height); return new ChartContainer(svg, width, height, margins); } //# sourceMappingURL=plotFactory.js.map var title = (function () { function title(container, width, height) { this._group = container.append('g') .classed('chart-title', true) .attr('transform', "translate(" + width / 2 + "," + 30 + ")"); this._group.append('text'); } title.prototype.text = function (value) { this._group.select('text').text(value); }; title.prototype.classed = function (value) { this._group.classed(value, true); }; return title; }()); //# sourceMappingURL=title.js.map var ChartBase = (function () { function ChartBase(selector, _width, _height, plotMargins) { this._width = _width; this._height = _height; var container = GetContainer(selector, _width, _height, plotMargins); this._container = container; this._group = container.group(); this._plotWidth = container.width(); this._plotHeight = container.height(); this._title = new title(this.parent(), _width, _height); } ChartBase.prototype.group = function () { return this._group; }; ChartBase.prototype.width = function () { return this._plotWidth; }; ChartBase.prototype.height = function () { return this._plotHeight; }; ChartBase.prototype.parent = function () { return this._container.parent(); }; ChartBase.prototype.x = function (value) { if (arguments.length) { this._x = value; return this; } else { return this._x; } }; ChartBase.prototype.y = function (value) { if (arguments.length) { this._y = value; return this; } else { return this._y; } }; ChartBase.prototype.title = function (value) { this._title.text(value); return this; }; return ChartBase; }()); //# sourceMappingURL=ChartBase.js.map var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var HorizontalBarChart = (function (_super) { __extends(HorizontalBarChart, _super); function HorizontalBarChart(selector, width, height) { var _this = _super.call(this, selector, width, height, { top: 60, bottom: 30, left: 120, right: 30 }) || this; var plotGroup = _this.group(); var plotHeight = _this.height(); var plotWidth = _this.width(); _this._yAxis = new LeftCategoricalAxis(plotGroup, plotWidth, plotHeight) .padding(0.5); _this._xScale = d3$5.scaleLinear() .range([0, plotWidth]); _this._seriesGroup = plotGroup.append('g') .classed('series-group', true); _this._color = function () { return 'lightgray'; }; return _this; } HorizontalBarChart.prototype.padding = function (value) { this._yAxis.padding(value); return this; }; HorizontalBarChart.prototype.color = function (value) { this._color = value; return this; }; HorizontalBarChart.prototype.format = function (value) { this._format = d3$4.format(value); return this; }; HorizontalBarChart.prototype.update = function (data) { var _this = this; var xFunction = this.x(); var yFunction = this.y(); this._xScale.domain([0, d3.max(data, xFunction)]); this._yAxis.domain(data.map(yFunction)); var dataBound = this._seriesGroup.selectAll('.series') .data(data); dataBound .exit() .remove(); var enterSelection = dataBound .enter() .append('g') .classed('series', true); var rect = enterSelection.append('rect') .attr('x', 0) .attr('y', 0) .attr('height', this._yAxis.bandWidth()) .style('stroke', 'none'); enterSelection.append('text') .classed('bar-label', true) .attr('y', this._yAxis.bandWidth() / 2); var merged = enterSelection.merge(dataBound); merged.attr('transform', function (d, i) { return "translate(" + 0 + "," + _this._yAxis.scale(yFunction(d, i)) + ")"; }); merged.select('rect') .transition() .attr('width', function (d, i) { return _this._xScale(xFunction(d, i)); }) .style('fill', function (d) { return _this._color(d); }); merged.select('text') .transition() .style('text-anchor', function (d, i) { return _this._xScale(xFunction(d, i)) < 30 ? 'start' : 'end'; }) .attr('x', function (d, i) { var initial = _this._xScale(xFunction(d, i)); return initial < 30 ? initial + 5 : initial - 5; }) .text(function (d, i) { return _this._format ? _this._format(xFunction(d, i)) : xFunction(d, i); }); }; return HorizontalBarChart; }(ChartBase)); var __extends$1 = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var LinearLinearChart = (function (_super) { __extends$1(LinearLinearChart, _super); function LinearLinearChart(selector, width, height) { var _this = _super.call(this, selector, width, height, { top: 60, bottom: 30, left: 60, right: 90 }) || this; _this._hasLine = true; _this._hasPoints = false; _this._pointColor = function () { return 'lightgray'; }; var plotGroup = _this.group(); var plotWidth = _this.width(); var plotHeight = _this.height(); var container = plotGroup.append('g') .classed('chart-container', true); _this._xAxis = new BottomLinearAxis(container, plotWidth, plotHeight); _this._yAxis = new LeftLinearAxis(container, plotWidth, plotHeight) .format('s'); _this.initPathGenerator(container); _this._pointsGroup = container.append('g') .classed('points', true); return _this; } LinearLinearChart.prototype.hasLine = function (value) { this._hasLine = value; return this; }; LinearLinearChart.prototype.hasPoints = function (value) { this._hasPoints = value; return this; }; LinearLinearChart.prototype.pointColor = function (value) { this._pointColor = value; return this; }; LinearLinearChart.prototype.xFormat = function (value) { this._xAxis.format(value); return this; }; LinearLinearChart.prototype.yFormat = function (value) { this._yAxis.format(value); return this; }; LinearLinearChart.prototype.update = function (data, xDomain, yDomain) { var _this = this; var xFunction = this.x(); var yFunction = this.y(); if (!xDomain) { xDomain = d3.extent(data, function (d) { return xFunction(d); }); } if (!yDomain) { yDomain = d3.extent(data, function (d) { return yFunction(d); }); } this._xAxis.domain(xDomain); this._yAxis.domain(yDomain); this._pathGroup .attr('d', this._pathGenerator(data)) .style('visibility', this._hasLine ? 'visible' : 'hidden'); var dataBound = this._pointsGroup.selectAll('.point') .data(data); dataBound .exit() .remove(); var enterSelection = dataBound .enter() .append('g') .classed('point', true); enterSelection.append('circle') .attr('r', 2); var merged = enterSelection.merge(dataBound); merged.style('visibility', this._hasPoints ? 'visible' : 'hidden'); merged.select('circle') .attr('cx', function (d) { return _this._xAxis.scale(xFunction(d)); }) .attr('cy', function (d) { return _this._yAxis.scale(yFunction(d)); }) .style('fill', function (d, i) { return _this._pointColor(d, i); }); }; LinearLinearChart.prototype.initPathGenerator = function (container) { var _this = this; this._pathGenerator = d3$7.line() .x(function (d) { return _this._xAxis.scale(_this.x()(d)); }) .y(function (d) { return _this._yAxis.scale(_this.y()(d)); }); this._pathGroup = container.append('g') .append('path') .classed('trace', true) .style('fill', 'none'); }; return LinearLinearChart; }(ChartBase)); //# sourceMappingURL=LinearLinearChart.js.map var Legend = (function () { function Legend(container, _width, _height) { var _this = this; this._width = _width; this._height = _height; this._legendWidth = 90; this._itemHeight = 20; this._legend = container.append('g') .classed('legend', true) .attr('transform', function (d, i) { return "translate(" + -_this._legendWidth + "," + 0 + ")"; }); this._legend.append('rect') .classed('legend-rect', true) .style('fill', 'none') .style('stroke', 'lightgray'); } Legend.prototype.label = function (value) { if (arguments.length) { this._label = value; } return this; }; Legend.prototype.color = function (value) { if (arguments.length) { this._color = value; } return this; }; Legend.prototype.update = function (data) { var _this = this; var legendBound = this._legend.selectAll('.legend-item') .data(function (d) { return data; }); legendBound.exit().remove(); var enterLegend = legendBound .enter() .append('g') .classed('legend-item', true) .attr('transform', function (d, i) { return "translate(" + 10 + "," + (i * 20 + 10) + ")"; }); enterLegend.append('rect') .attr('width', 10) .attr('height', 10) .style('fill', function (d, i) { return _this._color(d, i); }); enterLegend.append('text') .attr('x', 15) .attr('y', 9) .text(function (d, i) { return _this._label(d, i); }); var legendHeight = data.length * this._itemHeight + 10; this._legend .attr('transform', function (d, i) { return "translate(" + -_this._legendWidth + "," + -legendHeight + ")"; }); this._legend.select('rect.legend-rect') .attr('width', this._legendWidth - 10) .attr('height', legendHeight); }; return Legend; }()); //# sourceMappingURL=Legend.js.map var __extends$2 = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CategoricalLinearChart = (function (_super) { __extends$2(CategoricalLinearChart, _super); function CategoricalLinearChart(selector, width, height) { var _this = _super.call(this, selector, width, height, { top: 60, bottom: 30, left: 60, right: 90 }) || this; var plotGroup = _this.group(); var plotWidth = _this.width(); var plotHeight = _this.height(); _this._xAxis = new BottomCategoricalAxis(plotGroup, plotWidth, plotHeight); _this._yAxis = new LeftLinearAxis(plotGroup, plotWidth, plotHeight); _this._lineGenerator = d3$7.line() .curve(d3$7.curveStep) .x(function (d, i) { return _this._xAxis.scale(_this.x()(d, i)) + _this._xAxis.bandWidth() / 2; }) .y(function (d, i) { return _this._yAxis.scale(_this.y()(d, i)); }); var legendWidth = 90; var legendContainer = _this.parent() .append('g') .attr('transform', function (d, i) { return "translate(" + width + "," + height / 2 + ")"; }); _this._legend = new Legend(legendContainer, width, plotHeight) .label(function (d) { return d.key; }) .color(function (d, i) { return d3$5.schemeCategory10[i]; }); return _this; } CategoricalLinearChart.prototype.groupBy = function (value) { if (arguments.length) { this._groupBy = value; } return this; }; CategoricalLinearChart.prototype.update = function (data) { var _this = this; this._xAxis.domain(data.map(function (d, i) { return _this.x()(d, i); })); this._yAxis.domain([0, d3.max(data, function (d, i) { return _this.y()(d, i); })]); var grouped = d3$2.nest() .key(function (d) { return _this._groupBy(d); }) .entries(data); var dataBound = this.group().selectAll('.series') .data(grouped); dataBound.exit() .remove(); var enterSelection = dataBound .enter() .append('g') .classed('year-series', true); enterSelection.append('path') .attr('d', function (d) { return _this._lineGenerator(d.values); }) .style('stroke', function (d, i) { return d3$5.schemeCategory10[i]; }); this._legend.update(grouped); }; return CategoricalLinearChart; }(ChartBase)); //# sourceMappingURL=CategoricalLinearChart.js.map var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TimeLinearChart = (function (_super) { __extends$3(TimeLinearChart, _super); function TimeLinearChart(selector, width, height) { var _this = _super.call(this, selector, width, height, { top: 60, bottom: 30, left: 60, right: 90 }) || this; var plotGroup = _this.group(); var plotWidth = _this.width(); var plotHeight = _this.height(); _this._timeAxis = new BottomTimeAxis(plotGroup, plotWidth, plotHeight); _this._leftAxis = new LeftLinearAxis(plotGroup, plotWidth, plotHeight); var group = plotGroup.append('g'); _this._path = group.append('path') .style('fill', 'none') .style('stroke', 'lightgray'); return _this; } TimeLinearChart.prototype.color = function (value) { this._path.style('stroke', value); return this; }; TimeLinearChart.prototype.xFormat = function (value) { this._timeAxis.format(value); return this; }; TimeLinearChart.prototype.yFormat = function (value) { this._leftAxis.format(value); return this; }; TimeLinearChart.prototype.update = function (data) { var _this = this; var lineGenerator = d3$7.line() .x(function (d, i) { return _this._timeAxis.scale(_this.x()(d, i)); }) .y(function (d, i) { return _this._leftAxis.scale(_this.y()(d, i)); }); this._timeAxis.domain(d3.extent(data, function (d, i) { return _this.x()(d, i); })); this._leftAxis.domain([0, d3.max(data, function (d, i) { return _this.y()(d, i); })]); this._path.attr('d', lineGenerator(data)); }; return TimeLinearChart; }(ChartBase)); //# sourceMappingURL=TimeLinearChart.js.map var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var MultiCategoricalChart = (function (_super) { __extends$4(MultiCategoricalChart, _super); function MultiCategoricalChart(selector, width, height) { var _this = _super.call(this, selector, width, height, { top: 60, bottom: 30, left: 60, right: 90 }) || this; _this._colorScale = function (i) { return d3$5.schemeCategory20[i]; }; var plotMargins = { top: 60, bottom: 30, left: 60, right: 90 }; var plotGroup = _this.group(); var plotWidth = _this.width(); var plotHeight = _this.height(); _this._xAxis = new BottomCategoricalAxis(plotGroup, plotWidth, plotHeight) .padding(0.3); _this._yAxis = new LeftLinearAxis(plotGroup, plotWidth, plotHeight); _this._seriesGroup = plotGroup.append('g') .classed('series', true); var legendContainer = _this.parent() .append('g') .classed('legend-container', true) .attr('transform', "translate(" + (plotWidth + plotMargins.left + plotMargins.right) + "," + plotHeight / 2 + ")"); _this._legend = new Legend(legendContainer, plotWidth, plotHeight) .color(function (d, i) { return _this._colorScale(i); }) .label(function (d) { return d; }); return _this; } MultiCategoricalChart.prototype.color = function (value) { if (value) { this._colorScale = value; } return this; }; MultiCategoricalChart.prototype.yFormat = function (value) { if (arguments.length) { this._yAxis.format(value); } return this; }; MultiCategoricalChart.prototype.groupBy = function (value) { if (arguments.length) { this._groupBy = value; } return this; }; MultiCategoricalChart.prototype.update = function (data, yDomain) { var _this = this; this._xAxis.domain(data.map(this.x())); if (!yDomain) { yDomain = d3.extent(data, this.y()); } this._yAxis.domain(yDomain); var bandWidth = this._xAxis.bandWidth(); var secondaryScale = d3$5.scaleBand() .domain(data.map(this._groupBy)) .range([0, bandWidth]); var byCategory = d3$2.nest() .key(this.x()) .entries(data); var dataBound = this._seriesGroup.selectAll('.category') .data(byCategory); dataBound .exit() .remove(); var enterSelection = dataBound .enter() .append('g') .classed('category', true) .attr('transform', function (d, i) { return "translate(" + _this._xAxis.scale(d.key) + "," + 0 + ")"; }); enterSelection .selectAll('rect') .data(function (d) { return d.values; }) .enter() .append('rect') .attr('y', function (d, i) { return _this._yAxis.scale(_this.y()(d)); }) .attr('width', secondaryScale.bandwidth()) .attr('height', function (d, i) { return _this.height() - _this._yAxis.scale(_this.y()(d)); }) .attr('transform', function (d, i) { return "translate(" + secondaryScale(_this._groupBy(d)) + "," + 0 + ")"; }) .style('fill', function (d, i) { return _this._colorScale(i); }); this._legend.update(secondaryScale.domain()); }; return MultiCategoricalChart; }(ChartBase)); //# sourceMappingURL=MultiCategoricalChart.js.map //# sourceMappingURL=Charts.js.map var Slider = (function () { function Slider(selector, _width, _height) { this._width = _width; this._height = _height; var margins = { top: 10, bottom: 0, left: 30, right: 30 }; var svg = d3$6.select(selector) .append('svg') .attr('width', _width) .attr('height', _height); var group = svg.append('g') .classed('slider', true) .attr('transform', "translate(" + margins.left + "," + margins.top + ")"); var sliderWidth = _width - margins.left - margins.right; this._xScale = d3$5.scaleLinear() .range([0, sliderWidth]); group.append('line') .classed('track', true) .attr('x1', 0) .attr('x2', sliderWidth); group.append('line') .classed('track-inset', true) .attr('x1', 0) .attr('x2', sliderWidth); this._handle = group.append('circle') .classed('handle', true) .attr('r', 8); this._ticksGroup = group.append('g') .classed('ticks', true) .attr('transform', function (d, i) { return "translate(" + 0 + "," + (margins.top + 10) + ")"; }); this._dispatch = d3$3.dispatch('click'); } Slider.prototype.domain = function (value) { var _this = this; this._xScale.domain(value); this._ticksGroup.selectAll('.tick') .data(this._xScale.ticks()) .enter() .append('text') .classed('tick', true) .attr('x', function (d, i) { return _this._xScale(d); }) .attr('y', 10) .text(function (d) { return d; }) .on('click', function (d, i) { _this._handle .transition() .attr('transform', "translate(" + _this._xScale(d) + ",0)"); _this._dispatch.call('click', null, d, i); }); }; Slider.prototype.on = function (event, callback) { this._dispatch.on(event, callback); return this; }; return Slider; }()); //# sourceMappingURL=Slider.js.map //# sourceMappingURL=index.js.map exports.ChartContainer = ChartContainer; exports.title = title; exports.GetContainer = GetContainer; exports.Slider = Slider; exports.BottomLinearAxis = BottomLinearAxis; exports.BottomTimeAxis = BottomTimeAxis; exports.LeftCategoricalAxis = LeftCategoricalAxis; exports.LeftLinearAxis = LeftLinearAxis; exports.TopLinearAxis = TopLinearAxis; exports.BottomCategoricalAxis = BottomCategoricalAxis; exports.HorizontalBarChart = HorizontalBarChart; exports.LinearLinearChart = LinearLinearChart; exports.CategoricalLinearChart = CategoricalLinearChart; exports.TimeLinearChart = TimeLinearChart; exports.MultiCategoricalChart = MultiCategoricalChart; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=ldd3.js.map
import Ember from 'ember'; export default Ember.Controller.extend({ actions: { new() { this.transitionToRoute('images.new'); } } });
var vsf = require('./lib/vsf'); module.exports = vsf;
(function(externals){ var me = {}; function createEmptyMap(width, height){ var map = []; for (var i = 0; i < height; i++) { map.push([]); for (var j = 0; j < width; j++){ map[i].push(0); } } return map; } function centerInMap(obj, map){ if (!obj) return map; var vCenterOfMap = Math.floor(map.length / 2); var hCenterOfMap = Math.floor(map[0].length / 2); var objWidth = obj[0].length; var objHeight = obj.length; var vOffset = vCenterOfMap - Math.floor(objHeight/2); var hOffset = hCenterOfMap - Math.floor(objWidth/2); for (var y = 0; y < objHeight; y++) { for (var x = 0; x < objWidth; x++) { map[vOffset + y][hOffset + x] = obj[y][x]; } } return map; } me.getBlinker = function(){ return [[1,1,1]]; }; me.getRpentomino = function(){ return [[0,1,1],[1,1,0],[0,1,0]]; }; me.create = function(width, height, obj){ var map = createEmptyMap(width, height); map = centerInMap(obj, map); return map; }; externals.mapcreator = me; }(this))
// 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.4.4.18-5-24 description: Array.prototype.forEach - string primitive can be used as thisArg includes: [runTestCase.js] ---*/ function testcase() { var result = false; function callbackfn(val, idx, obj) { result = (this.valueOf() === "abc"); } [11].forEach(callbackfn, "abc"); return result; } runTestCase(testcase);
{ objectNestedInArrayDoc: { typeFilter: simpleTypeFilter, channels: { write: 'write' }, propertyValidators: { elementList: { type: 'array', arrayElementsValidator: { type: 'object', propertyValidators: { id: { type: 'string', immutable: true }, content: { type: 'string' } } } } } }, objectNestedInHashtableDoc: { typeFilter: simpleTypeFilter, channels: { write: 'write' }, propertyValidators: { hash: { type: 'hashtable', hashtableValuesValidator: { type: 'object', propertyValidators: { id: { type: 'string', immutable: true }, content: { type: 'string' } } } } } }, objectNestedInObjectDoc: { typeFilter: simpleTypeFilter, channels: { write: 'write' }, propertyValidators: { object: { type: 'object', propertyValidators: { value: { type: 'object', propertyValidators: { id: { type: 'string', immutable: true }, content: { type: 'string' } } } } } } }, hashtableNestedInArrayDoc: { typeFilter: simpleTypeFilter, channels: { write: 'write' }, propertyValidators: { elementList: { type: 'array', arrayElementsValidator: { type: 'hashtable', hashtableValuesValidator: { type: 'integer', immutable: true } } } } }, hashtableNestedInObjectDoc: { typeFilter: simpleTypeFilter, channels: { write: 'write' }, propertyValidators: { object: { type: 'object', propertyValidators: { hash: { type: 'hashtable', hashtableValuesValidator: { type: 'integer', immutable: true } } } } } }, hashtableNestedInHashtableDoc: { typeFilter: simpleTypeFilter, channels: { write: 'write' }, propertyValidators: { hash: { type: 'hashtable', hashtableValuesValidator: { type: 'hashtable', hashtableValuesValidator: { type: 'integer', immutable: true } } } } } }
import React, {Component, PropTypes} from 'react'; import {connect} from 'react-redux'; import {Link} from 'react-router'; import {login} from '../../actions/account'; import './login.css'; class Login extends Component { constructor(props) { super(props); this.state = { username: '', password: '' }; this.handleCredentialsChange = this.handleCredentialsChange.bind(this); this.handleLogin = this.handleLogin.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.loggedIn && this.props.loggingIn) { try { const redirect = this.props.location.query.redirect; this.context.router.replace(redirect); } catch (e) { this.context.router.replace('/'); } } } handleLogin(event) { event.preventDefault(); const {username, password} = this.state; this.props.dispatch(login(username, password)); } handleCredentialsChange(event) { this.setState({ [event.target.name]: event.target.value }); } render() { const {username, password} = this.state; const {error} = this.props; return ( <div className="container"> <div className="row"> <div className="col-md-4" style={{ float: 'none', margin: '0 auto' }}> <div className="login-wrapper"> { error && <div className="alert alert-danger"> {error.message}. </div> } <div className="card"> <div className="card-header">Login</div> <form className="card-block" onChange={this.handleCredentialsChange} onSubmit={this.handleLogin}> <div className="input-group"> <span className="input-group-addon"> <i className="fa fa-user"/> </span> <input type="text" value={username} className="form-control" placeholder="username" name="username" autoFocus required/> </div> <div className="input-group"> <span className="input-group-addon"> <i className="fa fa-lock"/> </span> <input type="password" value={password} className="form-control" placeholder="password" name="password" required/> </div> <button type="submit" className="btn btn-primary btn-block"> Login </button> <hr/> <small> Don't have an account? <Link to={'/register'}>Register</Link> </small> </form> </div> </div> </div> </div> </div> ); } } Login.contextTypes = { router: PropTypes.object.isRequired, store: PropTypes.object.isRequired }; Login.propTypes = { error: PropTypes.object, dispatch: PropTypes.func.isRequired, location: PropTypes.object }; function mapStateToProps(state) { const {login} = state; if (login) { return {loggedIn: login.loggedIn, error: login.error, loggingIn: login.loggingIn}; } return {loggedIn: false}; } export default connect(mapStateToProps)(Login);
let ActionType = require('./action-type'); module.exports = { ActionType: ActionType.default };
// Define module using Universal Module Definition pattern // https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // Support AMD. Register as an anonymous module. define([], factory); } else if (typeof exports === 'object') { // Node/CommonJS module.exports = factory(); } else { // No AMD. Set module as a global variable root.gridmapLayoutUsa = factory(); } }(this, function () { return [ { "x": 1, "y": 0, "key": "AK", "name": "Alaska" }, { "x": 12, "y": 0, "key": "ME", "name": "Maine" }, { "x": 11, "y": 1, "key": "VT", "name": "Vermont" }, { "x": 12, "y": 1, "key": "NH", "name": "New Hampshire" }, { "x": 4, "y": 2, "key": "ND", "name": "North Dakota" }, { "x": 5, "y": 2, "key": "MN", "name": "Minnesota" }, { "x": 9, "y": 2, "key": "NY", "name": "New York" }, { "x": 10, "y": 2, "key": "NJ", "name": "New Jersey" }, { "x": 11, "y": 2, "key": "MA", "name": "Massachusetts" }, { "x": 12, "y": 2, "key": "RI", "name": "Rhode Island" }, { "x": 1, "y": 3, "key": "WA", "name": "Washington" }, { "x": 2, "y": 3, "key": "ID", "name": "Idaho" }, { "x": 3, "y": 3, "key": "MT", "name": "Montana" }, { "x": 4, "y": 3, "key": "SD", "name": "South Dakota" }, { "x": 5, "y": 3, "key": "IA", "name": "Iowa" }, { "x": 6, "y": 3, "key": "WI", "name": "Wisconsin" }, { "x": 7, "y": 3, "key": "MI", "name": "Michigan" }, { "x": 9, "y": 3, "key": "PA", "name": "Pennsylvania" }, { "x": 10, "y": 3, "key": "DE", "name": "Delaware" }, { "x": 11, "y": 3, "key": "CT", "name": "Connecticut" }, { "x": 1, "y": 4, "key": "OR", "name": "Oregon" }, { "x": 2, "y": 4, "key": "NV", "name": "Nevada" }, { "x": 3, "y": 4, "key": "WY", "name": "Wyoming" }, { "x": 4, "y": 4, "key": "NE", "name": "Nebraska" }, { "x": 5, "y": 4, "key": "MO", "name": "Missouri" }, { "x": 6, "y": 4, "key": "IL", "name": "Illinois" }, { "x": 7, "y": 4, "key": "IN", "name": "Indiana" }, { "x": 8, "y": 4, "key": "OH", "name": "Ohio" }, { "x": 9, "y": 4, "key": "VA", "name": "Virginia" }, { "x": 10, "y": 4, "key": "DC", "name": "District of Columbia" }, { "x": 11, "y": 4, "key": "MD", "name": "Maryland" }, { "x": 1, "y": 5, "key": "CA", "name": "California" }, { "x": 2, "y": 5, "key": "UT", "name": "Utah" }, { "x": 3, "y": 5, "key": "CO", "name": "Colorado" }, { "x": 4, "y": 5, "key": "KS", "name": "Kansas" }, { "x": 5, "y": 5, "key": "AR", "name": "Arkansas" }, { "x": 6, "y": 5, "key": "TN", "name": "Tennessee" }, { "x": 7, "y": 5, "key": "KY", "name": "Kentucky" }, { "x": 8, "y": 5, "key": "WV", "name": "West Virginia" }, { "x": 9, "y": 5, "key": "NC", "name": "North Carolina" }, { "x": 2, "y": 6, "key": "AZ", "name": "Arizona" }, { "x": 3, "y": 6, "key": "NM", "name": "New Mexico" }, { "x": 4, "y": 6, "key": "OK", "name": "Oklahoma" }, { "x": 5, "y": 6, "key": "LA", "name": "Louisiana" }, { "x": 6, "y": 6, "key": "MS", "name": "Mississippi" }, { "x": 7, "y": 6, "key": "AL", "name": "Alabama" }, { "x": 8, "y": 6, "key": "GA", "name": "Georgia" }, { "x": 9, "y": 6, "key": "SC", "name": "South Carolina" }, { "x": 0, "y": 7, "key": "HI", "name": "Hawaii" }, { "x": 4, "y": 7, "key": "TX", "name": "Texas" }, { "x": 8, "y": 7, "key": "FL", "name": "Florida" } ]; }));
import 'antd-mobile/lib/nav-bar/style/css';
export default { forward: 'Encaminhar', cancel: 'Cancelar', customNumber: 'Número personalizado' }; // @key: @#@"forward"@#@ @source: @#@"Forward"@#@ // @key: @#@"cancel"@#@ @source: @#@"Cancel"@#@ // @key: @#@"customNumber"@#@ @source: @#@"Custom number"@#@
// VIEW IS ... // any html or plain text content // or if src= // an optional <loading> element // and/or an optional <error> element 'use strict'; // STUBS ... var selectAll = selectAll || function() {}; var toArray = toArray || function() {}; // MAIN ... var registerViewElements = function (root) { var views = toArray(selectAll(root, 'view')); for (var view, html, as, src, i = 0; i < views.length; i ++) { view = views[i]; as = view.as; src = view.src; if (!as) { throw new Error('<view> elements must have an as="alias" attribute defined at', view ); } if (src) { } else { // parse by type ... see data html = view.innerHTML; // validate here or at registerViewHTML registerViewHTML(as, html); } } }; var _viewHTML = (function () { var _html = {}; // var validKey = function (key) { // var valid = typeof key === 'string'; // // if (!valid) throw new Error('') // return valid; // }; // var validVal = function (val) { // var valid = typeof val === 'string'; // // if (!valid) throw new Error(''); // return valid; // }; return { set: function (key, val) { // validate here ... _html[key] = val; return this.has(key); }, get: function (key) { return _html[key]; }, has: function (key) { return key in _html; }, del: function (key) { delete _html[key]; return !this.has(key); } }; })(); var viewHTML = {}; function registerViewHTML (name, html) { // transform name to lower case _viewHTML.set (name, html); Object.defineProperty(viewHTML, name, { get: function () { return _viewHTML.get(name); }, set: function (value) { _viewHTML.set(name, value); console.log(`do update elements bound to ${name} here`); } }); } var activeView = function (node) { // viewHist store, next, prev, last, swap/toggle node._activeView = []; node._viewIndex = 0; node.activeView = { store: function (view) { // push node._activeView.push(view); return node.activeView.last(); }, next: function () { node._viewIndex = node._viewIndex + 1 < node._viewIndex.length ? node._viewIndex + 1 : node._viewIndex.length - 1; return node._activeView[node._viewIndex]; }, prev: function () { node._viewIndex = node._viewIndex ? node._viewIndex - 1 : 0; return node._activeView[node._viewIndex]; }, first: function () { node._viewIndex = 0; return node._activeView[node._viewIndex]; }, last: function () { node._viewIndex = node.activeView.length - 1; return node._activeView[node._viewIndex]; } }; }; var registerView = function (node, html) { // register specific states 'original|base', 'dataset', 'view', 'test' if (!node.activeView) { activeView(node); } if (!html) { html = node.outerHTML; } node.activeView.store(html); };
Ember.Handlebars.registerBoundHelper('date', function(date) { if(arguments.length == 1) { date = new Date(); } return moment(date).format('MMMM Do YYYY, h:mm a'); }); Ember.Handlebars.registerBoundHelper('date_ago', function(date) { return moment(date).fromNow(); }); Ember.Handlebars.registerBoundHelper('seconds_ago', function(seconds) { if(!seconds || seconds < 0) { return ""; } else if(seconds < 60) { return i18n.t('seconds_ago', "second", {hash: {count: seconds}}); } else if(seconds < 3600) { var minutes = Math.round(seconds / 60 * 10) / 10; return i18n.t('minutes_ago', "minute", {hash: {count: minutes}}); } else { var hours = Math.round(seconds / 3600 * 10) / 10; return i18n.t('hours_ago', "hour", {hash: {count: hours}}); } }); Ember.Handlebars.registerBoundHelper('round', function(number) { return Math.round(number * 100) / 100; }); Ember.Handlebars.registerBoundHelper('t', function(str, options) { return new Ember.Handlebars.SafeString(i18n.t(options.key, str, options)); }); Ember.Handlebars.registerBoundHelper('count', function(str, options) { if(str == 1 && options.hash && options.hash.singular) { return new Ember.Handlebars.SafeString(i18n.t(options.hash.key, str + " " + options.hash.singular)); } else if(str != 1 && options.hash && options.hash.plural) { return new Ember.Handlebars.SafeString(i18n.t(options.hash.key + '_plural', str + " " + options.hash.plural)); } else { return new Ember.Handlebars.SafeString(str); } }); Ember.Handlebars.registerBoundHelper('size', function(str, options) { var i = -1; var fileSizeInBytes = parseFloat(str) var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB']; do { fileSizeInBytes = fileSizeInBytes / 1024; i++; } while (fileSizeInBytes > 1024); return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i]; }); var i18n = Ember.Object.extend({ init: function() { this._super(); for(var idx in this.substitutions) { var replaces = {}; for(var jdx in this.substitutions[idx]) { for(var kdx in this.substitutions[idx][jdx]) { replaces[kdx] = jdx; } } this.substitutions[idx].replacements = replaces; } }, t: function(key, str, options) { var terms = str.match(/%{(\w+)}/); for(var idx = 0; terms && idx < terms.length; idx+= 2) { var word = terms[idx + 1]; if(options[word]) { var value = options[word]; str = str.replace(terms[idx], value); } else if(options.hash && options.hash[word]) { var value = options.hash[word]; if(options.hashTypes[word] == 'ID') { value = Ember.get(options.hashContexts[word], options.hash[word].toString()); value = value || options.hash[word]; } str = str.replace(terms[idx], value); } } return str; } }).create();
Mind.fn.Canvas.fn.extend({ line : function(points, style) { style = style || {}; style.width = style.width || 2, style.color = style.color || '#000'; this.context.strokeStyle = style.color; this.context.lineWidth = style.width; this.context.beginPath(); if (!$.isArray(points[0])) {//说明是点集合 points = [points]; } for (var i = 0; i < points.length; i++) { var p = points[i]; this.context.moveTo(p[0], p[1]); this.context.lineTo(p[2], p[3]); } this.context.closePath(); this.context.stroke(); }, rect : function(x1, y1, x2, y2, style) { style = style || {}; style.width = style.width || 2, style.color = style.color || '#000',style.fillcolor = style.fillcolor|| '#666'; var ctx = this.context; ctx.fillStyle = style.fillcolor; ctx.strokeStyle = style.color; ctx.lineWidth = style.width; console.log(style.width); if (style.shadowWidth) { ctx.shadowBlur = style.shadowWidth; ctx.shadowColor = style.shadowColor || "#000"; ctx.shadowOffsetX = style.shadowX || 5; ctx.shadowOffsetY = style.shadowY || 5; } if (style.r) { ctx.beginPath(); ctx.moveTo(x1 + style.r, y1); ctx.lineTo(x2 - style.r, y1); ctx.arc(x2 - style.r, y1 + style.r, style.r, 3 * Math.PI / 2, 2 * Math.PI, false); ctx.lineTo(x2, y2 - style.r); ctx.arc(x2 - style.r, y2 - style.r, style.r, 0, Math.PI / 2, false); ctx.lineTo(x1 + style.r, y2); ctx.arc(x1 + style.r, y2 - style.r, style.r, Math.PI / 2, Math.PI, false); ctx.lineTo(x1, y1 + style.r); ctx.arc(x1 + style.r, y1 + style.r, style.r, Math.PI, 3 * Math.PI / 2, false); ctx.closePath(); if (style.fillcolor) { ctx.fill(); } ctx.stroke(); } else { if (style.fillcolor) { ctx.fillRect(x1, y1, Math.abs(x2 - x1), Math.abs(y2 - y1)); // 画出矩形并使用颜色填充矩形区域 } ctx.strokeRect(x1, y1, Math.abs(x2 - x1), Math.abs(y2 - y1)); // 只勾画出矩形的外框 } }, arc : function(x, y, r, startDegree, endDegree, style) { style = style || {}; style.width = style.width || 0, style.color = style.color || '#000',style.fillcolor = style.fillcolor|| '#666'; var ctx = this.context; if(style.fillcolor){ ctx.fillStyle = style.fillcolor; } ctx.strokeStyle = style.color; ctx.lineWidth = style.width; if (style.shadowWidth) { ctx.shadowBlur = style.shadowWidth; ctx.shadowColor = style.shadowColor || "#000"; ctx.shadowOffsetX = style.shadowX || 5; ctx.shadowOffsetY = style.shadowY || 5; } var sarc = startDegree * (Math.PI / 180); var earc = endDegree * (Math.PI / 180); ctx.beginPath(); ctx.arc(x, y, r, sarc, earc); // 从 -1/4π 到 3/4π, 以 (230, 90) 为圆心, 半径 60px 画圆. ctx.closePath(); ctx.fill(); ctx.stroke(); }, polygon : function(points, style) { style = style || {}; style.width = style.width || 2, style.color = style.color || '#000',style.fillcolor = style.fillcolor|| '#666'; var ctx = this.context; ctx.fillStyle = style.fillcolor; ctx.strokeStyle = style.color; ctx.lineWidth = style.width; if (style.shadowWidth) { ctx.shadowBlur = style.shadowWidth; ctx.shadowColor = style.shadowColor || "#000"; ctx.shadowOffsetX = style.shadowX || 5; ctx.shadowOffsetY = style.shadowY || 5; } ctx.beginPath(); if ($.isArray(points[0]) && points.length > 2) {//说明是点集合 ctx.moveTo(points[0][0], points[0][1]); for (var i = 1; i < points.length; i++) { var p = points[i]; ctx.lineTo(p[0], p[1]); } } ctx.closePath(); ctx.fill(); ctx.stroke(); }, text : function(x, y, text,style) { if (style.shadowWidth) { ctx.shadowBlur = style.shadowWidth; ctx.shadowColor = style.shadowColor || "#000"; ctx.shadowOffsetX = style.shadowX || 5; ctx.shadowOffsetY = style.shadowY || 5; } style.size = style.size || 24; style.font = style.font || 'Georgia'; this.context.fillStyle = style.fillcolor || '#000'; this.context.font = style.size + "px "+ style.font; this.context.fillText(text, x, y); }, });
var datasource = exports; var juggler = require('jugglingdb'); var all = require('./datasource/all'), checkUniqueKey = require('./datasource/checkUniqueKey'), create = require('./datasource/create'), destroy = require('./datasource/destroy'), findOne = require('./datasource/findOne'), find = require('./datasource/find'), get = require('./datasource/get'), set = require('./datasource/set'), update = require('./datasource/update'), updateOrCreate = require('./datasource/updateOrCreate'); // // Persists resource to datasource using JugglingDB // datasource.persist = function persist (r, options) { options = options || { "type": "memory" }; if (typeof options === "string") { options = { type: options }; } var Schema = juggler.Schema, path = require('path'); // // Create new juggler schema, based on incoming datasource type // var _type = mappings[options.type] || options.type || 'memory'; // add datasource persistence methods to resource all(r); create(r); destroy(r); find(r); findOne(r); get(r); set(r); update(r); updateOrCreate(r); // TODO: better support for configuration of additional JugglingDB adapters besides CouchDB / Nano options.database = options.database || "resource"; options.host = options.host || "localhost"; options.port = options.port || 5984; // new custom bindings for couchdb, moving away from JugglingDB if (_type === "couch2") { options.url = options.host +':' + options.port; if (options.ssl) { options.url = 'https://' + options.url; } else { options.url = 'http://' + options.url; } var couch = require('./couch')({ url: options.url, username: options.username, password: options.password, db: options.database, model: r.name, resource: r }); r.database = options.database; r.model = couch; } else { var schema = new Schema(_type, options); // // Create empty schema object for mapping between resource and JugglingDB // var _schema = {}; // // For every property in the resource schema, map the property to JugglingDB // Object.keys(r.schema.properties).forEach(function(p){ var prop = r.schema.properties[p]; _schema[p] = { type: jugglingType(prop) }; if (prop.index) { _schema[p].index = true; } }); function jugglingType(prop) { var typeMap = { 'string': String, 'number': Number, 'integer': Number, 'array': Array, 'boolean': Boolean, 'object': Object, 'null': null, 'any': String }; var type = typeMap[prop.type] || String; if(Array.isArray(prop)) { type = Array; } return type; } // // Create a new JugglingDB schema based on temp schema // var Model = schema.define(r.name, _schema); // assign model to resource r.model = Model; r._schema = schema; // before the model is saved ( create / update, updateOrCreate / save ), check for unique keys r.model.beforeSave = function(next, data){ checkUniqueKey(r, data, next); }; } } var mappings = { "couchdb": "nano", "couch": "nano" };
var searchData= [ ['mycashflow',['MyCashFlow',['../namespaceMyCashFlow.html',1,'']]], ['myoption',['MyOption',['../namespaceMyOption.html',1,'']]], ['mytrinomialtree',['MyTrinomialTree',['../namespaceMyTrinomialTree.html',1,'']]] ];
'use strict'; /** * Unit tests for packagers/yarn */ const BbPromise = require('bluebird'); const chai = require('chai'); const sinon = require('sinon'); const Utils = require('../../lib/utils'); chai.use(require('chai-as-promised')); chai.use(require('sinon-chai')); const expect = chai.expect; describe('yarn', () => { let sandbox; let yarnModule; before(() => { sandbox = sinon.createSandbox(); sandbox.usingPromise(BbPromise.Promise); sandbox.stub(Utils, 'spawnProcess'); yarnModule = require('../../lib/packagers/yarn'); }); after(() => { sandbox.restore(); }); afterEach(() => { sandbox.reset(); }); it('should return "yarn.lock" as lockfile name', () => { expect(yarnModule.lockfileName).to.equal('yarn.lock'); }); it('should return packager sections', () => { expect(yarnModule.copyPackageSectionNames).to.deep.equal(['resolutions']); }); it('does not require to copy modules', () => { expect(yarnModule.mustCopyModules).to.be.false; }); describe('getProdDependencies', () => { it('should use yarn list', () => { Utils.spawnProcess.returns(BbPromise.resolve({ stdout: '{}', stderr: '' })); return expect(yarnModule.getProdDependencies('myPath', 1)).to.be.fulfilled.then(result => { expect(result).to.be.an('object'); expect(Utils.spawnProcess).to.have.been.calledOnce; expect(Utils.spawnProcess.firstCall).to.have.been.calledWith( sinon.match(/^yarn/), ['list', '--depth=1', '--json', '--production'], { cwd: 'myPath' } ); return null; }); }); it('should transform yarn trees to npm dependencies', () => { const testYarnResult = '{"type":"activityStart","data":{"id":0}}\n' + '{"type":"activityTick","data":{"id":0,"name":"bestzip@^2.1.5"}}\n' + '{"type":"activityTick","data":{"id":0,"name":"bluebird@^3.5.1"}}\n' + '{"type":"activityTick","data":{"id":0,"name":"fs-extra@^4.0.3"}}\n' + '{"type":"activityTick","data":{"id":0,"name":"mkdirp@^0.5.1"}}\n' + '{"type":"activityTick","data":{"id":0,"name":"minimist@^0.0.8"}}\n' + '{"type":"activityTick","data":{"id":0,"name":"@sls/webpack@^1.0.0"}}\n' + '{"type":"tree","data":{"type":"list","trees":[' + '{"name":"bestzip@2.1.5","children":[],"hint":null,"color":"bold",' + '"depth":0},{"name":"bluebird@3.5.1","children":[],"hint":null,"color":' + '"bold","depth":0},{"name":"fs-extra@4.0.3","children":[],"hint":null,' + '"color":"bold","depth":0},{"name":"mkdirp@0.5.1","children":[{"name":' + '"minimist@0.0.8","children":[],"hint":null,"color":"bold","depth":0}],' + '"hint":null,"color":null,"depth":0},{"name":"@sls/webpack@1.0.0",' + '"children":[],"hint":null,"color":"bold","depth":0}]}}\n'; const expectedResult = { problems: [], dependencies: { bestzip: { version: '2.1.5', dependencies: {} }, bluebird: { version: '3.5.1', dependencies: {} }, 'fs-extra': { version: '4.0.3', dependencies: {} }, mkdirp: { version: '0.5.1', dependencies: { minimist: { version: '0.0.8', dependencies: {} } } }, '@sls/webpack': { version: '1.0.0', dependencies: {} } } }; Utils.spawnProcess.returns(BbPromise.resolve({ stdout: testYarnResult, stderr: '' })); return expect(yarnModule.getProdDependencies('myPath', 1)).to.be.fulfilled.then(result => { expect(result).to.deep.equal(expectedResult); return null; }); }); it('should reject on critical yarn errors', () => { Utils.spawnProcess.returns( BbPromise.reject(new Utils.SpawnError('Exited with code 1', '', 'Yarn failed.\nerror Could not find module.')) ); return expect(yarnModule.getProdDependencies('myPath', 1)).to.be.rejectedWith('Exited with code 1'); }); }); describe('rebaseLockfile', () => { it('should return the original lockfile', () => { const testContent = 'eugfogfoigqwoeifgoqwhhacvaisvciuviwefvc'; const testContent2 = 'eugfogfoigqwoeifgoqwhhacvaisvciuviwefvc'; expect(yarnModule.rebaseLockfile('.', testContent)).to.equal(testContent2); }); it('should rebase file references', () => { const testContent = ` acorn@^2.1.0, acorn@^2.4.0: version "2.7.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-2.7.0.tgz#ab6e7d9d886aaca8b085bc3312b79a198433f0e7" acorn@^3.0.4: version "3.3.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" otherModule@file:../../otherModule/the-new-version: version "1.2.0" acorn@^2.1.0, acorn@^2.4.0: version "2.7.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-2.7.0.tgz#ab6e7d9d886aaca8b085bc3312b79a198433f0e7" "@myCompany/myModule@../../myModule/the-new-version": version "6.1.0" dependencies: aws-xray-sdk "^1.1.6" aws4 "^1.6.0" base-x "^3.0.3" bluebird "^3.5.1" chalk "^1.1.3" cls-bluebird "^2.1.0" continuation-local-storage "^3.2.1" lodash "^4.17.4" moment "^2.20.0" redis "^2.8.0" request "^2.83.0" ulid "^0.1.0" uuid "^3.1.0" acorn@^5.0.0, acorn@^5.5.0: version "5.5.3" resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.5.3.tgz#f473dd47e0277a08e28e9bec5aeeb04751f0b8c9" `; const expectedContent = ` acorn@^2.1.0, acorn@^2.4.0: version "2.7.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-2.7.0.tgz#ab6e7d9d886aaca8b085bc3312b79a198433f0e7" acorn@^3.0.4: version "3.3.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" otherModule@file:../../project/../../otherModule/the-new-version: version "1.2.0" acorn@^2.1.0, acorn@^2.4.0: version "2.7.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-2.7.0.tgz#ab6e7d9d886aaca8b085bc3312b79a198433f0e7" "@myCompany/myModule@../../project/../../myModule/the-new-version": version "6.1.0" dependencies: aws-xray-sdk "^1.1.6" aws4 "^1.6.0" base-x "^3.0.3" bluebird "^3.5.1" chalk "^1.1.3" cls-bluebird "^2.1.0" continuation-local-storage "^3.2.1" lodash "^4.17.4" moment "^2.20.0" redis "^2.8.0" request "^2.83.0" ulid "^0.1.0" uuid "^3.1.0" acorn@^5.0.0, acorn@^5.5.0: version "5.5.3" resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.5.3.tgz#f473dd47e0277a08e28e9bec5aeeb04751f0b8c9" `; expect(yarnModule.rebaseLockfile('../../project', testContent)).to.equal(expectedContent); }); }); describe('install', () => { it('should use yarn install', () => { Utils.spawnProcess.returns(BbPromise.resolve({ stdout: 'installed successfully', stderr: '' })); return expect(yarnModule.install('myPath', {})).to.be.fulfilled.then(result => { expect(result).to.be.undefined; expect(Utils.spawnProcess).to.have.been.calledOnce; expect(Utils.spawnProcess).to.have.been.calledWithExactly( sinon.match(/^yarn/), ['install', '--non-interactive', '--frozen-lockfile'], { cwd: 'myPath' } ); return null; }); }); it('should use ignoreScripts option', () => { Utils.spawnProcess.returns(BbPromise.resolve({ stdout: 'installed successfully', stderr: '' })); return expect(yarnModule.install('myPath', { ignoreScripts: true })).to.be.fulfilled.then(result => { expect(result).to.be.undefined; expect(Utils.spawnProcess).to.have.been.calledOnce; expect(Utils.spawnProcess).to.have.been.calledWithExactly( sinon.match(/^yarn/), ['install', '--non-interactive', '--frozen-lockfile', '--ignore-scripts'], { cwd: 'myPath' } ); return null; }); }); it('should use noFrozenLockfile option', () => { Utils.spawnProcess.returns(BbPromise.resolve({ stdout: 'installed successfully', stderr: '' })); return expect(yarnModule.install('myPath', { noFrozenLockfile: true })).to.be.fulfilled.then(result => { expect(result).to.be.undefined; expect(Utils.spawnProcess).to.have.been.calledOnce; expect(Utils.spawnProcess).to.have.been.calledWithExactly( sinon.match(/^yarn/), ['install', '--non-interactive'], { cwd: 'myPath' } ); return null; }); }); it('should use networkConcurrency option', () => { Utils.spawnProcess.returns(BbPromise.resolve({ stdout: 'installed successfully', stderr: '' })); return expect(yarnModule.install('myPath', { networkConcurrency: 1 })).to.be.fulfilled.then(result => { expect(result).to.be.undefined; expect(Utils.spawnProcess).to.have.been.calledOnce; expect(Utils.spawnProcess).to.have.been.calledWithExactly( sinon.match(/^yarn/), ['install', '--non-interactive', '--frozen-lockfile', '--network-concurrency 1'], { cwd: 'myPath' } ); return null; }); }); }); describe('noInstall', () => { it('should skip yarn install', () => { return expect(yarnModule.install('myPath', { noInstall: true })).to.be.fulfilled.then(result => { expect(result).to.be.undefined; return null; }); }); }); describe('prune', () => { let installStub; before(() => { installStub = sandbox.stub(yarnModule, 'install').returns(BbPromise.resolve()); }); after(() => { installStub.restore(); }); it('should call install', () => { return expect(yarnModule.prune('myPath', {})).to.be.fulfilled.then(() => { expect(installStub).to.have.been.calledOnce; expect(installStub).to.have.been.calledWithExactly('myPath', {}); return null; }); }); }); describe('runScripts', () => { it('should use yarn run for the given scripts', () => { Utils.spawnProcess.returns(BbPromise.resolve({ stdout: 'success', stderr: '' })); return expect(yarnModule.runScripts('myPath', ['s1', 's2'])).to.be.fulfilled.then(result => { expect(result).to.be.undefined; expect(Utils.spawnProcess).to.have.been.calledTwice; expect(Utils.spawnProcess.firstCall).to.have.been.calledWithExactly(sinon.match(/^yarn/), ['run', 's1'], { cwd: 'myPath' }); expect(Utils.spawnProcess.secondCall).to.have.been.calledWithExactly(sinon.match(/^yarn/), ['run', 's2'], { cwd: 'myPath' }); return null; }); }); }); });
/* eslint no-console: 0 */ const path = require('path'); const express = require('express'); const webpack = require('webpack'); const webpackMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const config = require('./webpack.config.js'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var srvsRoutes = require('./routes/test-services'); const isDeveloping = process.env.NODE_ENV !== 'production'; //const port = isDeveloping ? 3000 : process.env.PORT; const port = isDeveloping ? 3000 : 80; const app = express(); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); //source for public files app.use(express.static(path.join(__dirname, 'public'))); //app.use('/', routes); app.use('/srv', srvsRoutes); //app.use('/users', users); if (isDeveloping) { const compiler = webpack(config); const middleware = webpackMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: 'app', stats: { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false } }); app.use(middleware); app.use(webpackHotMiddleware(compiler)); app.get('*', function response(req, res) { res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html'))); res.end(); }); } else { app.use(express.static(__dirname + '/dist')); app.get('*', function response(req, res) { res.sendFile(path.join(__dirname, 'dist/index.html')); }); } app.listen(port, '0.0.0.0', function onStart(err) { if (err) { console.log(err); } console.info('==> 🌎 Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port); });
const async = require('async'); const crypto = require('crypto'); const nodemailer = require('nodemailer'); const passport = require('passport'); const User = require('../models/user'); /** * GET /login * Login page. */ exports.getLogin = (req, res) => { User.find({ admin: true }).limit(1).exec(function (err, users) { if (users.length === 0) { return res.redirect('/proxizy/signup?return_url=' + req.query.return_url); } res.render('account/login', { title: 'Login' }); }); }; /** * POST /login * Sign in using email and password. */ exports.postLogin = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/proxizy/login'); } passport.authenticate('local', (err, user, info) => { if (err) { return next(err); } if (!user) { req.flash('errors', info); return res.redirect('/proxizy/login'); } req.logIn(user, (err) => { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); res.redirect(req.session.returnTo || '/proxizy'); }); })(req, res, next); }; /** * GET /logout * Log out. */ exports.logout = (req, res) => { req.logout(); res.redirect('/proxizy'); }; /** * GET /signup * Signup page. */ exports.getSignup = (req, res) => { User.find({ admin: true }, function (err, users) { if (users.length > 0) { return res.redirect('/proxizy/login'); } if (req.user) { return res.redirect('/proxizy'); } res.render('account/signup', { title: 'Create Account' }); }); }; /** * POST /signup * Create a new local account. */ exports.postSignup = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/proxizy/signup'); } var user = { email: req.body.email, password: req.body.password, admin: true }; User.findOne({ email: req.body.email }, (err, existingUser) => { if (err) { return next(err); } if (existingUser) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/proxizy/signup'); } User.save(user, (err, userDb) => { if (err) { return next(err); } req.logIn(userDb, (err) => { if (err) { return next(err); } res.redirect('/proxizy/'); }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = (req, res) => { res.render('account/profile', { title: 'Account Management' }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; User.save(user, (err) => { if (err) { if (err.code === 11000) { req.flash('errors', { msg: 'The email address you have entered is already associated with an account.' }); return res.redirect('/account'); } return next(err); } req.flash('success', { msg: 'Profile information has been updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.password = req.body.password; user.save(user, (err) => { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = (req, res, next) => { User.remove({ _id: req.user.id }, (err) => { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = (req, res, next) => { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset' }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long.').len(4); req.assert('confirm', 'Passwords must match.').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } async.waterfall([ function resetPassword(done) { User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.passwordResetToken = undefined; user.passwordResetExpires = undefined; user.save((err) => { if (err) { return next(err); } req.logIn(user, (err) => { done(err, user); }); }); }); }, function sendResetPasswordEmail(user, done) { const transporter = nodemailer.createTransport({ service: 'SendGrid', auth: { user: process.env.SENDGRID_USER, pass: process.env.SENDGRID_PASSWORD } }); const mailOptions = { to: user.email, from: 'hackathon@starter.com', subject: 'Your Hackathon Starter password has been changed', text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n` }; transporter.sendMail(mailOptions, (err) => { req.flash('success', { msg: 'Success! Your password has been changed.' }); done(err); }); } ], (err) => { if (err) { return next(err); } res.redirect('/'); }); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = (req, res) => { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } async.waterfall([ function createRandomToken(done) { crypto.randomBytes(16, (err, buf) => { const token = buf.toString('hex'); done(err, token); }); }, function setRandomToken(token, done) { User.findOne({ email: req.body.email }, (err, user) => { if (err) { return done(err); } if (!user) { req.flash('errors', { msg: 'Account with that email address does not exist.' }); return res.redirect('/forgot'); } user.passwordResetToken = token; user.passwordResetExpires = Date.now() + 3600000; // 1 hour user.save((err) => { done(err, token, user); }); }); }, function sendForgotPasswordEmail(token, user, done) { const transporter = nodemailer.createTransport({ service: 'SendGrid', auth: { user: process.env.SENDGRID_USER, pass: process.env.SENDGRID_PASSWORD } }); const mailOptions = { to: user.email, from: 'hackathon@starter.com', subject: 'Reset your password on Hackathon Starter', text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n Please click on the following link, or paste this into your browser to complete the process:\n\n http://${req.headers.host}/reset/${token}\n\n If you did not request this, please ignore this email and your password will remain unchanged.\n` }; transporter.sendMail(mailOptions, (err) => { req.flash('info', { msg: `An e-mail has been sent to ${user.email} with further instructions.` }); done(err); }); } ], (err) => { if (err) { return next(err); } res.redirect('/forgot'); }); };
angular.module('adExtreme') .controller('homeController', function ($scope, $rootScope, User) { $rootScope.loggedIn = false; $rootScope.currentUser = {}; });
var distance = require('turf-distance'); var point = require('turf-helpers').point; var bearing = require('turf-bearing'); var destination = require('turf-destination'); /** * Takes a {@link LineString|line} and returns a {@link Point|point} at a specified distance along the line. * * @name along * @category measurement * @param {Feature<LineString>} line input line * @param {Number} distance distance along the line * @param {String} [units=miles] can be degrees, radians, miles, or kilometers * @return {Feature<Point>} Point `distance` `units` along the line * @example * var line = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "LineString", * "coordinates": [ * [-77.031669, 38.878605], * [-77.029609, 38.881946], * [-77.020339, 38.884084], * [-77.025661, 38.885821], * [-77.021884, 38.889563], * [-77.019824, 38.892368] * ] * } * }; * * var along = turf.along(line, 1, 'miles'); * * var result = { * "type": "FeatureCollection", * "features": [line, along] * }; * * //=result */ module.exports = function (line, dist, units) { var coords; if (line.type === 'Feature') coords = line.geometry.coordinates; else if (line.type === 'LineString') coords = line.coordinates; else throw new Error('input must be a LineString Feature or Geometry'); var travelled = 0; for (var i = 0; i < coords.length; i++) { if (dist >= travelled && i === coords.length - 1) break; else if (travelled >= dist) { var overshot = dist - travelled; if (!overshot) return point(coords[i]); else { var direction = bearing(coords[i], coords[i - 1]) - 180; var interpolated = destination(coords[i], overshot, direction, units); return interpolated; } } else { travelled += distance(coords[i], coords[i + 1], units); } } return point(coords[coords.length - 1]); };
import THREE from 'three' import events from 'dom-events' const glslify = require('glslify') const noop = () => {} module.exports = function(app, cb) { cb = cb || noop const video = document.createElement('video') video.setAttribute('loop', true) video.setAttribute('muted', 'muted') addSource('video/mp4', 'assets/motion2.mp4') video.load() const texture = new THREE.Texture(video) texture.minFilter = THREE.LinearFilter texture.generateMipmaps = false const result = { video, texture } events.on(video, 'error', err => { cb(new Error(err)) cb = noop }) events.on(video, 'canplay', () => { texture.needsUpdate = true video.play() cb(null, result) cb = noop }) function addSource(type, path) { var source = document.createElement('source') source.src = path source.type = type return video.appendChild(source) } app.on('tick', () => { if (video.readyState !== video.HAVE_ENOUGH_DATA) return texture.needsUpdate = true }) const vert = glslify('./shaders/pass.vert') const frag = glslify('./shaders/debug.frag') const mat = new THREE.ShaderMaterial({ uniforms: { iChannel0: { type: 't', value: texture } }, vertexShader: vert, fragmentShader: frag, defines: { 'USE_MAP': '' } }) const geo = new THREE.BoxGeometry(1,1,1) const mesh = new THREE.Mesh(geo, mat) app.scene.add(mesh) return result }
const expect = require('expect') const handler = require('./handler') let lambdaResponse handler.hello(null, null, (body, response) => { lambdaResponse = JSON.parse(response.body).message }) expect(lambdaResponse).toEqual( 'Go Serverless v1.0! Your function executed successfully!' ) console.log('all tests passed successfully')
'use strict'; var _ = R; var get = _.curry(function(x, obj) { return obj[x]; }); /****************************************** C O M P O S I T I O N E X A M P L E ******************************************/ // Curried functions are easy to compose. // Using _.map, _.size, and _.split we can // make a function that returns the lengths // of the words in a string. var lengths = _.compose( _.map(_.size), _.split(' ') ); console.log(lengths('once upon a time')); /******************************************* Y O U R T U R N ********************************************/ var articles = [{ title: 'Everything Sucks', url: 'http://do.wn/sucks.html', author: { name: 'Debbie Downer', email: 'debbie@do.wn' } }, { title: 'If You Please', url: 'http://www.geocities.com/milq', author: { name: 'Caspar Milquetoast', email: 'hello@me.com' } }]; // -- Challenge 1 ------------------------- // Return a list of the author names in // articles using only get, _.compose, and // _.map. var names = _.map(_.compose(get('name'), get('author'))); assertEqualArrays( ['Debbie Downer', 'Caspar Milquetoast'], names(articles) ); // -- Challenge 2 ------------------------- // Make a boolean function that says whether // a given person wrote any of the articles. // Use the names function you wrote above // with _.compose and _.contains. var isAuthor = function(name, articles){ return _.compose(_.contains(name), names)(articles); }; assertEqual( false, isAuthor('New Guy', articles) ); assertEqual( true, isAuthor('Debbie Downer', articles) ); // -- Challenge 3 ------------------------- // There is more to point-free programming // than compose! Let's build ourselves // another function that combines functions // to let us write code without glue variables. var fork = _.curry(function(lastly, f, g, x) { return lastly(f(x), g(x)); }); // As you can see, the fork function is a // pipeline like compose, except it duplicates // its value, sends it to two functions, then // sends the results to a combining function. // // Your challenge: implement a function to // compute the average values in a list using // only fork, _.divide, _.sum, and _.size. var avg = fork(_.divide, _.sum, _.size); // change this assertEqual(3, avg([1, 2, 3, 4, 5])); console.log("All tests pass."); /****************************************** B A C K G R O U N D C O D E *******************************************/ function assertEqualArrays(x, y) { if (x.length !== y.length) throw ("expected " + x + " to equal " + y); for (var i in x) { if (x[i] !== y[i]) { throw ("expected " + x + " to equal " + y); } } } function assertEqual(x, y) { if (x !== y) throw ("expected " + x + " to equal " + y); }
export default class DeleteController { constructor($scope, $window, $state, $q, $translate, WriteQueries, Configuration, notification, params, view, entry) { this.$scope = $scope; this.$window = $window; this.$state = $state; this.$translate = $translate; this.WriteQueries = WriteQueries; this.config = Configuration(); this.entityLabel = params.entity; this.entityId = params.id; this.view = view; this.title = view.title(); this.description = view.description(); this.actions = view.actions(); this.entity = view.getEntity(); this.notification = notification; this.$scope.entry = entry; this.$scope.view = view; $scope.$on('$destroy', this.destroy.bind(this)); this.previousStateParametersDeferred = $q.defer(); $scope.$on('$stateChangeSuccess', (event, to, toParams, from, fromParams) => { this.previousStateParametersDeferred.resolve(fromParams); }); } deleteOne() { const entityName = this.entity.name(); const { $translate, notification } = this; return this.WriteQueries.deleteOne(this.view, this.entityId) .then(() => this.previousStateParametersDeferred.promise) .then(previousStateParameters => { // if previous page was related to deleted entity, redirect to list if (previousStateParameters.entity === entityName && previousStateParameters.id === this.entityId) { this.$state.go(this.$state.get('list'), angular.extend({ entity: entityName }, this.$state.params)); } else { this.back(); } $translate('DELETE_SUCCESS').then(text => notification.log(text, { addnCls: 'humane-flatty-success' })); }) .catch(error => { const errorMessage = this.config.getErrorMessageFor(this.view, error) | 'ERROR_MESSAGE'; $translate(errorMessage, { status: error && error.status, details: error && error.data && typeof error.data === 'object' ? JSON.stringify(error.data) : {} }).then(text => notification.log(text, { addnCls: 'humane-flatty-error' })); }); } back() { this.$window.history.back(); } destroy() { this.$scope = undefined; this.$window = undefined; this.$state = undefined; this.$translate = undefined; this.WriteQueries = undefined; this.view = undefined; this.entity = undefined; } } DeleteController.$inject = ['$scope', '$window', '$state', '$q', '$translate', 'WriteQueries', 'NgAdminConfiguration', 'notification', 'params', 'view', 'entry'];
"use strict"; /** * Module dependencies. */ const mongoose = require('mongoose'); const Schema = mongoose.Schema; var OrderSchema = new Schema({ id: {type: Number}, user_id: {type: Number}, type: {type: String, default: 'normal'}, status: {type: Number, default: 0}, status_list: {type: Array, default: []}, price_total: {type: Number, default: 0}, created: {type: Date, default: Date.now}, updated: {type: Date, default: Date.now}, address_id: {type: Number, required: true}, discount_id: {type: Number, required: true} }); OrderSchema.methods = { /** * Schema Methods * * @param {String} * * @return {Boolean} * @api public */ } mongoose.model('Order', OrderSchema)
/* eslint standard/no-callback-literal: 0 */ import Vott from 'vott' import express from 'express' import bodyParser from 'body-parser' import request from 'request-promise-native' export class MessengerBot extends Vott { constructor (config) { super(config) this.platform = 'Messenger' this.config.endpoint = '/facebook/receive' this.config.port = 8080 this.config = Object.assign(this.config, config) } send (event) { const payload = { recipient: { id: event.user.id } } if (event.messaging_type) { payload.messaging_type = event.messaging_type } else { payload.messaging_type = !event.tag ? 'RESPONSE' : 'MESSAGE_TAG' } if (event.tag) { payload.tag = event.tag } if (event.sender_action) { payload.sender_action = event.sender_action } else { payload.message = event.message } if (event.notification_type) { payload.notification_type = event.notification_type } if (!event.user.id && event.user.phone_number) { payload.recipient.phone_number = event.user.phone_number } this.getAccessToken(event.user.page_id, (token) => { if (token) { payload.access_token = token this.outbound(payload, (bot, message) => { const options = { method: 'POST', uri: this.config.api_url || 'https://graph.facebook.com/v2.6/me/messages', body: message, json: true } request(options).then((response) => { this.emit('message_sent', { response, message }) }).catch((error) => { this.emit('error', error) }) }) } else { this.emit('error', { message: 'Token not found.' }) } }) } /** sends typing_on sender action */ typingOn (event) { this.send({ user: event.user, sender_action: 'typing_on' }) } /** sends typing_off sender action */ typingOff (event) { this.send({ user: event.user, sender_action: 'typing_off' }) } /** routes received messages */ receive (event) { this.inbound(event, (bot, event) => { if (event.message) { if (event.message.is_echo) { this.dispatch('message_echo', event) } else { event.chat_enabled = true this.dispatch('message_received', event) } } else if (event.delivery) { this.dispatch('message_delivered', event) } else if (event.read) { this.dispatch('message_read', event) } else if (event.postback) { event.message = { text: event.postback.payload } event.chat_enabled = true this.dispatch('postback_received', event) } else if (event.optin) { this.dispatch('optin', event) } else if (event.referral) { this.dispatch('referral', event) } else if (event.payment) { event.chat_enabled = true event.message = event.payment this.dispatch('payment', event) } else if (event.pre_checkout) { this.dispatch('pre_checkout', event) } else if (event.checkout_update) { event.chat_enabled = true event.message = event.checkout_update this.dispatch('checkout_update', event) } else if (event.account_linking) { this.dispatch('account_linking', event) } else { this.dispatch('unhandled_event', event) } }) } /** gets access token for a given page_id */ getAccessToken (id, callback) { if (this.config.access_token) { if (typeof this.config.access_token === 'string') { callback(this.config.access_token) } else if (this.config.access_token[id]) { callback(this.config.access_token[id]) } else { callback(false) } } else { callback(false) } } /** sets up an express server */ setupServer (port = this.config.port, callback) { this.webserver = express() this.webserver.set('x-powered-by', false) this.webserver.use(bodyParser.json()) this.webserver.use(bodyParser.urlencoded({ extended: true })) this.webserver.listen(port, () => { this.emit('webserver_listening', this.webserver) if (callback) callback(null, this.webserver) }) return this } /** handles POST webhook */ _post (req, res) { if (req.body && req.body.entry) { req.body.entry.forEach((entry) => { if (entry.messaging) { entry.messaging.forEach((e) => { const isEcho = e.message && e.message.is_echo === true const event = { user: { id: isEcho ? e.recipient.id : e.sender.id, page_id: isEcho ? e.sender.id : e.recipient.id } } for (let key in e) { if (key !== 'sender' && key !== 'recipient') { event[key] = e[key] } } this.receive(event) }) } }) res.send('OK') } else { res.sendStatus(400) } } /** handles GET endpoint for verification */ _get (req, res) { const isSubscribeMode = req.query['hub.mode'] === 'subscribe' const sameToken = req.query['hub.verify_token'] === this.config.verify_token if (isSubscribeMode && sameToken) { res.send(req.query['hub.challenge']) } else { res.sendStatus(401) } } /** sets up webhooks */ setupWebhooks (webserver = this.webserver, endpoint = this.config.endpoint) { webserver.post(endpoint, this._post.bind(this)) webserver.get(endpoint, this._get.bind(this)) return this } useAsMiddleware () { const router = express.Router() this.setupWebhooks(router, '/') return router } } module.exports = MessengerBot
/** * Created by debayan on 7/24/16. */ Module.register("internet-monitor",{ defaults : { }, payload: [], downloadBarState: 'not_started', updating: false, start : function(){ console.log("Internet-monitor module started!"); this.sendSocketNotification('Start',this.config); // Schedule update timer. var self = this; if(this.config.updateInterval != 0) { setInterval(function() { self.updating= true; self.sendSocketNotification('Start',self.config); }, this.config.updateInterval); } }, getScripts: function(){ return [this.file('justgage-1.2.2/justgage.js'),this.file('justgage-1.2.2/raphael-2.1.4.min.js'),this.file('jquery.js')] }, getStyles: function(){ return ["internet-monitor.css"] }, addScript: function(mode){ var script = document.createElement('script'); if(this.config.type == 'minimal'){ script.innerHTML = 'var download, upload;' + 'download = new JustGage({' + 'id: "downloadSpeedGauge",' + 'value: ' + 0 + ',' + 'min: 0,' + 'max: ' + this.config.maxGaugeScale + ',' + 'title: "Download Speed",' + 'refreshAnimationType:"linear",' + 'gaugeWidthScale: "0.8",' + 'valueFontColor: "#fff",' + 'valueFontFamily: "Roboto Condensed",' + 'titleFontFamily: "Roboto Condensed",' + 'titleFontColor: "#aaa",' + 'hideMinMax: true,'+ 'gaugeColor: "#000",'+ 'levelColors: ["#fff"],'+ 'hideInnerShadow: true,'+ 'symbol: "Mbps"});' + 'upload = new JustGage({' + 'id: "uploadSpeedGauge",' + 'value: ' + 0 + ',' + 'min: 0,' + 'max: ' + this.config.maxGaugeScale + ',' + 'title: "Upload Speed",' + 'refreshAnimationType:"linear",' + 'gaugeWidthScale: "0.8",' + 'valueFontColor: "#fff",' + 'valueFontFamily: "Roboto Condensed",' + 'titleFontFamily: "Roboto Condensed",' + 'titleFontColor: "#aaa",' + 'hideMinMax: true,'+ 'gaugeColor: "#000",'+ 'levelColors: ["#fff"],'+ 'hideInnerShadow: true,'+ 'symbol: "Mbps"});'; } else{ script.innerHTML = 'var download, upload;' + 'download = new JustGage({' + 'id: "downloadSpeedGauge",' + 'value: ' + 0 + ',' + 'min: 0,' + 'max: ' + this.config.maxGaugeScale + ',' + 'title: "Download Speed",' + 'refreshAnimationType:"linear",' + 'gaugeWidthScale: "0.8",' + 'valueFontColor: "#fff",' + 'valueFontFamily: "Roboto Condensed",' + 'titleFontFamily: "Roboto Condensed",' + 'titleFontColor: "#aaa",' + 'symbol: "Mbps"});' + 'upload = new JustGage({' + 'id: "uploadSpeedGauge",' + 'value: ' + 0 + ',' + 'min: 0,' + 'max: ' + this.config.maxGaugeScale + ',' + 'title: "Upload Speed",' + 'refreshAnimationType:"linear",' + 'gaugeWidthScale: "0.8",' + 'valueFontColor: "#fff",' + 'valueFontFamily: "Roboto Condensed",' + 'titleFontFamily: "Roboto Condensed",' + 'titleFontColor: "#aaa",' + 'symbol: "Mbps"});'; } $(script).appendTo('body'); }, socketNotificationReceived: function(notification, payload) { if (notification == 'downloadSpeedProgress') { if (this.config.displaySpeed) { if (this.downloadBarState == 'not_started') { this.addScript(); this.downloadBarState = 'started'; } console.log('updating DOWNLOAD'); download.refresh(payload, this.config.maxGaugeScale); } } if (notification == 'uploadSpeedProgress') { if (this.config.displaySpeed) { console.log('updating UPLOAD'); upload.refresh(payload, this.config.maxGaugeScale); } } if (notification == 'data') { if (this.config.verbose) { if (!this.updating) { var d = document.createElement("div"); d.style = 'text-align: left; display:inline-block;'; $(d).appendTo('#internetData'); } $('#internetData > div').html( ' Server: ' + payload.server.host).append('<br/>' + ' Location: ' + payload.server.location + ' (' + payload.server.country + ')').append('<br/>' + ' Distance: ' + payload.server.distance + ' km').append("</div>"); } } if (notification == 'ping') { console.log('ping') if (this.downloadBarState == 'not_started') this.updateDom(); if (this.config.displayStrength) { var d = document.createElement("div"); if (this.downloadBarState == 'not_started') { d = document.createElement("div"); $(d).appendTo('#pingDiv'); } else { $("#pingDiv").children().remove(); d = document.createElement("div"); $(d).appendTo('#pingDiv'); } payload = 150; if(this.config.hasOwnProperty('wifiSymbol')) { if (payload < 70) { $(d).append('<div class="wifi-symbol-4" > <div class="wifi-circle first"></div> <div class="wifi-circle second"></div> <div class="wifi-circle third"></div> <div class="wifi-circle fourth"></div> </div>'); } else if (payload >= 70 && payload < 100) { $(d).append('<div class="wifi-symbol-2" > <div class="wifi-circle first"></div> <div class="wifi-circle second"></div> <div class="wifi-circle third"></div> <div class="wifi-circle fourth"></div> </div>'); } else if (payload >= 100 && payload < 150) { $(d).append('<div class="wifi-symbol-3" > <div class="wifi-circle first"></div> <div class="wifi-circle second"></div> <div class="wifi-circle third"></div> <div class="wifi-circle fourth"></div> </div>'); } else if (payload >= 150) { $(d).append('<div class="wifi-symbol-1" > <div class="wifi-circle first"></div> <div class="wifi-circle second"></div> <div class="wifi-circle third"></div> <div class="wifi-circle fourth"></div> </div>'); } $(".wifi-symbol-1 .wifi-circle").css({ 'border-color': this.config.wifiSymbol.fullColor, 'font-size': this.config.wifiSymbol.size / 7, 'margin-top': 0 - this.config.wifiSymbol.size - this.config.wifiSymbol.size * 0.25, 'margin-left': 0.5 * (150 - this.config.wifiSymbol.size) }); $(".wifi-symbol-1 [foo], .wifi-symbol-1").css({ 'width': this.config.wifiSymbol.size, 'height': this.config.wifiSymbol.size }); $(".wifi-symbol-2 .wifi-circle").css({ 'border-color': this.config.wifiSymbol.almostColor, 'font-size': this.config.wifiSymbol.size / 7, 'margin-top': 0 - this.config.wifiSymbol.size - this.config.wifiSymbol.size * 0.25, 'margin-left': 0.5 * (150 - this.config.wifiSymbol.size), }); $(".wifi-symbol-2 [foo], .wifi-symbol-2").css({ 'width': this.config.wifiSymbol.size, 'height': this.config.wifiSymbol.size }); $(".wifi-symbol-3 .wifi-circle").css({ 'border-color': this.config.wifiSymbol.halfColor, 'font-size': this.config.wifiSymbol.size / 7, 'margin-top': 0 - this.config.wifiSymbol.size - this.config.wifiSymbol.size * 0.25, 'margin-left': 0.5 * (150 - this.config.wifiSymbol.size), }); $(".wifi-symbol-3 [foo], .wifi-symbol-3").css({ 'width': this.config.wifiSymbol.size, 'height': this.config.wifiSymbol.size }); $(".wifi-symbol-4 .wifi-circle").css({ 'border-color': this.config.wifiSymbol.noneColor, 'font-size': this.config.wifiSymbol.size / 7, 'margin-top': 0 - this.config.wifiSymbol.size - this.config.wifiSymbol.size * 0.25, 'margin-left': 0.5 * (150 - this.config.wifiSymbol.size), }); $(".wifi-symbol-4 [foo], .wifi-symbol-4").css({ 'width': this.config.wifiSymbol.size, 'height': this.config.wifiSymbol.size }); } else{ if(payload < 70){ $(d).append('<img src="' + this.data.path + 'images/' + 'strength_full.png" width=' + this.config.strengthIconSize +'"height=' + this.config.strengthIconSize +'/>'); } else if(payload >= 70 && payload < 100){ $(d).append('<img src="' + this.data.path + 'images/' + 'strength_almost.png" width=' + this.config.strengthIconSize +'"height=' + this.config.strengthIconSize + '/>'); } else if(payload >= 100 && payload < 150){ $(d).append('<img src="' + this.data.path + 'images/' + 'strength_half.png" width=' + this.config.strengthIconSize +'"height=' + this.config.strengthIconSize + '/>'); } else if(payload >= 150) { $(d).append('<img src="' + this.data.path + 'images/' + 'strength_none.png" width=' + this.config.strengthIconSize +'"height=' + this.config.strengthIconSize + '/>'); } } } } }, getDom: function(){ var wrapper = document.createElement("div"); wrapper.className = "small"; console.log(this.config); if(this.config.displayStrength) { console.log('creating pingDiv'); var pingDiv = document.createElement("div"); pingDiv.id = "pingDiv"; wrapper.appendChild(pingDiv); } if(this.config.displaySpeed) { console.log('creating strength'); var downloadSpeedGauge = document.createElement("div"); downloadSpeedGauge.id = 'downloadSpeedGauge'; var uploadSpeedGauge = document.createElement("div"); uploadSpeedGauge.id = 'uploadSpeedGauge'; wrapper.appendChild(downloadSpeedGauge); wrapper.appendChild(uploadSpeedGauge); } if(this.config.verbose) { var data = document.createElement("div"); data.id = 'internetData'; wrapper.appendChild(data); } return wrapper; } });
(function () { 'use strict'; var mainApp = angular.module('myApp', [ // lib // 'ngPrettyJson', 'ui.router' ]); // mainApp.directive('snippet', ['$timeout', '$interpolate', function ($timeout, $interpolate) { // "use strict"; // return { // restrict: 'E', // template: '<pre><code ng-transclude></code></pre>', // replace: true, // transclude: true, // link: function (scope, elm) { // var tmp = $interpolate(elm.find('code').text())(scope); // elm.find('code').html(hljs.highlightAuto(tmp).value); // } // }; // }]); mainApp.config(function ($stateProvider, $urlRouterProvider, routesCfg, $locationProvider) { // iterate over the routes (configured as constants in config/routes-cfg.js) _.forEach(routesCfg, function (route) { $stateProvider. state(route.state, { url: route.url, templateUrl: route.templateUrl, controller: route.controller, views : route.views, onEnter: function() { console.log('onEnter_'+route.state, true); }, onExit: function() { console.log('onExit_'+route.state, true); } }); }); // $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/init'); }); mainApp.config(function($httpProvider) { $httpProvider.defaults.useXDomain = true; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; delete $httpProvider.defaults.headers.common['X-CSRFToken']; }); })();
'use strict'; /* jshint indent: 2 */ var sequelize = require('../../config/sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('subject', { subjectID: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, title: { type: DataTypes.TEXT, allowNull: true }, lastname: { type: DataTypes.TEXT, allowNull: false }, firstname: { type: DataTypes.TEXT, allowNull: false }, middlename: { type: DataTypes.TEXT, allowNull: false }, suffix: { type: DataTypes.TEXT, allowNull: true }, maidenname: { type: DataTypes.TEXT, allowNull: true }, gender: { type: DataTypes.TEXT, allowNull: false }, height: { type: DataTypes.TEXT, allowNull: true }, weight: { type: DataTypes.TEXT, allowNull: true }, age: { type: DataTypes.TEXT, allowNull: true }, customerID: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false } }, { classMethods: { // Creates an association function that is run AFTER all the models are loaded into sequelize. associate: function (models) { models.subject.belongsTo(models.customer, {foreignKey: "customerID"}); } } }); };
/** * @class backImg * @memberOf lapps.lappsDirectives * @description This directive works similar to ng-src on background-image urls */ (function() { angular.module('lappsDirectives').directive('backImg', function() { return function(scope, element, attrs) { attrs.$observe('backImg', function(value) { if (value) { element.css({ 'background-image': 'url(' + value + ')', 'background-size': 'cover' }); } }); }; }); }).call(this);
/* * * Wijmo Library 0.6.1 * http://wijmo.com/ * * Copyright(c) ComponentOne, LLC. All rights reserved. * * Dual licensed under the MIT or GPL Version 2 licenses. * licensing@wijmo.com * http://www.wijmo.com/license * * * Wijmo Tabs widget. * * Depends: * jquery-1.4.2.js * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.position.js * jquery.effects.core.js * jquery.cookie.js * jquery.glob.js * */ (function($) { var tabId = 0, listId = 0; function getNextTabId() { return ++tabId; } function getNextListId() { return ++listId; } $.widget("ui.wijtabs", { options: { /// <summary> /// Determines the tabs' alignment to the content /// </summary> alignment: 'top', /// <summary> /// Determines whether the tab can be dragged to a new position /// </summary> sortable: false, /// <summary> /// Determines whether to wrap to the next line or scrolling is enabled when the tabs exceed the width /// </summary> scrollable: false, /// <summary> /// This event is triggered when a tab is added. /// </summary> add: null, /// <summary> /// Additional Ajax options to consider when loading tab content (see $.ajax). /// </summary> ajaxOptions: null, /// <summary> /// Whether or not to cache remote tabs content, e.g. load only once or with every click. /// Cached content is being lazy loaded, e.g once and only once for the first click. /// Note that to prevent the actual Ajax requests from being cached by the browser you need to provide an extra cache: /// false flag to ajaxOptions. /// </summary> cache: false, /// <summary> /// Store the latest selected tab in a cookie. /// The cookie is then used to determine the initially selected tab if the selected option is not defined. /// Requires cookie plugin. The object needs to have key/value pairs of the form the cookie plugin expects as options. /// </summary> cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } /// <summary> /// Determines whether a tab can be collapsed by a user. When this is set to true, an already selected tab will be collapsed upon reselection. /// </summary> collapsible: false, /// <summary> /// This is an animation option for hiding the tabs panel content. /// </summary> hideOption: null, // e.g. { blind: true, fade: true, duration: 200} /// <summary> /// This is an animation option for showing the tabs panel content. /// </summary> showOption: null, // e.g. { blind: true, fade: true, duration: 200} /// <summary> /// This event is triggered when a tab is disabled. /// </summary> disable: null, /// <summary> /// An array containing the position of the tabs (zero-based index) that should be disabled on initialization. /// </summary> disabled: [], /// <summary> /// This event is triggered when a tab is enabled. /// </summary> enable: null, /// <summary> /// The type of event to be used for selecting a tab. /// </summary> event: 'click', /// <summary> /// If the remote tab, its anchor element that is, has no title attribute to generate an id from, /// an id/fragment identifier is created from this prefix and a unique id returned by $.data(el), for example "ui-tabs-54". /// </summary> idPrefix: 'ui-tabs-', /// <summary> /// This event is triggered after the content of a remote tab has been loaded. /// </summary> load: null, /// <summary> /// HTML template from which a new tab panel is created in case of adding a tab with the add method or /// when creating a panel for a remote tab on the fly. /// </summary> panelTemplate: '<div></div>', /// <summary> /// This event is triggered when a tab is removed. /// </summary> remove: null, /// <summary> /// This event is triggered when clicking a tab. /// </summary> select: null, /// <summary> /// This event is triggered when a tab is shown. /// </summary> show: null, /// <summary> /// The HTML content of this string is shown in a tab title while remote content is loading. /// Pass in empty string to deactivate that behavior. /// An span element must be present in the A tag of the title, for the spinner content to be visible. /// </summary> spinner: '<em>Loading&#8230;</em>', /// <summary> /// HTML template from which a new tab is created and added. /// The placeholders #{href} and #{label} are replaced with the url and tab label that are passed as /// arguments to the add method. /// </summary> tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>' }, _create: function() { this._tabify(true); }, _setOption: function(key, value) { $.Widget.prototype._setOption.apply(this, arguments); switch(key){ case 'selected': if (this.options.collapsible && value == this.options.selected) { return; } this.select(value); break; case 'alignment': this.destroy(); this._tabify(true); break; default: this._tabify(); break; } }, _initScroller: function(){ var horz = $.inArray(this._getAlignment(), ['top', 'bottom']) != -1; if (!horz) return; var width = 0; this.lis.each(function() { width += $(this).outerWidth(true); }); if (!!this.options.scrollable && this.element.innerWidth() < width){ if (this.scrollWrap == undefined){ this.list.wrap("<div class='scrollWrap'></div>"); this.scrollWrap = this.list.parent(); $.effects.save(this.list, ['width', 'height', 'overflow']); } this.list.width(width + 2); this.scrollWrap.height(this.list.outerHeight(true)); this.scrollWrap.wijsuperpanel({ allowResize: false, hScroller: { scrollMode: 'edge' }, vScroller: { scrollBarVisibility: 'hidden' } }); }else{ this._removeScroller(); } }, _removeScroller: function(){ if (this.scrollWrap){ this.scrollWrap.wijsuperpanel('destroy').replaceWith(this.scrollWrap.contents()); this.scrollWrap = undefined; $.effects.restore(this.list, ['width', 'height', 'overflow']); } }, _tabId: function(a) { return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') || this.options.idPrefix + getNextTabId(); }, _sanitizeSelector: function(hash) { return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":" }, _cookie: function() { var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + getNextListId()); return $.cookie.apply(null, [cookie].concat($.makeArray(arguments))); }, _ui: function(tab, panel) { return { tab: tab, panel: panel, index: this.anchors.index(tab) }; }, _cleanup: function() { // restore all former loading tabs labels this.lis.filter('.ui-state-processing').removeClass('ui-state-processing') .find('span:data(label.tabs)') .each(function() { var el = $(this); el.html(el.data('label.tabs')).removeData('label.tabs'); }); }, _getAlignment : function(tabs){ tabs = tabs === undefined ? true : tabs; var align = this.options.alignment || 'top'; if (tabs) return align; switch(align){ case 'top': align = 'bottom'; break; case 'bottom': align = 'top'; break; case 'left': align = 'right'; break; case 'right': align = 'left'; break; } return align; }, _saveLayout: function(){ var props = ['width', 'height', 'overflow']; $.effects.save(this.element, props); $.effects.save(this.list, props); $.effects.save(this.element.find('.ui-wijtabs-content'), props); this.list.width(this.list.width()); $hide = this.panels.filter(':not(.ui-tabs-hide)'); this.element.data('panel.width', $hide.width()); this.element.data('panel.outerWidth', $hide.outerWidth(true)); }, _restoreLayout: function(){ var props = ['width', 'height', 'overflow']; $.effects.restore(this.element, props); $.effects.restore(this.list, props); $.effects.restore(this.element.find('.ui-wijtabs-content'), props); }, _hideContent: function(){ var content=this.element.find('.ui-wijtabs-content'); if (content.length){ this._saveLayout(); content.addClass('ui-tabs-hide'); this.element.width(this.list.outerWidth(true)); } }, _showContent: function(){ var content=this.element.find('.ui-wijtabs-content'); if (content.length){ this._restoreLayout(); content.removeClass('ui-tabs-hide'); } }, _blindPanel: function(panel, mode){ var o = this.options; var content = panel.parent('.ui-wijtabs-content'); if (!content.length) return; this.list.width(this.list.width()); var props = ['position','top','left', 'width']; $.effects.save(panel, props); panel.show(); // Save & Show if (mode == 'show') { panel.removeClass('ui-tabs-hide'); // Show panel.width(this.element.data('panel.width')); }else{ panel.width(panel.width()); } var blindOption = mode == 'show' ? o.showOption : o.hideOption; var wrapper = $.effects.createWrapper(panel).css({overflow:'hidden'}); // Create Wrapper if(mode == 'show'){ wrapper.css($.extend({width: 0}, blindOption.fade ? {opacity: 0} : {})); // Shift } // Animation var a = $.extend({width: mode == 'show' ? this.element.data('panel.outerWidth') : 0}, blindOption.fade ? {opacity: mode == 'show' ? 1 : 0} : {}); var self = this; var listWidth = this.list.outerWidth(true); // Animate wrapper.animate(a, { duration: blindOption.duration, step: function(){ var ww = wrapper.outerWidth(true); self.element.width(listWidth + ww); content.width(Math.max(0, self.element.innerWidth() - listWidth - 6)); }, complete: function() { if(mode == 'hide') { self.lis.removeClass('ui-tabs-selected ui-state-active'); panel.addClass('ui-tabs-hide'); // Hide }else{ panel.css('width', ''); } //$.effects.restore(panel, props); $.effects.removeWrapper(panel); // Restore if (mode == 'show') self._restoreLayout(); self._resetStyle(panel); panel.dequeue(); self.element.dequeue("tabs"); } }); }, // Reset certain styles left over from animation // and prevent IE's ClearType bug... _resetStyle: function ($el) { $el.css({ display: '' }); if (!$.support.opacity) { $el[0].style.removeAttribute('filter'); } }, _normalizeBlindOption: function(o){ if (o.blind === undefined) o.blind = false; if (o.fade === undefined) o.fade = false; if (o.duration === undefined) o.duration = 200; if (typeof o.duration == 'string'){ try{ o.duration = parseInt(o.duration); } catch(e){ o.duration = 200; } } }, _tabify: function(init) { this.list = this.element.find('ol,ul').eq(0); this.lis = $('li:has(a[href])', this.list); this.anchors = this.lis.map(function() { return $('a', this)[0]; }); this.panels = $([]); var self = this, o = this.options; var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash this.anchors.each(function(i, a) { var href = $(a).attr('href'); // For dynamically created HTML that contains a hash as href IE < 8 expands // such href to the full page url with hash and then misinterprets tab as ajax. // Same consideration applies for an added tab with a fragment identifier // since a[href=#fragment-identifier] does unexpectedly not match. // Thus normalize href attribute... var hrefBase = href.split('#')[0], baseEl; if (hrefBase && (hrefBase === location.toString().split('#')[0] || (baseEl = $('base')[0]) && hrefBase === baseEl.href)) { href = a.hash; a.href = href; } // inline tab if (fragmentId.test(href)) { self.panels = self.panels.add(self._sanitizeSelector(href)); } // remote tab else if (href != '#') { // prevent loading the page itself if href is just "#" $.data(a, 'href.tabs', href); // required for restore on destroy $.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data var id = self._tabId(a); a.href = '#' + id; var $panel = $('#' + id); if (!$panel.length) { $panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom') .insertAfter(self.panels[i - 1] || self.list); $panel.data('destroy.tabs', true); } self.panels = self.panels.add($panel); } // invalid tab href else { o.disabled.push(i); } }); var tabsAlign = this._getAlignment(), panelCorner = this._getAlignment(false); // initialization from scratch if (init) { this.element.addClass('ui-tabs ui-wijtabs' + ' ui-tabs-' + tabsAlign + ' ui-widget ui-widget-content ui-corner-all ui-helper-clearfix'); this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.lis.addClass('ui-state-default' + ' ui-corner-' + tabsAlign); this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-' + panelCorner); var content; // attach necessary classes for styling switch(tabsAlign){ case 'bottom': this.list.appendTo(this.element); break; case 'left': content = $('<div/>').addClass('ui-wijtabs-content').appendTo(this.element); this.panels.appendTo(content); break; case 'right': content = $('<div/>').addClass('ui-wijtabs-content').insertBefore(this.list); this.panels.appendTo(content); break; case 'top': this.list.prependTo(this.element); break; } // Selected tab // use "selected" option or try to retrieve: // 1. from fragment identifier in url // 2. from cookie // 3. from selected class attribute on <li> if (o.selected === undefined) { if (location.hash) { this.anchors.each(function(i, a) { if (a.hash == location.hash) { o.selected = i; return false; // break } }); } if (typeof o.selected != 'number' && o.cookie) { o.selected = parseInt(self._cookie(), 10); } if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) { o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected')); } o.selected = o.selected || (this.lis.length ? 0 : -1); } else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release o.selected = -1; } // sanity check - default to first tab... o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0; // Take disabling tabs via class attribute from HTML // into account and update option properly. // A selected tab cannot become disabled. o.disabled = $.unique(o.disabled.concat( $.map(this.lis.filter('.ui-state-disabled'), function(n, i) { return self.lis.index(n); } ) )).sort(); if ($.inArray(o.selected, o.disabled) != -1) { o.disabled.splice($.inArray(o.selected, o.disabled), 1); } // highlight selected tab this.panels.addClass('ui-tabs-hide'); this.lis.removeClass('ui-tabs-selected ui-state-active'); if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list this.panels.eq(o.selected).removeClass('ui-tabs-hide'); this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active'); // seems to be expected behavior that the show callback is fired self.element.queue("tabs", function() { self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected])); }); this.load(o.selected); } // clean up to avoid memory leaks in certain versions of IE 6 $(window).bind('unload', function() { if (self.lis) self.lis.add(self.anchors).unbind('.tabs'); self.lis = self.anchors = self.panels = null; }); } // update selected after add/remove else { o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected')); } // update collapsible this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible'); // set or update cookie after init and add/remove respectively if (o.cookie) { this._cookie(o.selected, o.cookie); } // disable tabs for (var i = 0, li; (li = this.lis[i]); i++) { $(li)[$.inArray(i, o.disabled) != -1 && !$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled'); } // reset cache if switching from cached to not cached if (o.cache === false) { this.anchors.removeData('cache.tabs'); } // remove all handlers before, tabify may run on existing tabs after add or option change this.lis.add(this.anchors).unbind('.tabs'); if (o.event != 'mouseover') { var addState = function(state, el) { if (el.is(':not(.ui-state-disabled)')) { el.addClass('ui-state-' + state); } }; var removeState = function(state, el) { el.removeClass('ui-state-' + state); }; this.lis.bind('mouseover.tabs', function() { addState('hover', $(this)); }); this.lis.bind('mouseout.tabs', function() { removeState('hover', $(this)); }); this.anchors.bind('focus.tabs', function() { addState('focus', $(this).closest('li')); }); this.anchors.bind('blur.tabs', function() { removeState('focus', $(this).closest('li')); }); } if (o.showOption === undefined || o.showOption === null) o.showOption = {}; this._normalizeBlindOption(o.showOption); if (o.hideOption === undefined || o.hideOption === null) o.hideOption = {}; this._normalizeBlindOption(o.hideOption); // Show a tab... var showTab = ((o.showOption.blind || o.showOption.fade) && o.showOption.duration > 0) ? function(clicked, $show) { $(clicked).closest('li').addClass('ui-tabs-selected ui-state-active'); self._showContent(); $show.removeClass('ui-tabs-hide'); if (tabsAlign == 'top' || tabsAlign == 'bottom'){ var props = { duration: o.showOption.duration }; if (o.showOption.blind) props.height = 'toggle'; if (o.showOption.fade) props.opacity = 'toggle'; $show.hide().removeClass('ui-tabs-hide') // avoid flicker that way .animate(props, o.showOption.duration || 'normal', function() { self._resetStyle($show); self._trigger('show', null, self._ui(clicked, $show[0])); }); }else{ self._showContent(); self._blindPanel($show, 'show'); } } : function(clicked, $show) { $(clicked).closest('li').addClass('ui-tabs-selected ui-state-active'); self._showContent(); $show.removeClass('ui-tabs-hide'); self._trigger('show', null, self._ui(clicked, $show[0])); }; // Hide a tab, $show is optional... var hideTab = ((o.hideOption.blind || o.hideOption.fade) && o.hideOption.duration > 0) ? function(clicked, $hide) { if (tabsAlign == 'top' || tabsAlign == 'bottom'){ var props = { duration: o.hideOption.duration }; if (o.hideOption.blind) props.height = 'toggle'; if (o.hideOption.fade) props.opacity = 'toggle'; $hide.animate(props, o.hideOption.duration || 'normal', function() { self.lis.removeClass('ui-tabs-selected ui-state-active'); $hide.addClass('ui-tabs-hide'); self._resetStyle($hide); self.element.dequeue("tabs"); }); }else{ self._saveLayout(); self._blindPanel($hide, 'hide'); } } : function(clicked, $hide, $show) { self.lis.removeClass('ui-tabs-selected ui-state-active'); self._hideContent(); $hide.addClass('ui-tabs-hide'); self.element.dequeue("tabs"); }; // attach tab event handler, unbind to avoid duplicates from former tabifying... this.anchors.bind(o.event + '.tabs', function() { var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'), $show = $(self._sanitizeSelector(this.hash)); // If tab is already selected and not collapsible or tab disabled or // or is already loading or click callback returns false stop here. // Check if click handler returns false last so that it is not executed // for a disabled or loading tab! if (($li.hasClass('ui-tabs-selected') && !o.collapsible) || $li.hasClass('ui-state-disabled') || $li.hasClass('ui-state-processing') || self._trigger('select', null, self._ui(this, $show[0])) === false) { this.blur(); return false; } o.selected = self.anchors.index(this); self.abort(); // if tab may be closed if (o.collapsible) { if ($li.hasClass('ui-tabs-selected')) { o.selected = -1; if (o.cookie) { self._cookie(o.selected, o.cookie); } self.element.queue("tabs", function() { hideTab(el, $hide); }).dequeue("tabs"); this.blur(); return false; } else if (!$hide.length) { if (o.cookie) { self._cookie(o.selected, o.cookie); } self.element.queue("tabs", function() { showTab(el, $show); }); self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171 this.blur(); return false; } } if (o.cookie) { self._cookie(o.selected, o.cookie); } // show new tab if ($show.length) { if ($hide.length) { self.element.queue("tabs", function() { hideTab(el, $hide); }); } self.element.queue("tabs", function() { showTab(el, $show); }); self.load(self.anchors.index(this)); } else { throw 'jQuery UI Tabs: Mismatching fragment identifier.'; } // Prevent IE from keeping other link focussed when using the back button // and remove dotted border from clicked link. This is controlled via CSS // in modern browsers; blur() removes focus from address bar in Firefox // which can become a usability and annoying problem with tabs('rotate'). if ($.browser.msie) { this.blur(); } }); this._initScroller(); // disable click in any case this.anchors.bind('click.tabs', function(){return false;}); }, destroy: function() { var o = this.options; this.abort(); this._removeScroller(); this.element.unbind('.tabs') .removeClass([ 'ui-wijtabs', 'ui-tabs-top', 'ui-tabs-bottom', 'ui-tabs-left', 'ui-tabs-right', 'ui-tabs', 'ui-widget', 'ui-widget-content', 'ui-corner-all', 'ui-tabs-collapsible', 'ui-helper-clearfix' ].join(' ')) .removeData('tabs'); this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'); this.anchors.each(function() { var href = $.data(this, 'href.tabs'); if (href) { this.href = href; } var $this = $(this).unbind('.tabs'); $.each(['href', 'load', 'cache'], function(i, prefix) { $this.removeData(prefix + '.tabs'); }); }); this.lis.unbind('.tabs').add(this.panels).each(function() { if ($.data(this, 'destroy.tabs')) { $(this).remove(); } else { $(this).removeClass([ 'ui-state-default', 'ui-corner-top', 'ui-corner-bottom', 'ui-corner-left', 'ui-corner-right', 'ui-tabs-selected', 'ui-state-active', 'ui-state-hover', 'ui-state-focus', 'ui-state-disabled', 'ui-tabs-panel', 'ui-widget-content', 'ui-tabs-hide' ].join(' ')).css({position:'', left: '', top: ''}); } }); var content = $('.ui-wijtabs-content'); if (content.length) content.replaceWith(content.contents()); if (o.cookie) { this._cookie(null, o.cookie); } return this; }, add: function(url, label, index) { /// <summary>Add a new tab.</summary> /// <param name="url" type="String">A URL consisting of a fragment identifier only to create an in-page tab or a full url (relative or absolute, no cross-domain support) to turn the new tab into an Ajax (remote) tab.</param> /// <param name="label" type="String">The tab label.</param> /// <param name="index" type="Number">Zero-based position where to insert the new tab.</param> if (index === undefined) { index = this.anchors.length; // append by default } var self = this, o = this.options, $li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)), id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]); var tabsAlign = this._getAlignment(), panelCorner = this._getAlignment(false); $li.addClass('ui-state-default' + ' ui-corner-' + tabsAlign).data('destroy.tabs', true); // try to find an existing element before creating a new one var $panel = $('#' + id); if (!$panel.length) { $panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true); } $panel.addClass('ui-tabs-panel ui-widget-content ui-corner-' + panelCorner + ' ui-tabs-hide'); if (index >= this.lis.length) { $li.appendTo(this.list); if (this.panels.length > 0) $panel.insertAfter(this.panels[this.panels.length - 1]); else $panel.appendTo(this.list[0].parentNode); } else { $li.insertBefore(this.lis[index]); $panel.insertBefore(this.panels[index]); } o.disabled = $.map(o.disabled, function(n, i) { return n >= index ? ++n : n; }); this._tabify(); if (this.anchors.length == 1) { // after tabify o.selected = 0; $li.addClass('ui-tabs-selected ui-state-active'); $panel.removeClass('ui-tabs-hide'); this.element.queue("tabs", function() { self._trigger('show', null, self._ui(self.anchors[0], self.panels[0])); }); this.load(0); } // callback this._trigger('add', null, this._ui(this.anchors[index], this.panels[index])); return this; }, remove: function(index) { /// <summary>Remove a tab.</summary> /// <param name="index" type="Number">The zero-based index of the tab to be removed.</param> var o = this.options, $li = this.lis.eq(index).remove(), $panel = this.panels.eq(index).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) { this.select(index + (index + 1 < this.anchors.length ? 1 : -1)); } o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }), function(n, i) { return n >= index ? --n : n; }); this._tabify(); // callback this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0])); return this; }, enable: function(index) { /// <summary>Enable a disabled tab.</summary> /// <param name="index" type="Number">The zero-based index of the tab to be enabled.</param> var o = this.options; if ($.inArray(index, o.disabled) == -1) { return; } this.lis.eq(index).removeClass('ui-state-disabled'); o.disabled = $.grep(o.disabled, function(n, i) { return n != index; }); // callback this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index])); return this; }, disable: function(index) { /// <summary>Disabled a tab.</summary> /// <param name="index" type="Number">The zero-based index of the tab to be disabled.</param> var self = this, o = this.options; if (index != o.selected) { // cannot disable already selected tab this.lis.eq(index).addClass('ui-state-disabled'); o.disabled.push(index); o.disabled.sort(); // callback this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index])); } return this; }, select: function(index) { /// <summary>Select a tab, as if it were clicked.</summary> /// <param name="index" type="Number">The zero-based index of the tab to be selected or the id selector of the panel the tab is associated with.</param> if (typeof index == 'string') { index = this.anchors.index(this.anchors.filter('[href$=' + index + ']')); } else if (index === null) { // usage of null is deprecated, TODO remove in next release index = -1; } if (index == -1 && this.options.collapsible) { index = this.options.selected; } this.anchors.eq(index).trigger(this.options.event + '.tabs'); return this; }, load: function(index) { /// <summary>Reload the content of an Ajax tab programmatically.</summary> /// <param name="index" type="Number">The zero-based index of the tab to be loaded</param> var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs'); this.abort(); // not remote or from cache if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) { this.element.dequeue("tabs"); return; } // load remote from here on this.lis.eq(index).addClass('ui-state-processing'); if (o.spinner) { var span = $('span', a); span.data('label.tabs', span.html()).html(o.spinner); } this.xhr = $.ajax($.extend({}, o.ajaxOptions, { url: url, success: function(r, s) { $(self._sanitizeSelector(a.hash)).html(r); // take care of tab labels self._cleanup(); if (o.cache) { $.data(a, 'cache.tabs', true); // if loaded once do not load them again } // callbacks self._trigger('load', null, self._ui(self.anchors[index], self.panels[index])); try { o.ajaxOptions.success(r, s); } catch (e) {} }, error: function(xhr, s, e) { // take care of tab labels self._cleanup(); // callbacks self._trigger('load', null, self._ui(self.anchors[index], self.panels[index])); try { // Passing index avoid a race condition when this method is // called after the user has selected another tab. // Pass the anchor that initiated this request allows // loadError to manipulate the tab content panel via $(a.hash) o.ajaxOptions.error(xhr, s, index, a); } catch (e) {} } })); // last, so that load event is fired before show... self.element.dequeue("tabs"); return this; }, abort: function() { /// <summary>Terminate all running tab ajax requests and animations.</summary> this.element.queue([]); this.panels.stop(false, true); // "tabs" queue must not contain more than two elements, // which are the callbacks for the latest clicked tab... this.element.queue("tabs", this.element.queue("tabs").splice(-2, 2)); // terminate pending requests from other tabs if (this.xhr) { this.xhr.abort(); delete this.xhr; } // take care of tab labels this._cleanup(); return this; }, url: function(index, url) { /// <summary>Change the url from which an Ajax (remote) tab will be loaded.</summary> /// <param name="index" type="Number">The zero-based index of the tab of which its URL is to be updated.</param> /// <param name="url" type="String">A URL the content of the tab is loaded from.</param> this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url); return this; }, length: function() { /// <summary>Retrieve the number of tabs of the first matched tab pane.</summary> return this.anchors.length; } }); })(jQuery);
import config from '../config' function requestContacts() { return { type: 'FETCH_CONTACTS', } } function receiveContacts(contacts=[], status='success', partial=false) { return { type: 'FETCH_CONTACTS', receivedAt: !partial && Date.now(), contacts, status, } } function receiveContact(contact, status='success') { return { type: 'FETCH_CONTACT', contact, status, } } export function fetchContacts(options={}) { return async function(dispatch, getState) { dispatch(requestContacts()); const result = await config.adapter.getContacts(options); dispatch(receiveContacts(result.contacts, 'success', !!options.ids)) } } export function fetchContact(id) { return async function(dispatch, getState) { const result = await config.adapter.getContact(id); dispatch(receiveContact(result.contact)) } } export function handleContactEvent(event, payload) { // Ouput action based on event and payload return { type: 'UPDATE_CONTACT', id, update, } } export function subscribeToContactEvents(contactCallback) { config.adapter.subscribeToContactEvents(contactCallback); }
/*Copyright (C) 2013 David Orchard 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. */ // Filename: client.js define(function(){ var client = null; return { setClient: function( newClient ) { client = newClient; }, getClient: function() { return client; }, }; });
if (process.platform === 'darwin') { // this uses the binaries brought by npm package imagemagick-darwin-static const imagemagickPath = __dirname + "/../../node_modules/imagemagick-darwin-static/bin/osx/imagemagick/7.0.5-5"; process.env['MAGICK_HOME'] = imagemagickPath; process.env['PATH'] = imagemagickPath + "/bin:" + process.env['PATH']; process.env['DYLD_LIBRARY_PATH'] = imagemagickPath + "/lib:" } var gm = require('gm').subClass({ imageMagick: true /*, appPath: imagemagickPath + "/bin/"*/}); class TileMerger { constructor(zoom, tileRange , tileFolder, outputFilename ){ this._zoom = zoom; this._tileRange = tileRange; this._tileFolder = tileFolder; this._outputFilename = outputFilename; this._stripNames = []; this._nbStripsSuccesfullyWritten = 0; this._events = { stripWriten: null, // args: (index, total) successMerge: null // args: ( path final image ) } } on( eventName, cb ){ if( eventName in this._events ){ this._events[ eventName ] = cb; } } build(){ var that = this; var nbTileWidth = this._tileRange.x.max - this._tileRange.x.min + 1; var nbTileHeight = this._tileRange.y.max - this._tileRange.y.min + 1; // reinint the stripname list this._stripNames.length = 0; this._nbStripsSuccesfullyWritten = 0; for(var y=this._tileRange.y.min; y<=this._tileRange.y.max; y++){ var currentStripGm = gm(); for(var x=this._tileRange.x.min; x<=this._tileRange.x.max; x++){ var toBeMerged = this._tileFolder + "/" + x + "_" + y + "_" + this._zoom + ".png"; currentStripGm.append( toBeMerged , true) } var currentStripName = this._tileFolder + "/strip_" + this._stripNames.length + ".png"; this._stripNames.push( currentStripName ) currentStripGm.write( currentStripName, function (err) { if( err ){ console.error( err ); }else{ //console.log("success strip: " + that._nbStripsSuccesfullyWritten); that._nbStripsSuccesfullyWritten++; if( that._events.stripWriten ){ that._events.stripWriten( that._nbStripsSuccesfullyWritten, nbTileHeight ) } if( nbTileHeight == that._nbStripsSuccesfullyWritten){ //console.log( "wrote all stripes!" ); that._mergeStrips(); } } } ); } } // end build _mergeStrips(){ var that = this; var allStrips = gm(); allStrips.append(this._stripNames, false) allStrips.write( this._outputFilename, function (err) { if( err ){ console.error( err ); }else{ if( that._events.successMerge ){ that._events.successMerge( that._outputFilename ) } } } ); } } module.exports = TileMerger;
var _ = require('lodash'), assert = require('chai').assert, Picture = require('../client/picture'), Shape = require('../client/shape'), Arc = require('../client/shape/arc'), Polyline = require('../client/shape/polyline'), arcify = require('../client/suggest/arcify'), MockPaper = require('./mockPaper'), guid = require('../lib/guid'); describe('Arcify suggestor', function () { var paper = MockPaper(10, 10), picture = new Picture(paper); it('should arcify a small arc with positive sweep', function () { var line = paper.polyline([0, 0, 1, 1, 2, 1, 3, 0]).attr('id', guid()); var action = arcify(picture, { results : [line] }); assert.isOk(action); assert.isAtLeast(action.confidence, 0.7); var arc = Shape.of(_.last(action.do(picture))); assert.instanceOf(arc, Arc); assert.equal(arc.path[1].curve.rx, 1.625); assert.equal(arc.path[1].curve.ry, 1.625); assert.isNotOk(arc.path[1].curve.sweepFlag); assert.isNotOk(arc.path[1].curve.largeArcFlag); }); it('should arcify a small arc with negative sweep', function () { var line = paper.polyline([0, 1, 1, 0, 2, 0, 3, 1]).attr('id', guid()); var action = arcify(picture, { results : [line] }); assert.isOk(action); assert.isAtLeast(action.confidence, 0.7); var arc = Shape.of(_.last(action.do(picture))); assert.instanceOf(arc, Arc); assert.equal(arc.path[1].curve.rx, 1.625); assert.equal(arc.path[1].curve.ry, 1.625); assert.isOk(arc.path[1].curve.sweepFlag); assert.isNotOk(arc.path[1].curve.largeArcFlag); }); it('should arcify a large arc with positive sweep', function () { // Octagon under x-axis with topmost side missing, c = [1.5, 1.5] var line = paper.polyline([1, 0, 0, 1, 0, 2, 1, 3, 2, 3, 3, 2, 3, 1, 2, 0]).attr('id', guid()); var action = arcify(picture, { results : [line] }); assert.isOk(action); assert.isAtLeast(action.confidence, 0.8); var arc = Shape.of(_.last(action.do(picture))); assert.instanceOf(arc, Arc); assert.isAtLeast(arc.path[1].curve.rx, 1.5); assert.isAtMost(arc.path[1].curve.rx, 1.6); assert.isAtLeast(arc.path[1].curve.ry, 1.5); assert.isAtMost(arc.path[1].curve.rx, 1.6); assert.isNotOk(arc.path[1].curve.sweepFlag); assert.isOk(arc.path[1].curve.largeArcFlag); }); });
const assert = require("assert") describe("white algo", function () { const white = require("./white") it("", function () { const result = white([ [false, true, false], [true, true, false] ]) assert.deepEqual(result, [ {command: "PAINT_LINE", args: [0, 0, 0, 2]}, {command: "PAINT_LINE", args: [1, 0, 1, 2]}, {command: "ERASE_CELL", args: [0, 0]}, {command: "ERASE_CELL", args: [0, 2]}, {command: "ERASE_CELL", args: [1, 2]}, ]) }) })
'use strict'; export default function routes($routeProvider) { 'ngInject'; $routeProvider .when('/courses/:id/sections/create', { template: require('./create/newsection.html'), controller: 'NewSectionCtrl', authenticate: 'instructor' }) .when('/courses/:id/sections/:sectionId/edit', { template: require('./edit/sectionedit.html'), controller: 'SectionEditCtrl', authenticate: 'instructor' }) .when('/courses/:id/sections/:sectionId', { template: require('./view/sectionview.html'), controller: 'SectionViewCtrl' }); }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /* hash functions: https://github.com/darkskyapp/string-hash | 18 lines (13 sloc) 408 Bytes https://github.com/srijs/rusha | 532 lines (532 sloc) 22 KB | 2 lines (2 sloc) 7.31 KB min https://github.com/vigour-io/quick-hash ← murmurhash | 62 lines (52 sloc) 1.96 KB */ // import XXH from 'xxhashjs' import stringHash from 'string-hash'; var classes = []; var styleSheet = void 0, rulesInserted = 0; export function parseStyles(styles, rootSelector) { var curpos = 0, currentSelector = [rootSelector], currentProps = '', result = {}, mediaBraces = 0, mediaQuery = false; var chunks = styles.split(/[;}{]/); var flushSelector = function flushSelector() { var generatedSelector = currentSelector[currentSelector.length - 1]; currentProps = currentProps.replace(/\s+/g, ' ').trim(); if (mediaQuery !== false) { result[mediaQuery][generatedSelector] = (result[mediaQuery][generatedSelector] || '') + currentProps; } else { result[generatedSelector] = (result[generatedSelector] || '') + currentProps; } }; chunks.forEach(function (chunk) { var suffix = curpos + chunk.length < styles.length ? styles.charAt(curpos + chunk.length) : ''; switch (suffix) { case '{': if (currentProps !== '') { flushSelector(); } currentProps = ''; if (chunk.indexOf('@media') !== -1) { mediaQuery = chunk.replace(/[\r\n\s]+/g, ' ').trim(); mediaBraces = 0; currentSelector = currentSelector.slice(0, 1); result[mediaQuery] = {}; } else { var chunkSelector = chunk.replace(/[\r\n\s]+/g, ' ').trim().split(',').map(function (sel) { return sel.trim(); }).map(function (sel) { return sel.charAt(0) === '&' ? sel : '& ' + sel; }).join(','); currentSelector.push(chunkSelector.replace(/[&]/g, currentSelector[currentSelector.length - 1])); if (mediaQuery !== false) { mediaBraces++; } } break; case '}': flushSelector(); currentSelector.pop(); currentProps = ''; if (mediaQuery !== false) { mediaBraces--; if (mediaBraces === -1) { mediaQuery = false; } } break; case ';': currentProps += chunk + ';'; break; default: } curpos += chunk.length + 1; }); if (currentProps !== '') { flushSelector(); } return result; } function createStyleTag() { var styleTag = document.createElement('style'); styleTag.appendChild(document.createTextNode('')); document.head.appendChild(styleTag); styleSheet = styleTag.sheet; } function appendRule(styleHash, styles) { if (!styleSheet) { createStyleTag(); } if (classes.indexOf(styleHash) === -1) { var parsedStyles = parseStyles(styles, '.' + styleHash); for (var selector in parsedStyles) { if (parsedStyles.hasOwnProperty(selector)) { if (selector.substr(0, 6) === '@media') { var nestedSelectorsString = ''; for (var nestedSelector in parsedStyles[selector]) { if (parsedStyles[selector].hasOwnProperty(nestedSelector)) { nestedSelectorsString += nestedSelector + ' {' + parsedStyles[selector][nestedSelector] + '}'; } } styleSheet.insertRule(selector + ' {' + nestedSelectorsString + '}', rulesInserted); // console.log(`${selector} {${nestedSelectorsString}}`) } else { styleSheet.insertRule(selector + ' {' + parsedStyles[selector] + '}', rulesInserted); } rulesInserted++; } } classes.push(styleHash); } } export function css(styles) { for (var _len = arguments.length, values = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { values[_key - 1] = arguments[_key]; } var interpolatedStyles = String.raw.apply(String, [styles].concat(_toConsumableArray(values.map(function (val) { return val === false || val === undefined ? '' : val; })))); // const styleHash = '_' + XXH.h32(interpolatedStyles.replace(/\s+/g, ' '), 0x0000 ).toString(16) var styleHash = '_' + stringHash(interpolatedStyles.replace(/\s+/g, ' ')); appendRule(styleHash, interpolatedStyles); return styleHash; }
/** * 定义公共参数 * 设置回调函数定义名称 * 定义返回错误码 */ export const commonParams = { g_tk: 5381, inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, format: 'jsonp' } export const options = { param: 'jsonpCallback' } export const ERR_OK = 0
angular.module('app.controllers', []) .controller('vagasDeEmpregoEmAtibaiaCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('sobreCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('notificaEsCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('vagasDoPATCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('vagasDoAtibaiaComBrCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('vagasDaRMDesenvEmRHCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('cursosDoPATCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }]) .controller('cursosDaEtecCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams) { }])
const { getInstanceWithoutData } = require('../parse/objects').default import moment from 'moment'; import Posts from "../lib/posts"; import Topics from "../lib/topics"; /** * The states were interested in */ const { PARSE_POSTS, } = require('../lib/constants').default export default class PostsParameters { constructor(query: Parse.Query) { this.query = query } addParameters(terms: Any) { this.query.descending("createdAt") // order: nextOrder, // orderby: columnName, const {date, from, author, userId, topicId, s} = terms; if (!!date) { let split = date.split('-'); let year = split[0]; let month = split[1]; month = parseInt(month) - 1; const startDate = moment([year, month]).startOf('month'); const endDate = moment(startDate).endOf('month'); this.query.greaterThanOrEqualTo('postedAt', startDate.toDate()); this.query.lessThan('postedAt', endDate.toDate()); } if (!!from) { this.query.equalTo("sourceFrom", from) } if (!!author) { this.query.equalTo("author", author) } if (!!userId) { this.query.equalTo("userId", userId) } if (!!topicId) { this.query.containedIn("topics", [topicId]) } if (!!s) { this.query.matches('title', s, 'i') } this.addStatusPostsParameter(terms) this.addSortParameter(terms) return this } addSortParameter(terms) { // order: nextOrder, // orderby: columnName, const {order, orderby} = terms; if (!!orderby) { const order = terms.order || "desc"; switch (orderby) { case "title": if (order === 'desc') { this.query.descending("title") } else if (order === 'asc') { this.query.ascending("title") } break; case "date": if (order === 'desc') { this.query.descending("postedAt") } else if (order === 'asc') { this.query.ascending("postedAt") } break; } } else { this.query.descending("postedAt") } } addStatusPostsParameter(terms) { const queryStatus = terms.status; switch (queryStatus) { case "publish": this.query.equalTo("status", Posts.config.STATUS_APPROVED) break; case "pending": this.query.equalTo("status", Posts.config.STATUS_PENDING) break; case "reject": this.query.equalTo("status", Posts.config.STATUS_REJECTED) break; case "draft": this.query.equalTo("status", Posts.config.STATUS_SPAM) break; case "trash": this.query.equalTo("status", Posts.config.STATUS_DELETED) break; default: this.query.containedIn("status", Posts.config.PUBLISH_STATUS) break; } } end() { return this.query } }
var tape = require("tape") var clone = require("../lib/clone") tape("clone", function(test){ var array = [1,2,3,4,5] var object = (function(){ function K(){ this.constructor = "foo" this.foo = "bar" } K.prototype.bar = "baz" return new K() })() var clonedArray = clone(array) var clonedObject = clone(object) var deepArray = [1,2, [1,2, {foo:"bar"}], 3] var deepClonedArray = clone(deepArray, true) test.notEqual(array, clonedArray, "clone(array), reference not equal") test.deepEqual(array, clonedArray, "clone(array), deep equal") array[0] = 2 test.equal(clonedArray[0], 1, "clone(array), reference broken") test.notEqual(object, clonedObject, "clone(object), reference not equal") test.equal(clonedObject.foo, "bar", "clone(object), equal") test.equal(clonedObject.bar, void 0, "ignores not owned properties") test.equal(clonedObject.constructor, "foo", "passes through `constructor` property") object.foo = "baz" test.equal(clonedObject.foo, "bar", "clone(object), reference broken") test.deepEqual(deepClonedArray, deepArray, "deep cloning") test.notEqual(deepClonedArray[2], deepArray[2], "deep cloning, inner array references") test.notEqual(deepClonedArray[2][2], deepArray[2][2], "deep cloning, inner object references") test.end() })
/* Promise library used only for supporting PhantomJS */ (function(global){ // // Check for native Promise and it has correct interface // var NativePromise = global['Promise']; var nativePromiseSupported = NativePromise && // Some of these methods are missing from // Firefox/Chrome experimental implementations 'resolve' in NativePromise && 'reject' in NativePromise && 'all' in NativePromise && 'race' in NativePromise && // Older version of the spec had a resolver object // as the arg rather than a function (function(){ var resolve; new NativePromise(function(r){ resolve = r; }); return typeof resolve === 'function'; })(); // // export if necessary // if (typeof exports !== 'undefined' && exports) { // node.js exports.Promise = nativePromiseSupported ? NativePromise : Promise; exports.Polyfill = Promise; } else { // AMD if (typeof define == 'function' && define.amd) { define(function(){ return nativePromiseSupported ? NativePromise : Promise; }); } else { // in browser add to global if (!nativePromiseSupported) global['Promise'] = Promise; } } // // Polyfill // var PENDING = 'pending'; var SEALED = 'sealed'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function(){}; function isArray(value) { return Object.prototype.toString.call(value) === '[object Array]'; } // async calls var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout; var asyncQueue = []; var asyncTimer; function asyncFlush(){ // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) asyncQueue[i][0](asyncQueue[i][1]); // reset async asyncQueue asyncQueue = []; asyncTimer = false; } function asyncCall(callback, arg){ asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 0); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(subscriber){ var owner = subscriber.owner; var settled = owner.state_; var value = owner.data_; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch(e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) resolve(promise, value); if (settled === REJECTED) reject(promise, value); } } function handleThenable(promise, value) { var resolved; try { if (promise === value) throw new TypeError('A promises callback cannot return that same promise.'); if (value && (typeof value === 'function' || typeof value === 'object')) { var then = value.then; // then should be retrived only once if (typeof then === 'function') { then.call(value, function(val){ if (!resolved) { resolved = true; if (value !== val) resolve(promise, val); else fulfill(promise, val); } }, function(reason){ if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) reject(promise, e); return true; } return false; } function resolve(promise, value){ if (promise === value || !handleThenable(promise, value)) fulfill(promise, value); } function fulfill(promise, value){ if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason){ if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = reason; asyncCall(publishRejection, promise); } } function publish(promise) { var callbacks = promise.then_; promise.then_ = undefined; for (var i = 0; i < callbacks.length; i++) { invokeCallback(callbacks[i]); } } function publishFulfillment(promise){ promise.state_ = FULFILLED; publish(promise); } function publishRejection(promise){ promise.state_ = REJECTED; publish(promise); } /** * @class */ function Promise(resolver){ if (typeof resolver !== 'function') throw new TypeError('Promise constructor takes a function argument'); if (this instanceof Promise === false) throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); this.then_ = []; invokeResolver(resolver, this); } Promise.prototype = { constructor: Promise, state_: PENDING, then_: null, data_: undefined, then: function(onFulfillment, onRejection){ var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if (this.state_ === FULFILLED || this.state_ === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this.then_.push(subscriber); } return subscriber.then; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = function(promises){ var Class = this; if (!isArray(promises)) throw new TypeError('You must pass an array to Promise.all().'); return new Class(function(resolve, reject){ var results = []; var remaining = 0; function resolver(index){ remaining++; return function(value){ results[index] = value; if (!--remaining) resolve(results); }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') promise.then(resolver(i), reject); else results[i] = promise; } if (!remaining) resolve(results); }); }; Promise.race = function(promises){ var Class = this; if (!isArray(promises)) throw new TypeError('You must pass an array to Promise.race().'); return new Class(function(resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') promise.then(resolve, reject); else resolve(promise); } }); }; Promise.resolve = function(value){ var Class = this; if (value && typeof value === 'object' && value.constructor === Class) return value; return new Class(function(resolve){ resolve(value); }); }; Promise.reject = function(reason){ var Class = this; return new Class(function(resolve, reject){ reject(reason); }); }; })(typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : typeof self != 'undefined' ? self : this);
'use stirct'; module.exports = { Compiler: require('./Compiler') };
var tape = require("tape"), Queue = require(".."); tape("Queue: should enqueue callbacks and call all in order when notifyAll() is called", function(assert) { var queue = Queue.getPooled(), called0 = false, called1 = false; queue.enqueue(function() { called0 = true; }); queue.enqueue(function() { called1 = true; }); queue.notifyAll(); assert.equal(called0, true); assert.equal(called1, true); assert.end(); });
module.exports = function preg_grep (pattern, input, flags) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: If pass pattern as string, must escape backslashes, even for single quotes // % note 2: The regular expression itself must be expressed JavaScript style // % note 3: It is not recommended to submit the pattern as a string, as we may implement // % note 3: parsing of PHP-style expressions (flags, etc.) in the future // * example 1: var arr = [1, 4, 4.5, 3, 'a', 4.4]; // * example 1: preg_grep("/^(\\d+)?\\.\\d+$/", arr); // * returns 1: {2: 4.5, 5: 4.4} var p = '', retObj = {}; var invert = (flags === 1 || flags === 'PREG_GREP_INVERT'); // Todo: put flags as number and do bitwise checks (at least if other flags allowable); see pathinfo() if (typeof pattern === 'string') { pattern = eval(pattern); } if (invert) { for (p in input) { if (input[p].search(pattern) === -1) { retObj[p] = input[p]; } } } else { for (p in input) { if (input[p].search(pattern) !== -1) { retObj[p] = input[p]; } } } return retObj; }
var restify = require('restify'); var cb = require('./bin/Bots/BotConnectorBot') var nursebot = new cb.NurseBot(); var server = restify.createServer(); server.get('/', (req, res, next) => { res.send({ nurse: "remedi is live!", isCommandMode: nursebot.isCommandMode }); next(); }); server.post('/api/messages', nursebot.verifyBotFramework(), nursebot.listen()); server.listen(process.env.port || 3978, function () { console.log('%s listening to %s', server.name, server.url); });
var isFunction = function(obj) { return (obj && typeof obj === 'function'); } var isSemigroup = function(obj){ return isFunction(obj.empty) || isFunction(obj.constructor.empty); } var isMonoid = function(obj){ return isSemigroup(obj) && isFunction(obj.concat); } var isFunctor = function(obj){ return isFunction(obj.map); } var isApply = function(obj){ return isFunctor(obj) && isFunction(obj.ap); } var isApplicative = function(obj){ return isApply(obj) && ( isFunction(obj.of) || isFunction(obj.constructor.of) ); } var isChain = function(obj){ return isFunctor(obj) && isFunction(obj.chain); } var isMonad = function(obj){ return isChain(obj) && isApplicative(obj); } var isExtend = function(obj){ return isFunction(obj.extend); } var isComonad = function(obj){ return isExtend(obj) && ( isFunction(obj.from) || isFunction(obj.constructor.from) ); } module.exports = { isFunction : isFunction, isSemigroup : isSemigroup, isMonoid : isMonoid, isFunctor : isFunctor, isApply : isApply, isApplicative : isApplicative, isChain : isChain, isMonad : isMonad, isExtend : isExtend, isComonad : isComonad }
/** * Module dependencies. */ var fs = require('fs'); var express = require('express'); exports.boot = function(app){ bootApplication(app); bootControllers(app); }; // App settings and middleware function bootApplication(app) { app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ console.log("Running in production mode...") app.use(function(err, req, res, next){ res.render('500'); }); }); app.use(express.logger(':method :url :status')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({ secret: 'keyboard cat' })); app.use(app.router); app.use(express.static(__dirname + '/public')); // Example 404 page via simple Connect middleware app.use(function(req, res){ res.render('404', {locals: {url:'', luser: null}}); }); // Setup ejs views as default, with .html as the extension app.set('views', __dirname + '/views'); app.register('.html', require('ejs')); app.set('view engine', 'html'); // we always want a user object, campaign id and admin variable app.set('view options', { luser: null, campaignId: null, isAdmin: false, adminEmail: 'admin@yoursite.com' //TODO: make this a config setting }); // Some dynamic view helpers app.dynamicHelpers({ request: function(req){ return req; }, hasMessages: function(req){ if (!req.session) return false; return Object.keys(req.session.flash || {}).length; }, messages: function(req){ // depreciated messages function return function(){ var msgs = req.flash(); return Object.keys(msgs).reduce(function(arr, type){ return arr.concat(msgs[type]); }, []); } }, statuses: function(req) { return function() { var msgs = req.flash(); var ret = {}; ret.error = []; ret.info = []; ret.warn = []; if (msgs.error) { ret.error = msgs.error; } if (msgs.info) { ret.info = msgs.info; } if (msgs.warn) { ret.warn = msgs.warn; } return ret; } } }); // end app init } // Bootstrap controllers function bootControllers(app) { fs.readdir(__dirname + '/controllers', function(err, files){ if (err) throw err; files.forEach(function(file){ bootController(app, file); }); }); } // simple authentication support via sessions function requiresLogin(req, res, next) { if (req.session.user) { next(); } else { res.redirect('/users/validate?redir=' + req.url); } }; // Example (simplistic) controller support function bootController(app, file) { var name = file.replace('.js', ''); var actions = require('./controllers/' + name); var ending = "s"; if( name.substr(-1) === "s" ) { ending="es"; } var plural = name + ending; var prefix = '/' + plural; // Special case for "app" if (name == 'app') prefix = '/'; Object.keys(actions).map(function(action){ var isJson = actions.findJsonRoute && actions.findJsonRoute(action); var fn = controllerAction(name, plural, action, isJson, actions[action]); switch(action) { case 'index': app.get(prefix, fn); app.get(prefix + '/filter/:parentId', fn); break; case 'show': app.get(prefix + '/show/:id/*', fn); app.get(prefix + '/show/:id.:format?', fn); break; case 'add': app.get(prefix + '/add', requiresLogin, fn); app.get(prefix + '/add/:parentId', requiresLogin, fn); break; case 'create': app.post(prefix + '/create', requiresLogin, fn); break; case 'edit': app.get(prefix + '/edit/:id', requiresLogin, fn); break; case 'update': app.post(prefix + '/update/:id', requiresLogin, fn); break; case 'validate': app.get(prefix + '/validate', fn); app.post(prefix + '/validate', fn); break; case 'invalidate': app.get(prefix + '/invalidate', fn); app.post(prefix + '/invalidate', fn); break; case 'destroy': app.get(prefix + '/destroy/:id', requiresLogin, fn); break; case 'findGetRoute': // find route function is used to resolve unknown paths break; case 'findPostRoute': // find route function is used to resolve unknown paths break; case 'findJsonRoute': // find route function is used to resolve unknown paths break; case 'resolveSecurity': // TODO: stub for a security function break; default: // a function we don't know how to describe with the controller // use a generic findRoute function to tell us the path if it exists if (actions.findGetRoute && actions.findGetRoute(action)) { if (actions.findGetRoute(action)[1]) { // call with login app.get(prefix + actions.findGetRoute(action)[0], requiresLogin, fn); } else { // call without login app.get(prefix + actions.findGetRoute(action)[0], fn); } } if (actions.findPostRoute && actions.findPostRoute(action)) { if (actions.findPostRoute(action)[1]) { // call with login app.post(prefix + actions.findPostRoute(action)[0], requiresLogin, fn); } else { // call without login app.post(prefix + actions.findPostRoute(action)[0], fn); } } if (isJson) { if (actions.findJsonRoute(action)[1]) { // call with login app.get(prefix + actions.findJsonRoute(action)[0], requiresLogin, fn); } else { // call without login app.get(prefix + actions.findJsonRoute(action)[0], fn); } } break; } }); } // Proxy res.render() to add some magic function controllerAction(name, plural, action, isJson, fn) { return function(req, res, next){ var render = res.render; var format = req.params.format; var path = __dirname + '/views/' + name + '/' + action + '.html'; res.render = function(obj, options, fn){ res.render = render; // Template path if (typeof obj === 'string') { return res.render(obj, options, fn); } // Format support if (isJson) { format = 'json'; } if (format) { if (format === 'json') { return res.send(obj); } else { throw new Error('unsupported format "' + format + '"'); } } // Render template res.render = render; // make sure options is an array options = options || {}; // check for user and if they exist // add a local for all views if (req.session.user) { options['luser'] = req.session.user; } // Expose obj as the "users" or "user" local if (action == 'index') { options[plural] = obj; } else { options[name] = obj; } // always add current url to options options['url'] = req.url; return res.render(path, options, fn); }; fn.apply(this, arguments); }; }
'use strict'; var should = require('should'), request = require('supertest'), app = require('../../server'), mongoose = require('mongoose'), User = mongoose.model('User'), CostingSheet = mongoose.model('CostingSheet'), agent = request.agent(app); /** * Globals */ var credentials, user, costingSheet; /** * Costing sheet routes tests */ describe('Costing sheet CRUD tests', function() { beforeEach(function(done) { // Create user credentials credentials = { username: 'username', password: 'password' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Costing sheet user.save(function() { costingSheet = { name: 'Costing sheet Name' }; done(); }); }); it('should be able to save Costing sheet instance if logged in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Costing sheet agent.post('/costing-sheets') .send(costingSheet) .expect(200) .end(function(costingSheetSaveErr, costingSheetSaveRes) { // Handle Costing sheet save error if (costingSheetSaveErr) done(costingSheetSaveErr); // Get a list of Costing sheets agent.get('/costing-sheets') .end(function(costingSheetsGetErr, costingSheetsGetRes) { // Handle Costing sheet save error if (costingSheetsGetErr) done(costingSheetsGetErr); // Get Costing sheets list var costingSheets = costingSheetsGetRes.body; // Set assertions (costingSheets[0].user._id).should.equal(userId); (costingSheets[0].name).should.match('Costing sheet Name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save Costing sheet instance if not logged in', function(done) { agent.post('/costing-sheets') .send(costingSheet) .expect(401) .end(function(costingSheetSaveErr, costingSheetSaveRes) { // Call the assertion callback done(costingSheetSaveErr); }); }); it('should not be able to save Costing sheet instance if no name is provided', function(done) { // Invalidate name field costingSheet.name = ''; agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Costing sheet agent.post('/costing-sheets') .send(costingSheet) .expect(400) .end(function(costingSheetSaveErr, costingSheetSaveRes) { // Set message assertion (costingSheetSaveRes.body.message).should.match('Please fill Costing sheet name'); // Handle Costing sheet save error done(costingSheetSaveErr); }); }); }); it('should be able to update Costing sheet instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Costing sheet agent.post('/costing-sheets') .send(costingSheet) .expect(200) .end(function(costingSheetSaveErr, costingSheetSaveRes) { // Handle Costing sheet save error if (costingSheetSaveErr) done(costingSheetSaveErr); // Update Costing sheet name costingSheet.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update existing Costing sheet agent.put('/costing-sheets/' + costingSheetSaveRes.body._id) .send(costingSheet) .expect(200) .end(function(costingSheetUpdateErr, costingSheetUpdateRes) { // Handle Costing sheet update error if (costingSheetUpdateErr) done(costingSheetUpdateErr); // Set assertions (costingSheetUpdateRes.body._id).should.equal(costingSheetSaveRes.body._id); (costingSheetUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Costing sheets if not signed in', function(done) { // Create new Costing sheet model instance var costingSheetObj = new CostingSheet(costingSheet); // Save the Costing sheet costingSheetObj.save(function() { // Request Costing sheets request(app).get('/costing-sheets') .end(function(req, res) { // Set assertion res.body.should.be.an.Array.with.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Costing sheet if not signed in', function(done) { // Create new Costing sheet model instance var costingSheetObj = new CostingSheet(costingSheet); // Save the Costing sheet costingSheetObj.save(function() { request(app).get('/costing-sheets/' + costingSheetObj._id) .end(function(req, res) { // Set assertion res.body.should.be.an.Object.with.property('name', costingSheet.name); // Call the assertion callback done(); }); }); }); it('should be able to delete Costing sheet instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Costing sheet agent.post('/costing-sheets') .send(costingSheet) .expect(200) .end(function(costingSheetSaveErr, costingSheetSaveRes) { // Handle Costing sheet save error if (costingSheetSaveErr) done(costingSheetSaveErr); // Delete existing Costing sheet agent.delete('/costing-sheets/' + costingSheetSaveRes.body._id) .send(costingSheet) .expect(200) .end(function(costingSheetDeleteErr, costingSheetDeleteRes) { // Handle Costing sheet error error if (costingSheetDeleteErr) done(costingSheetDeleteErr); // Set assertions (costingSheetDeleteRes.body._id).should.equal(costingSheetSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete Costing sheet instance if not signed in', function(done) { // Set Costing sheet user costingSheet.user = user; // Create new Costing sheet model instance var costingSheetObj = new CostingSheet(costingSheet); // Save the Costing sheet costingSheetObj.save(function() { // Try deleting Costing sheet request(app).delete('/costing-sheets/' + costingSheetObj._id) .expect(401) .end(function(costingSheetDeleteErr, costingSheetDeleteRes) { // Set message assertion (costingSheetDeleteRes.body.message).should.match('User is not logged in'); // Handle Costing sheet error error done(costingSheetDeleteErr); }); }); }); afterEach(function(done) { User.remove().exec(); CostingSheet.remove().exec(); done(); }); });
/* * Copyright 2013 Jive Software * * 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. */ var assert = require('assert'); var test = require('../base-connector-service-test'); describe('jive', function () { describe('#test.connectorServiceTest', function () { it('test', function (done) { //run the testcase test.testConnectorService() //fail on error .catch(function (e) { assert.fail(e); }) .finally(function () { done(); }); }); }); });
module.exports = function () { return { release: { options: { version: '<%= pkg.version %>', changelog: 'CHANGELOG.md' } } }; };
try{ var mongodb = require('mongodb'); }catch(e){ console.log('MongoDB is NOT installed, please "npm install mongodb" to use this module'); throw e; } var MongoClient = mongodb.MongoClient; var ObjectId = mongodb.ObjectID; var config = require('../../lib/config.js').section('store', { connectionString: 'mongodb://localhost:27017/hapi-base' }); var utils = require('../../lib/utils'); var isNumeric = function (n) { return !isNaN(parseFloat(n)) && isFinite(n); }; var Store = module.exports = function(collectionName){ var self = this; self.collectionName = collectionName; self._opened = false; MongoClient.connect(config.connectionString, config, function(err, db){ self.db = db; self._opened = true; self.db.writeConcern = self.db.writeConcern||'majority'; }); }; var updateFilterIds = module.exports.updateFilterIds = function(root){ var keys = Object.keys(root), i, l=keys.length, key, value; for(i=0; i<l; i++){ key = keys[i]; if(key.match(/\_id$/)){ try{ root[key] = ObjectId(root[key]); }catch(e){ } }else{ switch(typeof(root[key])){ case('object'): updateFilterIds(root[key]); break; case('string'): // DateTime String: 2013-08-17T00:00:00.000Z if(root[key].match(/^\d{4}\-\d{2}\-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/i)){ root[key] = new Date(root[key]); }else{ switch(root[key].toLowerCase()){ case("$today"): root[key] = new Date(); root[key].setHours(0, 0, 0, 0); break; case("$yesterday"): root[key] = new Date(); root[key].setDate(root[key].getDate() - 1); root[key].setHours(0, 0, 0, 0); break; case("$thisweek"): root[key] = getMonday(new Date()); break; case("$thismonth"): root[key] = new Date(); root[key].setDate(1); root[key].setHours(0, 0, 0, 0); break; case("$thisyear"): root[key] = new Date(); root[key].setMonth(1); root[key].setDate(1); root[key].setHours(0, 0, 0, 0); break; } } default: } } } return root; }; Store.prototype.collection = function(callback, collectionCallback){ var self = this; if(!self._opened){ return process.nextTick(function(){ self.collection(callback, collectionCallback); }); } self.db.collection(self.collectionName, function(err, collection){ if(err){ callback(err); }else{ collectionCallback(collection); } }); }; Store.prototype.get = function(_id, callback){ var self = this; self.collection(callback, function(collection){ var filter = updateFilterIds(((typeof(_id)==='object')&&(!(_id instanceof ObjectId)))?_id:{_id: ObjectId(_id)}); collection.find(filter, function(err, cursor){ if(err){ callback(err); }else{ cursor.toArray(function(err, records){ if(err){ callback(err); }else{ var response = { root: self.collectionName }; if(records.length>1){ response = { root: self.collectionName, length: records.length, count: records.length, offset: 0, limit: records.length } response[self.collectionName] = records; }else{ response[self.collectionName] = records[0]; } callback(null, response); } }); } }); }); }; Store.prototype.insert = function(record, callback, noRetry){ var self = this; self.collection(callback, function(collection){ record._created = new Date(); collection.insert(record, self.db.writeConcern, function(err, responseRecord){ if(err&&(err.err === "norepl")&&(err.wnote === 'no replication has been enabled, so w=2+ won\'t work')){ self.insert(record, callback); }else if(err && (!noRetry) && (!!responseRecord)){ callback(null, responseRecord); }else{ callback(err, responseRecord); } }); }); }; Store.prototype.update = function(_id, record, callback){ var self = this; var findKey; if(typeof(record)==='function'){ callback = record; } if(typeof(_id)==='object' && (!_id instanceof ObjectId)){ record = _id; _id = record._id; } if(_id===void 0||_id===''||_id===false||_id===null){ _id = (record||{})._id||false; } if((!!_id)!==false){ try{ findKey = _id instanceof ObjectId?{_id: _id}:{_id: ObjectId(_id)}; }catch(e){ if(typeof(_id) === 'object'){ findKey = _id; }else{ throw e; } } }else{ findKey = utils.extend(true, {}, record.$set||record); } delete (record.$set||{})._id; delete record._id; record._updated = new Date(); self.collection(callback, function(collection){ collection.findAndModify(findKey, {$natural: -1}, record, {upsert: true, 'new': true}, function(err, srcRecord){ if(srcRecord){ try{ srcRecord._id = srcRecord._id||((!!_id)!==false)?(_id instanceof ObjectId?_id:ObjectId(_id)):null; }catch(e){ } } callback(err, srcRecord); }); }); }; Store.prototype.asArray = function(options, callback){ var self = this; self.collection(callback, function(collection){ var cursor; options.skip=parseInt(options.offset)||0; options.limit=parseInt(options.limit)||100; cursor = collection.find(options.filter, options); cursor.count(function(err, count){ cursor.toArray(function(err, arr){ var response; if(err){ return callback(err); } response = { length: arr.length, count: count, limit: options.limit||arr.length, offset: options.skip||0, root: self.collectionName, }; response[self.collectionName] = arr; callback(null, response); }); }); }); }; Store.prototype.upsert = function(key, record, callback){ var self = this; var findKey; record = utils.extend(record.$set?record:{$set: record}); if(typeof(record)==='function'){ callback = record; } if(typeof(_id)==='object' && (!_id instanceof ObjectId)){ record = _id; _id = record._id; } if(_id===void 0||_id===''||_id===false||_id===null){ _id = (record||{})._id||false; } if((!!_id)!==false){ try{ findKey = _id instanceof ObjectId?{_id: _id}:{_id: ObjectId(_id)}; }catch(e){ if(typeof(_id) === 'object'){ findKey = _id; }else{ throw e; } } }else{ findKey = utils.extend(true, {}, record.$set||record); } delete (record.$set||{})._id; delete record._id; self.collection(callback, function(collection){ collection.findAndModify(findKey, {$natural: -1}, record, {upsert: true, 'new': true}, function(err, srcRecord){ if(srcRecord){ try{ srcRecord._id = srcRecord._id||((!!_id)!==false)?(_id instanceof ObjectId?_id:ObjectId(_id)):null; }catch(e){ } } callback(err, srcRecord); }); }); }; Store.prototype.delete = function(_id, callback){ var self = this; var key = _id instanceof ObjectId?{_id: _id}:{_id: ObjectId(_id)}; self.collection(callback, function(collection){ collection.remove(key, callback); }); }; Store.prototype.ensure = function(record, callback){ var self = this; self.asArray({filter: record}, function(err, recs){ if(err){ return callback(err); } recs = recs[recs.root]; if((!recs)||recs.length==0){ self.insert(record, callback); }else{ callback(null, recs[0]); } }); };
(function () { 'use strict'; angular .module('colleges') .run(menuConfig); menuConfig.$inject = ['menuService']; function menuConfig(menuService) { menuService.addMenuItem('topbar', { title: 'تسجيل الكليات', state: 'colleges', type: 'dropdown', roles: ['*'] }); // Add the dropdown list item menuService.addSubMenuItem('topbar', 'colleges', { title: 'قائمة الكليات', state: 'colleges.list' }); // Add the dropdown create item menuService.addSubMenuItem('topbar', 'colleges', { title: 'إضافة كلية', state: 'colleges.create', roles: ['user'] }); menuService.addSubMenuItem('topbar', 'colleges', { title: 'عرض تجريبي للكليات', state: 'colleges.show', roles: ['user'] }); } }());
export const CHANGE = 'change'; export const CLICK = 'click'; export var viewEventTypes = [CHANGE, CLICK].join(' ');
import React from "react"; import cn from "classnames"; import { Link } from "react-router"; export const NewsViewSidebar = ({ articleSources, onSourceSelect, }) => ( <aside className="NewsViewSidebar"> <div className="NewsViewSidebar__inner"> <header className="NewsViewSidebar__header"> <h1 className="NewsViewSidebar__header__h1"> Muchnews </h1> </header> <nav className="NewsViewSidebar__sources"> <ul className="NewsViewSidebar__sources__list"> {articleSources.map(articleSource => <li className="NewsViewSidebar__sources__item" onClick={() => onSourceSelect(articleSource.id)}> {articleSource.name} </li> )} </ul> </nav> </div> </aside> ); NewsViewSidebar.propTypes = { articleSources: React.PropTypes.array.isRequired, }; export default NewsViewSidebar;
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ /** * @ignore */ ccs.VERSION_COMBINED = 0.30; ccs.VERSION_CHANGE_ROTATION_RANGE = 1.0; ccs.VERSION_COLOR_READING = 1.1; ccs.MAX_VERTEXZ_VALUE = 5000000.0; ccs.ARMATURE_MAX_CHILD = 50.0; ccs.ARMATURE_MAX_ZORDER = 100; ccs.ARMATURE_MAX_COUNT = ((ccs.MAX_VERTEXZ_VALUE) / (ccs.ARMATURE_MAX_CHILD) / ccs.ARMATURE_MAX_ZORDER); ccs.AUTO_ADD_SPRITE_FRAME_NAME_PREFIX = false; ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT = false; ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX = false; /** * Returns the version of Armature. * @returns {string} */ ccs.armatureVersion = function(){ return "v1.1.0.0"; };
var buildify = require('buildify'); buildify() .load('src/impress.js') .concat(['src/lib/gc.js']) .concat(['src/plugins/autoplay/autoplay.js', 'src/plugins/blackout/blackout.js', 'src/plugins/extras/extras.js', 'src/plugins/form/form.js', 'src/plugins/goto/goto.js', 'src/plugins/help/help.js', 'src/plugins/mobile/mobile.js', 'src/plugins/mouse-timeout/mouse-timeout.js', 'src/plugins/navigation/navigation.js', 'src/plugins/navigation-ui/navigation-ui.js', 'src/plugins/progress/progress.js', 'src/plugins/rel/rel.js', 'src/plugins/resize/resize.js', 'src/plugins/skip/skip.js', 'src/plugins/stop/stop.js', 'src/plugins/touch/touch.js', 'src/plugins/toolbar/toolbar.js']) .save('js/impress.js') .uglify() .save('js/impress.min.js');
//main server code that sends everything out to other code paths //is launched by the Procfile locally 'use strict' const express = require('express'); const bodyParser = require('body-parser'); var mongoose = require('mongoose'); const app = express(); const fb= require('./fb.js'); const db= require('./db.js'); const game= require('./game.js'); //"process.env.*" pulls from the environment variables. these are set on heroku's site //locally they are contained in the ".env" file const token = process.env.PAGE_ACCESS_TOKEN; const verify_token = process.env.VERIFY_TOKEN; app.set('port', (process.env.PORT || 3000)); //connect to the mlab mongo database //all the database specific code lives in "db.json" //and is referenced through the db object, created above db.connect(); // Parse application/json app.use(bodyParser.json()); // Parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: false})); // Root get via http app.get('/', function (req, res) { res.send('<h1>This is a Facebook Messenger bot</h1>'); }); // Facebook verification app.get('/webhook/', verification); // Post data from Facebook Messenger app.post('/webhook/', webhookListener); // Server listener app.listen(app.get('port'), function() { console.log('Facebook Messenger server started on port', app.get('port')); }); function verification(req, res) { if (req.query['hub.verify_token'] === verify_token) { res.send(req.query['hub.challenge']); } res.send('Error, wrong token'); } // Facebook webhook listener for Incoming msgs. This is where the ICMs (incoming messages) arrive and are parsed accordingly function webhookListener(req, res) { console.log("Got ICM"); if (!req.body || !req.body.entry[0] || !req.body.entry[0].messaging) return console.error("no entries on received body"); let messaging_events = req.body.entry[0].messaging; for (let messagingItem of messaging_events) { let user_id = messagingItem.sender.id; //HERE - this is the key function. It sends out the info to see if we have //a user. if not it will make a new user. either way it will pass the //message and the user info to the game.parseIncoming callback function //where the game logic code decides what to do db.getUserById(user_id, messagingItem, game.parseIncoming); } res.sendStatus(200); }
/*globals describe, it, beforeEach, afterEach */ var assert = require("assert"), path = require("path"), describeReporting = require("./helpers.js").describeReporting; describeReporting(path.join(__dirname, "../"), ["html", "templates"], function (reporter) { describe('reporter', function () { it('should render html', function (done) { reporter.render({ template: { content: "Hey", engine: "handlebars", recipe: "html" } }).then(function(resp) { assert.equal("Hey", resp.result); done(); }).catch(done); }); it('should call before render and after render listeners', function (done) { var listenersCall = []; reporter.beforeRenderListeners.add("test", this, function() { listenersCall.push("before"); }); reporter.afterRenderListeners.add("test", this, function() { listenersCall.push("after"); }); reporter.render({ template: { content: "Hey", engine: "handlebars", recipe: "html" } }).then(function(resp) { assert.equal(listenersCall[0], "before"); assert.equal(listenersCall[1], "after"); done(); }).catch(done); }); it('should parse string request.data into json', function (done) { reporter.render({ template: { content: "{{{a}}}", engine: "handlebars", recipe: "html" }, data: "{ \"a\":\"1\" }" }).then(function(resp) { assert.equal("1", resp.result); done(); }); }); it('getEngines should return some engines', function (done) { reporter.getEngines().then(function(res) { assert.equal(true, res.length > 0); done(); }).catch(done); }); }); });
'use strict'; module.exports = function (N, apiPath) { N.validate(apiPath, { settings: { type: 'object', required: true } }); N.wire.on(apiPath, async function global_settings_update(env) { let settings = {}; for (let [ name, value ] of Object.entries(env.params.settings)) { settings[name] = { value }; } try { await N.settings.getStore('global').set(settings, {}); } catch (err) { throw { code: N.io.BAD_REQUEST, message: String(err) }; } }); };
version https://git-lfs.github.com/spec/v1 oid sha256:9a834fdc93d5b0edf085e932a5c907818cc83d28443f2b73bf13b898693f574b size 142
'use strict'; const gulp = require('gulp'); const connect = require('gulp-connect'); const open = require('gulp-open'); const browserify = require('browserify'); const reactify = require('reactify'); const source = require('vinyl-source-stream'); const babelify = require("babelify"); const config = { port: 9005, devBaseUrl: 'http://localhost', paths: { html: './src/*.html', js: './src/**/*.js', images: './src/images/*', dist: './dist' } }; gulp.task('connect', () => { connect.server({ root: ['dist'], port: config.port, base: config.devBaseUrl, livereload: true }); }); gulp.task('open', ['connect'], () => { gulp.src('dist/index.html') .pipe(open({ uri: config.devBaseUrl + ':' + config.port })); }); gulp.task('html', () => { gulp.src(config.paths.html) .pipe(gulp.dest(config.paths.dist)) .pipe(connect.reload()); }); gulp.task('js', () => { browserify('./src/main.js') .transform(babelify, {presets: ['es2015', 'react']}) .bundle() .on("error", function (err) { console.log("Error: " + err.message); }) .pipe(source('bundle.js')) .pipe(gulp.dest(config.paths.dist + '/scripts/')) .pipe(connect.reload()); }); gulp.task('image', () => { gulp.src(config.paths.images) .pipe(gulp.dest(config.paths.dist + '/images')) .pipe(connect.reload()) }); gulp.task('watch', () => { gulp.watch(config.paths.html, ['html']); gulp.watch(config.paths.js, ['js']); }); gulp.task('default', ['html', 'js', 'image', 'open', 'watch']);
var Method = require('aeolus').Method; var hello = new Method(); hello.handle(function(request, response) { var object = { message: "Performed PUT on /hello", data: request.getBody() || "No body on the request." }; response.respondJSON(object); }); module.exports = hello;
var hue = require("node-hue-api"), async = require('async'), dash_button = require('node-dash-button'), HueApi = hue.HueApi, lightState = hue.lightState; var host = "192.168.1.1", username = "354ccffd2126c1475d855b923845163", api = new HueApi(host, username), offDash = dash_button("10:ae:60:02:8d:66"), onDash = dash_button("74:75:48:f8:d0:c8"); /* Display Helper */ var displayResult = function(result) { console.log(JSON.stringify(result, null, 2)); }; /* Turn off all lights in a list. */ var turnOffAllLight = function(result){ //turn them off. var state = lightState.create().off(); //setup queue var q = async.queue(function (light, callback) { api.setLightState(light.id, state, callback); }, 3); //add to queue result.lights.forEach(function(light){ q.push(light); }); //drain queue q.drain = function() { console.log('all lights are off'); } } //when press detected, turns off all the lights offDash.on("detected", function (){ api.lights().then(turnOffAllLight).done(); }); onDash.on("detected", function (){ var state = lightState.create().on().brightness(50); api.setLightState(10, state, function(result){ console.log("Bedroom lights on"); }); });
import { useContext } from 'react' import Context from './Context' export { default as withStorage } from './with.js' export { default } from './Provider.js' export function useStorage() { return useContext(Context) }
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import { Setting, Star, Forward, Back, Reload } from '../icons' import Input from './input' import { load } from '../../actions' import './navigator.css' const handleSubmit = dispatch => event => { event.preventDefault() return dispatch(load()) } const Navigator = ({ url, isInputFocus, input, dispatch }) => ( <div className="nav"> <a> <Back /> </a> <a> <Forward /> </a> <a> <Reload /> </a> <form onSubmit={handleSubmit(dispatch)} className={classNames({ active: isInputFocus, })} > <Input {...{ url, isInputFocus, input, dispatch }} /> <Star /> </form> <a> <Setting /> </a> </div> ) Navigator.propTypes = { url: PropTypes.string.isRequired, isInputFocus: PropTypes.bool.isRequired, input: PropTypes.string.isRequired, dispatch: PropTypes.func.isRequired, } export default Navigator
'use strict'; module.exports = { url:"http://readly.io", db: process.env.MONGOHQ_URL, app: { name: "Readly.io" }, embedlyKey: process.env.EMBEDLY_KEY, redis: process.env.REDISTOGO_URL, mail: { service: "SendGrid", auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD } }, facebook: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/facebook/callback" }, twitter: { clientID: process.env.TWITTER_CONSUMER_KEY, clientSecret: process.env.TWITTER_CONSUMER_SECRET, callbackURL: "http://readly.io/auth/twitter/callback" }, github: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/github/callback" }, google: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/google/callback" } }
// Routes.js - Used to var Pokedex = require('./models/pokedex'); module.exports = function(app) { // All functionality for API routing e.g. app.get()... };
var Man = function() { var pub = this; pub.x = 30; pub.y = 50; var element; var health = 100; pub.name = 'Man'; pub.create = function() { element = $("<img>").attr("src", "img/running-man.jpg").attr('width', '30').appendTo("#container"); }; pub.render = function() { console.log('w: ' + health/10 + ' rgb(' + (100-health) + '%,' + health + '%, 0%)'); element.css({top: pub.y, left: pub.x, 'border-bottom': 5 + ' solid rgb(' + (100-health) + '%,' + health + '%, 0%)'}); }; var dispose = function() { element.remove(); towers.removeObject(pub); }; pub.on = function(event) { if ('tick' === event) { pub.x += 10; //pub.y = 50 + 2 * Math.sin(pub.x); pub.y += 5; pub.render(); } else if ('hit' === event) { health -= 4; if (health <= 0) { alert('shit!'); dispose(); } } }; };
/** * Templates/Extensions manager. Powered by MEAN stack * * @link http://github.com/nghuuphuoc/templatemanager * @author http://twitter.com/nghuuphuoc */ var // Environment env = process.env.NODE_ENV || 'development', express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server, { log: env == 'development' }), // Load configuration config = require('./config/config')[env]; // Connect DB var mongoose = require('mongoose'); mongoose.connect(config.db); // Load models var modelsPath = __dirname + '/app/models', fs = require('fs'); fs.readdirSync(modelsPath).forEach(function(file) { if (~file.indexOf('.js')) { require(modelsPath + '/' + file); } }); // Express settings require('./config/express')(app, config); // Load routes require('./config/routes')(app); // View helpers app.locals({ url: require('./app/helpers/url'), downloadable: require('./app/helpers/downloadable') }); var socketConnections = {}; io.sockets.on('connection', function(socket) { socket.on('userName', function(userName) { if (userName) { socketConnections[userName] = socket; app.set('socketConnections', socketConnections); } }); }); // Listening var port = process.env.PORT || 3000; server.listen(port); console.log('Start on port ' + port); module.exports = app;
({ // FIXME: move to netzke netzkeShowMessageBox( title, msg, additionalAttrs = {}, replaceNewlinesWithBr = true ) { const message = replaceNewlinesWithBr ? msg.replace(/(?:\r\n|\r|\n)/g, "<br>") : msg; Ext.MessageBox.show( Object.assign( { title, msg: message, buttons: Ext.Msg.OK }, additionalAttrs ) ); } });
Template.chapterList.events({ 'submit form': function (event) { event.preventDefault(); var chapterTitle = event.target.chaptertitle.value; Chapters.insert({title: chapterTitle}); }, 'click .list-group-item': function() { Bender.go('chapterQuestions', { chapterId: this._id }, { animation: 'slideLeft' }); } }); Template.chapterList.helpers({ numberOfQuestions: function () { return Questions.find({chapterId: this._id}).count(); }, numberOfCorrectQuestions: function () { return Questions.find({chapterId: this._id, status: 2}).count(); } });
/** * @file salt命令 * @author r2space@gmail.com * @module light.core.remote.salt * @version 1.0.0 */ "use strict"; var exec = require("child_process").exec , util = require("util") , fs = require("fs") , async = require("async"); // TODO Epel源改为自己的源,然后从定向到Epel var REPOS = "http://ftp.linux.ncsu.edu/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm"; /** * 安装minion,并启动服务 * 一条命令安装参照 https://github.com/saltstack/salt-bootstrap * 服务器需要密码方式访问,需要使用sshpass命令 * 服务器需要秘钥方式访问, * @param {String} master salt-master服务器 * @param {String} host 安装minion的服务器 * @param {String} param 密码,或键文件 * @param {Function} callback */ exports.minion = function(master, host, param, callback) { // bootstrap有BUG,所以采用手动安装 var bootstrap = "curl -L https://bootstrap.saltstack.com/develop | sh -s -- git develop" , addEpelRepos = "rpm -Uvh " + REPOS , installMinion = "yum install salt-minion -y" , addMasterName = "echo 'master: salt' >> /etc/salt/minion" , setMasterHost = "echo '" + master + " salt' >> /etc/hosts" , startMinion = "service salt-minion start" ; var isKeyFile = fs.existsSync(param); async.eachSeries([addEpelRepos, installMinion, addMasterName, setMasterHost, startMinion], function(cmd, loop) { var command = undefined; if (isKeyFile) { command = util.format("ssh -i %s root@%s '%s'", param, host, cmd); } else { command = util.format("sshpass -p %s ssh root@%s '%s'", param, host, cmd); } console.log(command); exec(command, function (error, stdout) { console.log(error); console.log(stdout); loop(error, stdout); }); }, function(error) { callback(error); }); }; /** * 安装salt-master * @param host * @param param * @param callback */ exports.master = function(host, param, callback) { var addRepos = "rpm -Uvh " + REPOS , installMaster = "yum install salt-master -y" , startMaster = "service salt-master start"; var isKeyFile = fs.existsSync(param); async.eachSeries([addRepos, installMaster, startMaster], function(cmd, loop) { var command = undefined; if (isKeyFile) { command = util.format("ssh -i %s root@%s '%s'", param, host, cmd); } else { command = util.format("sshpass -p %s ssh root@%s '%s'", param, host, cmd); } console.log(command); exec(command, function (error, stdout) { console.log(error); console.log(stdout); loop(error, stdout); }); }, function(error) { callback(error); }); }; /** * 接受minion的托管请求 * @param minion * @param callback */ exports.accepte = function(minion, callback) { var command = "salt-key -a " + minion; console.log(command); exec(command, function (error, stdout) { console.log(error); console.log(stdout); callback(error, stdout); }); };
/* globals obis, store */ // // HSBC UK plugin entry-point // import { actions } from '@/obis/actions' import { LEAVE_UNCHANGED } from '@/obis/store' import { generateIdForTransaction } from '@/obis/generators' import { fetchAccounts } from './api/accounts' import { fetchStatementsList } from './api/statements' import { fetchTransactions } from './api/transactions' import { map, onlyFulfilled } from './helpers' import { makePromisePool } from '@/cjs/promises' // const getYears = compose( // $ => [...new Set($)], // map(date => { // const [year, , day] = date.split('-') // return `${year}::${day}` // }) // ) const liveHost = 'https://www.hsbc.co.uk' function getHost() { return '' } const pool = makePromisePool(3) obis.makePluginAvailable('hsbc-uk-new-api', () => { const fetcher = obis.fetchMachine const { messages } = obis.deps const { emit } = messages const updateProgressBar = max => value => emit(actions.ui.UPDATE_PROGRESS_BAR, { max, value }) fetcher.performTransitions({ // // Accounts // 'idle -> getting-accounts': { on: actions.get.ACCOUNTS, then: requestedYearsToDownload => fetchAccounts() .then(accountsResponse => { // // Update store // const accountsUpdate = accountsResponse.map(accountResponse => { const [sortCode, accountNumber] = accountResponse.sortCodeAndAccountNumber.split(' ') return { id: accountResponse.id, accountNumber: accountNumber, sortCode: sortCode, name: accountResponse.accountHolderName, type: accountResponse.productCode, ledgerBalance: Math.round(accountResponse.ledgerBalance * 100), lastUpdatedTimestamp: new Date( accountResponse.lastUpdatedDate ).getTime(), iban: LEAVE_UNCHANGED, bic: LEAVE_UNCHANGED } }) emit(actions.add.ACCOUNTS, accountsUpdate) emit(actions.got.ACCOUNTS, { accountsResponse, yearsToDownload: requestedYearsToDownload }) }) .catch(fetcher.Emit(actions.error.ACCOUNTS)) }, 'getting-accounts -> found-accounts': { on: actions.got.ACCOUNTS, then: ({ accountsResponse, yearsToDownload }) => { // // Build next query // const statementsQueries = accountsResponse.map(accountResponse => ({ host: getHost(), accountId: accountResponse.id, productCategoryCode: accountResponse.productCategoryCode })) emit(actions.get.STATEMENTS, { statementsQueries, yearsToDownload }) } }, 'getting-accounts -> failed-accounts': { on: actions.error.ACCOUNTS, then: fetcher.Enter('idle') }, // // Statements list // 'found-accounts -> getting-statements': { on: actions.get.STATEMENTS, then: ({ statementsQueries, yearsToDownload }) => { const progress = updateProgressBar(statementsQueries.length) progress(0) const fetchStatementsJobs = statementsQueries.map( (statementsQuery, idx) => { const { accountId, productCategoryCode } = statementsQuery return pool(() => { progress(idx + 1) return fetchStatementsList(statementsQuery).then( map(statementsResponse => { const { endDate, accountNumber: mashed } = statementsResponse const [, sortCode1, sortCode2, sortCode3, accountNumber] = mashed.match(/^(\d{2})(\d{2})(\d{2})(\d{8})$/) const sortCode = `${sortCode1}-${sortCode2}-${sortCode3}` return { // // We're only actually interested in the endDate, not // the statement-ids. Requesting transactions requires // only the account-id + a date range. // id: statementsResponse.id, accountId, sortCode, accountNumber, productCategoryCode, endDate } }) ) }) } ) Promise.allSettled(fetchStatementsJobs) .then(onlyFulfilled) .then(allAcctStatements => { const allStatements = allAcctStatements.flat() if (allStatements.length === 0) { fetcher.emit(actions.error.STATEMENTS) return } // // Update store // const statementsUpdate = allStatements.map( ({ id, accountId, endDate: endDateString }) => { const endDate = new Date(endDateString) const startDate = new Date(endDate) startDate.setMonth(startDate.getMonth() - 1) return { id, accountId, endDate: endDate.getTime(), startDate: startDate.getTime(), startBalance: LEAVE_UNCHANGED, endBalance: LEAVE_UNCHANGED } } ) emit(actions.add.STATEMENTS, statementsUpdate) emit(actions.got.STATEMENTS, { allStatements, yearsToDownload }) }) } }, 'getting-statements -> found-statements': { on: actions.got.STATEMENTS, then: ({ allStatements, yearsToDownload }) => { // // Build next query // const accountsTransactionsQueries = allStatements.map( ({ id, accountId, endDate: endDateString, productCategoryCode }) => { const endDate = new Date(endDateString) const startDate = new Date(endDate) startDate.setMonth(startDate.getMonth() - 1) return { host: getHost(), id, accountId, productCategoryCode, transactionStartDate: startDate.toISOString().split('T')[0], transactionEndDate: endDate.toISOString().split('T')[0] } } ) emit(actions.get.ENTRIES, { accountsTransactionsQueries, yearsToDownload }) } }, 'getting-statements -> failed-statements': { on: actions.error.STATEMENTS, then: fetcher.Enter('idle') }, // // Transactions // 'found-statements -> getting-entries': { on: actions.get.ENTRIES, then: ({ accountsTransactionsQueries, yearsToDownload }) => { const progress = updateProgressBar(accountsTransactionsQueries.length) progress(0) const fetchAccountsTransactionsJobs = accountsTransactionsQueries.map( (query, idx) => { const { id, accountId } = query return pool(() => { progress(idx + 1) return fetchTransactions(query).then( map(transaction => ({ accountId, statementId: id, ...transaction })) ) }) } ) Promise.allSettled(fetchAccountsTransactionsJobs) .then(onlyFulfilled) .then(allTransactionsInAccount => { const allTransactions = allTransactionsInAccount.flat() if (allTransactions.length === 0) { fetcher.emit(actions.error.ENTRIES) return } // // Update store // allTransactions.map(transaction => { const { date, debit, credit, type, payee, note } = transaction const { accountNumber, sortCode } = store().accounts.find( acct => acct.id === transaction.accountId ) return Object.assign(transaction, { id: generateIdForTransaction({ date, debit, credit, accountNumber, sortCode, type, payee, note }) }) }) emit(actions.add.ENTRIES, allTransactions) emit(actions.got.ENTRIES) }) } }, 'getting-entries -> found-entries': { on: actions.got.ENTRIES, then: () => {} }, 'getting-entries -> failed-entries': { on: actions.error.ENTRIES, then: fetcher.Enter('idle') }, // // Downloading // 'found-entries -> download-all': { on: actions.ui.DOWNLOAD_STATEMENTS, then: () => {} }, 'download-all -> found-entries': { on: actions.ui.DOWNLOADED_STATEMENTS, then: () => {} } }) fetcher.onTransitions({ // // Flag a problem // [` failed-accounts | failed-statements | failed-entries -> idle `]: () => { console.warn('Problem fetching data. Please try again.') } }) fetcher.info() })
'use strict'; // From https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md // Test via a getter in the options object to see if the passive property is accessed var opts; var supportsPassive = false; try { opts = Object.defineProperty({}, 'passive', { get: function () { supportsPassive = true; } }); window.addEventListener('testPassive', null, opts); window.removeEventListener('testPassive', null, opts); } catch (e) { // ignore errors } module.exports = supportsPassive;
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: { dist: { src: ['dist'] } }, copy: { dist: { files: [ { expand: true, cwd: 'src/', src: '**', dest: 'dist/' }, { src: 'package.json', dest: 'dist/' }, { src: 'README.md', dest: 'dist/' }, { src: 'LICENSE', dest: 'dist/' } ] } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('default', ['clean:dist', 'copy:dist']); }
import { uuid } from 'utils/utils'; export function remoteToState(remote = []) { return remote.reduce((acc, redirection) => { const { Description: label, Expression: condition, IfTrue: cible } = redirection; const id = redirection.id || uuid(); return { ...acc, [id]: { id, label, condition, cible } }; }, {}); } export function stateToRemote(state) { return Object.keys(state).map(key => { const { id, label: Description, condition: Expression, cible: IfTrue } = state[key]; return { id, Description, Expression, IfTrue }; }); }
// Pull in fractal const fractal = require('./fractal.js'); const logger = fractal.cli.console; // Gulpy gulp const gulp = require('gulp'); const autoprefixer = require('gulp-autoprefixer'); const babel = require('gulp-babel'); const buffer = require('vinyl-buffer'); const browserify = require('browserify'); const concat = require('gulp-concat'); const del = require('del'); const eslint = require('gulp-eslint'); const fs = require('fs'); const glob = require('glob'); const replace = require('gulp-replace'); const rename = require('gulp-rename'); const sass = require('gulp-sass'); const sassLint = require('gulp-sass-lint'); const source = require('vinyl-source-stream'); const sourcemaps = require('gulp-sourcemaps'); const surge = require('gulp-surge'); const svgmin = require('gulp-svgmin'); const svgsymbols = require('gulp-svg-symbols'); const uglify = require('gulp-uglify'); // Paths const paths = { src: `${__dirname}/src/`, tmp: `${__dirname}/tmp/`, build: `${__dirname}/www/`, dist: `${__dirname}/dist/` }; // Deploy location: const surgeURL = 'https://vam-design-guide.surge.sh'; // Empty temp folders function clean() { return del([`${paths.tmp}`, `${paths.build}`]); } // Setup a local server function serve() { const server = fractal.web.server({ sync: true }); server.on('error', err => logger.error(err.message)); return server.start().then(() => { logger.success(`Fractal online at: ${server.url}`); }); } // Create a static build of fractal // Build location defined in `fractal.js` function staticBuild() { const builder = fractal.web.builder(); builder.on('progress', (completed, total) => logger.update(`Exported ${completed} of ${total} items`, 'info')); builder.on('error', err => logger.error(err.message)); return builder.build().then(() => { logger.success('Fractal build complete'); }); } // Deploy to surge function deploy() { return surge({ project: paths.build, domain: surgeURL }); } // Style function styles() { // Look at replacing a lot of this with postCSS return gulp.src(`${paths.src}/assets/styles/*.scss`) .pipe(sourcemaps.init()) .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError)) .pipe(autoprefixer()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(`${paths.tmp}/assets/styles`)); } // Fonts function fonts() { return gulp.src(`${paths.src}/assets/fonts/**/*`) .pipe(gulp.dest(`${paths.tmp}/assets/fonts`)); } // Scripts const opts = { transform: [ ["babelify", { presets: ["es2015"], plugins: ["transform-class-properties"] } ], ], debug: true }; const newBundle = entry => { opts.entries = entry; let b = browserify(opts); const rebundle = () => { b.bundle() .on('error', swallowError) .pipe(source(entry)) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(rename('vamscript.js')) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(`${paths.tmp}/assets/scripts`)); } return rebundle(); } function scripts() { gulp.src(`${paths.src}/assets/scripts/precompiled/*.js`) .pipe(gulp.dest(`${paths.tmp}/assets/scripts`)); glob(`${paths.src}/assets/scripts/*.js`, function(err, files) { var tasks = files.map(function(entry) { newBundle(entry); }); }); return gulp.src('package.json'); } function swallowError (error) { console.log(error.toString()) this.emit('end') } // SVG Icons function svg() { return gulp.src(`${paths.src}/assets/svg/*.svg`) .pipe(svgmin()) .pipe(svgsymbols({ svgClassname: 's-svg-icon', templates: [`${paths.src}/assets/templates/svg-template.svg`], title: false, })) .pipe(gulp.dest(`${paths.tmp}/assets/svg`)); } function releaseCSS() { return gulp.src(`${paths.tmp}/assets/styles/vam-style.css*`) .pipe(gulp.dest(`${paths.dist}/css`)); } // Prepare for release function releaseSVG() { return gulp.src(`${paths.tmp}/assets/svg/*.svg`) .pipe(rename('vamicons.svg')) .pipe(gulp.dest(`${paths.dist}/svg`)); } let vamIcons = ''; function readVamIcons() { fs.readFile(`${paths.dist}/svg/vamicons.svg`, 'utf8', (err, data) => { vamIcons = data; }); return gulp.src('package.json'); } function releaseJS() { return gulp.src(`${paths.tmp}/assets/scripts/*.js*`) .pipe(replace(/\\n\s*/g, '')) .pipe(replace(/\>\<use [^#]+\/svg-template.svg#([^"]+)"\>\<\/use\>\<\//g, (match, p1, offset, string) => { const re = new RegExp(`\<symbol( id="${p1}".+)symbol\>`); const match2 = vamIcons.match(re); if (match2) { const svg = match2[1]; return svg.replace(/\<title[^\<]+\<\/title\>/g, ''); } })) .pipe(gulp.dest(`${paths.dist}/scripts`)); } // Linters function sassLinter() { return gulp.src(`${paths.src}/**/*.scss`) .pipe(sassLint()) .pipe(sassLint.format()) .pipe(sassLint.failOnError()); } function jsLinter() { return gulp.src(`${paths.src}/**/*.js`) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); } // Watch function watch() { serve(); gulp.watch(['src/assets/**/*.scss', 'src/components/**/*.scss'], styles); gulp.watch(['src/assets/**/*.js', 'src/components/**/_*.js'], scripts); gulp.watch('src/assets/svg/*.svg', svg); gulp.watch('src/assets/fonts', fonts); } const compile = gulp.series(clean, gulp.parallel(fonts, svg, styles, scripts)); const buildDistAssets = gulp.parallel(releaseCSS, gulp.series(releaseSVG, readVamIcons, releaseJS)); const linter = gulp.series(sassLinter, jsLinter); gulp.task('dev', gulp.series(compile, watch)); gulp.task('build', gulp.series(linter, compile, buildDistAssets, staticBuild)); gulp.task('dist', gulp.series(linter, compile, buildDistAssets, staticBuild, deploy, clean)); gulp.task('lint', gulp.series(linter));
var framework = require('./../../../framework'); var GeneratorService = module.exports = function GeneratorService() { }; framework.inheritService(GeneratorService); GeneratorService.prototype.postRegister = function() { var self = this; setInterval(function() { self.rpc('valueGenerated', {value: Math.random()}); }, 1000); };
////////////////////////////// // Sass Lint // - A Gulp Plugin // // Lints Sass files ////////////////////////////// 'use strict'; ////////////////////////////// // Variables ////////////////////////////// var through = require('through2'), gutil = require('gulp-util'), lint = require('sass-lint'), path = require('path'), PluginError = gutil.PluginError, PLUGIN_NAME = 'sass-lint'; ////////////////////////////// // Export ////////////////////////////// var sassLint = function (options) { options = options || {}; var compile = through.obj(function (file, encoding, cb) { if (file.isNull()) { return cb(); } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } file.sassLint = [lint.lintText({ 'text': file.contents, 'format': path.extname(file.path).replace('.', ''), 'filename': path.relative(process.cwd(), file.path) }, options)]; this.push(file); cb(); }); return compile; } sassLint.format = function () { var compile = through.obj(function (file, encoding, cb) { if (file.isNull()) { return cb(); } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } var result = lint.format(file.sassLint); if (result) { console.log(result); } this.push(file); cb(); }); return compile; } sassLint.failOnError = function () { var compile = through.obj(function (file, encoding, cb) { if (file.isNull()) { return cb(); } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } if (file.sassLint[0].errorCount > 0) { this.emit('error', new PluginError(PLUGIN_NAME, file.sassLint[0].errorCount + ' errors detected in ' + file.relative)); return cb(); } this.push(file); cb(); }); return compile; } module.exports = sassLint;
(function() { $.simpleWeather({ location: 'Berlin, Germany', woeid: '', unit: 'c', success: function(weather) { var temp = '<h2 class="title">' + weather.temp + '&deg;' + weather.units.temp + '</h2>', weat = '<i class="icon icon-' + weather.code + '">' + '</i>', loc = weather.city + ', ' + weather.region + ' (' + weather.country + ')'; $('#weather').html(temp + weat); $('#loc').html(loc); } }) })()
import React, { Component, Fragment, useEffect, useState, useRef } from 'react'; import dracula from 'prism-react-renderer/themes/dracula'; import CountUp, { useCountUp } from 'react-countup'; import { description, repository } from 'react-countup/package'; import { RotateCw } from 'react-feather'; import GithubCorner from 'react-github-corner'; import { LiveProvider, LiveEditor, LiveError, LivePreview } from 'react-live'; import styled from 'styled-components'; const RefreshButton = styled.button` background: none; border: none; color: slategray; opacity: 0.5; outline: none; padding: 0; position: absolute; right: 16px; top: 16px; transition: 0.2s; width: 16px; &:hover { opacity: 1; } `; const Error = styled(LiveError)` background: palevioletred; color: white; grid-column: span 2; padding: 16px; `; class Example extends Component { refresh = () => this.forceUpdate(); render() { const { children, code, title, ...rest } = this.props; return ( <Fragment> <Fragment> <Subtitle>{title}</Subtitle> <Provider scope={{ CountUp, useCountUp, useState, useRef, useEffect }} code={code.trim()} theme={dracula} {...rest} > <LiveEditor /> <RefreshButton onClick={this.refresh} title="Re-render"> <RotateCw size={16} /> </RefreshButton> <Preview /> <Error /> </Provider> {children} </Fragment> </Fragment> ); } } const Footer = styled.footer` border-top: 2px solid whitesmoke; margin-top: 64px; padding-top: 16px; `; const Main = styled.main` font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; margin: 32px auto; max-width: 960px; `; const Preview = styled(LivePreview)` align-items: center; background: whitesmoke; display: flex; justify-content: center; min-height: 64px; padding: 16px; & div { align-items: center; display: flex; flex-direction: column; } & span { display: flex; justify-content: center; } & button { background: white; border: none; border-radius: 4px; box-shadow: 0 4px 8px gainsboro; display: block; font-family: inherit; font-size: inherit; margin: 16px 0 auto; outline: none; padding: 8px 32px; &:active { transform: translateY(2px); } &:hover { background: snow; } } `; const Provider = styled(LiveProvider)` border-radius: 8px; box-shadow: 0 4px 8px gainsboro; overflow: hidden; display: grid; grid-template-columns: repeat(2, 50%); position: relative; `; const Subtitle = styled.h2` margin-top: 2em; `; const Text = styled.p``; const Title = styled.h1``; const simple = `<CountUp end={123457} />`; const accessibility = ` () => { const [loading, setLoading] = React.useState(false); const onStart = () => {setLoading(true)}; const onEnd = () => {setLoading(false)}; const containerProps = { 'aria-busy': loading }; return <CountUp end={123457} duration="3" onStart={onStart} onEnd={onEnd} containerProps={containerProps} /> } `; const renderProp = ` <CountUp className="account-balance" start={-875.039} end={160527.012} duration={2.75} separator=" " decimals={4} decimal="," prefix="EUR " suffix=" left" onEnd={() => console.log('Ended! 👏')} onStart={() => console.log('Started! 💨')} > {({ countUpRef, start }) => ( <div> <span ref={countUpRef} /> <button onClick={start}>Start</button> </div> )} </CountUp> `; const manualStart = ` <CountUp start={0} end={100}> {({ countUpRef, start }) => ( <div> <span ref={countUpRef} /> <button onClick={start}>Start</button> </div> )} </CountUp> `; const autoStart = ` <CountUp start={0} end={100} delay={0}> {({ countUpRef }) => ( <div> <span ref={countUpRef} /> </div> )} </CountUp> `; const delayStart = ` <CountUp delay={2} end={100} /> `; const hook = ` () => { const { start, pauseResume, reset, update } = useCountUp({ ref: "counter", start: 0, end: 1234567, delay: 2, duration: 5, onReset: () => console.log('Reseted!'), onUpdate: () => console.log('Updated!'), onPauseResume: () => console.log('Paused or resumed!'), onStart: () => console.log('Started! 💨'), onEnd: () => console.log('Ended! 👏') }); return ( <div> <div id="counter"/> <button onClick={start}>Start</button> <button onClick={reset}>Reset</button> <button onClick={pauseResume}>Pause/Resume</button> <button onClick={() => update(2000)}>Update to 2000</button> </div> ); }; `; const repo = `https://github.com/${repository}`; const App = () => ( <Main> <Title>React CountUp</Title> <Text>{description}</Text> <Text> <a href={`${repo}#installation`}>Installation</a> {' · '} <a href={`${repo}#api`}>API</a> </Text> <Example code={simple} title="Simple"> <Text>Edit the code to see live changes.</Text> </Example> <Example code={accessibility} title="Accessibility" /> <Example code={renderProp} title="Render prop" /> <Example code={manualStart} title="Manually start with render prop" /> <Example code={autoStart} title="Autostart with render prop" /> <Example code={delayStart} title="Delay start" /> <Example code={hook} title="Usage as hook" /> <GithubCorner bannerColor="palevioletred" href={repo} /> <Footer> <Text> MIT · <a href={repo}>GitHub</a> ·{' '} <a href="https://twitter.com/glnnrys">@glnnrys</a> </Text> </Footer> </Main> ); export default App;
(function () { 'use strict'; var scripts = document.getElementsByTagName("script"); var currentScriptPath = scripts[scripts.length - 1].src; angular.module('acdesarrollos.contacto', ['ngRoute']) .controller('ContactoController', ContactoController); /* .constant('googleAdsContact', { google_conversion_id: 956728168, google_conversion_label: "_8PjCNaT810Q6IaayAM", google_conversion_format: "3", google_remarketing_only: false }); */ //ContactoController.$inject = ['$scope', 'ContactsService', '$location', '$window', 'googleAdsContact']; ContactoController.$inject = ['$scope', 'ContactsService', '$location']; //function ContactoController($scope, ContactsService, $location, $window, googleAdsContact) { function ContactoController($scope, ContactsService, $location) { var vm = this; vm.email = ''; vm.nombre = ''; vm.mensaje = ''; vm.asunto = ''; //vm.enviado = false; vm.enviando = false; // FUNCTIONS vm.sendMail = sendMail; function sendMail() { if(vm.enviando){ return; } vm.enviando = true; //$window.google_trackConversion(googleAdsContact); ContactsService.sendMail(vm.email, [{mail: 'arielcessario@gmail.com'}, {mail: 'mmaneff@gmail.com'}, {mail: 'diegoyankelevich@gmail.com'}], vm.nombre, vm.mensaje, vm.asunto, function (data, result) { vm.enviando = false; vm.email = ''; vm.nombre = ''; vm.asunto = ''; vm.mensaje = ''; }); } }; })();
version https://git-lfs.github.com/spec/v1 oid sha256:82a37be7acd892f10114c12d01e95c7830cb9b8f18f531a1c6625c03996b6da9 size 53696
(function (angular) { var theModule = angular.module('notesView', ['ui.bootstrap']); theModule.controller('notesViewController', ['$scope', '$window','$http', function ($scope, $window, $http) { $scope.notes = []; $scope.newNote = createBlankNote(); // get the category name var urlParts = window.location.pathname.split('/'); var categoryName = urlParts[urlParts.length - 1]; var notesUrl = '/api/notes/' + categoryName; $http.get(notesUrl).then(function (result) { $scope.notes = result.data; }, function (err) { console.log(err); // TODO }); $scope.save = function () { $http.post(notesUrl, $scope.newNote) .then(function (result) { $scope.notes.push(result.data); $scope.newNote = createBlankNote(); }, function (err) { console.log(err); // TODO }); }; }]); function createBlankNote() { return { note: '', color: 'yellow' }; } })(window.angular);
//L systems. based on Daniel Shiffmans code //Paul Smith //this is a basic L system start file. the DOM elements need //to be uncomented in the index.html file. var axiom = "A"; var sentence = axiom; var rule1 = { a: "A", b: "AB" } var rule2 = { a: "B", b: "A" } function generate(){ var nextSentence = ""; for(var i=0;i<sentence.length;i++){ var current = sentence.charAt(i); if (current == rule1.a){ nextSentence += rule1.b; }else if (current == rule2.a){ nextSentence += rule2.b; }else{ nextSentence += current; } } sentence = nextSentence; createP(sentence); } function setup() { //createCanvas(400, 400); //fr = createP(''); //fr.html(floor(frameRate()) noCanvas(); createP(axiom); var button = createButton("generate"); button.mousePressed(generate); } function draw() { //background(50); noLoop(); }
const DateTimeZone = Jymfony.Component.DateTime.DateTimeZone; if (':UTC' === process.env.TZ) { delete process.env.TZ; } const NullTimeZone = DateTimeZone.get(0); const DEFAULT_TZ = process.env.TZ || 'Etc/UTC'; const daysPerMonth = [ [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ], [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ], ]; /** * @memberOf Jymfony.Component.DateTime.Struct * * @internal */ export default class TimeDescriptor { /** * Constructor. * * @param {string|DateTimeZone} [tz] */ __construct(tz = undefined) { if (undefined === tz) { tz = DEFAULT_TZ; } if (! (tz instanceof DateTimeZone)) { tz = DateTimeZone.get(tz); } /** * @type {Jymfony.Component.DateTime.DateTimeZone} */ this._timeZone = tz; /** * @type {int} * * @private */ this._milliseconds = 0; /** * @type {int} * * @private */ this._seconds = 0; /** * @type {int} * * @private */ this._minutes = 0; /** * @type {int} * * @private */ this._hour = 0; /** * @type {int} * * @private */ this._day = 1; /** * @type {int} * * @private */ this._month = 1; /** * @type {int} * * @private */ this._year = 1970; /** * @type {boolean} * * @private */ this._complete = false; const d = new Date(); this.unixTimestamp = 0; this.daysFromEpoch = ~~(d.getTime() / 86400000); } /** * Sets the year in short version (70-69 = 1970-2069). * * @param {int} year */ set shortYear(year) { year = ~~year; if (0 > year || 99 < year) { throw new InvalidArgumentException('Short _year cannot be greater than 99 or less than 0'); } if (70 > year) { this._year = 2000 + year; } else { this._year = 1900 + year; } if (this._complete) { this._makeTime(); } } /** * Gets the day. * * @returns {int} */ get day() { return this._day; } /** * Sets the day. * * @param {int} day * * @throws {InvalidArgumentException} If trying to set an invalid value */ set day(day) { day = ~~day; if (1 > day || 31 < day) { throw new InvalidArgumentException('Cannot set day greater than 31 or less than 1'); } this._day = day; if (this._complete) { this._makeTime(); } } /** * Gets the month. * * @returns {int} */ get month() { return this._month; } /** * Sets the month. * * @param {int} month * * @throws {InvalidArgumentException} If trying to set an invalid value */ set month(month) { month = ~~month; if (1 > month || 12 < month) { throw new InvalidArgumentException('Cannot set month greater than 12 or less than 1'); } this._month = month; if (this._complete) { this._makeTime(); } } /** * Get the seconds. * * @returns {int} */ get seconds() { return this._seconds; } /** * Set the seconds. * * @param {int} sec * * @throws {InvalidArgumentException} If trying to set an invalid value */ set seconds(sec) { sec = ~~sec; if (0 > sec || 59 < sec) { throw new InvalidArgumentException('Cannot set seconds greater than 59 or less than 0'); } this._seconds = sec; if (this._complete) { this._makeTime(); } } /** * Get the milliseconds. * * @returns {int} */ get milliseconds() { return this._milliseconds; } /** * Set the milliseconds. * * @param {int} msec */ set milliseconds(msec) { this._milliseconds = ~~msec.toString().substr(0, 3); } /** * Get the minutes. * * @returns {int} */ get minutes() { return this._minutes; } /** * Set the minutes. * * @param {int} min * * @throws {InvalidArgumentException} If trying to set an invalid value */ set minutes(min) { min = ~~min; if (0 > min || 59 < min) { throw new InvalidArgumentException('Cannot set minute greater than 59 or less than 0'); } this._minutes = min; if (this._complete) { this._makeTime(); } } /** * Get the hour. * * @returns {int} */ get hour() { return this._hour; } /** * Set the hour. * * @param {int} hour * * @throws {InvalidArgumentException} If trying to set an invalid value */ set hour(hour) { hour = ~~hour; if (23 < hour || 0 > hour) { throw new InvalidArgumentException('Cannot set hour greater than 23 or less than 0'); } this._hour = hour; if (this._complete) { this._makeTime(); } } /** * Gets the week day. * 1 = Monday, 7 = Sunday * * @returns {int} */ get weekDay() { /* Here is a formula for finding the day of the week for ANY date. N = d + 2m + [3(m+1)/5] + y + [y/4] - [y/100] + [y/400] + 2 where d is the number or the day of the month, m is the number of the month, and y is the _year. The brackets around the divisions mean to drop the remainder and just use the integer part that you get. Also, a VERY IMPORTANT RULE is the number to use for the months for January and February. The numbers of these months are 13 and 14 of the PREVIOUS YEAR. This means that to find the day of the week of New Year's Day this _year, 1/1/98, you must use the date 13/1/97. (It sounds complicated, but I will do a couple of examples for you.) After you find the number N, divide it by 7, and the REMAINDER of that division tells you the day of the week; 1 = Sunday, 2 = Monday, 3 = Tuesday, etc; BUT, if the remainder is 0, then the day is Saturday, that is: 0 = Saturday. */ let month = this.month; let year = this._year; if (3 > month) { month += 12; year--; } const N = this.day + 2 * month + ~~(3 * (month + 1) / 5) + year + ~~(year / 4) - ~~(year / 100) + ~~(year / 400) + 2; return (N + 5) % 7 + 1; } /** * Gets the first weekday of the _year. * 1 = Monday, 7 = Sunday * * @returns {int} */ get firstDayOfYear() { const y = this._year - 1; return (37 + y + ~~(y / 4) - ~~(y / 100) + ~~(y / 400) + 5) % 7 + 1; } /** * Gets the day no. in the _year. * * @returns {int} */ get yearDay() { const target = daysPerMonth[this.leap ? 1 : 0]; const months = target.slice(0, this.month - 1); return months.reduce((acc, val) => acc + val, 0) + this.day; } /** * Gets the ISO week number. * * @returns {int} */ get isoWeekNumber() { let w = ~~((this.yearDay - this.weekDay + 10) / 7); if (1 > w) { w += 52; } return w; } /** * Gets the ISO-week _year. * * @returns {int} */ get isoYear() { const target = this.copy(); target._addDays(-target.weekDay + 3); return target._year; } /** * Is this tm representing a leap _year? * * @returns {boolean} */ get leap() { return (0 === this._year % 4) && (0 !== this._year % 100 || 0 === this._year % 400); } /** * Gets the number of days in the current month. * * @returns {int} */ get daysInMonth() { return daysPerMonth[this.leap][this.month - 1]; } /** * Gets meridian (am/pm). * * @returns {string} */ get meridian() { return 12 > this._hour ? 'am' : 'pm'; } /** * Gets the number of days from epoch. * * @returns {int} */ get daysFromEpoch() { let y = this._year; const m = this.month; const d = this.day; y -= 2 >= m ? 1 : 0; const era = ~~((0 <= y ? y : y-399) / 400); const yoe = Math.abs(y - era * 400); const doy = ~~((153 * (m + (2 < m ? -3 : 9)) + 2)/5) + d-1; const doe = yoe * 365 + ~~(yoe/4) - ~~(yoe/100) + doy; return era * 146097 + doe - 719468; } /** * Sets the number of days from epoch. * * @param {int} days */ set daysFromEpoch(days) { const z = days + 719468; const era = ~~((0 <= z ? z : z - 146096) / 146097); const doe = Math.abs(z - era * 146097); const yoe = ~~((doe - ~~(doe/1460) + ~~(doe/36524) - ~~(doe/146096)) / 365); this._year = yoe + era * 400; const doy = Math.abs(doe - (365*yoe + ~~(yoe/4) - ~~(yoe/100))); const mp = ~~((5 * doy + 2)/153); this._day = doy - ~~((153 * mp + 2)/5) + 1; this._month = mp + (10 > mp ? 3 : -9); if (2 >= this._month) { this._year++; } } /** * Gets the unix timestamp for this tm. * * @returns {int} */ get unixTimestamp() { return this._unixTime; } /** * Sets the unix timestamp for this tm. * * @param {int} timestamp */ set unixTimestamp(timestamp) { this._unixTime = isString(timestamp) ? parseInt(timestamp) : timestamp; this._milliseconds = 0; this._updateTime(); } /** * Gets the swatch internet time. * * @see https://en.wikipedia.org/wiki/Swatch_Internet_Time * * @returns {int} */ get swatchInternetTime() { const utc1 = (this.unixTimestamp + 3600) % 86400; return ~~(utc1 / 86.4); } /** * Is this datetime valid? * * @returns {boolean} */ get valid() { const days_in_month = daysPerMonth[this.leap ? 1 : 0][this.month - 1]; return this.day <= days_in_month; } /** * Gets the timezone for this descriptor. * Currently returns a null timezone if _makeTime has not been called yet. * * @returns {Jymfony.Component.DateTime.DateTimeZone} */ get timeZone() { if (! this._complete) { return NullTimeZone; } return this._timeZone; } /** * Change the timezone for this descriptor. * * @param {Jymfony.Component.DateTime.DateTimeZone} timezone */ set timeZone(timezone) { if (! (timezone instanceof DateTimeZone)) { timezone = DateTimeZone.get(timezone); } this._timeZone = timezone; } /** * Adds a timespan. * * @param {Jymfony.Component.DateTime.TimeSpanInterface} timespan */ add(timespan) { this._addMilliseconds((timespan.inverse ? -1 : 1) * timespan.milliseconds); this._addSeconds((timespan.inverse ? -1 : 1) * ( timespan.seconds + timespan.minutes * 60 + timespan.hours * 3600 )); this._addDays((timespan.inverse ? -1 : 1) * timespan.days); this._addMonths((timespan.inverse ? -1 : 1) * timespan.months); this._addYears((timespan.inverse ? -1 : 1) * timespan.years); } /** * Clones this object. */ copy() { const retVal = new TimeDescriptor(this.timeZone.name); retVal._complete = this._complete; retVal.unixTimestamp = this.unixTimestamp; return retVal; } /** * Gets the wall clock timestamp for this tm. * * @returns {int} */ get _wallClockTimestamp() { return this.daysFromEpoch * 86400 + this._hour * 3600 + this._minutes * 60 + this._seconds; } /** * Use a Date object to populate this struct. * * @param {Date} date * * @private */ _fromDate(date) { this._milliseconds = date.getMilliseconds(); /* Milliseconds */ this._seconds = date.getSeconds(); /* Seconds */ this._minutes = date.getMinutes(); /* Minutes */ this._hour = date.getHours(); /* Hours */ this._day = date.getDate(); /* Day of the month */ this._month = date.getMonth() + 1; /* Month */ this._year = date.getFullYear(); /* Year */ this._makeTime(); } /** * @private */ _makeTime() { this._complete = true; const wallTimestamp = this._wallClockTimestamp; const offset = this.timeZone._getOffsetForWallClock(wallTimestamp); this._unixTime = wallTimestamp - offset; } /** * @private */ _updateTime() { const wall_ts = this._unixTime + this.timeZone.getOffset(this._unixTime); this._seconds = ~~(wall_ts % 60); this._minutes = ~~((wall_ts % 3600 - this._seconds) / 60); this._hour = ~~((wall_ts % 86400 - (this._minutes % 3600)) / 3600); this.daysFromEpoch = ~~(wall_ts / 86400); if (0 > this._seconds) { this._seconds += 60; this._minutes--; } if (0 > this._minutes) { this._minutes += 60; this._hour--; } if (0 > this._hour) { this._hour += 24; this._doAddDays(-1); } } /** * @param {int} milliseconds * * @private */ _addMilliseconds(milliseconds) { milliseconds = ~~milliseconds; if (! milliseconds) { return; } this._milliseconds += milliseconds; this._addSeconds(~~(this._milliseconds / 1000)); this._milliseconds %= 1000; } /** * @param {int} seconds * * @private */ _addSeconds(seconds) { seconds = ~~seconds; if (! seconds) { return; } this._unixTime += seconds; this._updateTime(); } /** * @param {int} days * * @private */ _doAddDays(days) { if (! days) { return; } this._day += days; const month = () => 1 <= this._month ? this._month - 1 : 11; while (this._day >= daysPerMonth[this.leap ? 1 : 0][month()]) { this._day -= daysPerMonth[this.leap ? 1 : 0][month()]; this._doAddMonths(1); } while (1 > this._day) { let m = month(); m = 0 === m ? 11 : m - 1; this._day += daysPerMonth[this.leap ? 1 : 0][m]; this._doAddMonths(-1); } } /** * @param {int} days * * @private */ _addDays(days) { days = ~~days; if (! days) { return; } this._doAddDays(days); if (this._complete) { const targetWallTimestamp = this._wallClockTimestamp; this._unixTime += (86400 * days) - (this.timeZone._getOffsetForWallClock(targetWallTimestamp) - this.timeZone.getOffset(this._unixTime)); } } /** * @param {int} months * * @private */ _doAddMonths(months) { if (! months) { return; } const month = () => 1 < this._month ? this._month - 1 : 11; this._month += months; while (12 < this._month) { this._month -= 12; this._doAddYears(1); } while (1 > this._month) { this._month += 12; this._doAddYears(-1); } if (this._day > daysPerMonth[this.leap ? 1 : 0][month()]) { this._day = daysPerMonth[this.leap ? 1 : 0][month()]; } } /** * @param {int} months * * @private */ _addMonths(months) { months = ~~months; if (! months) { return; } const wallTimestamp = this._wallClockTimestamp; this._doAddMonths(months); if (this._complete) { const targetWallTimestamp = this._wallClockTimestamp; this._unixTime += targetWallTimestamp - wallTimestamp - (this.timeZone._getOffsetForWallClock(targetWallTimestamp) - this.timeZone.getOffset(this._unixTime)); } } /** * @param {int} years * * @private */ _doAddYears(years) { if (! years) { return; } const month = () => 1 < this._month ? this._month - 1 : 11; this._year += years; if (this._day > daysPerMonth[this.leap ? 1 : 0][month()]) { this._day = daysPerMonth[this.leap ? 1 : 0][month()]; } } /** * @param {int} years * * @private */ _addYears(years) { years = ~~years; if (! years) { return; } const wallTimestamp = this._wallClockTimestamp; this._doAddYears(years); if (this._complete) { const targetWallTimestamp = this._wallClockTimestamp; this._unixTime += targetWallTimestamp - wallTimestamp - (this.timeZone._getOffsetForWallClock(targetWallTimestamp) - this.timeZone.getOffset(this._unixTime)); } } }
"use strict"; //////////////////////////////////////////////////////////////////////////////// // アカウント //////////////////////////////////////////////////////////////////////////////// Contents.account = function( cp ) { var p = $( '#' + cp.id ); var cont = p.find( 'div.contents' ); var scrollPos = null; let reqToken = '' let reqSecret = '' cp.SetIcon( 'icon-users' ); //////////////////////////////////////////////////////////// // リスト部作成 //////////////////////////////////////////////////////////// var ListMake = function() { var items = new Array(); var cnt = 0; var dt, reset_time; for ( var i = 0, _len = g_cmn.account_order.length ; i < _len ; i++ ) { var id = g_cmn.account_order[i]; dt = new Date(); dt.setTime( g_cmn.account[id]['reset'] * 1000 ); reset_time = ( '00' + dt.getHours() ).slice( -2 ) + ':' + ( '00' + dt.getMinutes() ).slice( -2 ) + ':' + ( '00' + dt.getSeconds() ).slice( -2 ); items.push( { name: g_cmn.account[id]['screen_name'], icon: g_cmn.account[id]['icon'], follow: g_cmn.account[id]['follow'], follower: g_cmn.account[id]['follower'], statuses_count: NumFormat( g_cmn.account[id]['statuses_count'] ), id: id, } ); cnt++; } var assign = { items: items, }; $( '#account_list' ).html( OutputTPL( 'account_list', assign ) ); cont.trigger( 'contents_resize' ); // 選択の保持 if ( $( '#account_del' ).attr( 'delid' ) != undefined ) { if ( g_cmn.account[$( '#account_del' ).attr( 'delid' )] != undefined ) { $( '#account_list' ).find( 'div.item[account_id=' + $( '#account_del' ).attr( 'delid' ) + ']' ).addClass( 'select' ); $( '#account_del' ).removeClass( 'disabled' ); $( '#account_setting' ).removeClass( 'disabled' ); $( '#account_posup' ).removeClass( 'disabled' ); $( '#account_posdown' ).removeClass( 'disabled' ); } } //////////////////////////////////////// // クリック時処理 //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).click( function( e ) { $( '#account_list' ).find( 'div.item' ).removeClass( 'select' ); $( this ).addClass( 'select' ); $( '#account_del' ) .attr( 'delid', $( this ).attr( 'account_id' ) ) .removeClass( 'disabled' ); $( '#account_setting' ) .removeClass( 'disabled' ); $( '#account_posup' ) .removeClass( 'disabled' ); $( '#account_posdown' ) .removeClass( 'disabled' ); SetFront( p ); e.stopPropagation(); } ); //////////////////////////////////////// // アイコンクリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.icon' ).find( 'img' ).click( function( e ) { var account_id = $( this ).parent().parent().attr( 'account_id' ); OpenUserShow( g_cmn.account[account_id].screen_name, g_cmn.account[account_id].user_id, account_id ); e.stopPropagation(); } ); //////////////////////////////////////// // 名前クリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.name' ).find( 'div:first-child' ).find( 'span:first-child' ).click( function( e ) { var account_id = $( this ).parent().parent().parent().attr( 'account_id' ); OpenUserTimeline( g_cmn.account[account_id].screen_name, account_id ); e.stopPropagation(); } ); //////////////////////////////////////// // APIクリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.apilimit' ).click( function( e ) { var account_id = $( this ).parent().parent().parent().attr( 'account_id' ); var _cp = new CPanel( null, null, 360, 400 ); _cp.SetType( 'api_remaining' ); _cp.SetParam( { account_id: account_id, } ); _cp.Start(); e.stopPropagation(); } ); //////////////////////////////////////// // ホームボタンクリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.buttons' ).find( '.home' ).click( function( e ) { var account_id = $( this ).parent().parent().attr( 'account_id' ); var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'home', reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); //////////////////////////////////////// // Mentionボタンクリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.buttons' ).find( '.mention' ).click( function( e ) { var account_id = $( this ).parent().parent().attr( 'account_id' ); var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'mention', reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); //////////////////////////////////////// // リストボタンクリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.buttons' ).find( '.lists' ).click( function( e ) { var account_id = $( this ).parent().parent().attr( 'account_id' ); var _cp = new CPanel( null, null, 400, 300 ); _cp.SetType( 'lists' ); _cp.SetParam( { account_id: account_id, } ); _cp.Start(); e.stopPropagation(); } ); //////////////////////////////////////// // DMボタンクリック //////////////////////////////////////// $( '#account_list' ).find( 'div.item' ).find( '.buttons' ).find( '.dm' ).click( function( e ) { var account_id = $( this ).parent().parent().attr( 'account_id' ); var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 ); _cp.SetType( 'timeline' ); _cp.SetParam( { account_id: account_id, timeline_type: 'dmrecv', reload_time: g_cmn.cmn_param['reload_time'], } ); _cp.Start(); e.stopPropagation(); } ); }; //////////////////////////////////////////////////////////// // アクセストークンを取得してアカウント追加 //////////////////////////////////////////////////////////// var GetAccessToken = function( pin ) { Blackout( true ); // アクセストークン取得 SendRequest( { action: 'access_token', reqToken: reqToken, reqSecret: reqSecret, pin: pin, }, function( res ) { var acsToken = ''; var acsSecret = ''; var user_id = ''; var screen_name = ''; if ( typeof res != 'string' ) { MessageBox( i18nGetMessage( 'i18n_0049' ) ); Blackout( false ); return; } if ( res.search( /oauth_token=([\w\-]+)\&/ ) != -1 ) { acsToken = RegExp.$1; } if ( res.search( /oauth_token_secret=([\w\-]+)\&/ ) != -1 ) { acsSecret = RegExp.$1; } if ( res.search( /user_id=([\w\-]+)\&/ ) != -1 ) { user_id = RegExp.$1; } if ( res.search( /screen_name=([\w\-]+)/ ) != -1 ) { screen_name = RegExp.$1; } if ( acsToken == '' || acsSecret == '' || user_id == '' || screen_name == '' ) { MessageBox( i18nGetMessage( 'i18n_0049' ) ); Blackout( false ); return; } // アイコンを取得 var param = { type: 'GET', url: ApiUrl( '1.1' ) + 'users/show.json', data: { user_id: user_id, }, }; $( '#account_list' ).activity( { color: '#ffffff' } ); SendRequest( { action: 'oauth_send', acsToken: acsToken, acsSecret: acsSecret, param: param, }, function( res ) { if ( res.status == 200 ) { if ( res.json.profile_image_url_https ) { var account_id = GetUniqueID(); // アカウント追加 g_cmn.account[account_id] = { accessToken: acsToken, accessSecret: acsSecret, user_id: user_id, screen_name: screen_name, name: res.json.name, icon: res.json.profile_image_url_https, follow: res.json.friends_count, follower: res.json.followers_count, statuses_count: res.json.statuses_count, notsave: { protected: res.json.protected, }, }; g_cmn.account_order.push( account_id.toString() ); // アカウントパネル更新 $( '#account_list' ).activity( false ); $( '#head' ).trigger( 'account_update' ); UpdateToolbarUser(); GetAccountInfo( account_id, function() { Blackout( false ); // フォローリクエストの表示(仮) if ( g_cmn.account[account_id].notsave.protected && g_cmn.account[account_id].notsave.incoming.length > 0 ) { setTimeout( function( _id ) { OpenNotification( 'incoming', { user: g_cmn.account[_id].screen_name, img: g_cmn.account[_id].icon, count: g_cmn.account[_id].notsave.incoming.length, } ) }, 1000, account_id ); } } ); } } else { ApiError( i18nGetMessage( 'i18n_0045' ), res ); $( '#account_list' ).activity( false ); Blackout( false ); } } ); } ); }; //////////////////////////////////////////////////////////// // 開始処理 //////////////////////////////////////////////////////////// this.start = function() { //////////////////////////////////////// // 最小化/設定切替時のスクロール位置 // 保存/復元 //////////////////////////////////////// cont.on( 'contents_scrollsave', function( e, type ) { // 保存 if ( type == 0 ) { if ( scrollPos == null ) { scrollPos = $( '#account_list' ).scrollTop(); } } // 復元 else { if ( scrollPos != null ) { $( '#account_list' ).scrollTop( scrollPos ); scrollPos = null; } } } ); //////////////////////////////////////// // リサイズ処理 //////////////////////////////////////// cont.on( 'contents_resize', function() { $( '#account_list' ).height( cont.height() - cont.find( '.panel_btns' ).height() - 1 ); } ); //////////////////////////////////////// // アカウント情報更新 //////////////////////////////////////// cont.on( 'account_update', function() { // 削除ボタン $( '#account_del' ).addClass( 'disabled' ); // 設定ボタン $( '#account_setting' ).addClass( 'disabled' ); // ▲▼ボタン $( '#account_posup' ).addClass( 'disabled' ); $( '#account_posdown' ).addClass( 'disabled' ); ListMake(); // 全削除ボタン有効/無効 if ( AccountCount() > 0 ) { $( '#account_alldel' ).removeClass( 'disabled' ); } else { $( '#account_alldel' ).addClass( 'disabled' ); } } ); // 全体を作成 cont.addClass( 'account' ) .html( OutputTPL( 'account', {} ) ); cp.SetTitle( i18nGetMessage( 'i18n_0044' ), false ); //////////////////////////////////////// // 追加ボタンクリック処理 //////////////////////////////////////// $( '#account_add' ).click( function( e ) { // リクエストトークン取得 SendRequest( { action: 'request_token', }, function( res ) { if ( res.search( /oauth_token=([\w\-]+)\&/ ) != -1 ) { reqToken = RegExp.$1; } if ( res.search( /oauth_token_secret=([\w\-]+)\&/ ) != -1 ) { reqSecret = RegExp.$1; } if ( reqToken == '' || reqSecret == '' ) { MessageBox( i18nGetMessage( 'i18n_0166' ) ); return; } // 認証ウィンドウを開く SendRequest( { action: 'oauth_window', reqToken: reqToken, reqSecret: reqSecret, }, function( res ) { chrome.tabs.create( { url: res }, function () { // PIN入力の表示 $( '#pin_input' ).show() $( '#pin_input_text' ).val( '' ) $( '#pin_input_ok' ).addClass( 'disabled' ) } ) } ); } ); } ); //////////////////////////////////////// // 入力文字数によるボタン制御(コード) //////////////////////////////////////// $( '#pin_input_text' ).on( 'keyup change', function() { if ( $( '#pin_input_text' ).val().match( /^\d+$/ ) ) { $( '#pin_input_ok' ).removeClass( 'disabled' ); } else { $( '#pin_input_ok' ).addClass( 'disabled' ); } } ) //////////////////////////////////////// // OKボタンクリック処理 //////////////////////////////////////// $( '#pin_input_ok' ).on( 'click', function() { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } GetAccessToken( $( '#pin_input_text' ).val() ) $( '#pin_input' ).hide(); $( '#pin_input_text' ).val( '' ); $( '#pin_input_ok' ).addClass( 'disabled' ); } ) //////////////////////////////////////// // Cancelボタンクリック処理 //////////////////////////////////////// $( '#pin_input_cancel' ).on( 'click', function() { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } $( '#pin_input' ).hide(); $( '#pin_input_text' ).val( '' ); $( '#pin_input_ok' ).addClass( 'disabled' ); } ); //////////////////////////////////////// // 削除ボタンクリック処理 //////////////////////////////////////// $( '#account_del' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } if ( confirm( i18nGetMessage( 'i18n_0185', [g_cmn.account[$( this ).attr( 'delid' )].screen_name] ) ) ) { delete g_cmn.account[$( this ).attr( 'delid' )]; for ( var i = 0, _len = g_cmn.account_order.length ; i < _len ; i++ ) { if ( g_cmn.account_order[i] == $( this ).attr( 'delid' ) ) { g_cmn.account_order.splice( i, 1 ); break; } } $( '#account_list' ).find( 'div.item' ).each( function() { if ( $( this ).hasClass( 'select' ) ) { $( this ).fadeOut( 'fast', function() { $( '#head' ).trigger( 'account_update' ); } ); } } ); UpdateToolbarUser(); } } ); //////////////////////////////////////// // 全削除ボタンクリック処理 //////////////////////////////////////// $( '#account_alldel' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } if ( confirm( i18nGetMessage( 'i18n_0073' ) ) ) { g_cmn.account = {}; g_cmn.account_order = []; $( '#account_list' ).find( 'div.item' ).fadeOut( 'fast', function() { $( '#head' ).trigger( 'account_update' ); } ); UpdateToolbarUser(); } } ); //////////////////////////////////////// // アカウント設定ボタンクリック処理 //////////////////////////////////////// $( '#account_setting' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } var pid = IsUnique( 'accountset' ); if ( pid == null ) { var _cp = new CPanel( null, null, 360, 420 ); _cp.SetType( 'accountset' ); _cp.SetParam( { account_id: $( '#account_del' ).attr( 'delid' ), } ); _cp.Start(); } else { var _cp = GetPanel( pid ); _cp.SetType( 'accountset' ); _cp.SetParam( { account_id: $( '#account_del' ).attr( 'delid' ), } ); $( '#' + pid ).find( 'div.contents' ).trigger( 'account_change' ); } e.stopPropagation(); } ); //////////////////////////////////////// // ▲ボタンクリック処理 //////////////////////////////////////// $( '#account_posup' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } var selid = $( '#account_del' ).attr( 'delid' ); for ( var i = 0, _len = g_cmn.account_order.length ; i < _len ; i++ ) { if ( g_cmn.account_order[i] == selid ) { if ( i > 0 ) { var tmp = g_cmn.account_order[i - 1]; g_cmn.account_order[i - 1] = g_cmn.account_order[i]; g_cmn.account_order[i] = tmp; $( '#head' ).trigger( 'account_update' ); } break; } } e.stopPropagation(); } ); //////////////////////////////////////// // ▼ボタンクリック処理 //////////////////////////////////////// $( '#account_posdown' ).click( function( e ) { // disabledなら処理しない if ( $( this ).hasClass( 'disabled' ) ) { return; } var selid = $( '#account_del' ).attr( 'delid' ); for ( var i = 0, _len = g_cmn.account_order.length ; i < _len ; i++ ) { if ( g_cmn.account_order[i] == selid ) { if ( i < g_cmn.account_order.length - 1 ) { var tmp = g_cmn.account_order[i + 1]; g_cmn.account_order[i + 1] = g_cmn.account_order[i]; g_cmn.account_order[i] = tmp; $( '#head' ).trigger( 'account_update' ); } break; } } e.stopPropagation(); } ); $( '#pin_input' ).hide() // リスト部作成処理 cont.trigger( 'account_update' ); }; //////////////////////////////////////////////////////////// // 終了処理 //////////////////////////////////////////////////////////// this.stop = function() { }; }
/* eslint camelcase: 0 */ // Dynamically set the webpack public path at runtime below // This magic global is used by webpack to set the public path at runtime. // The public path is set dynamically to avoid the following issues: // 1. https://github.com/coryhouse/react-slingshot/issues/205 // 2. https://github.com/coryhouse/react-slingshot/issues/181 // 3. https://github.com/coryhouse/react-slingshot/pull/125 // Documentation: // http://webpack.github.io/docs/configuration.html#output-publicpath // eslint-disable-next-line no-undef __webpack_public_path__ = window.location.protocol + '//' + window.location.host + '/';
/* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('../../lib/source-map/util'); // This is a test mapping which maps functions from two different files // (one.js and two.js) to a minified generated source. // // Here is one.js: // // ONE.foo = function (bar) { // return baz(bar); // }; // // Here is two.js: // // TWO.inc = function (n) { // return n + 1; // }; // // And here is the generated code (min.js): // // ONE.foo=function(a){return baz(a);}; // TWO.inc=function(a){return a+1;}; exports.testGeneratedCode = " ONE.foo=function(a){return baz(a);};\n"+ " TWO.inc=function(a){return a+1;};"; exports.testMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: '/the/root', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; exports.testMapNoSourceRoot = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; exports.testMapEmptySourceRoot = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: '', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; // This mapping is identical to above, but uses the indexed format instead. exports.indexedTestMap = { version: 3, file: 'min.js', sections: [ { offset: { line: 0, column: 0 }, map: { version: 3, sources: [ "one.js" ], sourcesContent: [ ' ONE.foo = function (bar) {\n' + ' return baz(bar);\n' + ' };', ], names: [ "bar", "baz" ], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID", file: "min.js", sourceRoot: "/the/root" } }, { offset: { line: 1, column: 0 }, map: { version: 3, sources: [ "two.js" ], sourcesContent: [ ' TWO.inc = function (n) {\n' + ' return n + 1;\n' + ' };' ], names: [ "n" ], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOA", file: "min.js", sourceRoot: "/the/root" } } ] }; exports.indexedTestMapDifferentSourceRoots = { version: 3, file: 'min.js', sections: [ { offset: { line: 0, column: 0 }, map: { version: 3, sources: [ "one.js" ], sourcesContent: [ ' ONE.foo = function (bar) {\n' + ' return baz(bar);\n' + ' };', ], names: [ "bar", "baz" ], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID", file: "min.js", sourceRoot: "/the/root" } }, { offset: { line: 1, column: 0 }, map: { version: 3, sources: [ "two.js" ], sourcesContent: [ ' TWO.inc = function (n) {\n' + ' return n + 1;\n' + ' };' ], names: [ "n" ], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOA", file: "min.js", sourceRoot: "/different/root" } } ] }; exports.testMapWithSourcesContent = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourcesContent: [ ' ONE.foo = function (bar) {\n' + ' return baz(bar);\n' + ' };', ' TWO.inc = function (n) {\n' + ' return n + 1;\n' + ' };' ], sourceRoot: '/the/root', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; exports.testMapRelativeSources = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['./one.js', './two.js'], sourcesContent: [ ' ONE.foo = function (bar) {\n' + ' return baz(bar);\n' + ' };', ' TWO.inc = function (n) {\n' + ' return n + 1;\n' + ' };' ], sourceRoot: '/the/root', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; exports.emptyMap = { version: 3, file: 'min.js', names: [], sources: [], mappings: '' }; function assertMapping(generatedLine, generatedColumn, originalSource, originalLine, originalColumn, name, map, assert, dontTestGenerated, dontTestOriginal) { if (!dontTestOriginal) { var origMapping = map.originalPositionFor({ line: generatedLine, column: generatedColumn }); assert.equal(origMapping.name, name, 'Incorrect name, expected ' + JSON.stringify(name) + ', got ' + JSON.stringify(origMapping.name)); assert.equal(origMapping.line, originalLine, 'Incorrect line, expected ' + JSON.stringify(originalLine) + ', got ' + JSON.stringify(origMapping.line)); assert.equal(origMapping.column, originalColumn, 'Incorrect column, expected ' + JSON.stringify(originalColumn) + ', got ' + JSON.stringify(origMapping.column)); var expectedSource; if (originalSource && map.sourceRoot && originalSource.indexOf(map.sourceRoot) === 0) { expectedSource = originalSource; } else if (originalSource) { expectedSource = map.sourceRoot ? util.join(map.sourceRoot, originalSource) : originalSource; } else { expectedSource = null; } assert.equal(origMapping.source, expectedSource, 'Incorrect source, expected ' + JSON.stringify(expectedSource) + ', got ' + JSON.stringify(origMapping.source)); } if (!dontTestGenerated) { var genMapping = map.generatedPositionFor({ source: originalSource, line: originalLine, column: originalColumn }); assert.equal(genMapping.line, generatedLine, 'Incorrect line, expected ' + JSON.stringify(generatedLine) + ', got ' + JSON.stringify(genMapping.line)); assert.equal(genMapping.column, generatedColumn, 'Incorrect column, expected ' + JSON.stringify(generatedColumn) + ', got ' + JSON.stringify(genMapping.column)); } } exports.assertMapping = assertMapping; function assertEqualMaps(assert, actualMap, expectedMap) { assert.equal(actualMap.version, expectedMap.version, "version mismatch"); assert.equal(actualMap.file, expectedMap.file, "file mismatch"); assert.equal(actualMap.names.length, expectedMap.names.length, "names length mismatch: " + actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); for (var i = 0; i < actualMap.names.length; i++) { assert.equal(actualMap.names[i], expectedMap.names[i], "names[" + i + "] mismatch: " + actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); } assert.equal(actualMap.sources.length, expectedMap.sources.length, "sources length mismatch: " + actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); for (var i = 0; i < actualMap.sources.length; i++) { assert.equal(actualMap.sources[i], expectedMap.sources[i], "sources[" + i + "] length mismatch: " + actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); } assert.equal(actualMap.sourceRoot, expectedMap.sourceRoot, "sourceRoot mismatch: " + actualMap.sourceRoot + " != " + expectedMap.sourceRoot); assert.equal(actualMap.mappings, expectedMap.mappings, "mappings mismatch:\nActual: " + actualMap.mappings + "\nExpected: " + expectedMap.mappings); if (actualMap.sourcesContent) { assert.equal(actualMap.sourcesContent.length, expectedMap.sourcesContent.length, "sourcesContent length mismatch"); for (var i = 0; i < actualMap.sourcesContent.length; i++) { assert.equal(actualMap.sourcesContent[i], expectedMap.sourcesContent[i],
var React = require('react'); var StoresStore = require('../stores/storeStore'); var DataFlowExplorer = require('./dataFlowExplorer'); var ObjectSidebarPane = require('./objectSidebarPane'); var DEFAULT_SIDEBAR_WIDTH = 325; var DEFAULT_SIDEBAR_HEIGHT = 325; var MINIMUM_CONTENT_WIDTH_PERCENT = 0.34; var MINIMUM_CONTENT_HEIGHT_PERCENT = 0.34; function MartyPanel() { WebInspector.View.call(this); this.element.addStyleClass('panel'); this.element.classList.add('vbox', 'fill'); this.registerRequiredCSS('networkLogView.css'); this.registerRequiredCSS('filter.css'); this.registerRequiredCSS('resourceView.css'); this.splitView = createSplitView(this.element); this.sidebarPaneView = new WebInspector.SidebarPaneStack(); this.storesPane = createStoresPane(this.sidebarPaneView); this.sidebarPaneView.show(this.splitView.sidebarElement); this.sidebarPanes = {}; this.sidebarPanes.stores = createStoresPane(); this.sidebarPaneView.addPane(this.sidebarPanes.stores); React.render(<DataFlowExplorer />, this.splitView.mainElement); function createGeneralPanel() { var pane = new ObjectSidebarPane('General', '', edit); pane.update({ State: {} }); pane.expand(); return pane; } function createStoresPane() { var pane = new ObjectSidebarPane('Stores', 'No stores'); updatePane(); StoresStore.addChangeListener(updatePane); pane.expand(); return pane; function updatePane() { pane.update(StoresStore.getStoreStates()); } } function createSplitView(parent) { var splitView = new WebInspector.SidebarView( WebInspector.SidebarView.SidebarPosition.End, function () { return 'ElementsSidebarWidth' }, DEFAULT_SIDEBAR_WIDTH, DEFAULT_SIDEBAR_HEIGHT ); splitView.show(parent); splitView.setSidebarElementConstraints( Preferences.minElementsSidebarWidth, Preferences.minElementsSidebarHeight ); splitView.setMainElementConstraints( MINIMUM_CONTENT_WIDTH_PERCENT, MINIMUM_CONTENT_HEIGHT_PERCENT ) return splitView; } } MartyPanel.prototype = { __proto__: WebInspector.View.prototype // jshint ignore:line }; module.exports = MartyPanel;
import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; class Privacy extends Component { render() { return ( <h1 className="text-center"><FormattedMessage id={ 'privacy' } /></h1> ); } } export default Privacy;
/* global describe, it, before, beforeEach, after, afterEach */ var Waif = require('../'); var wrap = require('../wrap'); var should = require('should'); describe('wrap middleware', function() { var waif = null; before(function() { waif = Waif.createInstance(); this.service = waif('local') .use(wrap, middleware) .listen(); waif.start(); }); after(function() { waif.stop(); }); it('request works', function(doneFn) { this.service('', function(err, resp, body) { if (err || resp.statusCode !== 200) { return doneFn(resp.statusCode); } should.exist(body); body.should.have.property('msg', 'ok'); doneFn(); }); }); }); function middleware(req, res, next) { res.send({msg: 'ok'}); }
/* jshint unused: false */ function getValue(selector, fn){ var value = $(selector).val(); value = value.trim(); $(selector).val(''); if(fn){ value = fn(value); } return value; } function parseUpperCase(string){ return string.toUpperCase(); } function parseLowerCase(string){ return string.toLowerCase(); } function formatCurrency(number){ return '$' + number.toFixed(2); } function sendAjaxRequest(url, data, verb, altVerb, event, successFn){ var options = {}; options.url = url; options.type = verb; options.data = data; options.success = successFn; options.error = function(jqXHR, status, error){console.log(error);}; if(altVerb){ if(typeof data === 'string'){ options.data += '&_method=' + altVerb; } else { options.data._method = altVerb; } } $.ajax(options); if(event) {event.preventDefault();} }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const __1 = require("../"); const ioc = require(".."); const chai = require("chai"); let should = chai.should(); describe('Lazy', function () { describe('inject lazy fn', function () { let injector; it('should inject lazy fn', function () { injector = ioc.createContainer(); let Test = class Test { }; tslib_1.__decorate([ __1.inject() ], Test.prototype, "testLazy", void 0); Test = tslib_1.__decorate([ __1.define() ], Test); injector.register('test', Test); injector.addDefinition("testLazy", { lazyFn: () => { return "working"; } }); injector.initialize(); let test = injector.getObject('test'); test.testLazy.should.be.eq("working"); let test2 = injector.getObject('testLazy'); test2.should.be.eq("working"); }); it('should inject lazy fn to class', function () { injector = ioc.createContainer(); let Test = class Test { }; Test = tslib_1.__decorate([ __1.define() ], Test); injector.register('test', Test).injectLazyFn("test", function (inject) { return "working"; }); injector.initialize(); let test = injector.getObject('test'); test.test.should.be.eq("working"); }); it('should custom inject lazy fn to class', function () { injector = ioc.createContainer(); let customDecorator = function (id) { return __1.customFn((inject) => { return inject.get(id).name; }); }; let Test2 = class Test2 { constructor() { this.name = "bbb"; } }; Test2 = tslib_1.__decorate([ __1.define() ], Test2); let Test = class Test { }; tslib_1.__decorate([ customDecorator("test2") ], Test.prototype, "test", void 0); Test = tslib_1.__decorate([ __1.define() ], Test); injector.registerMulti([Test, Test2]); injector.initialize(); let test = injector.getObject('test'); test.test.should.be.eq("bbb"); }); it('should custom inject lazy fn to class nested parent', function () { injector = ioc.createContainer(); let injector2 = ioc.createContainer(); let customDecorator = function (id) { return __1.customFn((inject) => { return injector2.get(id).name; }); }; let Test2 = class Test2 { constructor() { this.name = "bbb"; } }; Test2 = tslib_1.__decorate([ __1.define() ], Test2); let Test = class Test { }; tslib_1.__decorate([ customDecorator("test2") ], Test.prototype, "test", void 0); Test = tslib_1.__decorate([ __1.define() ], Test); injector2.parent = injector; injector2.register(Test2); injector.registerMulti([Test]); injector.initialize(); let test = injector.getObject('test'); test.test.should.be.eq("bbb"); }); }); describe('create lazy object', function () { let injector; beforeEach(function () { injector = ioc.createContainer(); class Rectangle { constructor() { this.number = Math.random(); } area() { return 25; } } injector.register('rectangle', Rectangle).singleton().lazy(); injector.initialize(); }); it('should not exist instances', function () { should.not.exist(injector.getInstances()['rectangle']); }); it('should created lazy', function () { let rectangle = injector.getObject('rectangle'); should.exist(rectangle); rectangle.area().should.equal(25); }); it('should created lazy once', function () { let rectangle = injector.getObject('rectangle'); should.exist(rectangle); rectangle.area().should.equal(25); let r = rectangle.number; let r2 = injector.getObject('rectangle').number; r.should.be.eq(r2); }); }); describe('inject lazy non singleton', function () { let injector; it('should crate lazy non singleton', async function () { injector = ioc.createContainer(); let Test = class Test { constructor(value) { this.value = value; } }; Test = tslib_1.__decorate([ __1.define() ], Test); let Rectangle = class Rectangle { constructor() { } }; tslib_1.__decorate([ __1.inject() ], Rectangle.prototype, "test", void 0); Rectangle = tslib_1.__decorate([ __1.define(), __1.singleton() ], Rectangle); injector.registerMulti([Test, Rectangle]); await injector.initialize(); let rectangle = injector.get(Rectangle); should.exist(rectangle); rectangle.test.should.be.ok; should.not.exist(rectangle.test.value); }); }); }); //# sourceMappingURL=lazy.js.map
/** * Created by Serge Balykov (ua9msn@mail.ru) on 2/12/17. */ 'use strict'; describe('Night suite', function(){ let $input, plug; const format = { hour12: true, hour: '2-digit', minute: '2-digit', second: '2-digit', weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; // Since I've got the problem with running tests both with karma and test runner, // due to the path and ajax loading of local files, I set the fixture as the string here. //jasmine.getFixtures().fixturesPath = 'base/spec/javascripts/fixtures'; beforeEach(function () { setFixtures('<input id="dt" type="text" />'); $input = $('#dt'); $input.datetime({ locale: 'ru', format: format, minTime: new Date('01/01/2017 17:00:00 UTC'), maxTime: new Date('01/01/2017 09:00:00 UTC') }); plug = $input.data().datetime; }); it('time - in range', function(){ const dt = new Date('01/05/2017 10:02:03 UTC'); const result = plug._validate(dt); expect( result ).toEqual( false ); }); it('time - less than limits', function(){ const dt = new Date('01/01/2015 08:02:03 UTC'); const result = plug._validate(dt); expect( result ).toEqual( false ); }); it('time - bigger than limits', function(){ const dt = new Date('01/01/2018 18:02:03 UTC'); const result = plug._validate(dt); expect( result ).toEqual( false ); }); });
// @flow import lonlat from '@conveyal/lonlat' import {Map, MouseEvent} from 'leaflet' import PropTypes from 'prop-types' import React, {Component} from 'react' import colors from '../../constants/colors' import type {Grid} from '../../types' import Gridualizer from './gridualizer' const NO_DATA = -Math.pow(2, 30) type Props = { _id: string, baseGrid: Grid, breaks: number[], comparisonId: string, differenceGrid: Grid, isRegionalAnalysisSamplingDistributionComponentOnMap: boolean, removeRegionalAnalysisSamplingDistributionComponentFromMap: () => void, setRegionalAnalysisOrigin: Object => void } /** * A layer showing a proabilistic regional comparison */ export default class Regional extends Component { props: Props static contextTypes = { map: PropTypes.instanceOf(Map) } componentDidMount () { const {map} = this.context map.on('click', this.onMapClick) } componentWillUnmount () { const {map} = this.context map.off('click', this.onMapClick) } onMapClick = (e: MouseEvent) => { const { _id, comparisonId, setRegionalAnalysisOrigin, isRegionalAnalysisSamplingDistributionComponentOnMap } = this.props // if the destination component is already on the map, don't add it - change // destination by dragging destination marker if (!isRegionalAnalysisSamplingDistributionComponentOnMap) { setRegionalAnalysisOrigin({ regionalAnalysisId: _id, comparisonRegionalAnalysisId: comparisonId, lonlat: lonlat(e.latlng) }) } } render () { const { baseGrid, comparisonId, differenceGrid, breaks } = this.props if (!breaks || breaks.length === 0) { return <span /> // TODO do this one level higher } else if (comparisonId == null) { return ( <Gridualizer breaks={breaks} colors={colors.REGIONAL_GRADIENT} grid={baseGrid} /> ) } else { // used to call mask() here return ( <Gridualizer grid={differenceGrid} colors={colors.REGIONAL_COMPARISON_GRADIENT} breaks={breaks} noDataValue={NO_DATA} /> ) } } }
/*! * Nodeunit * This reporter performs a single test exection of a given test, and stores the result in a formatted * 'result' object that has the following form: { name: *testName*, duration: *in milliseconds*, state: *true|false*, assertions: [{ method: *ok | fail etc..* success: *true|false*, message: *assertion message*, // included only for failed tests stack: *stack trace*, // included only for failed tests }... ] } */ // // Module dependencies var nodeunit = require('nodeunit'), utils = require('nodeunit/lib/utils'), AssertionError = require('nodeunit/lib/assert').AssertionError; // // Run all tests within each module, accumulating the results in the local testResult object. // testName {string} - the name of the test // testMethod {function} - the test method // testEnd {function}- callback that get the test result as a parameter and called when the test is done exports.run = function (testName, testMethod, testEnd) { var testResult = {}; nodeunit.runTest(testName, testMethod, { testDone: function (name, assertions) { var formattedAssertion; testResult.duration = assertions.duration; testResult.success = !assertions.failures() ? true : false; testResult.assertions = []; assertions.forEach(function (a) { formattedAssertion = {}; // add test method, e.g, ok | fail etc.. formattedAssertion.method = a.method; formattedAssertion.success = true; if (a.failed()) { formattedAssertion.success = false; a = utils.betterErrors(a); if (a.error) { if (a.error instanceof AssertionError && a.message) { formattedAssertion.message = a.message; } // add stack trace if available if (a.error.stack) { formattedAssertion.stack = a.error.stack; } } } testResult.assertions.push(formattedAssertion); }); }, testStart: function (name) { testResult.name = name.toString(); } }, function () { testEnd(null, testResult); } ); // callback function to be called when the test is done. };