code
stringlengths 2
1.05M
|
---|
'use babel'
export default function destroySession(self, sharedSession) {
// Checks if shared session in the stack
let shareStackIndex = self.shareStack.indexOf(sharedSession)
if (shareStackIndex !== -1) {
// Removes share session from the stack and updates UI
self.shareStack.splice(shareStackIndex, 1)
self.updateShareView()
} else {
// Logs an error message
console.error(sharedSession, 'not found')
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:7998c9520ed14ac4fc2dcf6956c1dcbd36b02d6dfe63b0e4ec15a1635b951e08
size 4403
|
version https://git-lfs.github.com/spec/v1
oid sha256:6f71532f9445b6d65fbaecee3fa6944aa804f3a8f7364028a6d8c71261adc0e5
size 3643
|
version https://git-lfs.github.com/spec/v1
oid sha256:b519d8c53881da3ce32f92a5c9f583c67d563ea9d7c5cacd3bf2503726443654
size 3420
|
/*! 一叶孤舟 | qq:28701884 | 欢迎指教 */
var bill = bill || {};
//初始化
bill.init = function (){
if (com.store){
clearInterval(bill.timer);
bill.setBillList(com.arr2Clone(com.initMap)); //写入棋谱列表
play.isPlay=false;
com.show();
}else {
bill.timer = setInterval("bill.init()",300);
}
}
//把所有棋谱写入棋谱列表
bill.setBillList = function (map){
var list=com.get("billList")
for (var i=0; i < com.store.length ; i++){
var option = document.createElement('option');
option.text='棋谱'+(i+1);
option.value=i;
list.add(option , null);
}
list.addEventListener("change", function(e) {
bill.setBox (com.store[this.value], map)
})
bill.setBox (com.store[0], map)
}
//棋谱分析 写入
bill.setMove = function (bl,inx,map){
var map = com.arr2Clone(map);
for (var i=0; i<map.length; i++){
for (var n=0; n<map[i].length; n++){
var key = map[i][n];
if (key){
com.mans[key].x=n;
com.mans[key].y=i;
com.mans[key].isShow = true;
}
}
}
for (var i=0; i<= inx ; i++){
var n = i*4
var y = bl[n+1]
var newX = bl[n+2]
var x = bl[n+0]
var newY = bl[n+3]
if (com.mans[map[newY][newX]]) {
com.mans[map[newY][newX]].isShow = false;
}
com.mans[map[y][x]].x = newX;
com.mans[map[y][x]].y = newY;
if (i == inx) {
com.showPane(x ,y,newX,newY);
}
map[newY][newX] = map[y][x];
delete map[y][x];
}
return map;
}
//写入棋谱
bill.setBox = function (bl,initMap){
var map = com.arr2Clone(initMap);
var bl= bl.split("");
var h='';
for (var i=0; i< bl.length ; i+=4){
h +='<li id="move_'+(i/4)+'">';
var x = bl[i+0];
var y = bl[i+1];
var newX = bl[i+2];
var newY = bl[i+3];
h += com.createMove(map,x,y,newX,newY);
h +='</li>\n\r';
}
com.get("billBox").innerHTML = h;
var doms=com.get("billBox").getElementsByTagName("li");
for (var i=0; i<doms.length; i++){
doms[i].addEventListener("click", function(e) {
var inx = this.getAttribute("id").split("_")[1];
bill.setMove (bl , inx , initMap)
com.show();
})
}
}
|
"use strict";
var now = Date.now;
var CircleQueue = require("../../misc/CircleQueue.js");
function TransCommandQueue(mainQueue, object) {
CircleQueue.call(this);
this.object = object;
this.mainQueue = mainQueue;
}
TransCommandQueue.prototype = {
__name__ : "TransCommandQueue",
"__proto__" : CircleQueue.prototype,
constructor : TransCommandQueue,
isClosed : false,
isExecuted : false,
execute : function () {
if (this.isExecuted || !this.length || this.isClosed) {
return;
}
var self = this;
var task = this.shift();
this.object.query(task.sql, task.options, function (err, result) {
self.isExecuted = false;
task.callback(err, result);
self.execute();
});
this.isExecuted = true;
},
destroy : function () {
if (this.isClosed) {
return;
}
this.isClosed = true;
this.clear();
this.mainQueue.pool.returnObject(this.object);
this.mainQueue.execute();
}
};
module.exports = TransCommandQueue;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
var STATUS_ICON = "_CSSClassnames2.default.STATUS_ICON";
var Label = function (_Component) {
(0, _inherits3.default)(Label, _Component);
function Label() {
(0, _classCallCheck3.default)(this, Label);
return (0, _possibleConstructorReturn3.default)(this, (Label.__proto__ || (0, _getPrototypeOf2.default)(Label)).apply(this, arguments));
}
(0, _createClass3.default)(Label, [{
key: 'render',
value: function render() {
var className = STATUS_ICON + ' ' + STATUS_ICON + '-label';
if (this.props.className) {
className += ' ' + this.props.className;
}
return _react2.default.createElement(
'svg',
{ className: className, viewBox: '0 0 24 24', version: '1.1' },
_react2.default.createElement(
'g',
{ className: STATUS_ICON + '__base' },
_react2.default.createElement('circle', { cx: '12', cy: '12', r: '12', stroke: 'none' })
)
);
}
}]);
return Label;
}(_react.Component);
Label.displayName = 'Label';
exports.default = Label;
module.exports = exports['default'];
|
module.exports = { // meta
/**
* The banner is the comment that is placed at the top of our compiled
* source files. It is first processed as a Grunt template, where the `<%=`
* pairs are evaluated based on this very configuration object.
*/
banner: '/**\n' +
' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' +
' * <%= pkg.homepage %>\n' +
' *\n' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
' * Licensed <%= pkg.licenses.type %> <<%= pkg.licenses.url %>>\n' +
' */\n'
};
|
function DashboardController($scope, $state, $stateParams, dashboardFactory) {
var dc = this;
dc.playerStats = {};
dc.itemForAuction = {};
dc.auctionStarted = false;
// Called on page load to retrieve player data
dashboardFactory.getData(dashboardFactory.getName()).then(function(response) {
dc.playerStats = response.data;
});
var unbindLogout = $scope.$on('logout', function() {
dashboardFactory.logout().then(function(response) {
if (response.status === 200) {
$state.go('login');
}
});
});
var unbindStart = $scope.$on('startAuction', function(evt, data) {
dc.auctionStarted = true;
dc.itemForAuction = data;
$scope.$broadcast('roll it');
});
var unbindClose = $scope.$on('auction closed', function(evt, data) {
updateData(dc.playerStats, data);
dashboardFactory.processBid(data).then(function(response) {
if (response.data === 200) {
dashboardFactory.getData(dashboardFactory.getName()).then(function(res) {
dc.playerStats = res.data;
});
}
});
});
// Clear events
$scope.$on('$destroy', function() {
unbindLogout();
unbindStart();
unbindClose();
});
/**
* @desc function that updates player dashboard in real-time
* @param {Object} playerData - logged in player's data
* @param {Object} newData - contains player's recent transaction
*/
function updateData(playerData, newData) {
playerData.coins = playerData.coins - newData.value;
angular.forEach(playerData.inventoryItems, function(item) {
if (item.name === newData.itemName) {
item.quantity = item.quantity - newData.qty;
}
});
}
}
module.exports = DashboardController;
|
export default class Paths {
/* url, path, relative path... anything */
static normalizePath(path, base, root=lively4url) {
base = base.replace(/[^/]*$/,"") // if it is not a dir
var normalized = path
if (path.match(/^[A-Za-z]+:/)) {
// do nothing
} else if (path.match(/^\//)) {
normalized = path.replace(/^\//, root + "/")
} else {
normalized = base + path
}
return Paths.normalizeURL(normalized)
}
static normalizeURL(urlString) {
var url = new URL(urlString);
url.pathname = this.normalize(url.pathname);
return "" + url;
}
/* normalize only the "path" part of an URL */
static normalize(path) {
let source = path.split(/\/+/)
let target = []
for(let token of source) {
if(token === '..') {
target.pop()
} else if(token !== '' && token !== '.') {
target.push(token)
}
}
if(path.charAt(0) === '/')
return '/' + target.join('/')
else
return target.join('/')
}
static join(a, b) {
if(b[0] === '/') {
return this.normalize(b)
} else {
return this.normalize(a + '/' + b)
}
}
}
|
/**
* Copyright (c) 2014 brian@bevey.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.
*/
/**
* @author brian@bevey.org
* @fileoverview Prevent an air filter or other device from being turned off if
* air quality is bad. The main intent of this is to prevent
* automated macros or machine learning from turning off a filter
* if air quality (PM 2.5) is really bad.
*/
module.exports = (function () {
'use strict';
return {
version : 20180822,
airFilterWhenSmoggy : function (deviceId, command, controllers, config) {
var deviceState = require(__dirname + '/../../lib/deviceState'),
commandParts = command.split('-'),
filter = config.filter,
maxLevel = config.maxLevel || 34.4,
commandSubdevice = '',
checkState,
status;
checkState = function () {
var currDevice,
currentDevice = {},
status = {},
subdeviceId,
i = 0;
for (currDevice in controllers) {
if (controllers[currDevice].config) {
switch (controllers[currDevice].config.typeClass) {
// Look for bad PM 2.5 values in Air Quality
case 'airQuality' :
currentDevice = deviceState.getDeviceState(currDevice);
if (currentDevice.value && currentDevice.value.report) {
for (i; i < currentDevice.value.report.length; i += 1) {
if (currentDevice.value.report[i].type === 'pm25') {
status.value = currentDevice.value.report[i].value;
}
}
}
break;
case 'nest' :
case 'smartthings' :
case 'wemo' :
currentDevice = deviceState.getDeviceState(currDevice);
if (currentDevice.value) {
for (subdeviceId in currentDevice.value.devices) {
if (currentDevice.value.devices[subdeviceId].label === filter) {
status.filter = currentDevice.value.devices[subdeviceId];
status.newState = currentDevice.value;
}
}
}
break;
}
}
}
return status;
};
if (commandParts.length === 3) {
commandSubdevice = commandParts[1];
// We only care if it's the given subdevice AND we're trying to
// potentially turn it off.
if ((filter === commandSubdevice) && ((commandParts[2] === 'toggle') || (commandParts[2] === 'off'))) {
status = checkState();
// Air quality is beyond it's determined safe bounds and the chosen
// filter is currently on - abort this off or toggle command.
if ((status.value >= maxLevel) && (status.filter.state === 'on')) {
return false;
}
}
}
}
};
}());
|
import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame
const fpsSamples = [];
const numFPSSamples = 30;
let lastTime = 0;
let elapsedTime;
let totalFPS = 0;
const frame = function () {
let time = Date.now();
if (lastTime > 0) { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.round(totalFPS / fpsSamples.length);
}
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
function fireTickEvents(time) { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0;
/**
* Fired on each game loop iteration.
*
* @event tick
* @param {String} sceneID The ID of this Scene.
* @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated.
* @param {Number} time The time in seconds since 1970 of this "tick" event.
* @param {Number} prevTime The time of the previous "tick" event from this Scene.
* @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene.
*/
scene.fire("tick", tickEvent, true);
}
}
tickEvent.prevTime = time;
}
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if (!renderInfo) {
renderInfo = scenesRenderInfo[id] = {}; // FIXME
}
ticksPerRender = scene.ticksPerRender;
if (renderInfo.ticksPerRender !== ticksPerRender) {
renderInfo.ticksPerRender = ticksPerRender;
renderInfo.renderCountdown = ticksPerRender;
}
if (--renderInfo.renderCountdown === 0) {
scene.render(forceRender);
renderInfo.renderCountdown = ticksPerRender;
}
}
}
}
window.requestAnimationFrame(frame);
const loop = {};
export{loop};
|
import BaseStatementNode from './BaseStatementNode';
import * as symbols from '../symbols';
export default class BaseBlockNode extends BaseStatementNode {
packBlock(bitstr, propName) {
var prop = this[propName]
if (!prop) {
bitstr.writebits(0, 1);
return;
}
bitstr.writebits(1, 1);
bitstr.writebits(prop.length, 32);
prop.forEach(p => p.pack(bitstr));
}
[symbols.FMAKEHLIRBLOCK](builder, arr, expectedType) {
return arr.map(a => a[symbols.FMAKEHLIR](builder, expectedType))
.map(a => Array.isArray(a) ? a : [a])
.reduce((a, b) => a.concat(b), []);
}
};
|
"use strict";
////////////////////////////////////////////////////////////////////////////////
// ニコニコ動画再生
////////////////////////////////////////////////////////////////////////////////
Contents.nicovideo = function( cp )
{
var p = $( '#' + cp.id );
var cont = p.find( 'div.contents' );
cp.SetIcon( null );
////////////////////////////////////////////////////////////
// 開始処理
////////////////////////////////////////////////////////////
this.start = function() {
cont.activity( { color: '#ffffff' } );
cont.addClass( 'nicovideo' )
.html( OutputTPL( 'nicovideo', { id: cp.param.id } ) );
cp.SetTitle( 'Nicovideo - ' + cp.param['url'], false );
cont.activity( false );
};
////////////////////////////////////////////////////////////
// 終了処理
////////////////////////////////////////////////////////////
this.stop = function() {
};
}
|
var prependChar = '#';
var util = require('util');
function convertToLines(str) {
return str.split('\n').map(function(newStr) {
return prependChar + newStr;
});
}
var newConsole = {
log : function log() {
convertToLines(util.format.apply(this, arguments)).forEach(function(line) {
console.log(line);
});
},
error : function error() {
convertToLines(util.format.apply(this, arguments)).forEach(function(line) {
console.error(line);
});
}
};
module.exports = newConsole;
|
var page = require('page'),
csp = require('js-csp');
class Router {
constructor(routes){
this.routes = routes;
this.chan = csp.chan();
this.nextTransition = null;
this.nextEl = null;
// Setup channel listening
for(var r in routes)
this.listenToRoute(r);
// Start listening
page();
}
/**
* Go to route
*/
go(route, transition){
this.nextTransition = transition;
page(route || '/');
return this;
}
loc(){ return location.pathname.substr(1); }
listenToRoute(routeName){
var chan = this.chan;
page(this.routes[routeName].path, function(){
csp.go(function*(){
yield csp.put(chan, routeName);
});
});
}
};
module.exports = Router;
|
//= require phaser
|
$(function() {
function cellValue(val) {
return { sortValue: val, displayValue: val.toString() };
}
var yAxis = [{ id: 'store', name: 'Store' }, { id: 'clerk', name: 'Clerk' }];
var keyfigures = [{ id: 'nocustomers', name: 'Customers' }, { id: 'turnover', name: 'Turnover' }];
// normally one would request data here from the server using yAxis and keyfigures
// but to keep things simple, we type in the result below
var reportState = new ReportState({ useExpandCollapse: true });
reportState.dimensionsY = _.map(yAxis, function(e) { return e.id; });
reportState.serverData = [
{ type: 'row', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] },
{ type: 'row', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] },
{ type: 'row', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] },
{ type: 'grandtotal', values: [cellValue('Grand total'), cellValue(''), cellValue(1073), cellValue(115232)] }
];
var allYAxisValues = reportBuilder.getYAxisValues(reportState.serverData, yAxis);
reportState.drawNewData = function(data) {
// this also simulates a server backend returning new results
reportState.serverData = [];
if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Copenhagen'; }))
{
reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue('Stine'), cellValue(110), cellValue(33100)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue('Dorthe'), cellValue(100), cellValue(10000)] });
reportState.serverData.push({ type: 'subtotal', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] });
}
else
reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] });
if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Stockholm'; }))
{
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Emma'), cellValue(30), cellValue(2100)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Anne'), cellValue(70), cellValue(18000)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Julia'), cellValue(20), cellValue(2000)] });
reportState.serverData.push({ type: 'subtotal', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] });
}
else
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] });
if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Berlin'; }))
{
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Sandra'), cellValue(93), cellValue(1182)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Katharina'), cellValue(100), cellValue(6700)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Nadine'), cellValue(120), cellValue(10030)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Julia'), cellValue(430), cellValue(30200)] });
reportState.serverData.push({ type: 'subtotal', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] });
}
else
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] });
reportState.serverData.push({ type: 'grandtotal', values: [cellValue('Grand total'), cellValue(''), cellValue(1073), cellValue(115232)] });
if (reportState.sortRowIndex != -1)
reportState.drawData(reportBuilder.sortExpandedData(reportState.serverData, reportState.dimensionsY, reportState.sortRowIndex, reportState.sortDirection, reportState.expandedCells));
else
reportState.drawData(reportState.serverData);
};
reportState.drawData = function(data) {
reportInterface.drawTable("data", reportState, allYAxisValues, data, yAxis, keyfigures);
reportInterface.addSortHeaders("data", reportState);
reportInterface.addExpandCollapseHeaders("data", reportState);
};
reportState.drawData(reportState.serverData);
});
|
var socketio = require('socket.io'),
dotProp = require('dot-prop');
/**
* Constructs a Socket.
* Socket manager powered by Socket.IO.
*
* @constructor
*/
function Socket(){
this.port = null;
this.io = null;
this.scope = {};
}
Socket.prototype.start = function () {
var self = this;
var settings = self.scope.settings();
self.io = socketio(settings.socket.port);
self.io.on('connection', function (socket) {
socket.emit('structure', {key: self.scope.key, title: self.scope.title, sub: self.scope.sub});
socket.on('call', function(data){
dotProp.get(self.scope, data.path).job.call(data);
});
});
return self;
};
module.exports = new Socket();
|
import TestUtils from 'react-dom/test-utils';
import React from 'react';
import ReactDOM from 'react-dom';
import Textarea from '../';
const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils;
function fake() {
return () => {
return 'fake function';
}
}
describe('The input textarea', () => {
describe('when mounted with no props', () => {
let reactComponent;
let domNode;
let inputNode;
beforeEach(() => {
reactComponent = renderIntoDocument(<Textarea name='myTextArea' onChange={fake} />);
domNode = ReactDOM.findDOMNode(reactComponent);
inputNode = ReactDOM.findDOMNode(reactComponent.refs.htmlInput);
});
it('should render a node with data-focus attribute', () => {
expect(reactComponent).toBeDefined();
expect(reactComponent).toBeInstanceOf(Object);
expect(domNode.tagName).toBe('DIV');
expect(domNode.getAttribute('data-focus')).toBe('input-textarea');
});
it('should be material designed', () => {
const divMdl = domNode.firstChild;
expect(divMdl).toBeDefined();
expect(divMdl.tagName).toBe('DIV');
expect(divMdl.className).toMatch('mdl-textfield mdl-js-textfield');
});
it('should have a material designed textarea', () => {
expect(inputNode.getAttribute('class')).toBe('mdl-textfield__input');
});
it('should render an empty textarea', () => {
expect(inputNode).toBeDefined();
expect(inputNode.type).toBe('textarea');
expect(inputNode.value).toBe('');
expect(() => findRenderedDOMComponentWithClass(reactComponent, 'label-error')).toThrow('Did not find exactly one match (found: 0) for class:label-error');
});
});
describe('when mounted with onChange props defined', () => {
let component, domNode, onChangeSpy;
const testValue = 'CHANGED_VALUE';
beforeEach(() => {
onChangeSpy = jest.fn(); // test that the method in props onChange is called
component = renderIntoDocument(<Textarea name='myTextArea' onChange={onChangeSpy} />);
});
it('should call the onChange function defined in props when textarea is changed', () => {
expect(onChangeSpy).not.toHaveBeenCalled();
Simulate.change(ReactDOM.findDOMNode(component.refs.htmlInput), { target: { value: testValue } });
expect(onChangeSpy).toHaveBeenCalledTimes(1);
});
});
describe('when an error is declared in props', () => {
let component, errorComponent, inputNode;
const errorLabel = 'this is an error';
beforeEach(() => {
component = renderIntoDocument(<Textarea error={errorLabel} name='myTextArea' onChange={fake} />);
inputNode = ReactDOM.findDOMNode(component.refs.htmlInput);
errorComponent = findRenderedDOMComponentWithClass(component, 'label-error');
});
it('should display the input textarea', () => {
expect(inputNode).toBeDefined();
expect(inputNode.getAttribute('pattern')).toBe('hasError');
});
it('should display the error', () => {
expect(errorComponent).toBeDefined();
expect(errorComponent.innerHTML).toBe(errorLabel);
});
});
});
|
System.register([], function (_export, _context) {
"use strict";
_export("default", function () {
return 'test';
});
return {
setters: [],
execute: function () {}
};
});
|
var arrayOfInts = [1, 10, -5, 1, -100];
function maxProduct(arr) {
var smallest = 0;
var almostSmallest = 0;
var largest = 0;
var second = 0;
var third = 0;
for(var i = 0; i < arr.length; i++ ) {
if(arr[i] > largest){
third = second
second = largest
largest = arr[i]
} else if(arr[i] > second) {
third = second
second = arr[i]
} else if(arr[i] > third){
third = arr[i]
} else if( arr[i] < 0) {
if(arr[i] < smallest) {
almostSmallest = smallest
smallest = arr[i];
} else {
if( arr[i] < almostSmallest) {
almostSmallest = arr[i]
}
}
}
}
if(smallest * almostSmallest > second * third) {
return largest * almostSmallest * smallest
}
return largest * second * third
}
maxProduct(arrayOfInts)
|
export default function isJavascript(scriptTag) {
// TODO: add a console warning if the script tag doesn't have an attribute?
// seems like it's required for some parts of ember consumption
let type = scriptTag.attributes.type ? scriptTag.attributes.type.value : 'text/javascript';
return /(?:application|text)\/javascript/i.test(type);
}
|
'use strict';
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); } }
(function () {
function pushComponent(array, component) {
if (!array) {
array = [];
}
array.push({ name: component.getAttribute('name'), source: '' + component.textContent });
return array;
}
function getComponents() {
var components = document.getElementsByClassName('component-template');
var componentTree = {};
[].concat(_toConsumableArray(components)).forEach(function (component) {
var componentType = component.getAttribute('data-type');
componentTree[componentType] = pushComponent(componentTree[componentType], component);
});
return componentTree;
}
function createFragment() {
return document.createDocumentFragment();
}
function listElementComponent() {}
function addToElement(source, destination) {
destination.innerHTML = source;
}
/* rewrite this */
function buildComponentList(tree) {
var fragment = createFragment();
var components = getComponents();
var keys = Object.keys(components);
var list = document.createElement('ul');
keys.forEach(function (key) {
var listItem = document.createElement('li');
var subList = document.createElement('ul');
var title = document.createElement('p');
title.textContent = key;
listItem.appendChild(title);
components[key].forEach(function (component) {
var item = document.createElement('li');
item.textContent = component.name;
subList.appendChild(item);
});
listItem.appendChild(subList);
list.appendChild(listItem);
});
fragment.appendChild(list);
document.getElementById('container').appendChild(fragment);
}
/* end */
// temp stuff for demo
buildComponentList(getComponents());
document.getElementById('addBanner').addEventListener('click', function () {
addToElement(getComponents().information[0].source, document.querySelector('.container'));
});
})();
|
(function(){
angular.module('nbTodos')
.component('todoEditor', {
templateUrl: '/app/todos/todo-editor/todo-editor.component.html',
controller: TodoEditorController,
controllerAs: 'vm'
});
TodoEditorController.$inject = ['todosStore'];
function TodoEditorController(todosStore) {
this.text = '';
this.create = function () {
if( this.text.trim().length === 0) {
this.error = true;
return;
}
todosStore.create(this.text);
this.text = '';
}
}
})();
|
import { UPDATE_BOMB_LOCATIONS, REMOVE_PLAYER_BOMBS } from './constants'
const initialState = {
}
//the bombs are stored in an 'allBombs' object within the state, that has keys of the user's socket ID, each with a property of an array of that user's bomb objects
export const bombs = (state = initialState, action) => {
let newState;
switch (action.type) {
case UPDATE_BOMB_LOCATIONS:
newState = Object.assign({}, state);
for (let key in action.allBombs) {
newState[key] = action.allBombs[key]
}
return newState;
case REMOVE_PLAYER_BOMBS:
newState = Object.assign({}, state)
delete newState[action.id]
return newState;
default:
return state;
}
}
|
$('.counter').countTo({
formatter: function (value, options) {
return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3);
}
});
function updateCount(to)
{
$('.counter').countTo({
from: parseInt($('.counter').html().replace(/,/g, '')),
to: to,
formatter: function (value, options) {
return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3);
}
});
}
function getUpdatedCount()
{
$.getJSON("https://petition.parliament.uk/petitions/131215.json", function (data){
updateCount(data.data.attributes.signature_count);
console.log("+" + (data.data.attributes.signature_count - parseInt($('.counter').html().replace(/,/g, ''))) );
});
}
function getCountryData()
{
$.getJSON("https://petition.parliament.uk/petitions/131215.json", function (data){
data.data.attributes.signatures_by_country.sort(function(a,b){
if (a.signature_count > b.signature_count){
return -1;
} else if (a.signature_count < b.signature_count){
return 1;
}
return 0;
});
$("#counties").html("");
data.data.attributes.signatures_by_country.slice(0, 10).forEach(function(item, index){
html = '<img class="flag flag-' + item.code.toLowerCase() + '"> <b>' + item.name + ':</b> ' + item.signature_count.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3) + '</p>';
$("#counties").append(html);
});
});
}
|
// LOL
import leftPad from 'left-pad';
export function stringToVec(string) {
// TODO: Handle #rgb form. We may want to use rgb(r, g, b) form, but
// it's not necessary.
if (string == null) return new Float32Array(3);
let r = parseInt(string.slice(1, 3), 16);
let g = parseInt(string.slice(3, 5), 16);
let b = parseInt(string.slice(5, 7), 16);
let vec = new Float32Array(3);
vec[0] = r / 255;
vec[1] = g / 255;
vec[2] = b / 255;
return vec;
}
export function vecToString(vec) {
let r = leftPad((vec[0] * 255 | 0).toString(16), 2, '0');
let g = leftPad((vec[1] * 255 | 0).toString(16), 2, '0');
let b = leftPad((vec[2] * 255 | 0).toString(16), 2, '0');
return '#' + r + g + b;
}
|
'use strict';
/**
* Rounds a number to decimal places
*
* @param {number} number to be rounded
* @param {integer} the number of place to round to
* @param {String} the rounding method to be used
* @returns {number} the number rounded to places
*/
function roundto(value, places, roundMethod) {
var rtn = 0;
var factorial = Math.pow(10, places);
roundMethod = typeof roundMethod !== 'undefined' ? roundMethod : 'round';
switch( roundMethod ) {
case 'floor':
case 'int':
rtn = Math.floor( value * factorial );
break;
case 'ceiling':
rtn = Math.ceil( value * factorial );
break;
default:
rtn = Math.round( value * factorial );
break;
}
// Divide number by factorial to get decimal places
rtn = rtn / factorial;
return rtn;
}
exports = module.exports = roundto;
|
'use strict'
const defaultAPIURL = 'https://api.runmycode.online/run'
const $ = s => document.querySelector(s)
const $$ = s => document.querySelectorAll(s)
const editBtn = $('#edit')
const error = $('#error')
const apiUrl = $('#api-url')
const apiKey = $('#api-key')
const saveBtn = $('#save')
const inputs = Array.from($$('input'))
const toggleInputs = () => {
inputs.forEach((el) => {
if (el.type === 'button') el.disabled = !el.disabled
else if (el.type === 'text') {
el.getAttribute('readonly') ? el.removeAttribute('readonly') : el.setAttribute('readonly', 'readonly')
}
})
}
const enableEdit = () => {
saveBtn.value = 'Save'
toggleInputs()
}
const saveOptions = (e) => {
if (apiUrl.value === '') apiUrl.value = defaultAPIURL
error.style.display = 'block'
if (apiUrl.value !== defaultAPIURL && apiUrl.value.indexOf('.amazonaws.com') === -1) {
error.textContent = `Only ${defaultAPIURL} and AWS API Gateway URLs are supported as API URL`
return
} else if (!apiKey.value && apiUrl.value === defaultAPIURL) {
error.textContent = 'Key cannot be empty for https://api.runmycode.online/run'
return
// key may be not required for custom RunMyCode deployment
}
error.style.display = 'none'
browser.storage.local.set({
'apiUrl': apiUrl.value,
'apiKey': apiKey.value
})
saveBtn.value = 'Saved'
if (e) toggleInputs() // toggle inputs only if save from btn click
}
const restoreOptions = () => {
const getApiUrl = browser.storage.local.get('apiUrl')
const getApiKey = browser.storage.local.get('apiKey')
Promise.all([getApiUrl, getApiKey])
.then((result) => {
apiUrl.value = result[0]['apiUrl'] || defaultAPIURL
apiKey.value = result[1]['apiKey'] || ''
saveOptions()
})
.catch((error) => {
console.log('Error: ', error)
})
}
document.addEventListener('DOMContentLoaded', restoreOptions)
saveBtn.addEventListener('click', saveOptions)
editBtn.addEventListener('click', enableEdit)
|
import React, { Component } from 'react'
import { Layout, Wrapper, Spacer } from './components/Styles'
/*eslint-disable*/
import IconTest from './IconTest'
import { ButtonTest, ButtonTest2 } from './ButtonTest'
/*eslint-enable*/
class App extends Component {
render() {
return (
<div>
<Wrapper>
<Layout>
<div>
<ButtonTest />
<Spacer space={'0.8rem'} />
<ButtonTest2 />
<Spacer space={'0.8rem'} />
{/*<IconTest />*/}
</div>
</Layout>
</Wrapper>
</div>
)
}
}
export default App
|
"use strict";
const forOwn = require('mout/object/forOwn');
const split = new RegExp("\\s*(.+?)(?:=\\s*(?:\"([^\"]*)\"|'([^']*)'|(.*?)))?\\s*(;|$)", "g");
var parse = function(str) {
var res;
var out = {};
while((res = split.exec(str)))
out[res[1]] = res[2] || res[3] || res[4] || null;
return out;
};
parse.parse_cookie = function(str) {
var raw = parse(str);
var name = Object.keys(raw)[0];
var cookie = {value : raw[name], name : name, extras : {}};
delete raw[name];
forOwn(raw, function(v, k) { cookie.extras[k.toLowerCase()] = v; });
return cookie;
};
module.exports = parse;
|
var through = require('through2');
var should = require('should');
var dat = require('dat');
var File = require('vinyl');
var bops = require('bops');
var vdat = require('..');
describe('dest stream', function () {
var destPath = 'test/data/test-dest';
beforeEach(function (done) {
var db = dat(destPath, function (err) {
if (err) return done(err);
db.destroy(done);
});
});
it('should be a stream', function (done) {
var db = dat(destPath, function (err) {
if (err) return done(err);
var output = vdat.dest(db);
should.exist(output.pipe);
output.on('end', function () {
db.close(done);
});
output.write({foo: 'bar'});
output.end();
});
});
it('should write a vinyl file to dat', function (done) {
var expected = new File({
path: 'test-001',
contents: bops.from(JSON.stringify({foo: 'bar'}))
});
var db = dat(destPath, function (err) {
if (err) return done(err);
var output = vdat.dest(db);
output.on('end', function () {
db.get('test-001', function (err, record) {
if (err) done(err);
should.exist(record);
should.exist(record.version);
record.version.should.eql(1);
db.close(done);
});
});
output.write(expected);
output.end();
});
});
});
|
define([], function() {
Path.map("#!/products").to(function(){
}).enter(function() {
require([
'tpl!template/products.html', 'tpl!template/username.html', 'tpl!template/product-tpl.html',
'bootstrap', 'bootstrapHover', 'utils'
], function(tpl, userTpl, productTpl) {
pageStart(tpl, userTpl);
function render(){
var products = JSON.parse(localStorage.getItem('products'));
$('.js-products').empty();
if(products != null){
$.each(products, function(index, value){
$('.js-products').append($(productTpl.apply(value)));
});
} else{
$('.js-products').append("<h3>No search results</h3>");
}
}
setTimeout(render, 100);
var done = false;
$(document).delegate('.js-form-search', 'submit', function(e){
setTimeout(render, 100);
})
.delegate('.js-brands span', 'click', function(e){
var $target = $(e.target),
search = $target.attr('data-search'),
xhr;
xhr = $.ajax({
url: 'api/index.php/products',
type: 'POST',
data: JSON.stringify({
search: search
})
});
xhr
.done(function(response){
var products = response.data;
localStorage.setItem('products', JSON.stringify(products));
setTimeout(render, 100);
}).fail(function(jqXHR, status, error){
var response = JSON.parse(jqXHR.responseText);
localStorage.setItem('products', null);
})
.always(function(response){
});
})
.delegate('.js-flavors a', 'click', function(e){
var $target = $(e.currentTarget),
filter = $target[0].text.toLowerCase(),
$ele = $('[data-flavor='+filter+']');
if(filter == 'clear'){
$('.js-product').parent().fadeIn().removeClass('hidden');
}else{
$('.js-product').parent().fadeOut(function(){
$(this).addClass('hidden');
$ele.parent().fadeIn().removeClass('hidden');
});
if(!done){
$ele.parent( ":hidden" ).fadeIn().removeClass('hidden');
done = true;
}
}
});
});
}).exit(function() {
// Exit from route
$('#main').off().empty();
});
});
|
/**
* aria support for slide
* @author yiminghe@gmail.com
*/
KISSY.add("switchable-ext/slide/aria", function (S, DOM, Event, Switchable) {
// var KEY_PAGEUP = 33;
// var KEY_PAGEDOWN = 34;
// var KEY_END = 35;
// var KEY_HOME = 36;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
// var KEY_TAB = 9;
// var KEY_SPACE = 32;
// var KEY_BACKSPACE = 8;
// var KEY_DELETE = 46;
// var KEY_ENTER = 13;
// var KEY_INSERT = 45;
// var KEY_ESCAPE = 27;
var Aria = Switchable.Aria;
var Slide = Switchable.Slide;
S.mix(Slide.Config, {
aria:false
});
var DOM_EVENT = {originalEvent:{target:1}};
var setTabIndex = Aria.setTabIndex;
Slide.Plugins.push({
name:"aria",
init:function (self) {
if (!self.config.aria) {
return;
}
var triggers = self.triggers;
var panels = self.panels;
var i = 0;
var activeIndex = self.activeIndex;
S.each(triggers, function (t) {
setTabIndex(t, "-1");
i++;
});
i = 0;
S.each(panels, function (p) {
setTabIndex(p, activeIndex == i ? "0" : "-1");
DOM.attr(p, "role", "option");
i++;
});
var content = self.content;
DOM.attr(content, "role", "listbox");
Event.on(content, "keydown", _contentKeydownProcess, self);
setTabIndex(panels[0], 0);
self.on("switch", function (ev) {
var index = ev.currentIndex,
domEvent = !!(ev.originalEvent.target || ev.originalEvent.srcElement),
last = ev.fromIndex;
if (last > -1) {
setTabIndex(panels[last], -1);
}
setTabIndex(panels[index], 0);
//dom 触发的事件,自动聚焦
if (domEvent) {
panels[index].focus();
}
});
}
});
function _contentKeydownProcess(e) {
var self = this,
key = e.keyCode;
switch (key) {
case KEY_DOWN:
case KEY_RIGHT:
self.next(DOM_EVENT);
e.halt();
break;
case KEY_UP:
case KEY_LEFT:
self.prev(DOM_EVENT);
e.halt();
break;
}
}
}, {
requires:["dom", "event", 'switchable']
});
/**
2011-05-12 yiminghe@gmail.com:add support for aria & keydown
<h2>键盘操作</h2>
<ul class="list">
<li>tab 进入卡盘时,停止自动播放</li>
<li>上/左键:当焦点位于卡盘时,切换到上一个 slide 面板</li>
<li>下/右键:当焦点位于卡盘时,切换到下一个 slide 面板</li>
<li>tab 离开卡盘时,开始自动播放</li>
</ul>
**/
|
if (!Number.isInteger) {
Number.isInteger = function(value) {
return typeof value === 'number'
&& isFinite(value)
&& Math.floor(value) === value;
};
}
|
import Immutable from 'immutable';
export const currentUser = Immutable.fromJS({
value: {
_id: 'user/0',
_rev: '55781764180',
_key: '0',
entityId: 'entities/0',
},
});
export const entitiesWithoutAttribute = Immutable.fromJS({
value: {
'entities/0': {
_id: 'entities/0',
_rev: '55781764180',
_key: '0',
type: 'entityTypes/10',
},
},
});
export const entitiesWithAttributes = Immutable.fromJS({
value: {
'entities/0': {
_id: 'entities/0',
_rev: '55781764180',
_key: '0',
type: 'entityTypes/10',
relatedIds: ['attributes/0', 'attributes/1'],
},
},
});
export const noAttribute = Immutable.fromJS({
value: {},
});
export const attributesLinkedToEntity = Immutable.fromJS({
value: {
'attributes/0': {
_id: 'attributes/0',
_rev: '55781764180',
_key: '0',
attrKey: 'attributeKeys/701',
entityId: 'entities/0',
},
'attributes/1': {
_id: 'attributes/0',
_rev: '55781764180',
_key: '1',
attrKey: 'attributeKeys/700',
entityId: 'entities/0',
},
},
});
export const attributeKeys = Immutable.fromJS({
value: {
'attributeKeys/700': {
_id: 'attributeKeys/700',
_rev: '21879324714',
_key: '700',
kind: 'X',
name: 'MINDSET',
constraint: 'entityTypes/10',
},
'attributeKeys/701': {
_id: 'attributeKeys/701',
_rev: '21879455786',
_key: '701',
kind: 'Y',
name: 'MINDSET',
constraint: 'entityTypes/100',
},
},
});
export const visualizations = Immutable.fromJS({
value: {
'vis/1': {
id: 'vis/1',
organisationId: 'entitiyes/1',
graphLayout: { nodes: {}, links: {} },
},
},
});
export const emptyVisualization = Immutable.fromJS({
value: {},
});
|
import Vue from 'vue';
import socket from './sockets';
export default () => new Vue({
el: '#test_donation',
data: {
name: '',
displayName: '',
amount: 0
},
methods: {
clear: function(){
this.name = '';
this.displayName = '';
this.amount = 0;
},
display: function(){
const send = {
name: this.name,
displayName: this.displayName,
amount: this.amount
};
console.log(send);
socket.emit('test-notification', send);
this.clear();
}
}
})
|
// Given a collection of intervals, merge all overlapping intervals.
// For example,
// Given [1,3],[2,6],[8,10],[15,18],
// return [1,6],[8,10],[15,18].
/**
* Definition for an interval.
* function Interval(start, end) {
* this.start = start;
* this.end = end;
* }
*/
/**
* @param {Interval[]} intervals
* @return {Interval[]}
*/
function merge(intervals) { // 148 ms runtime
if (!intervals.length) return intervals;
intervals.sort((a, b) => a.start !== b.start ? a.start - b.start : a.end - b.end);
var prev = intervals[0],
res = [prev];
for (var curr of intervals) {
if (curr.start <= prev.end) {
prev.end = Math.max(prev.end, curr.end);
} else {
res.push(curr);
prev = curr;
}
}
return res;
}
//---------------------------------------------------------
var merge = function(intervals) {
if( intervals.length < 1 ) return intervals;
var start = [],
end = [];
for( var i=0; i<intervals.length; i++ ){
start.push( intervals[i].start );
end.push( intervals[i].end );
}
// if end[i] < start[j]
// store end
// j++
// else
// store start
// i++
var result = [],
tempStart = start[0];
for( var j=0, k=0; j< start.length || k<end.length; ){
if( start[j] < end[k] ){
tempStart = Math.min(tempStart, start[j]);
j++;
} else {
result.push( [tempStart, end[k+1]] );
tempStart = start[j];
k++;
j++;
}
}
// [ 1, 2, 8, 15 ]
// [ 3, 6, 10, 18 ]
return result;
};
|
(function () {
'use strict';
angular
.module('tables')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('tables', {
abstract: true,
url: '/tables',
template: '<ui-view/>'
})
.state('tables.list', {
url: '',
templateUrl: 'modules/tables/client/views/list-tables.client.view.html',
controller: 'TablesListController',
controllerAs: 'vm',
data: {
pageTitle: 'Tables List'
}
})
.state('tables.create', {
url: '/create',
templateUrl: 'modules/tables/client/views/form-table.client.view.html',
controller: 'TablesController',
controllerAs: 'vm',
resolve: {
tableResolve: newTable
},
data: {
pageTitle : 'Tables Create'
}
})
.state('tables.edit', {
url: '/:tableId/edit',
templateUrl: 'modules/tables/client/views/form-table.client.view.html',
controller: 'TablesController',
controllerAs: 'vm',
resolve: {
tableResolve: getTable
},
data: {
roles: ['*'],
pageTitle: 'Edit Table {{ tableResolve.name }}'
}
})
.state('tables.view', {
url: '/:tableId',
templateUrl: 'modules/tables/client/views/view-table.client.view.html',
controller: 'TablesController',
controllerAs: 'vm',
resolve: {
tableResolve: getTable
},
data:{
pageTitle: 'Table {{ articleResolve.name }}'
}
});
}
getTable.$inject = ['$stateParams', 'TablesService'];
function getTable($stateParams, TablesService) {
return TablesService.get({
tableId: $stateParams.tableId
}).$promise;
}
newTable.$inject = ['TablesService'];
function newTable(TablesService) {
return new TablesService();
}
})();
|
import * as types from '../constants/actionTypes';
const initialState = {
startTime: 0,
endTime: null
};
export default function counter(state = initialState, action) {
switch (action.type) {
case types.SET_PLAY_TIME:
return {
startTime: action.startTime,
endTime: action.endTime
};
default:
return state;
}
};
|
/**
* @module og/bv/Sphere
*/
'use strict';
import { Vec3 } from '../math/Vec3.js';
/**
* Bounding sphere class.
* @class
* @param {Number} [radius] - Bounding sphere radius.
* @param {og.Vec3} [center] - Bounding sphere coordiantes.
*/
class Sphere {
constructor(radius, center) {
/**
* Sphere radius.
* @public
* @type {Number}
*/
this.radius = radius || 0;
/**
* Sphere coordiantes.
* @public
* @type {og.Vec3}
*/
this.center = center ? center.clone() : new Vec3();
}
/**
* Sets bounding sphere coordinates by the bounds array.
* @param {Array.<number>} bounds - Bounds is an array where [minX, minY, minZ, maxX, maxY, maxZ]
*/
setFromBounds(bounds) {
let m = new Vec3(bounds[0], bounds[1], bounds[2]);
this.center.set(m.x + (bounds[3] - m.x) * 0.5, m.y + (bounds[3] - m.y) * 0.5, m.z + (bounds[5] - m.z) * 0.5);
this.radius = this.center.distance(m);
}
/**
* Sets bounding sphere coordiantes by ellipsoid geodetic extend.
* @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {og.Extent} extent - Geodetic extent.
*/
setFromExtent(ellipsoid, extent) {
this.setFromBounds(extent.getCartesianBounds(ellipsoid));
}
};
export { Sphere };
|
/**
* @ngdoc object
* @name ui.router.state.$stateProvider
*
* @requires ui.router.router.$urlRouterProvider
* @requires ui.router.util.$urlMatcherFactoryProvider
*
* @description
* The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
* on state.
*
* A state corresponds to a "place" in the application in terms of the overall UI and
* navigation. A state describes (via the controller / template / view properties) what
* the UI looks like and does at that place.
*
* States often have things in common, and the primary way of factoring out these
* commonalities in this model is via the state hierarchy, i.e. parent/child states aka
* nested states.
*
* The `$stateProvider` provides interfaces to declare these states for your app.
*/
$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
// Builds state properties from definition passed to registerState()
var stateBuilder = {
// Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
// state.children = [];
// if (parent) parent.children.push(state);
parent: function(state) {
if (isDefined(state.parent) && state.parent) return findState(state.parent);
// regex matches any valid composite state name
// would match "contact.list" but not "contacts"
var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
return compositeName ? findState(compositeName[1]) : root;
},
// inherit 'data' from parent and override by own values (if any)
data: function(state) {
if (state.parent && state.parent.data) {
state.data = state.self.data = extend({}, state.parent.data, state.data);
}
return state.data;
},
// Build a URLMatcher if necessary, either via a relative or absolute URL
url: function(state) {
var url = state.url, config = { params: state.params || {} };
if (isString(url)) {
if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
return (state.parent.navigable || root).url.concat(url, config);
}
if (!url || $urlMatcherFactory.isMatcher(url)) return url;
throw new Error("Invalid url '" + url + "' in state '" + state + "'");
},
// Keep track of the closest ancestor state that has a URL (i.e. is navigable)
navigable: function(state) {
return state.url ? state : (state.parent ? state.parent.navigable : null);
},
// Derive parameters for this state and ensure they're a super-set of parent's parameters
params: function(state) {
if (!state.params) {
return state.url ? state.url.params : state.parent.params;
}
return state.params;
},
// If there is no explicit multi-view configuration, make one up so we don't have
// to handle both cases in the view directive later. Note that having an explicit
// 'views' property will mean the default unnamed view properties are ignored. This
// is also a good time to resolve view names to absolute names, so everything is a
// straight lookup at link time.
views: function(state) {
var views = {};
forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
if (name.indexOf('@') < 0) name += '@' + state.parent.name;
views[name] = view;
});
return views;
},
ownParams: function(state) {
state.params = state.params || {};
if (!state.parent) {
return objectKeys(state.params);
}
var paramNames = {}; forEach(state.params, function (v, k) { paramNames[k] = true; });
forEach(state.parent.params, function (v, k) {
if (!paramNames[k]) {
throw new Error("Missing required parameter '" + k + "' in state '" + state.name + "'");
}
paramNames[k] = false;
});
var ownParams = [];
forEach(paramNames, function (own, p) {
if (own) ownParams.push(p);
});
return ownParams;
},
// Keep a full path from the root down to this state as this is needed for state activation.
path: function(state) {
return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
},
// Speed up $state.contains() as it's used a lot
includes: function(state) {
var includes = state.parent ? extend({}, state.parent.includes) : {};
includes[state.name] = true;
return includes;
},
$delegates: {}
};
function isRelative(stateName) {
return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
}
function findState(stateOrName, base) {
if (!stateOrName) return undefined;
var isStr = isString(stateOrName),
name = isStr ? stateOrName : stateOrName.name,
path = isRelative(name);
if (path) {
if (!base) throw new Error("No reference point given for path '" + name + "'");
var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
for (; i < pathLength; i++) {
if (rel[i] === "" && i === 0) {
current = base;
continue;
}
if (rel[i] === "^") {
if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
current = current.parent;
continue;
}
break;
}
rel = rel.slice(i).join(".");
name = current.name + (current.name && rel ? "." : "") + rel;
}
var state = states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
return undefined;
}
function queueState(parentName, state) {
if (!queue[parentName]) {
queue[parentName] = [];
}
queue[parentName].push(state);
}
function registerState(state) {
// Wrap a new object around the state so we can store our private details easily.
state = inherit(state, {
self: state,
resolve: state.resolve || {},
toString: function() { return this.name; }
});
var name = state.name;
if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
// Get parent name
var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
: (isString(state.parent)) ? state.parent
: '';
// If parent is not registered yet, add state to queue and register later
if (parentName && !states[parentName]) {
return queueState(parentName, state.self);
}
for (var key in stateBuilder) {
if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
}
states[name] = state;
// Register the state in the global state list and with $urlRouter if necessary.
if (!state[abstractKey] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
$state.transitionTo(state, $match, { location: false });
}
}]);
}
// Register any queued children
if (queue[name]) {
for (var i = 0; i < queue[name].length; i++) {
registerState(queue[name][i]);
}
}
return state;
}
// Checks text to see if it looks like a glob.
function isGlob (text) {
return text.indexOf('*') > -1;
}
// Returns true if glob matches current $state name.
function doesStateMatchGlob (glob) {
var globSegments = glob.split('.'),
segments = $state.$current.name.split('.');
//match greedy starts
if (globSegments[0] === '**') {
segments = segments.slice(segments.indexOf(globSegments[1]));
segments.unshift('**');
}
//match greedy ends
if (globSegments[globSegments.length - 1] === '**') {
segments.splice(segments.indexOf(globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
segments.push('**');
}
if (globSegments.length != segments.length) {
return false;
}
//match single stars
for (var i = 0, l = globSegments.length; i < l; i++) {
if (globSegments[i] === '*') {
segments[i] = '*';
}
}
return segments.join('') === globSegments.join('');
}
// Implicit root state that is always active
root = registerState({
name: '',
url: '^',
views: null,
'abstract': true
});
root.navigable = null;
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#decorator
* @methodOf ui.router.state.$stateProvider
*
* @description
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by `$stateProvider`. This can be used
* to add custom functionality to ui-router, for example inferring templateUrl
* based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* @example
* <pre>
* // Override the internal 'views' builder with a function that takes the state
* // definition, and a reference to the internal function being overridden:
* $stateProvider.decorator('views', function (state, parent) {
* var result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* var autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
*
* // ...
*
* $state.go('home');
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* </pre>
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
this.decorator = decorator;
function decorator(name, func) {
/*jshint validthis: true */
if (isString(name) && !isDefined(func)) {
return stateBuilder[name];
}
if (!isFunction(func) || !isString(name)) {
return this;
}
if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
stateBuilder.$delegates[name] = stateBuilder[name];
}
stateBuilder[name] = func;
return this;
}
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#state
* @methodOf ui.router.state.$stateProvider
*
* @description
* Registers a state configuration under a given state name. The stateConfig object
* has the following acceptable properties.
*
* <a id='template'></a>
*
* - **`template`** - {string|function=} - html template as a string or a function that returns
* an html template as a string which should be used by the uiView directives. This property
* takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateUrl'></a>
*
* - **`templateUrl`** - {string|function=} - path or function that returns a path to an html
* template that should be used by uiView.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateProvider'></a>
*
* - **`templateProvider`** - {function=} - Provider function that returns HTML content
* string.
*
* <a id='controller'></a>
*
* - **`controller`** - {string|function=} - Controller fn that should be associated with newly
* related scope or the name of a registered controller if passed as a string.
*
* <a id='controllerProvider'></a>
*
* - **`controllerProvider`** - {function=} - Injectable provider function that returns
* the actual controller or string.
*
* <a id='controllerAs'></a>
*
* - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be
* published to scope under the controllerAs name.
*
* <a id='resolve'></a>
*
* - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which
* should be injected into the controller. If any of these dependencies are promises,
* the router will wait for them all to be resolved or one to be rejected before the
* controller is instantiated. If all the promises are resolved successfully, the values
* of the resolved promises are injected and $stateChangeSuccess event is fired. If any
* of the promises are rejected the $stateChangeError event is fired. The map object is:
*
* - key - {string}: name of dependency to be injected into controller
* - factory - {string|function}: If string then it is alias for service. Otherwise if function,
* it is injected and return value it treated as dependency. If result is a promise, it is
* resolved before its value is injected into controller.
*
* <a id='url'></a>
*
* - **`url`** - {string=} - A url with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* <a id='params'></a>
*
* - **`params`** - {object=} - An array of parameter names or regular expressions. Only
* use this within a state if you are not using url. Otherwise you can specify your
* parameters within the url. When a state is navigated or transitioned to, the
* $stateParams service will be populated with any parameters that were passed.
*
* <a id='views'></a>
*
* - **`views`** - {object=} - Use the views property to set up multiple views or to target views
* manually/explicitly.
*
* <a id='abstract'></a>
*
* - **`abstract`** - {boolean=} - An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
*
* <a id='onEnter'></a>
*
* - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='onExit'></a>
*
* - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='reloadOnSearch'></a>
*
* - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state
* just because a search/query parameter has changed (via $location.search() or $location.hash()).
* Useful for when you'd like to modify $location.search() without triggering a reload.
*
* <a id='data'></a>
*
* - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.
*
* @example
* <pre>
* // Some state name examples
*
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the
* // above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* </pre>
*
* @param {string} name A unique state name, e.g. "home", "about", "contacts".
* To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
* @param {object} definition State configuration object.
*/
this.state = state;
function state(name, definition) {
/*jshint validthis: true */
if (isObject(name)) definition = name;
else definition.name = name;
registerState(definition);
return this;
}
/**
* @ngdoc object
* @name ui.router.state.$state
*
* @requires $rootScope
* @requires $q
* @requires ui.router.state.$view
* @requires $injector
* @requires ui.router.util.$resolve
* @requires ui.router.state.$stateParams
* @requires ui.router.router.$urlRouter
*
* @property {object} params A param object, e.g. {sectionId: section.id)}, that
* you'd like to test against the current active state.
* @property {object} current A reference to the state's config object. However
* you passed it in. Useful for accessing custom data.
* @property {object} transition Currently pending transition. A promise that'll
* resolve or reject.
*
* @description
* `$state` service is responsible for representing states as well as transitioning
* between them. It also provides interfaces to ask for current state or even states
* you're coming from.
*/
this.$get = $get;
$get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter'];
function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter) {
var TransitionSuperseded = $q.reject(new Error('transition superseded'));
var TransitionPrevented = $q.reject(new Error('transition prevented'));
var TransitionAborted = $q.reject(new Error('transition aborted'));
var TransitionFailed = $q.reject(new Error('transition failed'));
// Handles the case where a state which is the target of a transition is not found, and the user
// can optionally retry or defer the transition
function handleRedirect(redirect, state, params, options) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateNotFound
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when a requested state **cannot be found** using the provided state name during transition.
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
* you can see its three properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
*
* @param {Object} event Event object.
* @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
* @param {State} fromState Current state object.
* @param {Object} fromParams Current state params.
*
* @example
*
* <pre>
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", {a:1, b:2}, {inherit:false});
*
* // somewhere else
* $scope.$on('$stateNotFound',
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* })
* </pre>
*/
var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
if (evt.defaultPrevented) {
$urlRouter.update();
return TransitionAborted;
}
if (!evt.retry) {
return null;
}
// Allow the handler to return a promise to defer state lookup retry
if (options.$retry) {
$urlRouter.update();
return TransitionFailed;
}
var retryTransition = $state.transition = $q.when(evt.retry);
retryTransition.then(function() {
if (retryTransition !== $state.transition) return TransitionSuperseded;
redirect.options.$retry = true;
return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
}, function() {
return TransitionAborted;
});
$urlRouter.update();
return retryTransition;
}
root.locals = { resolve: null, globals: { $stateParams: {} } };
$state = {
params: {},
current: root.self,
$current: root,
transition: null
};
/**
* @ngdoc function
* @name ui.router.state.$state#reload
* @methodOf ui.router.state.$state
*
* @description
* A method that force reloads the current state. All resolves are re-resolved, events are not re-fired,
* and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).
*
* @example
* <pre>
* var app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* $state.reload();
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: false
* });
* </pre>
*/
$state.reload = function reload() {
$state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: false });
};
/**
* @ngdoc function
* @name ui.router.state.$state#go
* @methodOf ui.router.state.$state
*
* @description
* Convenience method for transitioning to a new state. `$state.go` calls
* `$state.transitionTo` internally but automatically sets options to
* `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
* This allows you to easily use an absolute or relative to path and specify
* only the parameters you'd like to update (while letting unspecified parameters
* inherit from the currently active ancestor states).
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.go('contact.detail');
* };
* });
* </pre>
* <img src='../ngdoc_assets/StateGoExamples.png'/>
*
* @param {string} to Absolute state name or relative state path. Some examples:
*
* - `$state.go('contact.detail')` - will go to the `contact.detail` state
* - `$state.go('^')` - will go to a parent state
* - `$state.go('^.sibling')` - will go to a sibling state
* - `$state.go('.child.grandchild')` - will go to grandchild state
*
* @param {object=} params A map of the parameters that will be sent to the state,
* will populate $stateParams. Any parameters that are not specified will be inherited from currently
* defined parameters. This allows, for example, going to a sibling state that shares parameters
* specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
* transitioning to a sibling will get you the parameters for all parents, transitioning to a child
* will get you all current parameters, etc.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition.
*
* Possible success values:
*
* - $state.current
*
* <br/>Possible rejection values:
*
* - 'transition superseded' - when a newer transition has been started after this one
* - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
* - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
* when a `$stateNotFound` `event.retry` promise errors.
* - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
* - *resolve error* - when an error has occurred with a `resolve`
*
*/
$state.go = function go(to, params, options) {
return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
* uses `transitionTo` internally. `$state.go` is recommended in most situations.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.transitionTo('contact.detail');
* };
* });
* </pre>
*
* @param {string} to State name.
* @param {object=} toParams A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
$state.transitionTo = function transitionTo(to, toParams, options) {
toParams = toParams || {};
options = extend({
location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
}, options || {});
var from = $state.$current, fromParams = $state.params, fromPath = from.path;
var evt, toState = findState(to, options.relative);
if (!isDefined(toState)) {
var redirect = { to: to, toParams: toParams, options: options };
var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
if (redirectResult) {
return redirectResult;
}
// Always retry once if the $stateNotFound was not prevented
// (handles either redirect changed or state lazy-definition)
to = redirect.to;
toParams = redirect.toParams;
options = redirect.options;
toState = findState(to, options.relative);
if (!isDefined(toState)) {
if (!options.relative) throw new Error("No such state '" + to + "'");
throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
}
}
if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
to = toState;
var toPath = to.path;
// Starting from the root of the path, keep all levels that haven't changed
var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
if (!options.reload) {
while (state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams)) {
locals = toLocals[keep] = state.locals;
keep++;
state = toPath[keep];
}
}
// If we're going to the same state and all locals are kept, we've got nothing to do.
// But clear 'transition', as we still want to cancel any other pending transitions.
// TODO: We may not want to bump 'transition' if we're called from a location change
// that we've initiated ourselves, because we might accidentally abort a legitimate
// transition initiated from code?
if (shouldTriggerReload(to, from, locals, options)) {
if (to.self.reloadOnSearch !== false) $urlRouter.update();
$state.transition = null;
return $q.when($state.current);
}
// Filter parameters before we pass them to event handlers etc.
toParams = filterByKeys(objectKeys(to.params), toParams || {});
// Broadcast start event and cancel the transition if requested
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeStart
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when the state transition **begins**. You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*
* @example
*
* <pre>
* $rootScope.$on('$stateChangeStart',
* function(event, toState, toParams, fromState, fromParams){
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* </pre>
*/
if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
$urlRouter.update();
return TransitionPrevented;
}
}
// Resolve locals for the remaining states, but don't update any global state just
// yet -- if anything fails to resolve the current state needs to remain untouched.
// We also set up an inheritance chain for the locals here. This allows the view directive
// to quickly look up the correct definition for each view in the current state. Even
// though we create the locals object itself outside resolveState(), it is initially
// empty and gets filled asynchronously. We need to keep track of the promise for the
// (fully resolved) current locals, and pass this down the chain.
var resolved = $q.when(locals);
for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
locals = toLocals[l] = inherit(locals);
resolved = resolveState(state, toParams, state === to, resolved, locals);
}
// Once everything is resolved, we are ready to perform the actual transition
// and return a promise for the new state. We also keep track of what the
// current promise is, so that we can detect overlapping transitions and
// keep only the outcome of the last transition.
var transition = $state.transition = resolved.then(function () {
var l, entering, exiting;
if ($state.transition !== transition) return TransitionSuperseded;
// Exit 'from' states not kept
for (l = fromPath.length - 1; l >= keep; l--) {
exiting = fromPath[l];
if (exiting.self.onExit) {
$injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
}
exiting.locals = null;
}
// Enter 'to' states not kept
for (l = keep; l < toPath.length; l++) {
entering = toPath[l];
entering.locals = toLocals[l];
if (entering.self.onEnter) {
$injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
}
}
// Run it again, to catch any transitions in callbacks
if ($state.transition !== transition) return TransitionSuperseded;
// Update globals in $state
$state.$current = to;
$state.current = to.self;
$state.params = toParams;
copy($state.params, $stateParams);
$state.transition = null;
if (options.location && to.navigable) {
$urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
replace: options.location === 'replace'
});
}
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeSuccess
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired once the state transition is **complete**.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*/
$rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
}
$urlRouter.update(true);
return $state.current;
}, function (error) {
if ($state.transition !== transition) return TransitionSuperseded;
$state.transition = null;
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeError
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when an **error occurs** during transition. It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
* @param {Error} error The resolve error object.
*/
evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
return $q.reject(error);
});
return transition;
};
/**
* @ngdoc function
* @name ui.router.state.$state#is
* @methodOf ui.router.state.$state
*
* @description
* Similar to {@link ui.router.state.$state#methods_includes $state.includes},
* but only checks for the full state name. If params is supplied then it will be
* tested for strict equality against the current active params object, so all params
* must match with none missing and no extras.
*
* @example
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // absolute name
* $state.is('contact.details.item'); // returns true
* $state.is(contactDetailItemStateObject); // returns true
*
* // relative name (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.is('.item')}">Item</div>
* </pre>
*
* @param {string|object} stateName The state name (absolute or relative) or state object you'd like to check.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
* to test against the current active state.
* @returns {boolean} Returns true if it is the state.
*/
$state.is = function is(stateOrName, params) {
var state = findState(stateOrName);
if (!isDefined(state)) {
return undefined;
}
if ($state.$current !== state) {
return false;
}
return isDefined(params) && params !== null ? angular.equals($stateParams, params) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#includes
* @methodOf ui.router.state.$state
*
* @description
* A method to determine if the current active state is equal to or is the child of the
* state stateName. If any params are passed then they will be tested for a match as well.
* Not all the parameters need to be passed, just the ones you'd like to test for equality.
*
* @example
* Partial and relative names
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // Using partial names
* $state.includes("contacts"); // returns true
* $state.includes("contacts.details"); // returns true
* $state.includes("contacts.details.item"); // returns true
* $state.includes("contacts.list"); // returns false
* $state.includes("about"); // returns false
*
* // Using relative names (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
* </pre>
*
* Basic globbing patterns
* <pre>
* $state.$current.name = 'contacts.details.item.url';
*
* $state.includes("*.details.*.*"); // returns true
* $state.includes("*.details.**"); // returns true
* $state.includes("**.item.**"); // returns true
* $state.includes("*.details.item.url"); // returns true
* $state.includes("*.details.*.url"); // returns true
* $state.includes("*.details.*"); // returns false
* $state.includes("item.**"); // returns false
* </pre>
*
* @param {string} stateOrName A partial name, relative name, or glob pattern
* to be searched for within the current state name.
* @param {object} params A param object, e.g. `{sectionId: section.id}`,
* that you'd like to test against the current active state.
* @returns {boolean} Returns true if it does include the state
*/
$state.includes = function includes(stateOrName, params) {
if (isString(stateOrName) && isGlob(stateOrName)) {
if (!doesStateMatchGlob(stateOrName)) {
return false;
}
stateOrName = $state.$current.name;
}
var state = findState(stateOrName);
if (!isDefined(state)) {
return undefined;
}
if (!isDefined($state.$current.includes[state.name])) {
return false;
}
return equalForKeys(params, $stateParams);
};
/**
* @ngdoc function
* @name ui.router.state.$state#href
* @methodOf ui.router.state.$state
*
* @description
* A url generation method that returns the compiled url for the given state populated with the given params.
*
* @example
* <pre>
* expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
* </pre>
*
* @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
* @param {object=} params An object of parameter values to fill the state's required parameters.
* @param {object=} options Options object. The options are:
*
* - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
* first parameter, then the constructed href url will be built from the first navigable ancestor (aka
* ancestor with a valid url).
* - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
*
* @returns {string} compiled state url
*/
$state.href = function href(stateOrName, params, options) {
options = extend({
lossy: true,
inherit: false,
absolute: false,
relative: $state.$current
}, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) return null;
if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
var nav = (state && options.lossy) ? state.navigable : state;
if (!nav || !nav.url) {
return null;
}
return $urlRouter.href(nav.url, filterByKeys(objectKeys(state.params), params || {}), {
absolute: options.absolute
});
};
/**
* @ngdoc function
* @name ui.router.state.$state#get
* @methodOf ui.router.state.$state
*
* @description
* Returns the state configuration object for any specific state or all states.
*
* @param {string|Sbject=} stateOrName (absolute or relative) If provided, will only get the config for
* the requested state. If not provided, returns an array of ALL state configs.
* @returns {Object|Array} State configuration object or array of all objects.
*/
$state.get = function (stateOrName, context) {
if (arguments.length === 0) return objectKeys(states).map(function(name) { return states[name].self; });
var state = findState(stateOrName, context);
return (state && state.self) ? state.self : null;
};
function resolveState(state, params, paramsAreFiltered, inherited, dst) {
// Make a restricted $stateParams with only the parameters that apply to this state if
// necessary. In addition to being available to the controller and onEnter/onExit callbacks,
// we also need $stateParams to be available for any $injector calls we make during the
// dependency resolution process.
var $stateParams = (paramsAreFiltered) ? params : filterByKeys(objectKeys(state.params), params);
var locals = { $stateParams: $stateParams };
// Resolve 'global' dependencies for the state, i.e. those not specific to a view.
// We're also including $stateParams in this; that way the parameters are restricted
// to the set that should be visible to the state, and are independent of when we update
// the global $state and $stateParams values.
dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
var promises = [dst.resolve.then(function (globals) {
dst.globals = globals;
})];
if (inherited) promises.push(inherited);
// Resolve template and dependencies for all views.
forEach(state.views, function (view, name) {
var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
injectables.$template = [ function () {
return $view.load(name, { view: view, locals: locals, params: $stateParams }) || '';
}];
promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
// References to the controller (only instantiated at link time)
if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
var injectLocals = angular.extend({}, injectables, locals);
result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
} else {
result.$$controller = view.controller;
}
// Provide access to the state itself for internal use
result.$$state = state;
result.$$controllerAs = view.controllerAs;
dst[name] = result;
}));
});
// Wait for all the promises and then return the activation object
return $q.all(promises).then(function (values) {
return dst;
});
}
return $state;
}
function shouldTriggerReload(to, from, locals, options) {
if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) {
return true;
}
}
}
angular.module('ui.router.state')
.value('$stateParams', {})
.provider('$state', $StateProvider);
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as postsActions from 'redux/modules/posts';
import { asyncConnect } from 'redux-connect';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import ListPosts from '../Posts/ListPosts';
@asyncConnect([{
promise: ({ store: { dispatch, getState } }) => {
dispatch(postsActions.load({
user_id: getState().auth.user.id
}));
}
}])
@connect(
state => ({
posts: state.posts.items
}),
{ ...postsActions, pushState: push }
)
export default class Posts extends Component {
static propTypes = {
posts: PropTypes.array.isRequired,
clearItems: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired
};
static defaultProps = {
posts: []
};
static contextTypes = {
};
state = {
editId: 0
}
componentWillUnmount() {
if (!this.state.editId) {
this.props.dispatch(this.props.clearItems());
}
}
gotoEdit = id => {
this.setState({
editId: id
});
this.props.pushState(`/profile/edit_post/${id}`);
}
render() {
const { posts } = this.props;
return (
<div>
<h1>My Posts</h1>
<ListPosts items={posts} editable gotoEdit={this.gotoEdit} />
</div>
);
}
}
|
import React from 'react';
function Home(props) {
return (
<div id='react-home'>
<h1>BC</h1>
<h2>FreeCodeCamp Projects using React</h2>
</div>
);
}
export default Home
|
import axios from 'axios'
export const setAuthorization = token => {
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
} else {
delete axios.defaults.headers.common['Authorization']
}
}
|
/*
* Populate DB with sample data on server start
* to disable, edit config/environment/index.js, and set `seedDB: false`
*/
'use strict';
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var env = process.env.NODE_ENV || 'development';
var User = require('../api/user/user.model').model;
var Customer = require('../api/customer/customer.model').model;
var Lot = require('../api/lot/lot.model').model;
var Shipment = require('../api/shipment/shipment.model').model;
var Product = require('../api/product/product.model').model;
/*
// Insert some data needed to bootstrap or init the application
if ('production' === env) {
// Insert some data needed to init the production instance only, update a version info ...
}
*/
/*
* Insert dummy data to test the application
*/
exports.users = [{
provider: 'local',
name: 'Test User',
password: 'password',
active: true
}, {
provider: 'local',
role: 'admin',
name: 'Admin',
password: 'password',
active: true
}, {
provider: 'local',
role: 'root',
name: 'Root',
password: 'password',
active: true
}];
exports.shipments = [
{
// _id: '57b4bcf47a18a5b400923d78',
orderId:"DKcRNc7XN",
creationDate:"Aug 6, 2016",
shipByDate:"Aug 12, 2016",
status:"Shipment confirmed",
units:1,
payments:"$3.92",
sku: "06F",
// product: ObjectId('57b4bcf37a18a5b400923d75'),
// customer: ObjectId('57b4bcf37a18a5b400923d73')
}, {
// _id: '57b4bcf47a18a5b400923d79',
orderId:"DplMb07cN",
creationDate:"Aug 6, 2016",
shipByDate:"Aug 12, 2016",
status:"Unshipped",
units:1,
payments:"$6.78",
sku: '12P',
// product: ObjectId('57b4bcf37a18a5b400923d76'),
// customer: ObjectId('57b4bcf37a18a5b400923d74')
},{
// _id: '57b4bcf47a18a5b400923d7a',
orderId:"DpTMbp7bN",
creationDate:"Aug 6, 2016",
shipByDate:"Aug 12, 2016",
status:"Shipment confirmed",
units:1,
payments:"$3.92",
sku: "06F",
// product: '57b4bcf37a18a5b400923d77',
// customer: '57b4bcf37a18a5b400923d74'
}];
exports.customers = [{
// _id: '57b4bcf37a18a5b400923d73',
name: 'Amazon Locker - Hannah',
address: {
street: '12355 15th Ave NE at 7-Eleven',
city: 'Seattle',
state: 'WA',
zip: '98125-4819'
},
phone: "2064985471"
},{
// _id: '57b4bcf37a18a5b400923d74',
name: 'Amazon Locker - George',
address: {
street: '12355 15th Ave NE at 7-Eleven',
city: 'Seattle',
state: 'WA',
zip: '98125-4819'
},
phone: "2064985468"
}];
exports.lots = [{
created: "Aug 11, 2016",
shipped: "Aug 12, 2016",
shipments: []
}];
exports.products = [{
// _id: '57b4bcf37a18a5b400923d77',
name: 'Finess Softpatch for Stress Incontinence',
upc: '860507000213',
asin: 'B01438A52M'
}, {
// _id: '57b4bcf37a18a5b400923d76',
name: 'Finess Softpatch for Stress Incontinence',
upc: '860507000206',
asin: 'B013TT27TA'
}, {
// _id: '57b4bcf37a18a5b400923d75',
name: 'Finess Softpatch for Stress Incontinence',
upc: '860507000220',
asin: 'B01DEDVJLI'
}];
// Join all address fields of customers
exports.customers = exports.customers.map(function(customer) {
var addr = customer.address, lines = [];
lines.push(addr.street);
lines.push(addr.city + ', ' + addr.state + ' ' + addr.zip);
customer.address = lines.join('\n');
return customer;
})
if ('development' === env || 'test' === env) {
console.log('Populating test and development data ...');
User.find({}).remove(function () {
User.create(exports.users, function (err) {
if (err) {
console.error('Error while populating users: %s', err);
} else {
console.log('finished populating users');
}
});
});
Customer.find({}).remove(function () {
Customer.create(exports.customers, function (err) {
if (err) {
console.error('Error while populating customers: %s', err);
} else {
console.log('finished populating customers');
popProducts();
}
});
});
function popProducts() {
Product.find({}).remove(function () {
Product.create(exports.products, function (err) {
if (err) {
console.error('Error while populating products: %s', err);
} else {
console.log('finished populating products');
popShipments();
}
});
});
}
function popShipments() {
Shipment.find({}).remove(function () {
Customer.find({}).exec().then(function(customers) {
exports.shipments.forEach(function (shipment, i) {
shipment.customer = customers[i%2]['_id'];
})
Product.find({}).exec().then(function(products) {
exports.shipments.forEach(function (shipment, i) {
shipment.product = products[i%3]['_id'];
})
Shipment.create(exports.shipments, function (err) {
if (err) {
console.error('Error while populating shipments: %s', err);
} else {
console.log('finished populating shipments');
popLots();
}
});
});
})
});
}
function popLots() {
Lot.find({}).remove(function () {
Shipment.find({}).exec().then(function(shipments) {
// console.log('in popLots, shipments: ' + JSON.stringify(shipments))
exports.lots.forEach(function (lot, i) {
lot.shipments.push(shipments[0]['_id']);
lot.shipments.push(shipments[2]['_id']);
// console.log('created lot shipments: ' + JSON.stringify(lot.shipments))
})
Lot.create(exports.lots, function (err) {
if (err) {
console.error('Error while populating lots: %s', err);
} else {
console.log('finished populating lots');
}
});
})
});
}
}
|
/* global describe, test, expect, jest */
import React from "react";
import { mount } from "enzyme";
import Form from "../Form";
describe("HOC (WithWrapper)", () => {
test("[handleOnKeyup] should reset the error state", () => {
const onKeyUp = jest.fn();
const comp = mount(
<Form.Input onChange={spy} value="hey" error="asdas" onKeyUp={onKeyUp} />
);
const inst = comp.instance();
const spy = jest.spyOn(inst, "setState");
inst.handleOnKeyup({});
expect(spy).toHaveBeenCalledWith({ error: null });
expect(onKeyUp).toHaveBeenCalledWith({});
comp.setProps({ onKeyUp: undefined, error: undefined });
inst.handleOnKeyup({});
expect(onKeyUp).toHaveBeenCalledTimes(1);
});
test("[handleOnChange] should set a hasValue and call the onChange prop", () => {
// The Input is actually wrapped in a HOC
const spy = jest.fn();
const comp = mount(<Form.Input onChange={spy} value="hey" />);
const inst = comp.instance();
inst.handleOnChange("some value", { formValue: "some value" });
expect(comp.state("formValue")).toBe("some value");
expect(spy).toHaveBeenCalled();
comp.setProps({ onChange: undefined });
inst.handleOnChange("");
expect(comp.state("formValue")).toBe(undefined);
expect(spy).toHaveBeenCalledTimes(1);
});
test("hasValue gets updated when new props arrive", () => {
const comp = mount(<Form.Input />);
expect(comp.find(".hasValue").exists()).toBe(false);
comp.setProps({ value: "hey" });
expect(comp.state("formValue")).toBe("hey");
});
test("Handles initialvalues for Form.Select", () => {
const options = [
{
value: "blue",
text: "Blue"
},
{
value: "red",
text: "Red"
}
];
const comp = mount(
<Form.Select name="color" selected="blue" options={options} />
);
expect(comp.find(".hasValue").exists()).toBe(true);
expect(comp.state("formValue")).toBe("blue");
});
describe("snapshot", () => {
test("should include a label span when label is not defined in the child component", () => {
const comp = mount(
<Form.Input label="My awesome label" value="hello-world" />
);
expect(comp).toMatchSnapshot();
});
test("should not include a label span when the label is defined in the child component", () => {
const comp = mount(<Form.Checkbox checked />);
expect(comp).toMatchSnapshot();
});
test("should display an error span when there is an error", () => {
const comp = mount(
<Form.Checkbox checked error="Cannot proceed like this" />
);
expect(comp).toMatchSnapshot();
});
});
});
|
import { Blaze } from 'meteor/blaze';
/**
* A global Blaze UI helper to capitalizes the first letter of an input String
*
* Credit to:
*
* http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
*/
Blaze.registerHelper('capitalizeFirstLetter', function (context) {
if (!context) {
return;
}
return context.charAt(0).toUpperCase() + context.slice(1);
});
|
/* global require, describe, it */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Matrix data structure:
matrix = require( 'dstructs-matrix' ),
// Validate a value is NaN:
isnan = require( 'validate.io-nan' ),
// Cast typed arrays to a different data type
cast = require( 'compute-cast-arrays' ),
// Module to be tested:
ceil = require( './../lib' ),
// Floor function:
CEIL = require( './../lib/number.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'compute-ceil', function tests() {
it( 'should export a function', function test() {
expect( ceil ).to.be.a( 'function' );
});
it( 'should throw an error if provided an invalid option', function test() {
var values = [
'5',
5,
true,
undefined,
null,
NaN,
[],
{}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
ceil( [1,2,3], {
'accessor': value
});
};
}
});
it( 'should throw an error if provided an array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
ceil( [1,2,3], {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a typed-array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
ceil( new Int8Array([1,2,3]), {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a matrix and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
ceil( matrix( [2,2] ), {
'dtype': value
});
};
}
});
it( 'should return NaN if the first argument is neither a number, array-like, or matrix-like', function test() {
var values = [
// '5', // valid as is array-like (length)
true,
undefined,
null,
// NaN, // allowed
function(){},
{}
];
for ( var i = 0; i < values.length; i++ ) {
assert.isTrue( isnan( ceil( values[ i ] ) ) );
}
});
it( 'should compute the ceil function when provided a number', function test() {
assert.strictEqual( ceil( 0.4 ), 1 );
assert.strictEqual( ceil( 1.8 ), 2 );
assert.isTrue( isnan( ceil( NaN ) ) );
});
it( 'should evaluate the ceil function when provided a plain array', function test() {
var data, actual, expected;
data = [
-9.4,
-4.1,
-2.9,
-0.5,
0,
0.3,
2,
3.9,
4.2,
5.1
];
expected = [
-9,
-4,
-2,
-0,
0,
1,
2,
4,
5,
6
];
actual = ceil( data );
assert.notEqual( actual, data );
assert.deepEqual( actual, expected );
// Mutate...
actual = ceil( data, {
'copy': false
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function when provided a typed array', function test() {
var data, actual, expected;
data = new Float32Array([
-9.4,
-4.1,
-2.9,
-0.5,
0,
0.3,
2,
3.9,
4.2,
5.1
]);
expected = new Int32Array([
-9,
-4,
-2,
-0,
0,
1,
2,
4,
5,
6
]);
actual = ceil( data );
assert.notEqual( actual, data );
assert.deepEqual( actual, expected );
// Mutate:
actual = ceil( data, {
'copy': false
});
expected = new Float32Array([
-9,
-4,
-2,
-0,
0,
1,
2,
4,
5,
6
]);
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function element-wise and return an array of a specific type', function test() {
var data, actual, expected;
data = [ -3.3, -2, -1.3, 0, 1.3, 2.9, 3.3 ];
expected = new Int8Array( [ -3, -2, -1, 0, 2, 3, 4 ] );
actual = ceil( data, {
'dtype': 'int8'
});
assert.notEqual( actual, data );
assert.strictEqual( actual.BYTES_PER_ELEMENT, 1 );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function element-wise using an accessor', function test() {
var data, actual, expected;
data = [
[1,1e-306],
[2,-1e-306],
[3,1e-299],
[4,-1e-299],
[5,0.8],
[6,-0.8],
[7,1],
[8,-1],
[9,10.9],
[10,-10],
[11,2.4],
[12,-2.1],
[13,3.2],
[14,-3]
];
expected = [
1,
-0,
1,
-0,
1,
-0,
1,
-1,
11,
-10,
3,
-2,
4,
-3
];
actual = ceil( data, {
'accessor': getValue
});
assert.notEqual( actual, data );
assert.deepEqual( actual, expected );
// Mutate:
actual = ceil( data, {
'accessor': getValue,
'copy': false
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
function getValue( d ) {
return d[ 1 ];
}
});
it( 'should evaluate the ceil function element-wise and deep set', function test() {
var data, actual, expected;
data = [
{'x':[9,-9.4]},
{'x':[9,-4.1]},
{'x':[9,-2.9]},
{'x':[9,-0.5]},
{'x':[9,0]},
{'x':[9,0.3]},
{'x':[9,2]},
{'x':[9,3.9]},
{'x':[9,4.2]},
{'x':[9,5.1]}
];
expected = [
{'x':[9,-9]},
{'x':[9,-4]},
{'x':[9,-2]},
{'x':[9,-0]},
{'x':[9,0]},
{'x':[9,1]},
{'x':[9,2]},
{'x':[9,4]},
{'x':[9,5]},
{'x':[9,6]}
];
actual = ceil( data, {
'path': 'x.1'
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
// Specify a path with a custom separator...
data = [
{'x':[9,-9.4]},
{'x':[9,-4.1]},
{'x':[9,-2.9]},
{'x':[9,-0.5]},
{'x':[9,0]},
{'x':[9,0.3]},
{'x':[9,2]},
{'x':[9,3.9]},
{'x':[9,4.2]},
{'x':[9,5.1]}
];
actual = ceil( data, {
'path': 'x/1',
'sep': '/'
});
assert.strictEqual( actual, data );
assert.deepEqual( actual, expected );
});
it( 'should evaluate the ceil function element-wise when provided a matrix', function test() {
var mat,
out,
d1,
d2,
i;
d1 = new Float64Array( 25 );
d2 = new Int32Array( 25 );
for ( i = 0; i < d1.length; i++ ) {
d1[ i ] = i / 5;
d2[ i ] = CEIL( i / 5 );
}
mat = matrix( d1, [5,5], 'float64' );
out = ceil( mat );
assert.deepEqual( out.data, d2 );
// Mutate...
out = ceil( mat, {
'copy': false
});
assert.strictEqual( mat, out );
assert.deepEqual( mat.data, cast( d2, 'float64') );
});
it( 'should evaluate the ceil function element-wise and return a matrix of a specific type', function test() {
var mat,
out,
d1,
d2,
i;
d1 = new Float64Array( 25 );
d2 = new Float32Array( 25 );
for ( i = 0; i < d1.length; i++ ) {
d1[ i ] = i / 5;
d2[ i ] = CEIL( i / 5 );
}
mat = matrix( d1, [5,5], 'float64' );
out = ceil( mat, {
'dtype': 'float32'
});
assert.strictEqual( out.dtype, 'float32' );
assert.deepEqual( out.data, d2 );
});
it( 'should return an empty data structure if provided an empty data structure', function test() {
assert.deepEqual( ceil( [] ), [] );
assert.deepEqual( ceil( matrix( [0,0] ) ).data, new Int32Array() );
assert.deepEqual( ceil( new Int8Array() ), new Int32Array() );
});
});
|
// ==UserScript==
// @name Custom Message Tones
// @namespace pxgamer
// @version 0.5
// @description Adds options to load in custom tones when a message is received.
// @author pxgamer
// @include *kat.cr/*
// @grant none
// ==/UserScript==
(function() {
var AUDIO_FILE = ""; // URL of audio file (MP3, WAV, OGG)
var AUDIO_LENGTH = 5000; // Length in Ticks
// Do Not Edit Below Here
var acMethod = jQuery.fn.addClass;
var audio1;
jQuery.fn.addClass = function() {
var result = acMethod.apply(this, arguments);
jQuery(this).trigger('cssClassChanged');
return result;
};
$('body').append('<span id="chatMsgHandler"></span>');
$('#chatMsgHandler').css('display', 'none');
$(document).on('cssClassChanged', function() {
var msgBarElem = $('.chat-bar-new');
if (msgBarElem.length > 0) {
audio1.play();
setTimeout(function() { audio1.pause(); audio1.currentTime = 0; }, AUDIO_LENGTH);
}
});
var audioTypes = {
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
"wav": "audio/wav"
};
function pxS(sound) {
var audio_element = document.createElement('audio');
if (audio_element.canPlayType) {
for (var i = 0; i < arguments.length; i++) {
var source_element = document.createElement('source');
source_element.setAttribute('src', arguments[i]);
if (arguments[i].match(/\.(\w+)$/i)) {
source_element.setAttribute('type', audioTypes[RegExp.$1]);
}
audio_element.appendChild(source_element);
}
audio_element.load();
audio_element.pFunc = function() {
audio_element.pause();
audio_element.currentTime = 0;
audio_element.play();
};
return audio_element;
}
}
audio1 = pxS(AUDIO_FILE);
})();
|
'use strict';
export default class MainController {
/*@ngInject*/
constructor($scope, Auth) {
$scope.loggedIn = false;
$scope.isStudent = false;
$scope.isInstructor = false;
Auth.getCurrentUser((user) => {
$scope.user = user;
$scope.loggedIn = Auth.isLoggedInSync();
if ($scope.loggedIn){
$scope.isStudent = Auth.isStudentSync();
$scope.isInstructor = Auth.isInstructorSync();
}
});
}
}
|
VideoPlayer = function(ctx) {
this.autoplay = ctx.autoplay || true;
this.video = document.getElementById('bgvid');
this.video.src = ctx.file;
if(this.autoplay) {
this.video.play();
}
}
VideoPlayer.prototype.stop = function(){
this.video.pause();
this.video.currentTime = 0;
this.video.src = '';
}
VideoPlayer.prototype.pause = function(){
this.video.pause();
}
VideoPlayer.prototype.resume = function(){
this.video.play();
}
|
/*
* file.js: Transport for outputting to a local log file
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*
*/
var events = require('events'),
fs = require('fs'),
path = require('path'),
util = require('util'),
colors = require('colors'),
common = require('../common'),
Transport = require('./transport').Transport;
//
// ### function FileRotate (options)
// #### @options {Object} Options for this instance.
// Constructor function for the FileRotate transport object responsible
// for persisting log messages and metadata to one or more files.
//
var FileRotate = exports.FileRotate = function (options) {
Transport.call(this, options);
//
// Helper function which throws an `Error` in the event
// that any of the rest of the arguments is present in `options`.
//
function throwIf (target /*, illegal... */) {
Array.prototype.slice.call(arguments, 1).forEach(function (name) {
if (options[name]) {
throw new Error('Cannot set ' + name + ' and ' + target + 'together');
}
});
}
if (options.filename || options.dirname) {
throwIf('filename or dirname', 'stream');
this._basename = this.filename = path.basename(options.filename) || 'winston.log';
this.dirname = options.dirname || path.dirname(options.filename);
this.options = options.options || { flags: 'a' };
}
else if (options.stream) {
throwIf('stream', 'filename', 'maxsize');
this.stream = options.stream;
}
else {
throw new Error('Cannot log to file without filename or stream.');
}
this.json = options.json !== false;
this.colorize = options.colorize || false;
this.maxsize = options.maxsize || null;
this.maxFiles = options.maxFiles || null;
this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false;
//
// Internal state variables representing the number
// of files this instance has created and the current
// size (in bytes) of the current logfile.
//
this._size = 0;
this._created = 0;
this._buffer = [];
this._draining = false;
var today = new Date();
this._month = today.getMonth();
this._date = today.getDate();
};
//
// Inherit from `winston.Transport`.
//
util.inherits(FileRotate, Transport);
/*
*/
function getFormatToday() {
var d = new Date();
return [
d.getFullYear(),
common.pad(d.getMonth() + 1),
common.pad(d.getDate()),
'-'
].join('');
}
//
// Expose the name of this Transport on the prototype
//
FileRotate.prototype.name = 'fileRotate';
//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
FileRotate.prototype.log = function (level, msg, meta, callback) {
if (this.silent) {
return callback(null, true);
}
var self = this, output = common.log({
level: level,
message: msg,
meta: meta,
json: this.json,
colorize: this.colorize,
timestamp: this.timestamp
}) + '\n';
this._size += output.length;
if (!this.filename) {
console.log('no filename');
//
// If there is no `filename` on this instance then it was configured
// with a raw `WriteableStream` instance and we should not perform any
// size restrictions.
//
this.stream.write(output);
self._lazyDrain();
}
else {
this.open(function (err) {
console.log('opening callbak');
if (err) {
console.log('opening err');
//
// If there was an error enqueue the message
//
return self._buffer.push(output);
}
self.stream.write(output);
self._lazyDrain();
});
}
callback(null, true);
};
//
// ### function open (callback)
// #### @callback {function} Continuation to respond to when complete
// Checks to see if a new file needs to be created based on the `maxsize`
// (if any) and the current size of the file used.
//
FileRotate.prototype.open = function (callback) {
var now = new Date();
if (this.opening) {
console.log('opening');
//
// If we are already attempting to open the next
// available file then respond with a value indicating
// that the message should be buffered.
//
return callback(true);
}
else if (!this.stream || (this.maxsize && this._size >= this.maxsize) ||
(this._month <= now.getMonth() && this._date < now.getDate()) ) {
console.log('no stream, over max, new date');
//
// If we dont have a stream or have exceeded our size, then create
// the next stream and respond with a value indicating that
// the message should be buffered.
//
callback(true);
return this._createStream();
}
//
// Otherwise we have a valid (and ready) stream.
//
callback();
};
//
// ### function close ()
// Closes the stream associated with this instance.
//
FileRotate.prototype.close = function () {
var self = this;
console.log('close');
if (this.stream) {
this.stream.end();
this.stream.destroySoon();
this.stream.once('drain', function () {
self.emit('flush');
self.emit('closed');
});
}
};
//
// ### function flush ()
// Flushes any buffered messages to the current `stream`
// used by this instance.
//
FileRotate.prototype.flush = function () {
var self = this;
console.log('flush');
//
// Iterate over the `_buffer` of enqueued messaged
// and then write them to the newly created stream.
//
this._buffer.forEach(function (str) {
process.nextTick(function () {
self.stream.write(str);
self._size += str.length;
});
});
//
// Quickly truncate the `_buffer` once the write operations
// have been started
//
self._buffer.length = 0;
//
// When the stream has drained we have flushed
// our buffer.
//
self.stream.once('drain', function () {
self.emit('flush');
self.emit('logged');
});
};
//
// ### @private function _createStream ()
// Attempts to open the next appropriate file for this instance
// based on the common state (such as `maxsize` and `_basename`).
//
FileRotate.prototype._createStream = function () {
var self = this;
this.opening = true;
console.log('create Stream');
(function checkFile (target) {
console.log('check file');
var fullname = path.join(self.dirname, target);
//
// Creates the `WriteStream` and then flushes any
// buffered messages.
//
function createAndFlush (size) {
console.log('create and flush');
if (self.stream) {
console.log('end stream');
self.stream.end();
self.stream.destroySoon();
}
self._size = size;
self.filename = target;
self.stream = fs.createWriteStream(fullname, self.options);
//
// When the current stream has finished flushing
// then we can be sure we have finished opening
// and thus can emit the `open` event.
//
self.once('flush', function () {
self.opening = false;
self.emit('open', fullname);
});
//
// Remark: It is possible that in the time it has taken to find the
// next logfile to be written more data than `maxsize` has been buffered,
// but for sensible limits (10s - 100s of MB) this seems unlikely in less
// than one second.
//
self.flush();
}
fs.stat(fullname, function (err, stats) {
console.log('stats > ' + stats);
if (err) {
if (err.code !== 'ENOENT') {
return self.emit('error', err);
}
return createAndFlush(0);
}
if (stats) {
console.log('mtime > ' + stats.mtime);
console.log('type of > ' + typeof stats.mtime);
self._month = stats.mtime.getMonth();
self._date = stats.mtime.getDate();
}
console.log(self._month);
console.log(self._date);
var now = new Date();
if (!stats || (self.maxsize && stats.size >= self.maxsize) ||
(self._date < now.getDate() && self._month <= now.getMonth()) ) {
console.log('no stats, max size, new date');
//
// If `stats.size` is greater than the `maxsize` for
// this instance then try again
//
return checkFile(self._getFile(true));
}
createAndFlush(stats.size);
});
})(this._getFile());
};
//
// ### @private function _getFile ()
// Gets the next filename to use for this instance
// in the case that log filesizes are being capped.
//
FileRotate.prototype._getFile = function (inc) {
console.log('get file');
var self = this,
ext = path.extname(this._basename),
basename = getFormatToday() + path.basename(this._basename, ext),
remaining;
if (inc) {
//
// Increment the number of files created or
// checked by this instance.
//
// Check for maxFiles option and delete file
if (this.maxFiles && (this._created >= (this.maxFiles - 1))) {
remaining = this._created - (this.maxFiles - 1);
if (remaining === 0) {
fs.unlinkSync(path.join(this.dirname, basename + ext));
}
else {
fs.unlinkSync(path.join(this.dirname, basename + remaining + ext));
}
}
this._created += 1;
}
return this._created
? basename + this._created + ext
: basename + ext;
};
//
// ### @private function _lazyDrain ()
// Lazily attempts to emit the `logged` event when `this.stream` has
// drained. This is really just a simple mutex that only works because
// Node.js is single-threaded.
//
FileRotate.prototype._lazyDrain = function () {
console.log('lazy drain');
var self = this;
if (!this._draining && this.stream) {
this._draining = true;
this.stream.once('drain', function () {
this._draining = false;
self.emit('logged');
});
}
};
|
/*
JMG (Javascript Mini GUI)
(c) Roberto Lopez <jmg.contact.box *at* gmail.com>
The MIT License (MIT)
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.
*/
//------------------------------------------------------------------------------------------------------------------------
// public variables
//------------------------------------------------------------------------------------------------------------------------
var WIDGETS = [];
var CURRENTPAGE = "";
var STYLE='desktop';
var MAX_DIALOG_WIDTH = 700;
//------------------------------------------------------------------------------------------------------------------------
// showPage( id )
//------------------------------------------------------------------------------------------------------------------------
function showPage( id )
{
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#" + id );
}
//------------------------------------------------------------------------------------------------------------------------
// setPageStyle( style )
//------------------------------------------------------------------------------------------------------------------------
function setPageStyle( newStyle , width )
{
STYLE = newStyle;
if ( newStyle == "auto" || newStyle == "desktop" )
{
if ( typeof(width) == "undefined" )
{
MAX_DIALOG_WIDTH = 700;
}
else
{
MAX_DIALOG_WIDTH = width;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// doMethod
//------------------------------------------------------------------------------------------------------------------------
function doMethod( id , method , value )
{
var string = '';
var datarole = $('#' + id ).data('role');
if ( method == 'addRow' )
{
string += '<tr style="height:1.5em;" >';
string += '<td class="column0" style="border: 1px solid rgb(192,192,192); border-collapse: collapse;"> ' + '' + '<input type="checkbox" onclick="changeColor(this)" >' + '' + ' </td>';
for( var n = 0; n < value.length; n++ )
{
string += '<td style="border: 1px solid rgb(192,192,192); border-collapse: collapse;">' + value [n] + '</td>';
}
string += '</tr>';
$('#'+id).append( string );
if ( datarole == 'table' )
{
$("#"+id).table("refresh");
}
}
else if ( method == 'deleteRow' )
{
document.getElementById( id ).deleteRow(value);
}
else if ( method == 'selectRow' )
{
document.getElementById(id).rows[value].cells[0].getElementsByTagName("input")[0].checked = true ;
}
else if ( method == 'unSelectRow' )
{
document.getElementById(id).rows[value].cells[0].getElementsByTagName("input")[0].checked = false ;
}
else if ( method == 'load' )
{
doMethod(id,'deleteAllRows');
if ( typeof( value ) == 'string' )
{
var jsonData = value;
var arr = JSON.parse( jsonData );
}
else if ( typeof( value ) == 'object' )
{
var arr = value;
}
else
{
alert('Error (load method): Invalid Type');
}
var l = arr[0].length;
for( var i=0; i < arr.length; i ++ )
{
var row = [];
for ( var j=0 ; j<l ; j++ )
{
row.push(arr[i][j]);
}
doMethod(id,'addRow', row )
}
if ( datarole == 'table' )
{
$("#"+id).table("refresh");
}
}
else if ( method == 'deleteAllRows' )
{
while ( get(id,'rowCount') > 0 )
{
doMethod( id, 'deleteRow' , 1 );
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// get
//------------------------------------------------------------------------------------------------------------------------
function get( id , property , value1 , value2 )
{
var datarole = $('#' + id ).data('role');
var retval;
if ( datarole == 'flipswitch' || datarole == 'text' || datarole == 'textarea' || datarole == 'button' || datarole == 'number' || datarole == 'date' || datarole == 'select' )
{
var string = 'document.getElementById("' + id + '").' + property
retval = eval(string) ;
}
else if ( datarole == 'std-table' || datarole == 'table' )
{
if ( property == 'rowCount' )
{
retval = document.getElementById(id).rows.length - 1;
}
else if ( property == 'selectedRowCount' )
{
var i, n ; n = 0 ;
for ( i=1 ; i < document.getElementById(id).rows.length ; i++ )
{
if ( document.getElementById(id).rows[i].cells[0].getElementsByTagName("input")[0].checked == true )
{
n++ ;
}
}
retval = n;
}
else if ( property == 'selectedRows' )
{
var selectedRows=new Array();
var i, code, first, last, n ;
n = 0 ;
for ( i=1 ; i < document.getElementById(id).rows.length ; i++ )
{
if ( document.getElementById(id).rows[i].cells[0].getElementsByTagName("input")[0].checked == true )
{
selectedRows[n] = i ;
n++ ;
}
}
retval = selectedRows;
}
else if ( property == 'cell' )
{
retval = document.getElementById(id).rows[value1].cells[value2].childNodes[0].data;
}
else
{
alert('Property Not Supported');
}
}
else
{
if ( $('#' + id + '0' ).data('role') == 'radio' )
{
var radios = document.getElementsByName(id);
var radios_value;
for(var i = 0; i < radios.length; i++)
{
if(radios[i].checked)
{
retval = i;
break;
}
}
}
else
{
alert('error: widget not supported (01)');
}
}
return retval ;
}
//------------------------------------------------------------------------------------------------------------------------
// set( id , property , value , value2 , value3 )
//------------------------------------------------------------------------------------------------------------------------
function set( id , property , value , value2 , value3)
{
var datarole = $('#' + id ).data('role');
var string;
if ( datarole == 'flipswitch' )
{
if ( property == 'value' )
{
$('#'+id ).val( value ).flipswitch( "refresh" ) ;
}
else
{
setStandard(id , property , value);
}
}
else if ( datarole == 'button' )
{
if ( property == 'value')
{
$("#"+id).val(value);
$("#"+id).button("refresh");
}
else
{
setStandard(id , property , value);
}
}
else if ( datarole == 'text' || datarole == 'number' || datarole == 'date' || datarole == 'textarea' )
{
setStandard(id , property , value);
}
else if ( datarole == 'select' )
{
if ( property == 'value')
{
setStandard(id , 'selectedIndex' , value);
$("#"+id).selectmenu('refresh');
}
}
else if ( datarole == 'std-table' || datarole == 'table' )
{
if ( property == 'cell')
{
document.getElementById(id).rows[value].cells[value2].childNodes[0].data = value3 ;
}
}
else
{
if ( $('#' + id + '0' ).data('role') == 'radio' )
{
if ( property == 'value')
{
$( '#' + id + value ).prop("checked","checked").checkboxradio("refresh");
$("input[type='radio']").checkboxradio("refresh");
}
}
else
{
alert('error: widget not supported(02)');
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// beginGrid
//------------------------------------------------------------------------------------------------------------------------
function beginGrid()
{
WIDGETS.push( [ "begingrid" ] );
}
//------------------------------------------------------------------------------------------------------------------------
// endGrid
//------------------------------------------------------------------------------------------------------------------------
function endGrid()
{
WIDGETS.push( [ "endgrid" ] );
}
//------------------------------------------------------------------------------------------------------------------------
// beginBlock
//------------------------------------------------------------------------------------------------------------------------
function beginBlock()
{
WIDGETS.push( [ "beginblock" ] );
}
//------------------------------------------------------------------------------------------------------------------------
// endBlock
//------------------------------------------------------------------------------------------------------------------------
function endBlock()
{
WIDGETS.push( [ "endblock" ] );
}
//------------------------------------------------------------------------------------------------------------------------
// text
//------------------------------------------------------------------------------------------------------------------------
function text( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "text" , prop['id' ] , prop['label'] , prop['default'] , prop['placeholder'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// textArea
//------------------------------------------------------------------------------------------------------------------------
function textArea( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "textarea" , prop['id' ] , prop['label'] , prop['default'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// date
//------------------------------------------------------------------------------------------------------------------------
function date( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "date" , prop['id' ] , prop['label'] , prop['default'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// number
//------------------------------------------------------------------------------------------------------------------------
function number( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "number" , prop['id' ] , prop['label'] , prop['default'] , prop['placeholder'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// table
//------------------------------------------------------------------------------------------------------------------------
function table( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "table" , prop['id' ] , prop['headers'] , prop['style'] , prop['height'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// button
//------------------------------------------------------------------------------------------------------------------------
function button( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "button" , prop["id"] , prop["caption"] , prop["action"] , prop["inline"] , prop["iconType"] , prop["iconPos"] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// flipswitch
//------------------------------------------------------------------------------------------------------------------------
function flipswitch ( prop )
{
checkDup(prop['id']);
WIDGETS.push( ["flipswitch" , prop['id'] , prop['label'] , prop['onValue'] , prop['offValue'] , prop['default'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// radio
//------------------------------------------------------------------------------------------------------------------------
function radio ( prop )
{
checkDup(prop['id']);
WIDGETS.push( ["radio" , prop['id'] , prop['options'] , prop['default'] , prop['label'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// select
//------------------------------------------------------------------------------------------------------------------------
function select ( prop )
{
checkDup(prop['id']);
WIDGETS.push( ["select" , prop['id'] , prop['options'] , prop['label'] , prop['default'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// header
//------------------------------------------------------------------------------------------------------------------------
function header( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "header" , prop['id'] , prop['caption'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// footer
//------------------------------------------------------------------------------------------------------------------------
function footer( prop )
{
checkDup(prop['id']);
WIDGETS.push( [ "header" , prop['id'] , prop['caption'] ] );
}
//------------------------------------------------------------------------------------------------------------------------
// beginPage
//------------------------------------------------------------------------------------------------------------------------
function beginPage( id )
{
checkDup(id);
CURRENTPAGE = id;
}
//------------------------------------------------------------------------------------------------------------------------
// endPage
//------------------------------------------------------------------------------------------------------------------------
function endPage()
{
var currentRole = '';
var blockCount = 0;
var closedBlocks = 0;
//----------------------------------------------------------------------
// Page Style Parser
//----------------------------------------------------------------------
if ( STYLE == 'desktop' )
{
var styleString = 'data-dialog="true" ';
currentRole = 'dialog';
}
else if ( STYLE == 'mobile' )
{
var styleString = 'data-dialog="false"';
currentRole = 'page';
}
else if ( STYLE == 'auto' )
{
if (window.screen.availWidth > MAX_DIALOG_WIDTH )
{
var styleString = 'data-dialog="true"';
currentRole = 'dialog';
}
else
{
var styleString = 'data-dialog="false"';
currentRole = 'page';
}
}
else
{
alert('error: Invalid Style');
return;
}
//----------------------------------------------------------------------
// Widget Parser
//----------------------------------------------------------------------
var contentString = '';
for ( var i = 0 ; i < WIDGETS.length ; i++ )
{
//----------------------------
// flipswitch
//----------------------------
// 0 -> Widget Type ('flipswitch')
// 1 -> id
// 2 -> Label
// 3 -> On Value
// 4 -> Off Value
// 5 -> Default
//----------------------------
if ( WIDGETS[i][0] == 'flipswitch' )
{
var selected1 = '';
var selected2 = '';
if ( WIDGETS[i][4] == WIDGETS[i][5] )
{
selected1 = 'selected';
}
else if ( WIDGETS[i][3] == WIDGETS[i][5] )
{
selected2 = 'selected';
}
else
{
if ( typeof( WIDGETS[i][5] ) == 'string' )
{
alert('Error (FlipSwitch): Invalid default value');
return;
}
else
{
selected1 = 'selected';
}
}
if ( typeof( WIDGETS[i][2] ) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1] + '">' + WIDGETS[i][2] + '</label>';
}
contentString += '<select id="' + WIDGETS[i][1] +'" data-role="flipswitch">';
contentString += '<option ' + selected1 + ' value="' + WIDGETS[i][4] + '">' + WIDGETS[i][4] + '</option>';
contentString += '<option ' + selected2 + ' value="' + WIDGETS[i][3] + '">' + WIDGETS[i][3] + '</option>';
contentString += '</select>';
}
//----------------------------
// button
//----------------------------
// 0 -> Widget Type ('button')
// 1 -> id
// 2 -> Caption
// 3 -> Action
// 4 -> Inline
// 5 -> Icon Type
// 6 -> Icon Position
//----------------------------
else if ( WIDGETS[i][0] == 'button' )
{
if ( WIDGETS[i][4] == true )
{
var inline = ' data-inline="true" ';
}
else
{
var inline = '';
}
if ( typeof(WIDGETS[i][5]) == 'string' )
{
var iconType = ' data-icon="' + WIDGETS[i][5] + '"' ;
}
else
{
var iconType = '';
}
if ( typeof(WIDGETS[i][6]) == 'string' )
{
var iconPos = ' data-iconpos="' + WIDGETS[i][6] + '"' ;
}
else
{
var iconPos = '';
}
contentString += '<input type="button" data-role="button" ' + iconType + iconPos + ' value="' + WIDGETS[i][2] + '" onclick="' + WIDGETS[i][3] + '" id="' + WIDGETS[i][1] + '"' + inline + '>' ;
}
//----------------------------
// beginGrid
//----------------------------
// 0 -> Widget Type ('begingrid')
//----------------------------
else if ( WIDGETS[i][0] == 'begingrid' )
{
contentString += '_JMG_BEGIN_GRID_PLACEHOLDER_' ;
}
//----------------------------
// endGrid
//----------------------------
// 0 -> Widget Type ('endgrid')
//----------------------------
else if ( WIDGETS[i][0] == 'endgrid' )
{
contentString += '</div>' ;
if ( blockCount == 1 )
{
contentString = contentString.replace( '_JMG_BEGIN_GRID_PLACEHOLDER_' , '<div class="ui-grid-solo ui-responsive">' );
}
else if ( blockCount == 2 )
{
contentString = contentString.replace( '_JMG_BEGIN_GRID_PLACEHOLDER_' , '<div class="ui-grid-a ui-responsive">' );
}
else if ( blockCount == 3 )
{
contentString = contentString.replace( '_JMG_BEGIN_GRID_PLACEHOLDER_' , '<div class="ui-grid-b ui-responsive">' );
}
else if ( blockCount == 4 )
{
contentString = contentString.replace( '_JMG_BEGIN_GRID_PLACEHOLDER_' , '<div class="ui-grid-c ui-responsive">' );
}
else if ( blockCount == 5 )
{
contentString = contentString.replace( '_JMG_BEGIN_GRID_PLACEHOLDER_' , '<div class="ui-grid-d ui-responsive">' );
}
else
{
alert('ERROR: Maximun number of blocks!');
return;
}
}
//----------------------------
// beginBlock
//----------------------------
// 0 -> Widget Type ('beginblock')
//----------------------------
else if ( WIDGETS[i][0] == 'beginblock' )
{
blockCount++;
if ( blockCount == 1 )
{
contentString += '<div class="ui-block-a">' ;
}
else if ( blockCount == 2 )
{
contentString += '<div class="ui-block-b">' ;
}
else if ( blockCount == 3 )
{
contentString += '<div class="ui-block-c">' ;
}
else if ( blockCount == 4 )
{
contentString += '<div class="ui-block-d">' ;
}
else if ( blockCount == 5 )
{
contentString += '<div class="ui-block-e">' ;
}
else
{
alert('ERROR: Maximun number of blocks!');
return;
}
}
//----------------------------
// endBlock
//----------------------------
// 0 -> Widget Type ('endblock')
//----------------------------
else if ( WIDGETS[i][0] == 'endblock' )
{
contentString += '</div>' ;
}
//----------------------------
// header
//----------------------------
// 0 -> Widget Type ('header')
// 1 -> id
// 2 -> Caption
//----------------------------
else if ( WIDGETS[i][0] == 'header' )
{
contentString += '<div data-role="header" id="' + WIDGETS[i][1] + '"> ' ;
contentString += '<h1>' + WIDGETS[i][2] + '</h1>';
contentString += '</div>' ;
}
//----------------------------
// footer
//----------------------------
// 0 -> Widget Type ('footer')
// 1 -> id
// 2 -> Caption
//----------------------------
else if ( WIDGETS[i][0] == 'footer' )
{
contentString += '<div data-role="footer" id="' + WIDGETS[i][1] + '"> ' ;
contentString += '<h1>' + WIDGETS[i][2] + '</h1>';
contentString += '</div>' ;
}
//----------------------------
// text
//----------------------------
// 0 -> Widget Type ('text')
// 1 -> id
// 2 -> Label
// 3 -> Default
// 4 -> Placeholder
//----------------------------
else if ( WIDGETS[i][0] == 'text' )
{
if ( typeof( WIDGETS[i][3]) == 'string' )
{
var value = 'value="' + WIDGETS[i][3] + '"';
}
else
{
var value = '';
}
if ( typeof( WIDGETS[i][4]) == 'string' )
{
var placeholder = 'placeholder="' + WIDGETS[i][4] + '"';
}
else
{
var placeholder = '';
}
if ( typeof( WIDGETS[i][2]) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1] + '">' + WIDGETS[i][2] + '</label>' ;
}
contentString += '<input type="text" data-role="text" data-clear-btn="true" ' + placeholder + ' id="' + WIDGETS[i][1] + '" ' + value + ' >';
}
//----------------------------
// textArea
//----------------------------
// 0 -> Widget Type ('textarea')
// 1 -> id
// 2 -> Label
// 3 -> Default
//----------------------------
else if ( WIDGETS[i][0] == 'textarea' )
{
if ( typeof( WIDGETS[i][2]) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1] + '">' + WIDGETS[i][2] + '</label>' ;
}
contentString += '<textarea data-role="textarea" id="' + WIDGETS[i][1] + '" >';
if ( typeof( WIDGETS[i][3]) == 'string' )
{
contentString += WIDGETS[i][3];
}
contentString += '</textarea>';
}
//----------------------------
// number
//----------------------------
// 0 -> Widget Type ('number')
// 1 -> id
// 2 -> Label
// 3 -> default
// 4 -> placeholder
//----------------------------
else if ( WIDGETS[i][0] == 'number' )
{
if ( typeof( WIDGETS[i][3]) == 'string' || typeof( WIDGETS[i][3]) == 'number' )
{
var value = 'value="' + WIDGETS[i][3] + '"';
}
else
{
var value = '';
}
if ( typeof( WIDGETS[i][4]) == 'string' )
{
var placeholder = 'placeholder="' + WIDGETS[i][4] + '"';
}
else
{
var placeholder = '';
}
if ( typeof( WIDGETS[i][2]) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1] + '">' + WIDGETS[i][2] + '</label>' ;
}
contentString += '<input type="number" data-clear-btn="true" data-role="number" ' + placeholder + ' id="' + WIDGETS[i][1] + '" ' + value + ' >';
}
//----------------------------
// date
//----------------------------
// 0 -> Widget Type ('date')
// 1 -> id
// 2 -> Label
// 3 -> Default
//----------------------------
else if ( WIDGETS[i][0] == 'date' )
{
if ( typeof( WIDGETS[i][2]) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1] + '">' + WIDGETS[i][2] + '</label>' ;
}
if ( typeof( WIDGETS[i][3]) == 'string' )
{
var value = ' value="' + WIDGETS[i][3] + '" ' ;
}
else
{
var value = '' ;
}
contentString += '<input type="date" data-clear-btn="true" data-role="date" id="' + WIDGETS[i][1] + '" ' + value + ' >';
}
//----------------------------
// radio
//----------------------------
// 0 -> Widget Type ('radio')
// 1 -> id
// 2 -> Options Array
// 3 -> Default
// 4 -> Label
//----------------------------
else if ( WIDGETS[i][0] == 'radio' )
{
var checked = '';
var options = WIDGETS[i][2];
if ( typeof( WIDGETS[i][4]) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1]+'L' + '">' + WIDGETS[i][4] + '</label>';
}
contentString += '<fieldset data-role="controlgroup" id="' + WIDGETS[i][1]+'L' + '" >';
for( var n = 0; n < options.length; n++ )
{
if ( WIDGETS[i][3] == n )
{
checked = 'checked="checked"';
}
else
{
checked = '';
}
contentString += '<input type="radio" value="' + options[n] + '" name="' + WIDGETS[i][1] + '" id="' + WIDGETS[i][1]+n + '" data-role="radio" ' + checked + ' >';
contentString += '<label for="' + WIDGETS[i][1]+n + '">' + options[n] + '</label>';
}
contentString += '</fieldset>';
}
//----------------------------
// select
//----------------------------
// 0 -> Widget Type ('select')
// 1 -> id
// 2 -> Options Array
// 3 -> Label
// 4 -> Default
//----------------------------
else if ( WIDGETS[i][0] == 'select' )
{
var selected = '';
var options = WIDGETS[i][2];
if ( typeof( WIDGETS[i][3]) == 'string' )
{
contentString += '<label for="' + WIDGETS[i][1] + '" class="select">' + WIDGETS[i][3] + '</label>';
}
contentString += '<select name="' + WIDGETS[i][1] + '" id="' + WIDGETS[i][1] + '"' + ' data-role="select" ' + '>';
for( var n = 0; n < options.length; n++ )
{
if ( WIDGETS[i][4] == n )
{
selected = 'selected';
}
else
{
selected = '';
}
contentString += '<option ' + selected + ' value="' + n + '">' + options[n] + '</option>';
}
contentString += '</select>';
}
//----------------------------
// table
//----------------------------
// 0 -> Widget Type ('table')
// 1 -> id
// 2 -> headers
// 3 -> style
// 4 -> height
//----------------------------
else if ( WIDGETS[i][0] == 'table' )
{
if ( typeof( WIDGETS[i][3]) == 'string' )
{
if ( WIDGETS[i][3] == 'standard' )
{
var rolemode = ' data-role="std-table" ';
}
else if ( WIDGETS[i][3] == 'columntoggle' )
{
var rolemode = ' data-role="table" data-mode="columntoggle" class="ui-responsive" ';
}
else if ( WIDGETS[i][3] == 'reflow' )
{
var rolemode = ' data-role="table" ';
}
else
{
alert('error: Invalid table style');
return;
}
}
else
{
var rolemode = ' data-role="std-table" ';
}
if ( typeof( WIDGETS[i][4]) == 'string' )
{
var tableHeight = 'height: ' + WIDGETS[i][4] + ';'
}
else
{
var tableHeight = 'height: 16em;'
}
var headers = WIDGETS[i][2];
var tableStyle = 'style="' + tableHeight + 'overflow-y:scroll;border:1px solid rgb(192,192,192);border: 1px solid rgb(192,192,192); border-collapse: collapse;"';
contentString += '<div ' + tableStyle + ' >';
contentString += '<table ' + ' style="border: 1px solid rgb(192,192,192);" ' + rolemode + ' width="100%" id="' + WIDGETS[i][1] + '" >' ;
contentString += '<thead style="height:2em;">';
contentString += '<tr>';
contentString += '<th class="column0" style="border: 1px solid rgb(192,192,192); border-collapse: collapse;" >' + '' + '</th>';
for( var n = 0; n < headers.length; n++ )
{
contentString += '<th data-priority="' + n+1 + '" style="border: 1px solid rgb(192,192,192); border-collapse: collapse;" >' + headers [n] + '</th>';
}
contentString += '</tr>';
contentString += '</thead>';
contentString += '<tbody>';
contentString += '</tbody>';
contentString += '</table>' ;
contentString += '</div>'
}
}
//----------------------------------------------------------------------
// add dialog width css to header
//----------------------------------------------------------------------
var dialogStyle = '';
dialogStyle += '<style>';
dialogStyle += '.ui-dialog-contain {';
dialogStyle += 'width: 92.5%;';
dialogStyle += 'max-width: ' + MAX_DIALOG_WIDTH.toString() + 'px;' ;
dialogStyle += 'margin: 10% auto 15px auto;';
dialogStyle += 'padding: 0;';
dialogStyle += 'position: relative;';
dialogStyle += 'top: -50px;';
dialogStyle += '}';
dialogStyle += 'input[type="checkbox"] {'
dialogStyle += ' width: 1.5em;'
dialogStyle += ' height:1.5em;'
dialogStyle += ' padding: 0.5em;'
dialogStyle += ' border: 1px solid #369;'
dialogStyle += '}'
dialogStyle += '.column0 {'
dialogStyle += 'width: 2em;'
dialogStyle += '}'
dialogStyle += '.grid tr.selected'
dialogStyle += '{'
dialogStyle += ' color: rgb(255,255,255);'
dialogStyle += ' background-color: rgb(100,100,100);'
dialogStyle += '}'
dialogStyle += '.grid tr.unselected'
dialogStyle += '{'
dialogStyle += ' color: rgb(0,0,0);'
dialogStyle += ' background-color: rgb(255,255,255);'
dialogStyle += '}'
$('head').append( dialogStyle );
//----------------------------------------------------------------------
// add page to body
//----------------------------------------------------------------------
$('#main_body').append('<div data-role="page" id="' + CURRENTPAGE + '" ' + styleString + '><div data-role="content">' + contentString + '</div></div>');
CURRENTPAGE = "";
WIDGETS = [];
}
//////////////////////////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////
function setStandard(id , property , value)
{
if ( typeof(value) == "string" )
{
var string = 'document.getElementById("' + id + '").' + property + ' = ' + '"' + value + '"'
}
else
{
var string = 'document.getElementById("' + id + '").' + property + ' = ' + value
}
eval(string);
}
//------------------------------------------------------------------------------------------------------------------------
function checkDup( id )
{
var l = len = WIDGETS.length;
for ( var i = 0, l ; i < len ; i++ )
{
if ( WIDGETS[i][1] === id )
{
alert('warning: id duplicated (' + id + ')' );
return;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
function changeColor(o)
{
if( o.checked )
{
o.parentNode.parentNode.style.backgroundColor='darkgray';
}
else
{
o.parentNode.parentNode.style.backgroundColor='transparent';
}
}
|
require('newrelic');
var express = require('express');
var app = express();
var http = require("http");
app.use(express.static(__dirname));
module.exports = app;
var server = app.listen(process.env.PORT || 3000, function() {
console.log('express server listening on port ' + server.address().port);
});
setInterval(function() {
http.get("http://cherrystreet.herokuapp.com");
}, 300000);
|
!
function() {
"use strict";
angular.module("multiselect-searchtree", [])
} (),
function() {
"use strict";
var a = angular.module("multiselect-searchtree");
a.controller("multiSelectTreeCtrl", ["$scope", "$document",
function(a, b) {
function d() {
e(),
a.$apply()
}
function e() {
a.showTree = !1,
c && (c.isActive = !1, c = void 0),
b.off("click", d)
}
function f(b) {
for (var c = 0,
d = b.length; c < d; c++) g(b[c]) || b[c].selected !== !0 ? g(b[c]) && b[c].selected === !1 && (b[c].selected = !0) : a.selectedItems.push(b[c]),
b[c] && b[c].children && f(b[c].children)
}
function g(b) {
var c = !1;
if (a.selectedItems){
for (var d = 0; d < a.selectedItems.length; d++){
if (a.selectedItems[d].name === b.name) {
c = !0;
break
}
}
}
return c
}
var c;
a.showTree = !1,
a.selectedItems = [],
a.multiSelect = a.multiSelect || !1,
a.onActiveItem = function(a) {
c !== a && (c && (c.isActive = !1), c = a, c.isActive = !0)
},
a.refreshOutputModel = function() {
a.outputModel = [];
var tmp = angular.copy(a.selectedItems);
angular.forEach(tmp,function(v){
v.children.length === 0 && v.selected && a.outputModel.push(v.name)
})
},
a.refreshSelectedItems = function() {
a.selectedItems = [],
a.inputModel && f(a.inputModel)
},
a.deselectItem = function(b, c) {
c.stopPropagation(),
a.selectedItems.splice(a.selectedItems.indexOf(b), 1),
b.selected = !1,
this.refreshOutputModel()
},
a.onControlClicked = function(c) {
c.stopPropagation(),
a.showTree = !a.showTree,
a.showTree && b.on("click", d)
},
a.onFilterClicked = function(a) {
a.stopPropagation()
},
a.clearFilter = function(b) {
b.stopPropagation(),
a.filterKeyword = ""
},
a.canSelectItem = function(b) {
return a.callback({
item: b,
selectedItems: a.selectedItems
})
},
a.itemSelected = function(b) {
function f(c) {
c.forEach(function(c) {
b.selected && !c.selected ? a.selectedItems.push(c) : !b.selected && c.selected && a.selectedItems.splice(a.selectedItems.indexOf(c), 1),
c.selected = b.selected,
c.children && c.children.length > 0 && f(c.children)
})
}
if (! (a.useCallback && a.canSelectItem(b) === !1 || a.selectOnlyLeafs && b.children && b.children.length > 0)) {
if (a.multiSelect) {
var d = a.selectedItems.indexOf(b);
if(g(b)){
b.selected = !1, a.selectedItems.splice(d, 1)
}else{
b.selected = !0
a.selectedItems.push(b)
}
b.children && b.children.length > 0 && f(b.children)
} else {
e();
for (var c = 0; c < a.selectedItems.length; c++) a.selectedItems[c].selected = !1;
b.selected = !0,
a.selectedItems = [],
a.selectedItems.push(b)
}
this.refreshOutputModel()
}
},
a.onSelectAll = function(a, b) {
function c(a) {
a.selected = !0,
a.children.length > 0 && a.children.forEach(function(a) {
c(a)
})
}
a.forEach(function(a) {
c(a)
}),
this.refreshSelectedItems(),
this.refreshOutputModel()
},
a.onClearAll = function(a, b) {
function c(a) {
a.selected = !1,
a.children.length > 0 && a.children.forEach(function(a) {
c(a)
})
}
a.forEach(function(a) {
c(a)
}),
this.refreshSelectedItems(),
this.refreshOutputModel()
}
}]),
a.directive("multiselectSearchtree",
function() {
return {
restrict: "E",
templateUrl: "src/multiselect-searchtree.tpl.html",
scope: {
inputModel: "=",
outputModel: "=?",
multiSelect: "=?",
selectOnlyLeafs: "=?",
callback: "&",
defaultLabel: "@",
extraButtons: "=?",
directSearch: "=?"
},
link: function(a, b, c) {
function d(a, b) {
for (var c = e(a, []), d = 0, f = c.length; d < f; d++) if (c[d].name.toLowerCase().indexOf(b.toLowerCase()) !== -1) return ! 1;
return ! 0
}
function e(a, b) {
for (var c = 0; c < a.children.length; c++) b.push(a.children[c]),
e(a.children[c], b);
return b
}
function f(a) {
a.isFiltered = !1,
void 0 != a.p && f(a.p)
}
function g(b, c) {
b.name.toLowerCase().indexOf(a.filterKeyword.toLowerCase()) !== -1 ? f(b) : b.isFiltered = !0,
b.children.length > 0 && angular.forEach(b.children,
function(a) {
a.p = b,
g(a)
})
}
function h(b) {
b.name.toLowerCase().indexOf(a.filterKeyword.toLowerCase()) !== -1 ? b.isFiltered = !1 : d(b, a.filterKeyword) ? b.isFiltered = !0 : b.isFiltered = !1
}
c.callback && (a.useCallback = !0),
a.extraButtons && (a.clearSearchIconStyle = {
right: "210px"
}),
a.$watch("inputModel",
function(b) {
b && (a.refreshSelectedItems(), a.refreshOutputModel())
}),
a.$watch("filterKeyword",
function() {
void 0 !== a.filterKeyword && (a.directSearch ? angular.forEach(a.inputModel,
function(a) {
g(a)
}) : angular.forEach(a.inputModel,
function(a) {
h(a)
}))
})
},
controller: "multiSelectTreeCtrl"
}
})
} (),
function() {
"use strict";
var a = angular.module("multiselect-searchtree");
a.controller("treeItemCtrl", ["$scope",
function(a) {
a.item.isExpanded !== !1 && a.item.isExpanded !== !0 && (a.item.isExpanded = !1),
a.showExpand = function(a) {
return a.children && a.children.length > 0
},
a.onExpandClicked = function(a, b) {
b.stopPropagation(),
a.isExpanded = !a.isExpanded
},
a.clickSelectItem = function(b, c) {
c.stopPropagation(),
a.itemSelected && a.itemSelected({
item: b
})
},
a.subItemSelected = function(b, c) {
a.itemSelected && a.itemSelected({
item: b
})
},
a.activeSubItem = function(b, c) {
a.onActiveItem && a.onActiveItem({
item: b
})
},
a.onMouseOver = function(b, c) {
c.stopPropagation(),
a.onActiveItem && a.onActiveItem({
item: b
})
},
a.showCheckbox = function() {
return !! a.multiSelect && (!a.selectOnlyLeafs && (a.useCallback ? a.canSelectItem(a.item) : void 0))
}
}]),
a.directive("treeItem", ["$compile",
function(a) {
return {
restrict: "E",
templateUrl: "src/tree-item.tpl.html",
scope: {
item: "=",
itemSelected: "&",
onActiveItem: "&",
multiSelect: "=?",
selectOnlyLeafs: "=?",
isActive: "=",
useCallback: "=",
canSelectItem: "="
},
controller: "treeItemCtrl",
compile: function(b, c, d) {
angular.isFunction(d) && (d = {
post: d
});
var f, e = b.contents().remove();
return {
pre: d && d.pre ? d.pre: null,
post: function(b, c, g) {
f || (f = a(e)),
f(b,
function(a) {
c.append(a)
}),
d && d.post && d.post.apply(null, arguments)
}
}
}
}
}])
} ();
|
module.exports = function(grunt) {
grunt.config.set('sass', {
options: {
loadPath: 'src/styles'
},
dev: {
files: {
'build/dist/styles.css': 'build/tmp/styles.scss'
}
},
prod: {
files: {
'build/dist/styles.css': 'build/tmp/styles.scss'
}
}
});
grunt.loadNpmTasks('grunt-contrib-sass');
};
|
const express = require('express')
const path = require('path')
const logger = require('morgan')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const index = require('./routes/index')
const app = express()
// view engine setup
app.engine('html', require('ejs').renderFile)
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'html')
app.use(logger('dev'))
app.use(bodyParser.json()) // convert to json to obj(application/json)
app.use(bodyParser.urlencoded({ extended: false }))// convert x-www-form-urlencoded to Obj
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', index)
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found')
err.status = 404
next(err)
})
// error handler
app.use((err, req, res) => {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
// render the error page
res.status(err.status || 500)
res.render('error')
})
module.exports = app
|
import Storyview from './Story'
export default {
path: '/stories/:storyid',
component: Storyview
}
|
'use strict';
// ==============================
// ABSTRACT PC BUILDER
// ==============================
var Workforce = function () {
if (this.constructor === Workforce) {
throw new Error("You cannot instantiate an abstract class!");
}
};
Workforce.prototype.assemblePC = function () {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setMotherboard = function (motherboard) {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setCpu = function (cpu) {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setRam = function (ram) {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setSsd = function (ssd) {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setNic = function (nic) {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setPowerSupply = function (powerSupply) {
throw new Error("You cannot call an abstract method!");
};
Workforce.prototype.setCaseDesign = function (caseDesign) {
throw new Error("You cannot call an abstract method!");
};
module.exports = Workforce;
|
var task = function(request, callback, configuration){
var template = "helloParamterized.ejs";
var AWS = configuration.aws;
var S3 = new AWS.S3();
callback(null, {template: template, params:{info:"Hello World from code!"}});
}
exports.action = task;
|
'use strict';
const MongoClient = require('mongodb').MongoClient;
module.exports = class Events {
constructor() {
this.database = null;
this.collections = {};
}
getDatabase(callback) {
if (this.database) {
callback(this.database);
} else {
MongoClient.connect('mongodb://writer:writer@ds017584.mlab.com:17584/events', (err, db) => {
if (!err) {
console.log('connected to database!');
this.database = db;
callback(this.database);
} else {
console.log(err);
}
});
}
}
getCollection(collection, callback) {
if (this.collections[collection]) {
callback(this.collections[collection]);
} else {
this.getDatabase(database => {
this.collections[collection] = database.collection(collection);
callback(this.collections[collection]);
});
}
}
addEvent(event, callback) {
this.getCollection('events', collection => {
collection.insertOne(event, callback);
});
}
getTags(callback) {
this.getCollection('events', collection => {
//collection.find().toArray(callback);
collection.aggregate([
{ "$group": { "_id": "$tags", "count": { $sum: 1 } } }
], callback);
});
}
}
|
module.exports = require('./../make')({
build: true
});
|
import * as $ from './utilities';
export default {
start(event) {
const self = this;
const e = $.getEvent(event);
const target = e.target;
if (target.tagName.toLowerCase() === 'img') {
self.target = target;
self.show();
}
},
click(event) {
const self = this;
const e = $.getEvent(event);
const target = e.target;
const action = $.getData(target, 'action');
const imageData = self.imageData;
switch (action) {
case 'mix':
if (self.played) {
self.stop();
} else if (self.options.inline) {
if (self.fulled) {
self.exit();
} else {
self.full();
}
} else {
self.hide();
}
break;
case 'view':
self.view($.getData(target, 'index'));
break;
case 'zoom-in':
self.zoom(0.1, true);
break;
case 'zoom-out':
self.zoom(-0.1, true);
break;
case 'one-to-one':
self.toggle();
break;
case 'reset':
self.reset();
break;
case 'prev':
self.prev();
break;
case 'play':
self.play();
break;
case 'next':
self.next();
break;
case 'rotate-left':
self.rotate(-90);
break;
case 'rotate-right':
self.rotate(90);
break;
case 'flip-horizontal':
self.scaleX(-imageData.scaleX || -1);
break;
case 'flip-vertical':
self.scaleY(-imageData.scaleY || -1);
break;
default:
if (self.played) {
self.stop();
}
}
},
load() {
const self = this;
const options = self.options;
const image = self.image;
const index = self.index;
const viewerData = self.viewerData;
if (self.timeout) {
clearTimeout(self.timeout);
self.timeout = false;
}
$.removeClass(image, 'viewer-invisible');
image.style.cssText = (
'width:0;' +
'height:0;' +
`margin-left:${viewerData.width / 2}px;` +
`margin-top:${viewerData.height / 2}px;` +
'max-width:none!important;' +
'visibility:visible;'
);
self.initImage(() => {
$.toggleClass(image, 'viewer-transition', options.transition);
$.toggleClass(image, 'viewer-move', options.movable);
self.renderImage(() => {
self.viewed = true;
$.dispatchEvent(self.element, 'viewed', {
originalImage: self.images[index],
index,
image,
});
});
});
},
loadImage(event) {
const e = $.getEvent(event);
const image = e.target;
const parent = image.parentNode;
const parentWidth = parent.offsetWidth || 30;
const parentHeight = parent.offsetHeight || 50;
const filled = !!$.getData(image, 'filled');
$.getImageSize(image, (naturalWidth, naturalHeight) => {
const aspectRatio = naturalWidth / naturalHeight;
let width = parentWidth;
let height = parentHeight;
if (parentHeight * aspectRatio > parentWidth) {
if (filled) {
width = parentHeight * aspectRatio;
} else {
height = parentWidth / aspectRatio;
}
} else if (filled) {
height = parentWidth / aspectRatio;
} else {
width = parentHeight * aspectRatio;
}
$.setStyle(image, {
width,
height,
marginLeft: (parentWidth - width) / 2,
marginTop: (parentHeight - height) / 2
});
});
},
resize() {
const self = this;
self.initContainer();
self.initViewer();
self.renderViewer();
self.renderList();
if (self.viewed) {
self.initImage(() => {
self.renderImage();
});
}
if (self.played) {
$.each($.getByTag(self.player, 'img'), (image) => {
$.addListener(image, 'load', $.proxy(self.loadImage, self), true);
$.dispatchEvent(image, 'load');
});
}
},
wheel(event) {
const self = this;
const e = $.getEvent(event);
if (!self.viewed) {
return;
}
e.preventDefault();
// Limit wheel speed to prevent zoom too fast
if (self.wheeling) {
return;
}
self.wheeling = true;
setTimeout(() => {
self.wheeling = false;
}, 50);
const ratio = Number(self.options.zoomRatio) || 0.1;
let delta = 1;
if (e.deltaY) {
delta = e.deltaY > 0 ? 1 : -1;
} else if (e.wheelDelta) {
delta = -e.wheelDelta / 120;
} else if (e.detail) {
delta = e.detail > 0 ? 1 : -1;
}
self.zoom(-delta * ratio, true, e);
},
keydown(event) {
const self = this;
const e = $.getEvent(event);
const options = self.options;
const key = e.keyCode || e.which || e.charCode;
if (!self.fulled || !options.keyboard) {
return;
}
switch (key) {
// (Key: Esc)
case 27:
if (self.played) {
self.stop();
} else if (options.inline) {
if (self.fulled) {
self.exit();
}
} else {
self.hide();
}
break;
// (Key: Space)
case 32:
if (self.played) {
self.stop();
}
break;
// View previous (Key: ←)
case 37:
self.prev();
break;
// Zoom in (Key: ↑)
case 38:
// Prevent scroll on Firefox
e.preventDefault();
self.zoom(options.zoomRatio, true);
break;
// View next (Key: →)
case 39:
self.next();
break;
// Zoom out (Key: ↓)
case 40:
// Prevent scroll on Firefox
e.preventDefault();
self.zoom(-options.zoomRatio, true);
break;
// Zoom out to initial size (Key: Ctrl + 0)
case 48:
// Fall through
// Zoom in to natural size (Key: Ctrl + 1)
// eslint-disable-next-line
case 49:
if (e.ctrlKey || e.shiftKey) {
e.preventDefault();
self.toggle();
}
break;
// No default
}
},
dragstart(e) {
if (e.target.tagName.toLowerCase() === 'img') {
e.preventDefault();
}
},
mousedown(event) {
const self = this;
const options = self.options;
const pointers = self.pointers;
const e = $.getEvent(event);
if (!self.viewed) {
return;
}
if (e.changedTouches) {
$.each(e.changedTouches, (touch) => {
pointers[touch.identifier] = $.getPointer(touch);
});
} else {
pointers[e.pointerId || 0] = $.getPointer(e);
}
let action = options.movable ? 'move' : false;
if (Object.keys(pointers).length > 1) {
action = 'zoom';
} else if ((e.pointerType === 'touch' || e.type === 'touchmove') && self.isSwitchable()) {
action = 'switch';
}
self.action = action;
},
mousemove(event) {
const self = this;
const options = self.options;
const pointers = self.pointers;
const e = $.getEvent(event);
const action = self.action;
const image = self.image;
if (!self.viewed || !action) {
return;
}
e.preventDefault();
if (e.changedTouches) {
$.each(e.changedTouches, (touch) => {
$.extend(pointers[touch.identifier], $.getPointer(touch), true);
});
} else {
$.extend(pointers[e.pointerId || 0], $.getPointer(e, true));
}
if (action === 'move' && options.transition && $.hasClass(image, 'viewer-transition')) {
$.removeClass(image, 'viewer-transition');
}
self.change(e);
},
mouseup(event) {
const self = this;
const pointers = self.pointers;
const e = $.getEvent(event);
const action = self.action;
if (!action) {
return;
}
if (e.changedTouches) {
$.each(e.changedTouches, (touch) => {
delete pointers[touch.identifier];
});
} else {
delete pointers[e.pointerId || 0];
}
if (!Object.keys(pointers).length) {
if (action === 'move' && self.options.transition) {
$.addClass(self.image, 'viewer-transition');
}
self.action = false;
}
},
};
|
var playersController = exports; exports.constructor = function playersController(){};
var _ = require('lodash');
var players = require('../sonos/players');
playersController.list = function(req, res, next) {
players.client.find(function(err, players) {
if (err) {
return next(err);
}
res.send(players);
});
};
playersController.get = function(req, res, next) {
players.client.find(req.params.name, function(err, players) {
if (err) {
return next(err);
}
if (!players || players.length < 1) {
err = new Error('The requested player could not be found');
err.type = 'not found';
return next(err);
}
// only return the one item
res.send(players[0]);
});
};
playersController.queue = function(req, res, next) {
players.client.queue(req.params.name, req.query, function(err, queue) {
if (err) {
return next(err);
}
res.send({
roomName: req.params.name,
currentIndex: queue.currentIndex,
limit: queue.limit,
offset: queue.offset,
tracks: queue.tracks
});
});
};
playersController.clearQueue = function(req, res, next) {
players.client.clearQueue(req.params.name, function(err, queue) {
if (err) {
return next(err);
}
res.send({
roomName: req.params.name,
currentIndex: queue.currentIndex,
limit: queue.limit,
offset: queue.offset,
tracks: queue.tracks
});
});
};
playersController.playlists = function(req, res, next) {
players.client.playlists(req.params.name, function(err, playlists) {
if (err) {
return next(err);
}
res.send({
roomName: req.params.name,
playlists: playlists
});
});
};
playersController.action = function(req, res, next) {
var action = req.params.action;
var playerName = req.params.name;
var opts = _.extend({}, req.body, req.query);
players.client.action(playerName, action, opts, function(err, state) {
if (err) {
return next(err);
}
res.send(state);
});
};
|
'use strict';
const setAction = (creep) => {
if (creep.memory.action && creep.carry.energy === 0 || creep.memory.role === 'attacker' || creep.memory.role === 'healer'){
creep.memory.action = false;
}
if (!creep.memory.action && creep.carry.energy === creep.carryCapacity){
creep.memory.action = true;
}
};
module.exports = setAction;
|
var gulp = require('gulp');
var jade = require('gulp-jade');
var config = require('../../config');
gulp.task('samples:jade', function () {
gulp.src(config.samples.jade.src)
.pipe(jade({}))
.pipe(gulp.dest(config.samples.html.dest));
});
|
var parseString = require('xml2js').parseString;
// The body of the response from each of our api requests can either be xml or json
// if body is json, simply return the json
// else body is xml, so asynchronously parse the xml and wait for the result
// This function returns a promise for the json value
var getJsonFromBody = function(body) {
var prom_json = new Promise(function(resolve, reject) {
try {
var json = JSON.parse(body);
resolve(json);
} catch(e) {
var xml = body;
parseString(xml, function(err, json) {
if (err)
reject(err);
else
resolve(json);
});
}
});
return prom_json;
};
module.exports = getJsonFromBody;
|
'use strict';
var url = require('url');
var zlib = require('zlib');
var _ = require('./helpers');
module.exports = function(options, callback){
var callbackDone = false,
httpProtocol = options.url.indexOf('https') === 0 ? 'https' : 'http',
requestData = url.parse(options.url),
method = (options.method || 'get').toLowerCase(),
isJson = options.json || false,
headers = options.headers || {},
isPost = method === 'post',
postBody = isPost ? JSON.stringify(options.body) : null,
contentLength = !!postBody ? Buffer.byteLength(postBody) : null,
timeout = options.timeout || 5,
setHeader = function(v, k){ requestData.headers[k] = v; };
var respond = function(body, details){
body = body.toString('utf-8');
var error = details.response.statusCode !== 200 ? details.response.statusCode : null,
response;
if(isJson){
try {
callback(error, JSON.parse(body), details);
} catch(e){
return callback('json parsing error', null, details);
}
} else {
callback(error, body, details);
}
};
requestData.headers = {};
requestData.method = method;
_.each(headers, setHeader);
setHeader('gzip', 'accept-encoding');
if(isPost){
setHeader(contentLength, 'content-length');
setHeader('application/json', 'content-type');
}
var req = require(httpProtocol).request(requestData).on('response', function(response) {
var body = [];
var details = {
response: {
headers: response.headers,
statusCode: response.statusCode
}
};
response.on('data', function(chunk){
body.push(chunk);
}).on('end', function(){
body = Buffer.concat(body);
if(!callbackDone){
callbackDone = true;
if(response.headers['content-encoding'] === 'gzip'){
zlib.gunzip(body, function(err, dezipped) {
if(!!err){ return callback(err); }
respond(dezipped, details);
});
} else {
respond(body, details);
}
}
});
}).on('error', function(e){
if(!callbackDone){
callbackDone = true;
callback(e);
}
});
req.setTimeout(1000 * timeout, function(){
if(!callbackDone){
callbackDone = true;
callback('timeout');
}
});
if(isPost){
req.write(postBody);
}
req.end();
};
|
import { Logging, Controller, Component, Evented } from "ng-harmony-decorator";
import { EventedController } from "ng-harmony-controller";
import CustomersFormTpl from "./customer_form.pug";
import "./customer_form.sass";
import Config from "../../../../assets/data/config.global.json";
@Component({
module: "webtrekk",
selector: "customerForm",
restrict: "E",
replace: true,
controller: "CustomersFormCtrl",
template: CustomersFormTpl
})
@Controller({
module: "webtrekk",
name: "CustomersFormCtrl",
deps: ["$location", "$rootScope", "CustomerService"],
scope: {
model: "@"
}
})
@Logging({
loggerName: "CustomersFormLogger",
...Config
})
export class CustomersFormCtrl extends EventedController {
constructor(...args) {
super(...args);
this.$scope.$on("change", this.handleEvent.bind(this));
}
handleEvent (ev, { scope, triggerTokens }) {
if (scope._name.fn === "CustomersFormCtrl" &&
triggerTokens.type === "mouseup") {
this.log({
level: "warn",
msg: "Button Clicked, Handle Behaviour Propagation?"
});
}
}
@Evented({
selector: "label#save",
type: "mouseup",
})
async saveAndReturn () {
let valid = Object.getOwnPropertyNames(this.$scope.model)
.map((tupel) => {
let valid = this.$scope.model[tupel].validate();
if (!valid) {
this.log({
level: "error",
msg: `${this.$scope.model[tupel].label} cannot be ${this.$scope.model[tupel].content} -- invalid`,
});
}
this.$scope.model[tupel].valid = valid;
return valid;
}).reduce((acc, tupel) => acc && tupel);
if (valid) {
await this.CustomerService.upsertCustomer({
customer_id: this.$scope.model.id.content,
first_name: this.$scope.model.first_name.content,
last_name: this.$scope.model.last_name.content,
birthday: this.$scope.model.age.content.toString(),
gender: this.$scope.model.gender.content,
last_contact: this.$scope.model.last_contact.content.toString(),
customer_lifetime_value: this.$scope.model.customer_lifetime_value.content,
});
this.$location.url("/");
this.$rootScope.$apply();
}
this._digest();
}
@Evented({
selector: "label#cancel",
type: "mouseup",
})
cancelByReturn () {
this.$location.path("/");
this.$rootScope.$apply();
}
}
|
handlers.getRegister = function (ctx) {
ctx.loadPartials({
header: '../views/common/header.hbs',
footer: '../views/common/footer.hbs'
}).then(function () {
this.partial('../views/user/register.hbs');
});
}
handlers.getLogin = function (ctx) {
ctx.loadPartials({
header: '../views/common/header.hbs',
footer: '../views/common/footer.hbs'
}).then(function () {
this.partial('../views/user/login.hbs');
});
}
handlers.registerUser = function (ctx) {
let username = ctx.params.username;
let firstName = ctx.params.firstName;
let lastName = ctx.params.lastName;
let password = ctx.params.password;
let repeatPassword = ctx.params.repeatPassword;
if (firstName.length < 2) {
notify.showError("The firstName should be at least 2 characters long");
return;
}
if (lastName.length < 2) {
notify.showError("The lastName should be at least 2 characters long");
return;
}
if (username.length < 3) {
notify.showError("The username should be at least 3 characters long");
return;
}
if (password.length < 6) {
notify.showError('The password should be at least 6 characters long');
return;
}
if (password !== repeatPassword) {
notify.showError('The repeat password should be equal to the password');
return;
}
userService.register(username, password, firstName, lastName).then((res) => {
userService.saveSession(res);
notify.showInfo('User registration successful.');
ctx.redirect('#/home');
}).catch(function (err) {
notify.handleError(err);
});
}
handlers.logoutUser = function (ctx) {
userService.logout().then(() => {
sessionStorage.clear();
notify.showInfo('Logout successful.');
ctx.redirect('#/home');
})
}
handlers.loginUser = function (ctx) {
let username = ctx.params.username;
let password = ctx.params.password;
userService.login(username, password).then((res) => {
userService.saveSession(res);
notify.showInfo('Login successful.');
ctx.redirect('#/home');
}).catch(function (err) {
notify.handleError(err);
});
}
|
module.exports = class BackstopException {
constructor (msg, scenario, viewport, originalError) {
this.msg = msg;
this.scenario = scenario;
this.viewport = viewport;
this.originalError = originalError;
}
toString () {
return 'BackstopException: ' +
this.scenario.label + ' on ' +
this.viewport.label + ': ' +
this.originalError.toString();
}
};
|
import React from "react";
import Griddle from 'griddle-react';
import styles from "./style.css";
import restCalls from '../../utils/restCalls';
import { browserHistory } from 'react-router';
import AddNewCaseModal from '../../common/components/CaseModal';
import ViewCaseModal from '../../common/components/ViewCaseModal';
import TreasuryModal from '../../common/components/TreasuryModal';
import ViewTreasuryModal from '../../common/components/ViewTreasuryModal';
import NachaDrop from '../../common/components/NachaDrop';
import {Nav, NavDropdown,Navbar, NavItem, MenuItem, Button,Accordion,Panel} from 'react-bootstrap';
var HomePage = React.createClass ({
getInitialState: function(){
return {
userInfo: JSON.parse(window.localStorage.getItem('user')),
currentCaseData: "No Case Selected"
}
},
calcDayDelta: function(theCase){
let oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
let dateCaseOpened = new Date(theCase.dateCreated);
let numDaysOpened = Math.round(Math.abs((Date.now() - dateCaseOpened.getTime())/(oneDay)));
theCase.daysOpen = numDaysOpened;
return theCase;
},
closedCases: function(){
//set cases to empty object
this.setState({ cases: {} })
//request all the cases from DB
restCalls.getDashboardInfo()
//after those cases come back pass to allCases
.then(function(allCases){
//for each case obj in all cases calc how long it has been open
var closedCases = allCases.filter(function(aCase){
return aCase.currentStatus == "closed";
});
closedCases.map( theCase => this.calcDayDelta(theCase) );
this.setState({cases: closedCases});
}.bind(this))
},
allCases: function(){
//request all the cases from DB
restCalls.getDashboardInfo()
//after those cases come back pass to allCases
.then(function(allCases){
//for each case obj in all cases calc how long it has been open
allCases.map( theCase => this.calcDayDelta(theCase) );
this.setState({cases: allCases});
}.bind(this))
},
myCases: function(){
//set cases to empty object
this.setState({ cases: {} })
//request all the cases from DB
restCalls.getDashboardInfo()
//after those cases come back pass to allCases
.then(function(allCases){
//for each case obj in all cases calc how long it has been open
//allCases = [ {assignedto:1}, {assignedto:2} ]
var myCasesMutated = allCases.filter(function(aCase){
return aCase.userIdAssigned == "8";
});
if (myCasesMutated.length > 0)
myCasesMutated.map( theCase => this.calcDayDelta(theCase) );
this.setState({cases: myCasesMutated});
}.bind(this))
},
componentDidMount: function() {
this.allCases();
},
logOut: function(){
window.localStorage.removeItem('user');
browserHistory.push('/');
},
openGovRecModal: function () {
this.refs.govRecCaseModal.open();
},
openTresModal: function () {
this.refs.tresModal.open();
},
//wrapping caseData attributes in H3 html element
//TODO should move this to an onShow() function in Modal
parseCaseData(theCase){
return Object.keys(theCase).map( (theKey, idx) => <h3 key={idx} > {theCase[theKey]} </h3>);
},
// open modal to view all case details
rowClick: function (rowCaseData) {
//setting state allows us to update data in viewCaseModal
this.setState({caseData: rowCaseData.props.data});
this.refs.viewCaseModal.open();
},
render() {
return (
<div className={styles.content}>
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a href="#">CCMS</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} active={true} href="#">Dashboard</NavItem>
<NavDropdown eventKey={3} title="Add Case" id="basic-nav-dropdown">
<MenuItem eventKey={3.1} onClick={this.openGovRecModal}>Government Reclamation</MenuItem>
<MenuItem eventKey={3.2} onClick={this.openTresModal}>Treasury Form</MenuItem>
</NavDropdown>
<NavDropdown eventKey={5} title="Case Views" id="basic-nav-dropdown">
<MenuItem eventKey={5.1} onClick={this.allCases} >All Cases</MenuItem>
<MenuItem eventKey={5.2} onClick={this.myCases} >My Cases</MenuItem>
<MenuItem eventKey={5.2} onClick={this.closedCases} >Closed Cases</MenuItem>
</NavDropdown>
<NavItem eventKey={1} onClick={this.logOut}>Log out</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<NachaDrop className={styles.dropbox} refreshCases={this.allCases} />
<br/>
<h1 className={styles.welcomeText} > Cases for {this.state.userInfo.firstName} {this.state.userInfo.LastName} </h1>
<br/>
<Griddle
results={this.state.cases}
tableClassName="table" showFilter={true}
showSettings={true}
columns={["caseId","benName", "totalAmount", "sla", 'daysOpen', 'currentStatus']}
noDataMessage={"No Cases to Display. Try Refreshing the page or click Add New above."}
onRowClick={this.rowClick}
enableInfiniteScroll={true}
bodyHeight={500}
filterPlaceholderText={"Search"}
columnMetadata={meta}
initialSort={"dateCreated"}
initialSortAscending={false}
/>
{/* This is the modal that is rendered when a row is click
currentCaseData is passed as a property which the modal can render*/}
<ViewCaseModal refreshCases={this.allCases} case={this.state.caseData} ref={'viewCaseModal'} />
<AddNewCaseModal refreshCases={this.allCases} ref={'govRecCaseModal'} />
<ViewTreasuryModal case={this.state.caseData} ref={'viewTreasuryModal'} />
<TreasuryModal refreshCases={this.allCases} ref={'tresModal'} />
</div>
);
}
})
var meta = [
{
"columnName": "caseId",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Case ID"
},
{
"columnName": "id",
"order": 1,
"locked": false,
"visible": false,
"displayName": "ID"
},
{
"columnName": "benName",
"order": 2,
"locked": false,
"visible": true,
"displayName": "Beneficiary Name"
},
{
"columnName": "totalAmount",
"order": 3,
"locked": false,
"visible": true,
"displayName": "Total Amount"
},
{
"columnName": "sla",
"order": 4,
"locked": false,
"visible": true,
"displayName": "SLA"
},
{
"columnName": "daysOpen",
"order": 5,
"locked": false,
"visible": true,
"displayName": "Days Open"
},
{
"columnName": "dateCreated",
"order": 5,
"locked": false,
"visible": false,
"displayName": "Date Created"
},
{
"columnName": "currentStatus",
"order": 6,
"locked": false,
"visible": true,
"displayName": "Status"
},
{
"columnName": "dateCreated",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Date Created"
},
{
"columnName": "assigned",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Assigned"
},
{
"columnName": "dateVerified",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Date Verified"
},
{
"columnName": "userIdClosed",
"order": 1,
"locked": false,
"visible": false,
"displayName": "User Id Closed"
},
{
"columnName": "watchItem",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Watch"
},
{
"columnName": "checkNumber",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Check Number"
},
{
"columnName": "locked",
"order": 1,
"locked": false,
"visible": false,
"displayName": "locked"
},
{
"columnName": "benAccountNumber",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Account Number"
},
{
"columnName": "otherBenefitsComments",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Benefits Comments"
},
{
"columnName": "mailedTo",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Mailed to"
},
{
"columnName": "userIdVerified",
"order": 1,
"locked": false,
"visible": false,
"displayName": "User Id Verified"
},
{
"columnName": "reviewDeadline",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Review Deadline"
},
{
"columnName": "userIdAssigned",
"order": 1,
"locked": false,
"visible": false,
"displayName": "User Id Assigned"
},
{
"columnName": "benSocialNumber",
"order": 1,
"locked": false,
"visible": true,
"displayName": "SSN"
},
{
"columnName": "numberPayments",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Number of Payments"
},
{
"columnName": "fullRecovery",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Full Recovery"
},
{
"columnName": "glCostCenter",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Cost Center"
},
{
"columnName": "userIdOpened",
"order": 1,
"locked": false,
"visible": false,
"displayName": "User ID Opened"
},
{
"columnName": "mainType",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Case Type"
},
{
"columnName": "benCustomerId",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Beneficiary ID"
},
{
"columnName": "claimNumber",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Claim Number"
},
{
"columnName": "completedDate",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Date Completed"
},
{
"columnName": "ddaAccountNumber",
"order": 1,
"locked": false,
"visible": false,
"displayName": "DDA Account Number"
},
{
"columnName": "dateClosed",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Date Closed"
},
{
"columnName": "subType",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Sub Type"
},
{
"columnName": "dateOfDeath",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Date of Death"
},
{
"columnName": "recoveryMethod",
"order": 1,
"locked": false,
"visible": true,
"displayName": "Recovery Method"
},
{
"columnName": "additionalNotes",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Additional Notes"
},
{
"columnName": "otherRecoveryComments",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Recovery Comments"
},
{
"columnName": "otherGovBenefits",
"order": 1,
"locked": false,
"visible": false,
"displayName": "Other Gov Benefits"
},
];
module.exports = HomePage;
|
Router.route('/users', {
name: 'menu.users',
template: 'users',
parent: 'menu',
title: 'Users',
});
|
export default function isNull(x) {
return x === null;
}
|
(function() {
'use strict';
angular
.module('app.home')
.controller('Home', Home);
Home.$inject = ['$scope', 'template'];
function Home($scope, template) {
var vm = this;
activate();
function activate() {
console.log('Activating Home Controller');
template.get('app/home/language/home.es.json')
.then(function(result) {
vm.text = result;
$scope.app.setTitle(vm.text.title);
}); // Loads text files.
}
}
})();
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Sdk = require('./Sdk');
var _Sdk2 = _interopRequireDefault(_Sdk);
var _global = require('./global');
var _global2 = _interopRequireDefault(_global);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
load: function load() {
var _this = this;
if (typeof _global2.default.URLSearchParams === 'function') {
this.URLSearchParams = _global2.default.URLSearchParams;
return _Sdk2.default.Promise.resolve();
}
return new _Sdk2.default.Promise(function (resolve) {
if (typeof require.ensure !== 'function') {
require.ensure = function (dependencies, callback) {
callback(require);
};
}
require.ensure(['url-search-params'], function (require) {
_this.URLSearchParams = require('url-search-params');
resolve();
}, 'QueryStringShim-polyfill');
});
}
};
|
import {VType, validateEventFactory, BaseEvent} from '../../common/events'
import oncePerServices from '../../common/services/oncePerServices'
export default oncePerServices(function defineEvents({bus = missingService('bus')}) {
bus.registerEvent([
{
kind: 'event',
type: 'connector.telegram.started',
toString: (ev) => `${ev.service}: bots webhooks: ${Object.entries(ev.bots).map(([botName, bot]) => `\n\t${botName} (${bot.ref}): ${bot.webhook}`)}`,
},
]);
})
|
function bomOverload() {
if(settings.verbose) console.log("RubberGlove: Creating PluginArray");
function PluginArray() { // native(PluginArray)
if(window.navigator.plugins.constructor === PluginArray)
throw new TypeError("Illegal constructor");
if(settings.verbose) console.log("RubberGlove: Creating PluginArray instance");
Object.defineProperty(this, 'length', {
enumerable: true,
get: (function(eventNode) {
return function() {
// native()
console.error('RubberGlove: Iteration of window.navigator.plugins blocked for ' + window.location.href + ' (Informational, not an error.)');
window.postMessage({
type: 'RubberGlove',
text: 'window.navigator.plugins',
url: window.location.href
}, '*');
return 0;
};
})(document.currentScript.parentNode)
});
// Add hidden named plugins
var plugins = window.navigator.plugins;
for(var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
if(typeof plugin != 'undefined' && typeof plugin.name != 'undefined' && plugin.name != null) {
Object.defineProperty(this, plugin.name, {
configurable: true,
value: plugin
});
}
}
}
Object.defineProperty(PluginArray, "toString", {
enumerable: true,
value: function toString() { // native(toString)
return "function PluginArray() { [native code] }";
}
});
if(settings.verbose) console.log("RubberGlove: Creating PluginArray.prototype.item()");
PluginArray.prototype.item = function item() { // native(item)
return this[arguments[0]];
};
if(settings.verbose) console.log("RubberGlove: Creating PluginArray.prototype.namedItem()");
PluginArray.prototype.namedItem = function namedItem() { // native(namedItem)
return this[arguments[0]];
};
if(settings.verbose) console.log("RubberGlove: Creating PluginArray.prototype.refresh()");
PluginArray.prototype.refresh = (function(plugins) {
if(settings.verbose) console.log("RubberGlove: Returning our custom PluginArray.refresh()");
return function refresh() { // native(refresh)
// Refresh the real plugins list
plugins.refresh.apply(plugins, Array.prototype.slice.apply(arguments));
// Delete our existing set of plugins
var propertyNames = Object.getOwnPropertyNames(this);
for(var i = 0; i < propertyNames.length; i++) {
var property = propertyNames[i];
if(property != 'length') delete this[property];
}
// Add hidden named plugins
for(var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
if(typeof plugin.name != 'undefined' && plugin.name != null) {
Object.defineProperty(this, plugin.name, {
configurable: true,
value: plugin
});
}
}
}
})(window.navigator.plugins);
if(settings.verbose) console.log("RubberGlove: Replacing window.PluginArray");
Object.defineProperty(window, 'PluginArray', {
enumerable: false,
configurable: false,
writable: true,
value: PluginArray
});
// TODO: This should refresh as well when PluginArray.refresh() is called.
if(settings.verbose) console.log("RubberGlove: Creating MimeTypeArray");
function MimeTypeArray() { // native(MimeTypeArray)
if(window.navigator.mimeTypes.constructor === MimeTypeArray)
throw new TypeError("Illegal constructor");
if(settings.verbose) console.log("RubberGlove: Creating MimeTypeArray instance");
Object.defineProperty(this, 'length', {
enumerable: true,
get: (function(eventNode) {
return function() {
// native()
console.error('RubberGlove: Iteration of window.navigator.mimeTypes blocked for ' + window.location.href + ' (Informational, not an error.)');
window.postMessage({
type: 'RubberGlove',
text: 'window.navigator.mimeTypes',
url: window.location.href
}, '*');
return 0;
};
})(document.currentScript.parentNode)
});
// Add hidden named mimeTypes
var mimeTypes = window.navigator.mimeTypes;
for(var i = 0; i < mimeTypes.length; i++) {
var mimeType = mimeTypes[i];
if(typeof mimeType != 'undefined' && typeof mimeType.type != 'undefined' && mimeType.type != null) {
Object.defineProperty(this, mimeType.type, {
configurable: true,
value: mimeType
});
}
}
}
Object.defineProperty(MimeTypeArray, "toString", {
enumerable: true,
value: function toString() { // native(toString)
return "function MimeTypeArray() { [native code] }";
}
});
// Yes, these duplicate the ones for PluginArray. No, they should
// not use the same functions as they shouldn't test as equal.
if(settings.verbose) console.log("RubberGlove: Creating MimeTypeArray.prototype.item()");
MimeTypeArray.prototype.item = function item(index) { // native(item)
return this[arguments[0]];
};
if(settings.verbose) console.log("RubberGlove: Creating MimeTypeArray.prototype.namedItem()");
MimeTypeArray.prototype.namedItem = function namedItem(name) { // native(namedItem)
return this[arguments[0]];
};
if(settings.verbose) console.log("RubberGlove: Replacing window.MimeTypeArray");
Object.defineProperty(window, 'MimeTypeArray', {
enumerable: false,
configurable: false,
writable: true,
value: MimeTypeArray
});
if(settings.verbose) console.log("RubberGlove: Creating Navigator");
function Navigator() { // native(Navigator)
if(window.navigator.constructor === Navigator)
throw new TypeError("Illegal constructor");
if(settings.verbose) console.log("RubberGlove: Creating Navigator instance");
var propertyNames = Object.getOwnPropertyNames(window.navigator);
for(var propertyIndex = 0; propertyIndex < propertyNames.length; propertyIndex++) {
var propertyName = propertyNames[propertyIndex];
var descriptor = Object.getOwnPropertyDescriptor(window.navigator, propertyName);
var writable = descriptor.writable == true || typeof descriptor.set == 'function';
delete descriptor.value;
delete descriptor.get;
delete descriptor.set;
delete descriptor.writable;
switch(propertyName) {
case 'plugins':
console.log('RubberGlove: Cloaking plugins for ' + window.location.href);
descriptor.value = new PluginArray();
break;
case 'mimeTypes':
console.log('RubberGlove: Cloaking mimeTypes for ' + window.location.href);
descriptor.value = new MimeTypeArray();
break;
default:
//console.log("RubberGlove: wrapping " + propertyName);
descriptor.get = (function(propertyName, navigator) {
return function() { /* native() */ return navigator[propertyName] };
})(propertyName, window.navigator);
if(writable) {
descriptor.set = (function(propertyName, navigator) {
return function(value) { /* native(item) */ navigator[propertyName] = value; };
})(propertyName, window.navigator);
}
break;
}
Object.defineProperty(this, propertyName, descriptor);
}
}
Object.defineProperty(Navigator, "toString", {
enumerable: true,
value: function toString() { // native(toString)
return "function Navigator() { [native code] }";
}
});
if(settings.verbose) console.log("RubberGlove: Replacing Navigator.prototype");
for(var property in window.Navigator.prototype) {
Navigator.prototype[property] = window.Navigator.prototype[property];
}
if(settings.verbose) console.log("RubberGlove: Replacing window.Navigator");
Object.defineProperty(window, 'Navigator', {
enumerable: false,
configurable: false,
writable: true,
value: Navigator
});
if(settings.verbose) console.log("RubberGlove: Constructing Navigator");
var navigatorProxy = new Navigator();
if(settings.verbose) console.log("RubberGlove: Replacing window.navigator");
Object.defineProperty(window, 'navigator', {
enumerable: true,
configurable: false,
writable: true,
value: navigatorProxy
});
if(settings.verbose) console.log("RubberGlove: Replacing window.clientInformation");
Object.defineProperty(window, 'clientInformation', {
enumerable: true,
configurable: false,
writable: true,
value: navigatorProxy
});
// Hides source code when it contains "// native(functionName)" or
// "/* native(functionName)" at the beginning of the function body.
if(settings.verbose) console.log("RubberGlove: Replacing Function.prototype.toString()");
Function.prototype.toString = (function(oldToString) {
return function toString() { // native(toString) <-- yes, it handles itself
var result = oldToString.apply(this, Array.prototype.slice.apply(arguments));
var match = result.match(/^\s*?function.*?\(.*?\)\s*?{\s*?\/[\*\/]\s*?native\((.*?)\)/);
if(match != null && match.length > 1)
return 'function ' + match[1] + '() { [native code] }';
return result;
};
})(Function.prototype.toString);
// Hides named plugins and mimeTypes
if(settings.verbose) console.log("RubberGlove: Replacing Object.getOwnPropertyNames()");
Object.getOwnPropertyNames = (function(oldGetOwnPropertyNames) {
return function getOwnPropertyNames() { // native(getOwnPropertyNames)
var propertyNames = oldGetOwnPropertyNames.apply(this, Array.prototype.slice.apply(arguments));
if(arguments[0] === window.navigator.plugins || arguments[0] === window.navigator.mimeTypes) {
var filteredNames = [];
for(var i=0; i < propertyNames.length; i++) {
var propertyName = propertyNames[i];
if(propertyName == 'item' || propertyName == 'namedItem' || propertyName == 'length') {
filteredNames.push(propertyName);
}
}
return filteredNames;
}
return propertyNames;
}
})(Object.getOwnPropertyNames);
// Makes our objects look like first class objects
if(settings.verbose) console.log("RubberGlove: Replacing Object.prototype.toString()");
Object.prototype.toString = (function(oldToString) {
return function toString() { // native(toString)
if(this === window.navigator) return "[object Navigator]";
if(this === window.navigator.plugins) return "[object PluginArray]";
if(this === window.navigator.mimeTypes) return "[object MimeTypeArray]";
return oldToString.apply(this, Array.prototype.slice.apply(arguments));
};
})(Object.prototype.toString);
}
|
module.exports = {
Errors: {
WrongAccount: "wrong-acount",
},
set: (req, error_type) => (req.appSession.flashError = error_type),
clear: (req) => {
if (!req.appSession.flashError) return;
const error_type = req.appSession.flashError;
delete req.appSession.flashError;
return error_type;
},
};
|
/*jshint node:true, mocha:true*/
/**
* Generated by PluginGenerator 0.14.0 from webgme on Wed Feb 24 2016 10:25:35 GMT-0600 (Central Standard Time).
*/
'use strict';
var testFixture = require('../../globals');
describe('SysMLImporter', function () {
var gmeConfig = testFixture.getGmeConfig(),
expect = testFixture.expect,
logger = testFixture.logger.fork('NewPlugin'),
PluginCliManager = testFixture.WebGME.PluginCliManager,
projectName = 'testProject',
pluginName = 'SysMLImporter',
project,
gmeAuth,
storage,
commitHash;
before(function (done) {
testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName)
.then(function (gmeAuth_) {
gmeAuth = gmeAuth_;
// This uses in memory storage. Use testFixture.getMongoStorage to persist test to database.
storage = testFixture.getMemoryStorage(logger, gmeConfig, gmeAuth);
return storage.openDatabase();
})
.then(function () {
var importParam = {
projectSeed: testFixture.path.join(testFixture.SEED_DIR, 'EmptyProject.json'),
projectName: projectName,
branchName: 'master',
logger: logger,
gmeConfig: gmeConfig
};
return testFixture.importProject(storage, importParam);
})
.then(function (importResult) {
project = importResult.project;
commitHash = importResult.commitHash;
return project.createBranch('test', commitHash);
})
.nodeify(done);
});
after(function (done) {
storage.closeDatabase()
.then(function () {
return gmeAuth.unload();
})
.nodeify(done);
});
it('should run plugin and update the branch', function (done) {
var manager = new PluginCliManager(null, logger, gmeConfig),
pluginConfig = {
},
context = {
project: project,
commitHash: commitHash,
branchName: 'test',
activeNode: '/960660211',
};
manager.executePlugin(pluginName, pluginConfig, context, function (err, pluginResult) {
expect(err).to.equal(null);
expect(typeof pluginResult).to.equal('object');
expect(pluginResult.success).to.equal(true);
project.getBranchHash('test')
.then(function (branchHash) {
expect(branchHash).to.not.equal(commitHash);
})
.nodeify(done);
});
});
});
|
module.exports = {
/*"installedPackages":{
"xmlName":"InstalledPackage",
"children":{
}
},*/
"labels":{
"xmlName":"CustomLabels",
"children":{
"CustomLabels":"CustomLabel"
}
},
"staticresources":{
"xmlName":"StaticResource",
"children":{
}
},
"scontrols":{
"xmlName":"Scontrol",
"children":{
}
},
"components":{
"xmlName":"ApexComponent",
"children":{
}
},
"customMetadata":{
"xmlName":"CustomMetadata",
"children":{
}
},
"globalValueSets":{
"xmlName":"GlobalValueSet",
"children":{
}
},
"globalValueSetTranslations":{
"xmlName":"GlobalValueSetTranslation",
"children":{
}
},
"standardValueSets":{
"xmlName":"StandardValueSet",
"children":{
}
},
"pages":{
"xmlName":"ApexPage",
"children":{
}
},
"queues":{
"xmlName":"Queue",
"children":{
}
},
"objects":{
"xmlName":"CustomObject",
"children":{
"actionOverrides":{"typeName":"ActionOverride","name":"actionName"},
"fields":{"typeName":"CustomField","name":"fullName"},
"businessProcesses":{"typeName":"BusinessProcess","name":"fullName"},
"recordTypes":{"typeName":"RecordType","name":"fullName"},
"webLinks":{"typeName":"WebLink","name":"fullName"},
"validationRules":{"typeName":"ValidationRule","name":"fullName"},
"namedFilters":{"typeName":"NamedFilter","name":"fullName"},
"sharingReasons":{"typeName":"SharingReason","name":"fullName"},
"listViews":{"typeName":"ListView","name":"fullName"},
"fieldSets":{"typeName":"FieldSet","name":"fullName"},
"compactLayouts":{"typeName":"CompactLayout","name":"fullName"}
}
},
"reportTypes":{
"xmlName":"ReportType",
"children":{
}
},
"reports":{
"xmlName":"Report",
"children":{
}
},
"dashboards":{
"xmlName":"Dashboard",
"children":{
}
},
"analyticSnapshots":{
"xmlName":"AnalyticSnapshot",
"children":{
}
},
"layouts":{
"xmlName":"Layout",
"children":{
}
},
"portals":{
"xmlName":"Portal",
"children":{
}
},
"documents":{
"xmlName":"Document",
"children":{
}
},
"weblinks":{
"xmlName":"CustomPageWebLink",
"children":{
}
},
"quickActions":{
"xmlName":"QuickAction",
"children":{
}
},
"flexipages":{
"xmlName":"FlexiPage",
"children":{
}
},
"tabs":{
"xmlName":"CustomTab",
"children":{
}
},
"customApplicationComponents":{
"xmlName":"CustomApplicationComponent",
"children":{
}
},
"applications":{
"xmlName":"CustomApplication",
"children":{
}
},
"letterhead":{
"xmlName":"Letterhead",
"children":{
}
},
"email":{
"xmlName":"EmailTemplate",
"children":{
}
},
"workflows":{
"xmlName":"Workflow",
"children":{
"alerts":{"typeName":"WorkflowAlert","name":"fullName"},
"tasks":{"typeName" : "WorkflowTask", "name" : "fullName"},
"outboundMessages":{"typeName" : "WorkflowOutboundMessage","name" : "fullName"},
"fieldUpdates":{"typeName" : "WorkflowFieldUpdate", "name" : "fullName"},
"rules":{"typeName" : "WorkflowRule", "name" : "fullName"},
"emailRecipients":{"typeName" : "WorkflowEmailRecipient", "name" : "fullName"},
"timeTriggers":{"typeName" : "WorkflowTimeTrigger", "name" : "fullName"},
"actionReferences":{"typeName" : "WorkflowActionReference", "name" : "fullName"}
}
},
"assignmentRules":{
"xmlName":"AssignmentRules",
"children":{
}
},
"autoResponseRules":{
"xmlName":"AutoResponseRules",
"children":{
}
},
"escalationRules":{
"xmlName":"EscalationRules",
"children":{
}
},
"roles":{
"xmlName":"Role",
"children":{
}
},
"groups":{
"xmlName":"Group",
"children":{
}
},
"postTemplates":{
"xmlName":"PostTemplate",
"children":{
}
},
"approvalProcesses":{
"xmlName":"ApprovalProcess",
"children":{
}
},
"homePageComponents":{
"xmlName":"HomePageComponent",
"children":{
}
},
"homePageLayouts":{
"xmlName":"HomePageLayout",
"children":{
}
},
"objectTranslations":{
"xmlName":"CustomObjectTranslation",
"children":{
}
},
"flows":{
"xmlName":"Flow",
"children":{
}
},
"classes":{
"xmlName":"ApexClass",
"children":{
}
},
"triggers":{
"xmlName":"ApexTrigger",
"children":{
}
},
"profiles":{
"xmlName":"Profile",
"children":{
}
},
"permissionsets":{
"xmlName":"PermissionSet",
"children":{
}
},
"datacategorygroups":{
"xmlName":"DataCategoryGroup",
"children":{
}
},
"remoteSiteSettings":{
"xmlName":"RemoteSiteSetting",
"children":{
}
},
"authproviders":{
"xmlName":"AuthProvider",
"children":{
}
},
"leadSharingRules":{
"xmlName":"LeadSharingRules",
"children":{
}
},
"campaignSharingRules":{
"xmlName":"CampaignSharingRules",
"children":{
}
},
"caseSharingRules":{
"xmlName":"CaseSharingRules",
"children":{
}
},
"contactSharingRules":{
"xmlName":"ContactSharingRules",
"children":{
}
},
"opportunitySharingRules":{
"xmlName":"OpportunitySharingRules",
"children":{
}
},
"accountSharingRules":{
"xmlName":"AccountSharingRules",
"children":{
}
},
"customObjectSharingRules":{
"xmlName":"CustomObjectSharingRules",
"children":{
}
},
"communities":{
"xmlName":"Community",
"children":{
}
},
"callCenters":{
"xmlName":"CallCenter",
"children":{
}
},
"connectedApps":{
"xmlName":"ConnectedApp",
"children":{
}
},
"samlssoconfigs":{
"xmlName":"SamlSsoConfig",
"children":{
}
},
"synonymDictionaries":{
"xmlName":"SynonymDictionary",
"children":{
}
},
"settings":{
"xmlName":"Settings",
"children":{
}
},
"aura":{
"xmlName":"AuraDefinitionBundle",
"children":{
}
},
"sharingRules":{
"xmlName":"SharingRules",
"children":{
"sharingTerritoryRules":"SharingTerritoryRule",
"sharingOwnerRules":"SharingOwnerRule",
"sharingCriteriaRules":"SharingCriteriaRule"
}
},
"contentassets":{
"xmlName":"ContentAsset",
"children":{
}
},
"networks":{
"xmlName":"Network",
"children":{
}
},
"siteDotComSites":{
"xmlName":"SiteDotCom",
"children":{
}
},
"flowDefinitions":{
"xmlName":"FlowDefinition",
"children":{
}
},
"matchingRules":{
"xmlName":"MatchingRules",
"children":{
}
}
};
|
import Ember from "ember";
var oneWay = Ember.computed.oneWay,
equal = Ember.computed.equal;
export default Ember.Controller.extend({
needs: ['mixin-stack', 'mixin-details'],
emberApplication: false,
navWidth: 180,
inspectorWidth: 360,
mixinStack: oneWay('controllers.mixin-stack').readOnly(),
mixinDetails: oneWay('controllers.mixin-details').readOnly(),
isChrome: equal('port.adapter.name', 'chrome'),
// Indicates that the extension window is focused,
active: true,
inspectorExpanded: false,
pushMixinDetails: function(name, property, objectId, details) {
details = {
name: name,
property: property,
objectId: objectId,
mixins: details
};
this.get('mixinStack').pushObject(details);
this.set('mixinDetails.model', details);
},
popMixinDetails: function() {
var mixinStack = this.get('controllers.mixin-stack');
var item = mixinStack.popObject();
this.set('mixinDetails.model', mixinStack.get('lastObject'));
this.get('port').send('objectInspector:releaseObject', { objectId: item.objectId });
},
activateMixinDetails: function(name, details, objectId) {
var self = this;
this.get('mixinStack').forEach(function(item) {
self.get('port').send('objectInspector:releaseObject', { objectId: item.objectId });
});
this.set('mixinStack.model', []);
this.pushMixinDetails(name, undefined, objectId, details);
},
droppedObject: function(objectId) {
var mixinStack = this.get('mixinStack.model');
var obj = mixinStack.findProperty('objectId', objectId);
if (obj) {
var index = mixinStack.indexOf(obj);
var objectsToRemove = [];
for(var i = index; i >= 0; i--) {
objectsToRemove.pushObject(mixinStack.objectAt(i));
}
objectsToRemove.forEach(function(item) {
mixinStack.removeObject(item);
});
}
if (mixinStack.get('length') > 0) {
this.set('mixinDetails.model', mixinStack.get('lastObject'));
} else {
this.set('mixinDetails.model', null);
}
}
});
|
/* eslint-env mocha */
/* globals expect */
import { getCredentials, api, request, credentials } from '../../data/api-data.js';
import { password } from '../../data/user';
import { closeRoom, createRoom } from '../../data/rooms.helper';
import { updatePermission } from '../../data/permissions.helper';
describe('[Rooms]', function() {
this.retries(0);
before((done) => getCredentials(done));
it('/rooms.get', (done) => {
request.get(api('rooms.get'))
.set(credentials)
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('update');
expect(res.body).to.have.property('remove');
})
.end(done);
});
it('/rooms.get?updatedSince', (done) => {
request.get(api('rooms.get'))
.set(credentials)
.query({
updatedSince: new Date,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('update').that.have.lengthOf(0);
expect(res.body).to.have.property('remove').that.have.lengthOf(0);
})
.end(done);
});
describe('/rooms.saveNotification:', () => {
let testChannel;
it('create an channel', (done) => {
createRoom({ type: 'c', name: `channel.test.${ Date.now() }` })
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('/rooms.saveNotification:', (done) => {
request.post(api('rooms.saveNotification'))
.set(credentials)
.send({
roomId: testChannel._id,
notifications: {
disableNotifications: '0',
emailNotifications: 'nothing',
audioNotificationValue: 'beep',
desktopNotifications: 'nothing',
desktopNotificationDuration: '2',
audioNotifications: 'all',
mobilePushNotifications: 'mentions',
},
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
});
describe('/rooms.favorite', () => {
let testChannel;
const testChannelName = `channel.test.${ Date.now() }`;
it('create an channel', (done) => {
createRoom({ type: 'c', name: testChannelName })
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('should favorite the room when send favorite: true by roomName', (done) => {
request.post(api('rooms.favorite'))
.set(credentials)
.send({
roomName: testChannelName,
favorite: true,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should unfavorite the room when send favorite: false by roomName', (done) => {
request.post(api('rooms.favorite'))
.set(credentials)
.send({
roomName: testChannelName,
favorite: false,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should favorite the room when send favorite: true by roomId', (done) => {
request.post(api('rooms.favorite'))
.set(credentials)
.send({
roomId: testChannel._id,
favorite: true,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should unfavorite room when send favorite: false by roomId', (done) => {
request.post(api('rooms.favorite'))
.set(credentials)
.send({
roomId: testChannel._id,
favorite: false,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should return an error when send an invalid room', (done) => {
request.post(api('rooms.favorite'))
.set(credentials)
.send({
roomId: 'foo',
favorite: false,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
});
describe('[/rooms.cleanHistory]', () => {
let publicChannel;
let privateChannel;
let directMessageChannel;
let user;
beforeEach((done) => {
const username = `user.test.${ Date.now() }`;
const email = `${ username }@rocket.chat`;
request.post(api('users.create'))
.set(credentials)
.send({ email, name: username, username, password })
.end((err, res) => {
user = res.body.user;
done();
});
});
let userCredentials;
beforeEach((done) => {
request.post(api('login'))
.send({
user: user.username,
password,
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
userCredentials = {};
userCredentials['X-Auth-Token'] = res.body.data.authToken;
userCredentials['X-User-Id'] = res.body.data.userId;
})
.end(done);
});
afterEach((done) => {
request.post(api('users.delete')).set(credentials).send({
userId: user._id,
}).end(done);
user = undefined;
});
it('create a public channel', (done) => {
createRoom({ type: 'c', name: `testeChannel${ +new Date() }` })
.end((err, res) => {
publicChannel = res.body.channel;
done();
});
});
it('create a private channel', (done) => {
createRoom({ type: 'p', name: `testPrivateChannel${ +new Date() }` })
.end((err, res) => {
privateChannel = res.body.group;
done();
});
});
it('create a direct message', (done) => {
createRoom({ type: 'd', username: 'rocket.cat' })
.end((err, res) => {
directMessageChannel = res.body.room;
done();
});
});
it('should return success when send a valid public channel', (done) => {
request.post(api('rooms.cleanHistory'))
.set(credentials)
.send({
roomId: publicChannel._id,
latest: '2016-12-09T13:42:25.304Z',
oldest: '2016-08-30T13:42:25.304Z',
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should return success when send a valid private channel', (done) => {
request.post(api('rooms.cleanHistory'))
.set(credentials)
.send({
roomId: privateChannel._id,
latest: '2016-12-09T13:42:25.304Z',
oldest: '2016-08-30T13:42:25.304Z',
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should return success when send a valid Direct Message channel', (done) => {
request.post(api('rooms.cleanHistory'))
.set(credentials)
.send({
roomId: directMessageChannel._id,
latest: '2016-12-09T13:42:25.304Z',
oldest: '2016-08-30T13:42:25.304Z',
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should return not allowed error when try deleting messages with user without permission', (done) => {
request.post(api('rooms.cleanHistory'))
.set(userCredentials)
.send({
roomId: directMessageChannel._id,
latest: '2016-12-09T13:42:25.304Z',
oldest: '2016-08-30T13:42:25.304Z',
})
.expect('Content-Type', 'application/json')
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('errorType', 'error-not-allowed');
})
.end(done);
});
});
describe('[/rooms.info]', () => {
let testChannel;
let testGroup;
let testDM;
const expectedKeys = ['_id', 'name', 'fname', 't', 'msgs', 'usersCount', 'u', 'customFields', 'ts', 'ro', 'sysMes', 'default', '_updatedAt'];
const testChannelName = `channel.test.${ Date.now() }-${ Math.random() }`;
const testGroupName = `group.test.${ Date.now() }-${ Math.random() }`;
after((done) => {
closeRoom({ type: 'd', roomId: testDM._id })
.then(done);
});
it('create an channel', (done) => {
createRoom({ type: 'c', name: testChannelName })
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('create a group', (done) => {
createRoom(({ type: 'p', name: testGroupName }))
.end((err, res) => {
testGroup = res.body.group;
done();
});
});
it('create a Direct message room with rocket.cat', (done) => {
createRoom(({ type: 'd', username: 'rocket.cat' }))
.end((err, res) => {
testDM = res.body.room;
done();
});
});
it('should return the info about the created channel correctly searching by roomId', (done) => {
request.get(api('rooms.info'))
.set(credentials)
.query({
roomId: testChannel._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('room').and.to.be.an('object');
expect(res.body.room).to.have.keys(expectedKeys);
})
.end(done);
});
it('should return the info about the created channel correctly searching by roomName', (done) => {
request.get(api('rooms.info'))
.set(credentials)
.query({
roomName: testChannel.name,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('room').and.to.be.an('object');
expect(res.body.room).to.have.all.keys(expectedKeys);
})
.end(done);
});
it('should return the info about the created group correctly searching by roomId', (done) => {
request.get(api('rooms.info'))
.set(credentials)
.query({
roomId: testGroup._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('room').and.to.be.an('object');
expect(res.body.room).to.have.all.keys(expectedKeys);
})
.end(done);
});
it('should return the info about the created group correctly searching by roomName', (done) => {
request.get(api('rooms.info'))
.set(credentials)
.query({
roomName: testGroup.name,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('room').and.to.be.an('object');
expect(res.body.room).to.have.all.keys(expectedKeys);
})
.end(done);
});
it('should return the info about the created DM correctly searching by roomId', (done) => {
request.get(api('rooms.info'))
.set(credentials)
.query({
roomId: testDM._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('room').and.to.be.an('object');
})
.end(done);
});
it('should return name and _id of public channel when it has the "fields" query parameter limiting by name', (done) => {
request.get(api('rooms.info'))
.set(credentials)
.query({
roomId: testChannel._id,
fields: JSON.stringify({ name: 1 }),
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('room').and.to.be.an('object');
expect(res.body.room).to.have.property('name').and.to.be.equal(testChannelName);
expect(res.body.room).to.have.all.keys(['_id', 'name']);
})
.end(done);
});
});
describe('[/rooms.leave]', () => {
let testChannel;
let testGroup;
let testDM;
const testChannelName = `channel.test.${ Date.now() }-${ Math.random() }`;
const testGroupName = `group.test.${ Date.now() }-${ Math.random() }`;
after((done) => {
closeRoom({ type: 'd', roomId: testDM._id })
.then(done);
});
it('create an channel', (done) => {
createRoom({ type: 'c', name: testChannelName })
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('create a group', (done) => {
createRoom(({ type: 'p', name: testGroupName }))
.end((err, res) => {
testGroup = res.body.group;
done();
});
});
it('create a Direct message room with rocket.cat', (done) => {
createRoom(({ type: 'd', username: 'rocket.cat' }))
.end((err, res) => {
testDM = res.body.room;
done();
});
});
it('should return an Error when trying leave a DM room', (done) => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testDM._id,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('errorType', 'error-not-allowed');
})
.end(done);
});
it('should return an Error when trying to leave a public channel and you are the last owner', (done) => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testChannel._id,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('errorType', 'error-you-are-last-owner');
})
.end(done);
});
it('should return an Error when trying to leave a private group and you are the last owner', (done) => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testGroup._id,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('errorType', 'error-you-are-last-owner');
})
.end(done);
});
it('should return an Error when trying to leave a public channel and not have the necessary permission(leave-c)', (done) => {
updatePermission('leave-c', []).then(() => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testChannel._id,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('errorType', 'error-not-allowed');
})
.end(done);
});
});
it('should return an Error when trying to leave a private group and not have the necessary permission(leave-p)', (done) => {
updatePermission('leave-p', []).then(() => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testGroup._id,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('errorType', 'error-not-allowed');
})
.end(done);
});
});
it('should leave the public channel when the room has at least another owner and the user has the necessary permission(leave-c)', (done) => {
updatePermission('leave-c', ['admin']).then(() => {
request.post(api('channels.addAll'))
.set(credentials)
.send({
roomId: testChannel._id,
})
.end(() => {
request.post(api('channels.addOwner'))
.set(credentials)
.send({
roomId: testChannel._id,
userId: 'rocket.cat',
})
.end(() => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testChannel._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
});
});
});
it('should leave the private group when the room has at least another owner and the user has the necessary permission(leave-p)', (done) => {
updatePermission('leave-p', ['admin']).then(() => {
request.post(api('groups.addAll'))
.set(credentials)
.send({
roomId: testGroup._id,
})
.end(() => {
request.post(api('groups.addOwner'))
.set(credentials)
.send({
roomId: testGroup._id,
userId: 'rocket.cat',
})
.end(() => {
request.post(api('rooms.leave'))
.set(credentials)
.send({
roomId: testGroup._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
});
});
});
});
});
|
// Second function
function mySecondFunction(number1, number2){
return number1 + number2;
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M17 4.14V2h-3v2h-4V2H7v2.14c-1.72.45-3 2-3 3.86v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8c0-1.86-1.28-3.41-3-3.86zM18 20H6V8c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2v12zm-1.5-8v4h-2v-2h-7v-2h9z" />
, 'BackpackOutlined');
|
Class('TemplatesModel', {
views: {
empty: {
name: 'empty',
label: 'Empty'
},
ListView: {
name: 'ListView',
label: 'List View',
subviews: ['ListItemView']
}
}
});
|
const filter = require('./filter')
module.exports = (collection, test, callback) => {
return filter(collection, function(value, index, collection) {
return !test(value, index, collection)
}, callback)
}
|
window.ww = window.innerWidth ? window.innerWidth: $(window).width();
window.wh = window.innerHeight ? window.innerHeight: $(window).height();
$(window).on('resize', function(){
window.ww = window.innerWidth ? window.innerWidth: $(window).width();
window.wh = window.innerHeight ? window.innerHeight: $(window).height();
});
|
/**
* DOM manipulation methods
*/
Firestorm.DOM = {
/**
* When turning HTML into nodes - it must be inserted into appropriate tags to stay valid
*/
_wrap_map: {
select: [1, "<select multiple='multiple'>", "</select>"],
fieldset: [1, "<fieldset>", "</fieldset>"],
table: [1, "<table>", "</table>"],
tbody: [2, "<table><tbody>", "</tbody></table>"],
thead: [2, "<table><tbody>", "</tbody></table>"],
tfoot: [2, "<table><tbody>", "</tbody></table>"],
tr: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
colgroup: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
map: [1, "<map>", "</map>"]
},
/**
* Workaround for browser bugs in IE. Equals to value of `STRIPS_INNER_HTML_SCRIPT_AND_STYLE_TAGS` capability
*/
_needs_shy: false,
/**
* Workaround for browser bugs in IE. Equals to value of `MOVES_WHITESPACE_BEFORE_SCRIPT` capability
*/
_moves_whitespace: false,
/**
* Init the object: choose appropriate methods for DOM manipulation, depending on browser capabilities
*/
init: function() {
var e = Firestorm.Environment;
this._needs_shy = e.capabilities[Firestorm.CAPABILITY_NAMES.STRIPS_INNER_HTML_SCRIPT_AND_STYLE_TAGS];
this._moves_whitespace = e.capabilities[Firestorm.CAPABILITY_NAMES.MOVES_WHITESPACE_BEFORE_SCRIPT];
if (Firestorm.schema.dom.PREFER_RANGE_API && e.capabilities[Firestorm.CAPABILITY_NAMES.SUPPORTS_RANGE]) {
this.insertHTMLBefore = this.insertHTMLBefore_Range;
this.insertHTMLAfter = this.insertHTMLAfter_Range;
this.insertHTMLTop = this.insertHTMLTop_Range;
this.insertHTMLBottom = this.insertHTMLBottom_Range;
this.clearOuterRange = this.clearOuterRange_Range;
this.clearInnerRange = this.clearInnerRange_Range;
this.replaceInnerRange = this.replaceInnerRange_Range;
this.moveRegionAfter = this.moveRegionAfter_Range;
this.moveRegionBefore = this.moveRegionBefore_Range;
} else {
this.insertHTMLBefore = this.insertHTMLBefore_Nodes;
this.insertHTMLAfter = this.insertHTMLAfter_Nodes;
this.insertHTMLTop = this.insertHTMLTop_Nodes;
this.insertHTMLBottom = this.insertHTMLBottom_Nodes;
this.clearOuterRange = this.clearOuterRange_Nodes;
this.clearInnerRange = this.clearInnerRange_Nodes;
this.replaceInnerRange = this.replaceInnerRange_Nodes;
this.moveRegionAfter = this.moveRegionAfter_Nodes;
this.moveRegionBefore = this.moveRegionBefore_Nodes;
}
},
/**
* Turn given HTML into DOM nodes and insert them before the given element
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLBefore: function(element, html) { Firestorm.t(1); },
/**
* Turn given HTML into DOM nodes and insert them after the given element
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLAfter: function(element, html) { Firestorm.t(1); },
/**
* Turn given HTML into DOM nodes and insert them inside the given element, at the top of it
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLTop: function(element, html) { Firestorm.t(1); },
/**
* Turn given HTML into DOM nodes and insert them inside the given element, at the bottom
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLBottom: function(element, html) { Firestorm.t(1); },
/**
* Remove all HTML nodes between the given elements and elements themselves
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
*/
clearOuterRange: function(start_element, end_element) { Firestorm.t(1); },
/**
* Remove all HTML nodes between the given elements
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
*/
clearInnerRange: function(start_element, end_element) { Firestorm.t(1); },
/**
* Remove all HTML nodes between the elements and insert the given html there
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
* @param {string} html
*/
replaceInnerRange: function(start_element, end_element, html) { Firestorm.t(1); },
/**
* Move `region_start_element`, `region_end_element` and all elements between them before `target`
* @param {HTMLElement} target
* @param {HTMLElement} region_start_element
* @param {HTMLElement} region_end_element
*/
moveRegionBefore: function(target, region_start_element, region_end_element) { Firestorm.t(1); },
/**
* Move `region_start_element`, `region_end_element` and all elements between them after `target`
* @param {HTMLElement} target
* @param {HTMLElement} region_start_element
* @param {HTMLElement} region_end_element
*/
moveRegionAfter: function(target, region_start_element, region_end_element) { Firestorm.t(1); },
/**
* Turn HTML into nodes and insert them relatively to the given element
* @param {HTMLElement} element
* @param {string} html
* @param {_eInsertPosition} [position='Bottom']
*/
insertHTML: function(element, html, position) {
this['insertHTML' + (position || 'Bottom')](element, html);
},
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// nodes api
/**
* Set the element's innerHTML, taking into account various browser bugs
* @param {HTMLElement} element
* @param {string} html
*/
_setInnerHTML: function(element, html) {
var matches,
count,
i,
script;
if (this._moves_whitespace) {
matches = [];
// Right now we only check for script tags with ids with the goal of targeting morphs.
// Remove space before script to insert it later.
html = html.replace(/(\s+)(<script id='([^']+)')/g, function(match, spaces, tag, id) {
matches.push([id, spaces]);
return tag;
});
}
element.innerHTML = html;
// If we have to do any whitespace adjustments, do them now
if (matches && matches.length > 0) {
count = matches.length;
for (i = 0; i < count; i++) {
script = Firestorm.Element.findChildById(element, matches[i][0]);
script.parentNode.insertBefore(document.createTextNode(matches[i][1]), script);
}
}
},
/**
* Given a parent node and some HTML, generate a set of nodes. Return the first
* node, which will allow us to traverse the rest using nextSibling.
*
* In cases of certain elements like tables and lists we cannot just assign innerHTML and get the nodes,
* cause innerHTML is either readonly on them in IE, or it would destroy some of the content
*
* @param {HTMLElement} parentNode
* @param {string} html
**/
_firstNodeFor: function(parentNode, html) {
var map = this._wrap_map[parentNode.nodeName.toLowerCase()] || [ 0, "", "" ],
depth = map[0],
start = map[1],
end = map[2],
element,
i,
shy_element;
if (this._needs_shy) {
// make the first tag an invisible text node to retain scripts and styles at the beginning
html = '­' + html;
}
element = document.createElement('div');
this._setInnerHTML(element, start + html + end);
for (i = 0; i <= depth; i++) {
element = element.firstChild;
}
if (this._needs_shy) {
// Look for ­ to remove it.
shy_element = element;
// Sometimes we get nameless elements with the shy inside
while (shy_element.nodeType === 1 && !shy_element.nodeName) {
shy_element = shy_element.firstChild;
}
// At this point it's the actual unicode character.
if (shy_element.nodeType === 3 && shy_element.nodeValue.charAt(0) === "\u00AD") {
shy_element.nodeValue = shy_element.nodeValue.slice(1);
}
}
return element;
},
/**
* Remove everything between two tags
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
*/
clearInnerRange_Nodes: function(start_element, end_element) {
var parent_node = start_element.parentNode,
node = start_element.nextSibling;
while (node && node !== end_element) {
parent_node.removeChild(node);
node = start_element.nextSibling;
}
},
/**
* Version of clearOuterRange, which manipulates HTML nodes
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
*/
clearOuterRange_Nodes: function(start_element, end_element) {
this.clearInnerRange_Nodes(start_element, end_element);
start_element.parentNode.removeChild(start_element);
end_element.parentNode.removeChild(end_element);
},
/**
* Version of replaceInnerRange, which manipulates HTML nodes
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
* @param {string} html
*/
replaceInnerRange_Nodes: function(start_element, end_element, html) {
this.clearInnerRange_Nodes(start_element, end_element);
this.insertHTMLBefore_Nodes(end_element, html);
},
/**
* Turn HTML into nodes with respect to the parent node and sequentially insert them before `insert_before` element
* @param {HTMLElement} parent_node
* @param {string} html
* @param {HTMLElement} insert_before
*/
_insertHTMLBefore: function(parent_node, html, insert_before) {
var node,
next_sibling;
node = this._firstNodeFor(parent_node, html);
while (node) {
next_sibling = node.nextSibling;
parent_node.insertBefore(node, insert_before);
node = next_sibling;
}
},
/**
* Version of insertHTMLAfter which works with nodes
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLAfter_Nodes: function(element, html) {
this._insertHTMLBefore(element.parentNode, html, element.nextSibling);
},
/**
* Version of insertHTMLBefore which works with nodes
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLBefore_Nodes: function(element, html) {
this._insertHTMLBefore(element.parentNode, html, element);
},
/**
* Version of insertHTMLTop which works with nodes
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLTop_Nodes: function(element, html) {
this._insertHTMLBefore(element, html, element.firstChild);
},
/**
* Version of insertHTMLBottom which works with nodes
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLBottom_Nodes: function(element, html) {
this._insertHTMLBefore(element, html, null);
},
/**
* Perform movement of a range of nodes
* @param {HTMLElement} parent
* @param {HTMLElement} target
* @param {HTMLElement} node
* @param {HTMLElement} region_end_element
*/
_moveRegionBefore: function(parent, target, node, region_end_element) {
var next_sibling;
while (node && node !== region_end_element) {
next_sibling = node.nextSibling;
parent.insertBefore(node, target);
node = next_sibling;
}
parent.insertBefore(region_end_element, target);
},
/**
* Version of `moveRegionBefore`, which works with DOM nodes.
* @param {HTMLElement} target
* @param {HTMLElement} region_start_element
* @param {HTMLElement} region_end_element
*/
moveRegionBefore_Nodes: function(target, region_start_element, region_end_element) {
this._moveRegionBefore(target.parentNode, target, region_start_element, region_end_element);
},
/**
* Version of `moveRegionAfter`, which works with DOM nodes.
* @param {HTMLElement} target
* @param {HTMLElement} region_start_element
* @param {HTMLElement} region_end_element
*/
moveRegionAfter_Nodes: function(target, region_start_element, region_end_element) {
this._moveRegionBefore(target.parentNode, target.nextSibling, region_start_element, region_end_element);
},
// endL nodes api
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// range api
/**
* Create a Range object, with limits between the given elements
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
* @returns {Range|TextRange}
*/
_createInnerRange: function(start_element, end_element) {
var range = document.createRange();
range.setStartAfter(start_element);
range.setEndBefore(end_element);
return range;
},
/**
* Create a Range object, which includes the given elements
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
* @returns {Range|TextRange}
*/
_createOuterRange: function(start_element, end_element) {
var range = document.createRange();
range.setStartBefore(start_element);
range.setEndAfter(end_element);
return range;
},
/**
* Version of replaceInnerRange, which works with Range API
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
* @param {string} html
*/
replaceInnerRange_Range: function(start_element, end_element, html) {
var range = this._createInnerRange(start_element, end_element);
range.deleteContents();
range.insertNode(range.createContextualFragment(html));
},
/**
* Version of clearOuterRange, which works with Range API
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
*/
clearOuterRange_Range: function(start_element, end_element) {
var range = this._createOuterRange(start_element, end_element);
range.deleteContents();
},
/**
* Version of clearInnerRange, which works with Range API
* @param {HTMLElement} start_element
* @param {HTMLElement} end_element
*/
clearInnerRange_Range: function(start_element, end_element) {
var range = this._createInnerRange(start_element, end_element);
range.deleteContents();
},
/**
* Version of insertHTMLAfter, which works with Range API
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLAfter_Range: function(element, html) {
var range = document.createRange();
range.setStartAfter(element);
range.setEndAfter(element);
range.insertNode(range.createContextualFragment(html));
},
/**
* Version of insertHTMLBefore, which works with Range API
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLBefore_Range: function(element, html) {
var range = document.createRange();
range.setStartBefore(element);
range.setEndBefore(element);
range.insertNode(range.createContextualFragment(html));
},
/**
* Version of insertHTMLTop, which works with Range API
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLTop_Range: function(element, html) {
var range = document.createRange();
range.setStart(element, 0);
range.collapse(true);
range.insertNode(range.createContextualFragment(html));
},
/**
* Version of insertHTMLBottom, which works with Range API
* @param {HTMLElement} element
* @param {string} html
*/
insertHTMLBottom_Range: function(element, html) {
var last_child = element.lastChild,
range;
if (last_child) {
range = document.createRange();
range.setStartAfter(last_child);
range.collapse(true);
range.insertNode(range.createContextualFragment(html));
} else {
this.insertHTMLTop_Range(element, html);
}
},
/**
* Version of `moveRegionBefore`, which works with ranges
* @param {HTMLElement} target
* @param {HTMLElement} region_start_element
* @param {HTMLElement} region_end_element
*/
moveRegionBefore_Range: function(target, region_start_element, region_end_element) {
target.parentNode.insertBefore(
this._createOuterRange(region_start_element, region_end_element).extractContents(),
target
);
},
/**
* Version of `moveRegionAfter`, which works with ranges
* @param {HTMLElement} target
* @param {HTMLElement} region_start_element
* @param {HTMLElement} region_end_element
*/
moveRegionAfter_Range: function(target, region_start_element, region_end_element) {
target.parentNode.insertBefore(
this._createOuterRange(region_start_element, region_end_element).extractContents(),
target.nextSibling
);
}
// end: range api
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
};
|
const express = require('express');
const libxmljs = require('libxmljs');
express().get('/some/path', function(req) {
// OK: libxml does not expand entities by default
libxmljs.parseXml(req.param("some-xml"));
});
|
/**
* @author mrdoob / http://mrdoob.com/
* based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
*/
THREE.OAMesh = function ( geometry, material ) {
THREE.Mesh.call( this, geometry, material );
this.oa = {
type: "",
depth: 0
};
return 0;
};
THREE.OAMesh.prototype = Object.create( THREE.Mesh.prototype );
|
/**
* @class Li
*/
/**
* DOM utility methods
*/
(function (factory) {
if (typeof define === "function" && define.amd) {
define(['./lithium', 'jquery'], factory);
} else if (typeof exports === 'object') { //For NodeJS
module.exports = factory(require('./lithium'), require('jquery-node'));
} else { //global
factory(window.Li, jQuery);
}
}(function (Li, $) {
Li.mix(Li, {
/**
* Given a DOM node, this method finds the next tag/node that would appear in the dom.
* WARNING: Do not remove or add nodes while traversing, because it could cause the traversal logic to go crazy.
* @param node Could be a any node (element node or text node)
* @param ancestor Node An ancestorial element that can be used to limit the search.
* The search algorithm, while traversing the ancestorial heirarcy, will not go past/above this element.
* @param {function} callback A callback called on each element traversed.
*
* callback gets following parameters:
* node: Current node being traversed.
* isOpenTag: boolean. On true, node would be the next open tag/node that one would find when going
* linearly downwards through the DOM. Filtering with isOpenTag=true, one would get exactly what native TreeWalker does.
* Similarly isOpenTag=false when a close tag is encountered when traversing the DOM. AFAIK TreeWalker doesn't give this info.
*
* callback can return one of the following values (with their meanings):
* 'halt': Stops immediately and returns null.
* 'return': Halts and returns node.
* 'continue': Skips further traversal of current node (i.e won't traverse it's child nodes).
* 'break': Skips all sibling elements of current node and goes to it's parent node.
*
* relation: The relation compared to the previously traversed node.
* @param {Object} [scope] Value of 'this' keyword within callback
* @method traverse
*/
traverse: function (node, ancestor, callback, scope) {
//if node = ancestor, we still can traverse it's child nodes
if (!node) {
return null;
}
var isOpenTag = true, ret = null;
do {
if (ret === 'halt') {
return null;
}
if (isOpenTag && node.firstChild && !ret) {
node = node.firstChild;
//isOpenTag = true;
ret = callback.call(scope, node, true, 'firstChild');
} else {
if (isOpenTag) { // close open tag first
callback.call(scope, node, false, 'current');
}
if (node.nextSibling && node !== ancestor && ret !== 'break') {
node = node.nextSibling;
isOpenTag = true;
ret = callback.call(scope, node, true, 'nextSibling');
} else if (node.parentNode && node !== ancestor) {
//Traverse up the dom till you find an element with nextSibling
node = node.parentNode;
isOpenTag = false;
ret = callback.call(scope, node, false, 'parentNode');
} else {
node = null;
}
}
} while (node && ret !== 'return');
return node || null;
},
/**
* Converts DOM to HTML string
* @param {DocumentFragment} frag
* @return {String}
* @method toHTML
*/
toHTML: (function () {
function unwrap(str) {
var o = {};
str.split(',').forEach(function (val) {
o[val] = true;
});
return o;
}
var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr');
return function (frag) {
var html = '';
Li.traverse(frag, frag, function (node, isOpenTag) {
if (node.nodeType === 1) {
var tag = node.nodeName.toLowerCase();
if (isOpenTag) {
html += '<' + tag;
Li.slice(node.attributes).forEach(function (attr) {
html += ' ' + attr.name + '="' + attr.value.replace(/"/g, '"') + '"';
});
html += (voidTags[tag] ? '/>' : '>');
} else if (!voidTags[tag]) {
html += '</' + tag + '>';
}
}
if (isOpenTag && node.nodeType === 3) {
var text = node.nodeValue || '';
//escape <,> and &. Except text node inside script or style tag.
if (!(/^(?:script|style)$/i).test(node.parentNode.nodeName)) {
text = text.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<");
}
html += text;
}
if (isOpenTag && node.nodeType === 8) {
html += '<!-- ' + node.data.trim() + ' -->';
}
}, this);
return html;
};
}()),
/**
* jQuery's index() method doesn't return the child index properly for non-element nodes (like text node, comment).
* @method childIndex
*/
childIndex: function (node) {
return Li.slice(node.parentNode.childNodes).indexOf(node);
}
});
return Li;
}));
|
var React = require('react');
var Firebase = require('firebase');
var Game = require('../../game.js');
var FirebaseIntegration = require('../../firebase-integration');
var GameContainer = require('../game-container/game-container');
//var gameListRef = new Firebase("https://blazing-inferno-190.firebaseio.com/-JqBmJEqKYiHdKFW8xg_/games/");
var gameListRef = new Firebase( FirebaseIntegration.getGamesPath() );
var GameList = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
var component = this;
gameListRef.on('value', function(snapshot) {
component.setState(snapshot.val());
});
},
createGame: function() {
gameListRef.push(new Game().data);
},
render: function() {
var games = Object.keys(this.state).map(function (gameId, index) {
return (
<GameContainer key={index} gameId={gameId}/>
);
}, this);
return (
<div>
{games}
<button onClick={this.createGame}>Create Game</button>
</div>
);
}
});
module.exports = GameList;
|
"use strict";
var responsive_window_1 = require("./responsive-window");
exports.ResponsiveWindow = responsive_window_1.ResponsiveWindow;
exports.RESPONSIVEWINDOW_DIRECTIVE = [
responsive_window_1.ResponsiveWindow
];
//# sourceMappingURL=index.js.map
|
import {keccak256, bufferToHex} from "ethereumjs-util"
import MerkleTree from "../../utils/merkleTree"
import Fixture from "./helpers/Fixture"
import {web3, ethers} from "hardhat"
import chai, {expect, assert} from "chai"
import {solidity} from "ethereum-waffle"
chai.use(solidity)
describe("MerkleSnapshot", () => {
let fixture
let merkleSnapshot
let signers
before(async () => {
signers = await ethers.getSigners()
fixture = new Fixture(web3)
await fixture.deploy()
const merkleFac = await ethers.getContractFactory("MerkleSnapshot")
merkleSnapshot = await merkleFac.deploy(fixture.controller.address)
})
beforeEach(async () => {
await fixture.setUp()
})
afterEach(async () => {
await fixture.tearDown()
})
describe("setSnapshot", () => {
it("reverts when caller is not controller owner", async () => {
expect(
merkleSnapshot
.connect(signers[1])
.setSnapshot(
ethers.utils.formatBytes32String("1"),
ethers.utils.formatBytes32String("helloworld")
)
).to.be.revertedWith("caller must be Controller owner")
})
it("sets a snapshot root for an snapshot ID", async () => {
const id = ethers.utils.formatBytes32String("1")
const root = ethers.utils.formatBytes32String("helloworld")
await merkleSnapshot.setSnapshot(id, root)
assert.equal(await merkleSnapshot.snapshot(id), root)
})
})
describe("verify", () => {
let leaves
let tree
const id = bufferToHex(keccak256("LIP-52"))
before(async () => {
leaves = ["a", "b", "c", "d"]
tree = new MerkleTree(leaves)
await merkleSnapshot.setSnapshot(id, tree.getHexRoot())
})
it("returns false when a proof is invalid", async () => {
const badLeaves = ["d", "e", "f"]
const badTree = new MerkleTree(badLeaves)
const badProof = badTree.getHexProof(badLeaves[0])
const leaf = bufferToHex(keccak256(leaves[0]))
assert.isFalse(await merkleSnapshot.verify(id, badProof, leaf))
})
it("returns false when leaf is not in the tree", async () => {
const proof = tree.getHexProof(leaves[0])
const leaf = bufferToHex(keccak256("x"))
assert.isFalse(await merkleSnapshot.verify(id, proof, leaf))
})
it("returns false when a proof is of invalid length", async () => {
let proof = tree.getHexProof(leaves[0])
proof = proof.slice(0, proof.length - 1)
const leaf = bufferToHex(keccak256(leaves[0]))
assert.isFalse(await merkleSnapshot.verify(id, proof, leaf))
})
it("returns true when a proof is valid", async () => {
const proof = tree.getHexProof(leaves[0])
const leaf = bufferToHex(keccak256(leaves[0]))
assert.isTrue(await merkleSnapshot.verify(id, proof, leaf))
})
})
})
|
export { default } from "./../../_gen/openfl/events/IOErrorEvent";
|
/*
Threesixty.prototype.getRow = function(index){
var perRow = this.perRow;
var rowsCount = Math.round(this.source.length/perRow);
var result = [];
if(index<rowsCount-1){
result = this.source.slice(index*perRow, (index*perRow)+perRow);
}
return result;
}
*/
|
'use strict';
// Setting up route
angular.module('prints').config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('listPrints', {
url: '/prints',
templateUrl: 'modules/prints/views/print-client-list.html'
});
}
]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.