code stringlengths 2 1.05M |
|---|
var stories = require("../routes/stories.js"),
string = require("string"),
config = require("../util/config"),
Promise = require('bluebird'),
util = require("../util/util");
exports.pastDelay = function(baseTime){
return (typeof baseTime == 'number') && ((new Date()).getTime() - baseTime) > config.requeueDelay;
}
exports.requeueCheck = function(){
return stories.findAll(stories.Status.Pending).then(function(pending){
var now = new Date().getTime();
pending.forEach(function(story){
var metadata = story.details.metadata;
if(exports.pastDelay(metadata.previewStartTime)){ // the issue occurred while generating a preview
console.log("Requeueing story with id " + story.id + " for preview");
util.mqPublish('story_needs_screenshot', story.id);
} else { // issue happened while validating or we don't know what happened
console.log("Requeueing story with id " + story.id + " for validation");
util.mqPublish('story_needs_validation', story.id);
}
});
});
};
exports.start = function(){
Promise.all([stories.prepDB(), util.prepMQ()]).then(function(){
util.runPeriodically(exports.requeueCheck, config.requeueInterval);
console.log("Requeue engine online");
});
};
|
var searchData=
[
['queue_351',['Queue',['../interface_n_a_t_s_1_1_client_1_1_i_subscription.html#a3e505b346b8dc6339e84059441d9b1f4',1,'NATS.Client.ISubscription.Queue()'],['../class_n_a_t_s_1_1_client_1_1_subscription.html#ad275b73355ef820f9ce461689170c028',1,'NATS.Client.Subscription.Queue()']]],
['queuedmessagecount_352',['QueuedMessageCount',['../interface_n_a_t_s_1_1_client_1_1_i_subscription.html#ab474bbe759abcb118e92890918b78fb8',1,'NATS.Client.ISubscription.QueuedMessageCount()'],['../class_n_a_t_s_1_1_client_1_1_subscription.html#a9ec19bba2b4606d7791a0db697baf962',1,'NATS.Client.Subscription.QueuedMessageCount()']]]
];
|
/**
* The graph data model used in sigma.js.
* @constructor
* @extends sigma.classes.Cascade
* @extends sigma.classes.EventDispatcher
* @this {Graph}
*/
function Graph() {
sigma.classes.Cascade.call(this);
sigma.classes.EventDispatcher.call(this);
/**
* Represents "this", without the well-known scope issue.
* @private
* @type {Graph}
*/
var self = this;
/**
* The different parameters that determine how the nodes and edges should be
* translated and rescaled.
* @type {Object}
*/
this.p = {
minNodeSize: 0,
maxNodeSize: 0,
minEdgeSize: 0,
maxEdgeSize: 0,
// Scaling mode:
// - 'inside' (default)
// - 'outside'
scalingMode: 'inside',
nodesPowRatio: 0.5,
edgesPowRatio: 0
};
/**
* Contains the borders of the graph. These are useful to avoid the user to
* drag the graph out of the canvas.
* @type {Object}
*/
this.borders = {};
/**
* Inserts a node in the graph.
* @param {string} id The node's ID.
* @param {object} params An object containing the different parameters
* of the node.
* @return {Graph} Returns itself.
*/
function addNode(id, params) {
if (self.nodesIndex[id]) {
throw new Error('Node "' + id + '" already exists.');
}
params = params || {};
var n = {
// Numbers :
'x': 0,
'y': 0,
'size': 1,
'degree': 0,
'inDegree': 0,
'outDegree': 0,
// Flags :
'fixed': false,
'active': false,
'hidden': false,
'forceLabel': false,
'drawBorder': false,
// Strings :
'label': id.toString(),
'id': id.toString()//,
// Custom attributes :
//'attr': {}
};
for (var k in params) {
switch (k) {
case 'id':
case 'degree':
case 'inDegree':
case 'outDegree':
break;
case 'x':
case 'y':
case 'size':
n[k] = +params[k];
break;
case 'fixed':
case 'active':
case 'hidden':
case 'forceLabel':
case 'drawBorder':
n[k] = !!params[k];
break;
/*case 'color':
case 'label':
n[k] = params[k];
break;
default:
n['attr'][k] = params[k];*/
default:
n[k] = params[k];
}
}
self.nodes.push(n);
self.nodesIndex[id.toString()] = n;
return self;
};
/**
* Generates the clone of a node, to make it easier to be exported.
* @private
* @param {Object} node The node to clone.
* @return {Object} The clone of the node.
*/
function cloneNode(node) {
/*return {
'x': node['x'],
'y': node['y'],
'size': node['size'],
'degree': node['degree'],
'inDegree': node['inDegree'],
'outDegree': node['outDegree'],
'displayX': node['displayX'],
'displayY': node['displayY'],
'displaySize': node['displaySize'],
'label': node['label'],
'id': node['id'],
'color': node['color'],
'fixed': node['fixed'],
'drawBorder': node['drawBorder'],
'active': node['active'],
'hidden': node['hidden'],
'forceLabel': node['forceLabel'],
'attr': node['attr']
};*/
var clone = {};
for (var k in node) {
clone[k] = node[k];
}
return clone;
};
/**
* Checks the clone of a node, and inserts its values when possible. For
* example, it is possible to modify the size or the color of a node, but it
* is not possible to modify its display values or its id.
* @private
* @param {Object} node The original node.
* @param {Object} copy The clone.
* @return {Graph} Returns itself.
*/
function checkNode(node, copy) {
for (var k in copy) {
switch (k) {
case 'id':
//case 'attr':
case 'degree':
case 'inDegree':
case 'outDegree':
case 'displayX':
case 'displayY':
case 'displaySize':
break;
case 'x':
case 'y':
case 'size':
node[k] = +copy[k];
break;
case 'fixed':
case 'active':
case 'hidden':
case 'forceLabel':
case 'drawBorder':
node[k] = !!copy[k];
break;
case 'color':
case 'label':
node[k] = (copy[k] || '').toString();
break;
default:
node[k] = copy[k];
}
}
return self;
};
/**
* Deletes one or several nodes from the graph, and the related edges.
* @param {(string|Array.<string>)} v A string ID, or an Array of several
* IDs.
* @return {Graph} Returns itself.
*/
function dropNode(v) {
var a = (v instanceof Array ? v : [v]) || [];
a.forEach(function(id) {
if (self.nodesIndex[id]) {
var index = null;
self.nodes.some(function(n, i) {
if (n['id'] == id) {
index = i;
return true;
}
return false;
});
index != null && self.nodes.splice(index, 1);
delete self.nodesIndex[id];
var edgesToRemove = [];
self.edges = self.edges.filter(function(e) {
if (e['source']['id'] == id) {
delete self.edgesIndex[e['id']];
e['target']['degree']--;
e['target']['inDegree']--;
return false;
}else if (e['target']['id'] == id) {
delete self.edgesIndex[e['id']];
e['source']['degree']--;
e['source']['outDegree']--;
return false;
}
return true;
});
}else {
sigma.log('Node "' + id + '" does not exist.');
}
});
return self;
};
/**
* Inserts an edge in the graph.
* @param {string} id The edge ID.
* @param {string} source The ID of the edge source.
* @param {string} target The ID of the edge target.
* @param {object} params An object containing the different parameters
* of the edge.
* @return {Graph} Returns itself.
*/
function addEdge(id, source, target, params) {
if (self.edgesIndex[id]) {
throw new Error('Edge "' + id + '" already exists.');
}
if (!self.nodesIndex[source]) {
var s = 'Edge\'s source "' + source + '" does not exist yet.';
throw new Error(s);
}
if (!self.nodesIndex[target]) {
var s = 'Edge\'s target "' + target + '" does not exist yet.';
throw new Error(s);
}
params = params || {};
var e = {
'source': self.nodesIndex[source],
'target': self.nodesIndex[target],
'size': 1,
'weight': 1,
'displaySize': 0.5,
'label': id.toString(),
'id': id.toString(),
'hidden': false//,
//'attr': {}
};
e['source']['degree']++;
e['source']['outDegree']++;
e['target']['degree']++;
e['target']['inDegree']++;
for (var k in params) {
switch (k) {
case 'id':
case 'source':
case 'target':
case 'displaySize':
break;
case 'hidden':
e[k] = !!params[k];
break;
case 'size':
case 'weight':
e[k] = +params[k];
break;
case 'color':
e[k] = params[k].toString();
break;
case 'type':
e[k] = params[k].toString();
break;
case 'label':
e[k] = params[k];
break;
//default:
// e['attr'][k] = params[k];
default:
e[k] = params[k];
}
}
self.edges.push(e);
self.edgesIndex[id.toString()] = e;
return self;
};
/**
* Generates the clone of a edge, to make it easier to be exported.
* @private
* @param {Object} edge The edge to clone.
* @return {Object} The clone of the edge.
*/
function cloneEdge(edge) {
/*return {
'source': edge['source']['id'],
'target': edge['target']['id'],
'size': edge['size'],
'type': edge['type'],
'weight': edge['weight'],
'displaySize': edge['displaySize'],
'label': edge['label'],
'hidden': edge['hidden'],
'id': edge['id'],
'attr': edge['attr'],
'color': edge['color']
};*/
var clone = {};
for (k in edge) {
if (k=="source" || k=="target")
clone[k]=edge[k].id;
else
clone[k] = edge[k];
}
return clone;
};
/**
* Checks the clone of an edge, and inserts its values when possible. For
* example, it is possible to modify the label or the type of an edge, but it
* is not possible to modify its display values or its id.
* @private
* @param {Object} edge The original edge.
* @param {Object} copy The clone.
* @return {Graph} Returns itself.
*/
function checkEdge(edge, copy) {
for (var k in copy) {
switch (k) {
case 'id':
case 'displaySize':
break;
case 'weight':
case 'size':
edge[k] = +copy[k];
break;
case 'source':
case 'target':
edge[k] = self.nodesIndex[k] || edge[k];
break;
case 'hidden':
edge[k] = !!copy[k];
break;
case 'color':
case 'label':
case 'type':
edge[k] = (copy[k] || '').toString();
break;
default:
edge[k] = copy[k];
}
}
return self;
};
/**
* Deletes one or several edges from the graph.
* @param {(string|Array.<string>)} v A string ID, or an Array of several
* IDs.
* @return {Graph} Returns itself.
*/
function dropEdge(v) {
var a = (v instanceof Array ? v : [v]) || [];
a.forEach(function(id) {
if (self.edgesIndex[id]) {
self.edgesIndex[id]['source']['degree']--;
self.edgesIndex[id]['source']['outDegree']--;
self.edgesIndex[id]['target']['degree']--;
self.edgesIndex[id]['target']['inDegree']--;
var index = null;
self.edges.some(function(n, i) {
if (n['id'] == id) {
index = i;
return true;
}
return false;
});
index != null && self.edges.splice(index, 1);
delete self.edgesIndex[id];
}else {
sigma.log('Edge "' + id + '" does not exist.');
}
});
return self;
};
/**
* Deletes every nodes and edges from the graph.
* @return {Graph} Returns itself.
*/
function empty() {
self.nodes = [];
self.nodesIndex = {};
self.edges = [];
self.edgesIndex = {};
return self;
};
/**
* Computes the display x, y and size of each node, relatively to the
* original values and the borders determined in the parameters, such as
* each node is in the described area.
* @param {number} w The area width (actually the width of the DOM
* root).
* @param {number} h The area height (actually the height of the
* DOM root).
* @param {boolean} parseNodes Indicates if the nodes have to be parsed.
* @param {boolean} parseEdges Indicates if the edges have to be parsed.
* @return {Graph} Returns itself.
*/
function rescale(w, h, parseNodes, parseEdges) {
var weightMax = 0, sizeMax = 0;
parseNodes && self.nodes.forEach(function(node) {
sizeMax = Math.max(node['size'], sizeMax);
});
parseEdges && self.edges.forEach(function(edge) {
weightMax = Math.max(edge['size'], weightMax);
});
sizeMax = sizeMax || 1;
weightMax = weightMax || 1;
// Recenter the nodes:
var xMin, xMax, yMin, yMax;
parseNodes && self.nodes.forEach(function(node) {
xMax = Math.max(node['x'], xMax || node['x']);
xMin = Math.min(node['x'], xMin || node['x']);
yMax = Math.max(node['y'], yMax || node['y']);
yMin = Math.min(node['y'], yMin || node['y']);
});
// First, we compute the scaling ratio, without considering the sizes
// of the nodes : Each node will have its center in the canvas, but might
// be partially out of it.
var scale = self.p.scalingMode == 'outside' ?
Math.max(w / Math.max(xMax - xMin, 1),
h / Math.max(yMax - yMin, 1)) :
Math.min(w / Math.max(xMax - xMin, 1),
h / Math.max(yMax - yMin, 1));
// Then, we correct that scaling ratio considering a margin, which is
// basically the size of the biggest node.
// This has to be done as a correction since to compare the size of the
// biggest node to the X and Y values, we have to first get an
// approximation of the scaling ratio.
var margin = (self.p.maxNodeSize || sizeMax) / scale;
xMax += margin;
xMin -= margin;
yMax += margin;
yMin -= margin;
scale = self.p.scalingMode == 'outside' ?
Math.max(w / Math.max(xMax - xMin, 1),
h / Math.max(yMax - yMin, 1)) :
Math.min(w / Math.max(xMax - xMin, 1),
h / Math.max(yMax - yMin, 1));
// Size homothetic parameters:
var a, b;
if (!self.p.maxNodeSize && !self.p.minNodeSize) {
a = 1;
b = 0;
}else if (self.p.maxNodeSize == self.p.minNodeSize) {
a = 0;
b = self.p.maxNodeSize;
}else {
a = (self.p.maxNodeSize - self.p.minNodeSize) / sizeMax;
b = self.p.minNodeSize;
}
var c, d;
if (!self.p.maxEdgeSize && !self.p.minEdgeSize) {
c = 1;
d = 0;
}else if (self.p.maxEdgeSize == self.p.minEdgeSize) {
c = 0;
d = self.p.minEdgeSize;
}else {
c = (self.p.maxEdgeSize - self.p.minEdgeSize) / weightMax;
d = self.p.minEdgeSize;
}
// Rescale the nodes:
parseNodes && self.nodes.forEach(function(node) {
node['displaySize'] = node['size'] * a + b;
if (!node['fixed']) {
node['displayX'] = (node['x'] - (xMax + xMin) / 2) * scale + w / 2;
node['displayY'] = (node['y'] - (yMax + yMin) / 2) * scale + h / 2;
}
});
parseEdges && self.edges.forEach(function(edge) {
edge['displaySize'] = edge['size'] * c + d;
});
return self;
};
/**
* Translates the display values of the nodes and edges relatively to the
* scene position and zoom ratio.
* @param {number} sceneX The x position of the scene.
* @param {number} sceneY The y position of the scene.
* @param {number} ratio The zoom ratio of the scene.
* @param {boolean} parseNodes Indicates if the nodes have to be parsed.
* @param {boolean} parseEdges Indicates if the edges have to be parsed.
* @return {Graph} Returns itself.
*/
function translate(sceneX, sceneY, ratio, parseNodes, parseEdges) {
var sizeRatio = Math.pow(ratio, self.p.nodesPowRatio);
parseNodes && self.nodes.forEach(function(node) {
if (!node['fixed']) {
node['displayX'] = node['displayX'] * ratio + sceneX;
node['displayY'] = node['displayY'] * ratio + sceneY;
}
node['displaySize'] = node['displaySize'] * sizeRatio;
});
sizeRatio = Math.pow(ratio, self.p.edgesPowRatio);
parseEdges && self.edges.forEach(function(edge) {
edge['displaySize'] = edge['displaySize'] * sizeRatio;
});
return self;
};
/**
* Determines the borders of the graph as it will be drawn. It is used to
* avoid the user to drag the graph out of the canvas.
*/
function setBorders() {
self.borders = {};
self.nodes.forEach(function(node) {
self.borders.minX = Math.min(
self.borders.minX == undefined ?
node['displayX'] - node['displaySize'] :
self.borders.minX,
node['displayX'] - node['displaySize']
);
self.borders.maxX = Math.max(
self.borders.maxX == undefined ?
node['displayX'] + node['displaySize'] :
self.borders.maxX,
node['displayX'] + node['displaySize']
);
self.borders.minY = Math.min(
self.borders.minY == undefined ?
node['displayY'] - node['displaySize'] :
self.borders.minY,
node['displayY'] - node['displaySize']
);
self.borders.maxY = Math.max(
self.borders.maxY == undefined ?
node['displayY'] - node['displaySize'] :
self.borders.maxY,
node['displayY'] - node['displaySize']
);
});
}
/**
* Checks which nodes are under the (mX, mY) points, representing the mouse
* position.
* @param {number} mX The mouse X position.
* @param {number} mY The mouse Y position.
* @return {Graph} Returns itself.
*/
function checkHover(mX, mY) {
var dX, dY, s, over = [], out = [];
self.nodes.forEach(function(node) {
if (node['hidden']) {
node['hover'] = false;
return;
}
dX = Math.abs(node['displayX'] - mX);
dY = Math.abs(node['displayY'] - mY);
s = node['displaySize'];
var oldH = node['hover'];
var newH = dX < s && dY < s && Math.sqrt(dX * dX + dY * dY) < s;
if (oldH && !newH) {
node['hover'] = false;
out.push(node.id);
} else if (newH && !oldH) {
node['hover'] = true;
over.push(node.id);
}
});
over.length && self.dispatch('overnodes', over);
out.length && self.dispatch('outnodes', out);
return self;
};
/**
* Applies a function to a clone of each node (or indicated nodes), and then
* tries to apply the modifications made on the clones to the original nodes.
* @param {function(Object)} fun The function to execute.
* @param {?Array.<string>} ids An Array of node IDs (optional).
* @return {Graph} Returns itself.
*/
function iterNodes(fun, ids) {
var a = ids ? ids.map(function(id) {
return self.nodesIndex[id];
}) : self.nodes;
var aCopies = a.map(cloneNode);
aCopies.forEach(fun);
a.forEach(function(n, i) {
checkNode(n, aCopies[i]);
});
return self;
};
/**
* Applies a function to a clone of each edge (or indicated edges), and then
* tries to apply the modifications made on the clones to the original edges.
* @param {function(Object)} fun The function to execute.
* @param {?Array.<string>} ids An Array of edge IDs (optional).
* @return {Graph} Returns itself.
*/
function iterEdges(fun, ids) {
var a = ids ? ids.map(function(id) {
return self.edgesIndex[id];
}) : self.edges;
var aCopies = a.map(cloneEdge);
aCopies.forEach(fun);
a.forEach(function(e, i) {
checkEdge(e, aCopies[i]);
});
return self;
};
/**
* Returns a specific node clone or an array of specified node clones.
* @param {(string|Array.<string>)} ids The ID or an array of node IDs.
* @return {(Object|Array.<Object>)} The clone or the array of clones.
*/
function getNodes(ids) {
var a = ((ids instanceof Array ? ids : [ids]) || []).map(function(id) {
return cloneNode(self.nodesIndex[id]);
});
return (ids instanceof Array ? a : a[0]);
};
/**
* Returns a specific edge clone or an array of specified edge clones.
* @param {(string|Array.<string>)} ids The ID or an array of edge IDs.
* @return {(Object|Array.<Object>)} The clone or the array of clones.
*/
function getEdges(ids) {
var a = ((ids instanceof Array ? ids : [ids]) || []).map(function(id) {
return cloneEdge(self.edgesIndex[id]);
});
return (ids instanceof Array ? a : a[0]);
};
empty();
this.addNode = addNode;
this.addEdge = addEdge;
this.dropNode = dropNode;
this.dropEdge = dropEdge;
this.iterEdges = iterEdges;
this.iterNodes = iterNodes;
this.getEdges = getEdges;
this.getNodes = getNodes;
this.empty = empty;
this.rescale = rescale;
this.translate = translate;
this.setBorders = setBorders;
this.checkHover = checkHover;
}
|
'use strict';
var requestretry = require('requestretry');
var assertStatus = require('pocci/util.js').assertStatus;
module.exports = function(url) {
var handleResponse = function(err, response) {
if(err) {
throw err;
}
assertStatus(response, 'response.statusCode === 200');
console.log(' OK: ' + response.request.href);
};
console.log('Waiting for');
console.log(' ' + url.join(', '));
for(var i = 0; i < url.length; i++) {
requestretry({
url: url[i],
json:false,
maxAttempts:1200,
retryDelay: 1000,
retryStrategy: requestretry.RetryStrategies.HTTPOrNetworkError
}, handleResponse);
}
};
|
/*!
* then-callback <https://github.com/hybridables/then-callback>
*
* Copyright (c) 2015-2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var fs = require('fs')
var path = require('path')
var redolent = require('redolent')
var readFile = redolent(fs.readFile)
var thenCallback = require('../index')
var promise = readFile(path.join(__dirname, '..', 'package.json'), 'utf8')
promise = thenCallback(promise)
promise.then(function (err, res) {
if (err) return console.error(err)
console.log(JSON.parse(res).name) // => 'then-callback'
})
|
export { default } from 'ember-bulma/components/bulma-panel-block'; |
(function() {
'use strict';
angular
.module('apinterest.visualization.json-editor')
.directive('jsonEditor', JsonEditor);
function JsonEditor() {
return {
restrict: 'A',
require: '^form',
scope: {
model: '=model',
name: '=name',
validators: '=validators'
},
templateUrl: 'apinterest/content/js/app/visualization/json-editor/json-editor.html',
link: function(scope, element, attributes, ngForm) {
scope.form = ngForm;
scope.activeTab = resolveActiveTab(scope.model);
}
};
function resolveActiveTab(parameter) {
return parameter.visualizationType === 'json' && (parameter.type === 'System.Net.Http.HttpResponseMessage' || parameter.type === 'System.String')
? 'raw' :'editor';
}
}
})();
|
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', 'formula-flatten'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('formula-flatten'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.FLATTEN);
global.XOR = mod.exports;
}
})(this, function (exports, module, _formulaFlatten) {
'use strict';
module.exports = XOR;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _FLATTEN = _interopRequireDefault(_formulaFlatten);
function XOR() {
var args = (0, _FLATTEN['default'])(arguments);
var result = 0;
for (var i = 0; i < args.length; i++) {
if (args[i]) {
result++;
}
}
return result & 1 ? true : false;
}
});
|
var Stream = require("stream"),
events = require("events");
module.exports = (function(){
// CONSTRUCTOR
var klass = module.exports = function DuplexStream(writable, readable){
// Function-mode support
var self = this instanceof Stream ? this : Object.create(proto);
// Build the Stream to be returned
Stream.call(self);
events.EventEmitter.call(self); // Can't call the Stream ctor like this in Node for some reason...
// Keyword-args Object support
if(arguments.length === 1 && typeof(arguments[0]) === "object" && arguments[0].constructor === Object){
var o = arguments[0];
writable = o.writable;
readable = o.readable;
}
// Sanity checks
if(writable && typeof(writable) !== "object" && writable.writable === true) throw new Error("The writable Stream must be writable.");
if(readable && typeof(readable) !== "object" && readable.readable === true) throw new Error("The readable Stream must be readable.");
// Shared close event
self.closed = false;
function _close(){
if(self.closed) return;
self.emit("close");
self.closed = true;
}
// Hook up writable
self.writable = self.readable = true;
["drain", "error", "pipe"].forEach(function(eventName){
writable.on(eventName, self.emit.bind(self, eventName));
});
writable.on("close", _close);
self.write = writable.write.bind(writable);
// Hook up readable
self.ended = false;
["data", "end", "error"].forEach(function(eventName){
readable.on(eventName, self.emit.bind(self, eventName));
});
readable.on("close", _close);
self.end = function(){
if(self.ended) return;
self.ended = true;
self.readable = false;
readable.end();
writable.end();
self.writable = false;
};
// Flow handling
self.paused = false;
self.pause = function(){
if(self.paused) return;
self.paused = true;
readable.pause();
};
self.resume = function(){
if(!self.paused) return;
self.paused = false;
readable.resume();
if(!self.paused)
self.emit("drain");
};
// Hook up destroy
self.destroy = function(){
if(!self.ended) self.end();
readable.destroy();
writable.destroy();
};
// Hook up reset
self.reset = function(){
readable.reset();
writable.reset();
self.writable = self.readable = true;
self.ended = self.closed = false;
};
return self;
}, base = Stream, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
return klass;
})()
|
var game = require('../game');
var Command = require('./Command');
function Slash(dx, dy, direction) {
Command.apply(this);
}
Slash.prototype = Object.create(Command.prototype);
Slash.prototype.constructor = Slash;
Slash.prototype.isNoop = function isNoop() {
return false;
};
Slash.prototype.send = function (socket) {
socket.emit('slash', {
timestamp: this.timestamp
});
};
module.exports = Slash;
|
import './ngbBookmarksTableFilter.scss';
import angular from 'angular';
// Import internal modules
import component from './ngbBookmarksTableFilter.component';
import controller from './ngbBookmarksTableFilter.controller';
import filterInput from './ngbBookmarksFilterInput';
import filterList from './ngbBookmarksFilterList';
// Import external modules
export default angular.module('ngbBookmarksTableFilter', [filterInput, filterList])
.controller(controller.UID, controller)
.component('ngbBookmarksTableFilter', component)
.name;
|
import { ipcRenderer } from 'electron';
import React from 'react';
import PropTypes from 'prop-types';
import { Checkbox } from '@blueprintjs/core';
import { isWindows } from 'utils/platform.util';
import { ElectronSettingsPaths } from 'enums';
import { DESTROY_TRAY_ICON } from 'channels';
const SystemPanel = ({
minimizeToTray,
onSettingsChange,
openGeneralAlert,
showTimerByTray,
showTrayIcon,
toggleMinimizeToTray,
toggleShowTimerByTray,
toggleShowTrayIcon,
}) => (
<div className="mt-1">
<Checkbox
label="Show tray icon"
checked={showTrayIcon}
onChange={e => {
const checked = e.target.checked;
onSettingsChange(
ElectronSettingsPaths.SHOW_TRAY_ICON,
checked,
toggleShowTrayIcon
);
if (checked) {
openGeneralAlert('Tray icon will appear after restart');
}
if (!checked) {
ipcRenderer.send(DESTROY_TRAY_ICON);
}
}}
/>
<Checkbox
label="Show timer by tray icon"
checked={showTimerByTray}
onChange={e => {
onSettingsChange(
ElectronSettingsPaths.SHOW_TIMER_BY_TRAY,
e.target.checked,
toggleShowTimerByTray
);
}}
/>
{isWindows() && (
<Checkbox
label="Minimize to Tray"
checked={minimizeToTray}
onChange={e =>
onSettingsChange(
ElectronSettingsPaths.MINIMIZE_TO_TRAY,
e.target.checked,
toggleMinimizeToTray
)}
/>
)}
</div>
);
SystemPanel.propTypes = {
minimizeToTray: PropTypes.bool.isRequired,
onSettingsChange: PropTypes.func.isRequired,
toggleMinimizeToTray: PropTypes.func.isRequired
};
export default SystemPanel;
|
var app=angular.module("yemaWebApp",[]),navIndex=1;app.controller("taskDetailControl",function($scope,$http,$location){var appurlList=$location.absUrl().split("/"),excTaskId=appurlList[appurlList.length-1],detailUrl="detail/"+excTaskId;$http.get(detailUrl).success(function(response){$scope.oneAppInfo=response.oneAppInfo,console.log("--------"+response.macTask),$scope.taskInfo=response.macTask})}); |
'use strict';
angular.module('myApp.view1', [])
.controller('View1Ctrl', [function() {
}]); |
module("Core - VIE 1.x API");
test("Disabled Classic API", function () {
var v = new VIE({classic: false});
ok(v);
equal(typeof v.EntityManager, "undefined");
equal(typeof v.RDFa, "undefined");
equal(typeof v.RDFaEntities, "undefined");
equal(typeof v.cleanup, "undefined");
});
test("Enabled Classic API", function() {
var v = new VIE({classic: true});
ok(v);
ok(v.EntityManager);
ok(v.RDFa);
ok(v.RDFaEntities);
ok(v.cleanup);
});
|
define("device", function (a) {
var b = this, c = a.media = {};
a.media.mediamsg = {
0: "NONE ACTIVE.",
1: "ABORT_ERR.",
2: "CONNECTION ERR.",
3: "DECODE ERR.",
4: "SRC NOT SUPPORT."
};
a.MEDIA_DESTINATION = {}, a.MEDIA_ENCODEING = {}, a.MEDIA_TYPE = {}, a.MEDIA_SOURCE = {}, a.MEDIA_DIRECTION = {}, a.MEDIA_DESTINATION.DATA_URL = 0, a.MEDIA_DESTINATION.FILE_URI = 1, a.MEDIA_DESTINATION.NATIVE_URI = 2, a.MEDIA_ENCODEING.JPEG = 0, a.MEDIA_ENCODEING.PNG = 1, a.MEDIA_TYPE.PICTURE = 0, a.MEDIA_TYPE.VIDEO = 1, a.MEDIA_TYPE.ALLMEDIA = 2, a.MEDIA_TYPE.AUDIO = 3, a.MEDIA_SOURCE.ALBUM = 1, a.MEDIA_SOURCE.CAMERA = 0, a.MEDIA_DIRECTION.BACK = 0, a.MEDIA_DIRECTION.FRONT = 1, a.MEDIA_FORMAT = {
FILE: 0,
BASE64: 1
}, a.MEDIA_STATUS = {NONE: 0, STARTING: 1, RUNNING: 2, PAUSED: 3, STOPPED: 4};
new DelegateClass("device", "camera", "getPicture"), new DelegateClass("device", "capture", "captureAudio"), new DelegateClass("device", "capture", "captureImage"), new DelegateClass("device", "capture", "captureVideo");
c.captureMedia = function (c) {
c.source || (c.source = clouda.device.MEDIA_SOURCE.CAMERA);
var d = function (a) {
a.lastModified && (a.lastModifiedDate = a.lastModified, delete a.lastModified), c.onsuccess(a)
}, e = function (a) {
"cancel" === a.error_info && (a.result = clouda.STATUS.USER_CANCELED), c.onfail(a)
}, g = {quality: c.quality, base64: c.base64, height: c.height, width: c.width, source: c.source};
return c.mediaType == clouda.device.MEDIA_TYPE.AUDIO ? b.error(ErrCode.NOT_FINISH, ErrCode.NOT_FINISH, c) : c.source == clouda.device.MEDIA_SOURCE.CAMERA ? (g.mediaType = c.mediaType === clouda.device.MEDIA_TYPE.VIDEO ? "lightapp.device.MEDIA_TYPE.VIDEO" : "lightapp.device.MEDIA_TYPE.IMAGE", cloudaBLight("cloudaLaunchCamera", JSON.stringify(g), d, e)) : c.source == clouda.device.MEDIA_SOURCE.ALBUM ? (g.mediaType = c.mediaType === clouda.device.MEDIA_TYPE.VIDEO ? "lightapp.device.MEDIA_TYPE.VIDEO" : "lightapp.device.MEDIA_TYPE.IMAGE", cloudaBLight("cloudaLaunchGallery", JSON.stringify(g), d, e)) : b.error(ErrCode.UNKNOW_INPUT, ErrCode.UNKNOW_INPUT, c), !1
};
return c.operateMedia = function (a, c, d) {
var f = function (a) {
d.onsuccess(a.fullPath)
}, h = function () {
d.onsuccess(clouda.STATUS.SUCCESS)
}, i = function (a) {
a.error_info || (a.error_info = clouda.device.media.mediamsg[a.result]), d.onfail(a)
};
switch (c) {
case"startRecord":
cloudaBLight("startRecording", a, h, i);
break;
case"stopRecord":
cloudaBLight("stopRecording", f, i);
break;
case"play":
cloudaBLight("playAudio", a, "lightapp.device.AUDIO_TYPE.PLAY", h, i);
break;
case"stop":
cloudaBLight("playAudio", a, "lightapp.device.AUDIO_TYPE.STOP", h, i);
break;
case"seekTo":
cloudaBLight("audioSeekTo", d.time, h, i);
break;
case"setVolume":
cloudaBLight("setVolume", d.volume, h, i);
break;
case"speedFF":
cloudaBLight("audioSpeedFF", h, i);
break;
default:
b.error(ErrCode.UNKNOW_INPUT, ErrCode.UNKNOW_INPUT, d)
}
return !1
}, c.checkSupport = function (a) {
var b = {};
b["native"] = BLightApp && "function" == typeof BLightApp.cloudaLaunchCamera ? 1 : 0, b.web = 0, a(b)
}, a
}); |
var Code = require('code');
var Lab = require('lab');
var partial = require('lodash.partial');
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var before = lab.before;
var after = lab.after;
var expect = Code.expect;
var bdd = {it: it, expect: expect};
var utilities = require('../lib/utilities');
var SharedStrings = require('../lib/parts/sharedStrings');
var Rels = require('../lib/parts/rels');
function readOnlyTest(obj, name, test) {
it('has a read-only property: ' + name, function (done) {
if (test) test();
expect(function () { obj[name] = 'foo'; }).to.throw(Error, new RegExp("Cannot set " + name + " directly\."));
done()
});
}
describe('SharedStrings', function () {
var sharedStrings = new SharedStrings();
var readOnlyTest = partial(utilities.readOnlyTest, bdd, sharedStrings);
var constantTest = partial(utilities.constantTest, bdd, sharedStrings);
var writeOnceTest = partial(utilities.writeOnceTest, bdd, sharedStrings);
constantTest('filename');
readOnlyTest('data', function () {
var sharedStrings = new SharedStrings();
sharedStrings.add('foo');
expect(sharedStrings.data).to.deep.equal({
count: 1,
strings: ['foo']
});
});
readOnlyTest('path', function () {
expect(sharedStrings.path).to.equal(sharedStrings.filename);
var sharedStrings2 = new SharedStrings({path: 'foo/bar.xml'});
expect(sharedStrings2.path).to.equal(utilities.dirname(sharedStrings2.parent.path) + '/' + sharedStrings2.filename);
});
readOnlyTest('strings');
readOnlyTest('stringMap');
writeOnceTest('parent');
it('count is incrememented by every add, even if no new string added', utilities.wrapDone(function () {
expect(sharedStrings.count).to.equal(0);
sharedStrings.add('foo');
sharedStrings.add('');
sharedStrings.add('foo');
expect(sharedStrings.count).to.equal(3);
expect(sharedStrings.strings.length).to.equal(2);
}));
}); |
import fs from 'fs';
let config = require('./environment');
/**
* Module init function.
*/
module.exports = {
getLogFormat: function() {
return config.log.format;
},
getLogOptions: function() {
let options = {};
try {
if ('stream' in config.log.options) {
options = {
stream: fs.createWriteStream(process.cwd() + '/' +
config.log.options.stream, {
flags: 'a'
})
};
}
} catch (e) {
options = {};
}
return options;
}
};
|
/**
* image-duplicate-remover
* https://github.com/paazmaya/image-duplicate-remover
*
* Remove duplicate images from the two given directories recursively
*
* Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi)
* Licensed under the MIT license
*/
const findFiles = require('tozan/lib/find-files');
const isMedia = require('./is-media');
/**
* Read a directory, by returning all files with full filepath
*
* @param {string} directory Directory to read
* @param {object} options Set of options that are all boolean
* @param {boolean} options.verbose Print out current process
* @param {boolean} options.dryRun Do not touch any files, just show what could be done
* @param {string} options.metric Method to use when comparing two images with GraphicsMagick
* @returns {array} List of image with full path
*/
const getImageFiles = (directory, options) => {
if (options.verbose) {
console.log(`Reading directory "${directory}"`);
}
return findFiles(directory, {}).filter((item) => isMedia(item));
};
module.exports = getImageFiles;
|
// SaltarelleCompiler Runtime (http://www.saltarelle-compiler.com)
// Modified version of Script# Core Runtime (http://projects.nikhilk.net/ScriptSharp)
if (typeof(global) === "undefined") {
if (typeof(window) !== "undefined")
global = window;
else if (typeof(self) !== "undefined")
global = self;
}
(function(global) {
"use strict";
var ss = { __assemblies: {} };
ss.initAssembly = function assembly(obj, name, res) {
res = res || {};
obj.name = name;
obj.toString = function() { return this.name; };
obj.__types = {};
obj.getResourceNames = function() { return Object.keys(res); };
obj.getResourceDataBase64 = function(name) { return res[name] || null; };
obj.getResourceData = function(name) { var r = res[name]; return r ? ss.dec64(r) : null; };
ss.__assemblies[name] = obj;
};
ss.initAssembly(ss, 'mscorlib');
ss.load = function ss$load(name) {
return ss.__assemblies[name] || require(name);
};
var enc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', dec;
ss.enc64 = function(a, b) {
var s = '', i;
for (i = 0; i < a.length; i += 3) {
var c1 = a[i], c2 = a[i+1], c3 = a[i+2];
s += (b && i && !(i%57) ? '\n' : '') + enc[c1 >> 2] + enc[((c1 & 3) << 4) | (c2 >> 4)] + (i < a.length - 1 ? enc[((c2 & 15) << 2) | (c3 >> 6)] : '=') + (i < a.length - 2 ? enc[c3 & 63] : '=');
}
return s;
};
ss.dec64 = function(s) {
s = s.replace(/\s/g, '');
dec = dec || (function() { var o = {'=':-1}; for (var i = 0; i < 64; i++) o[enc[i]] = i; return o; })();
var a = Array(Math.max(s.length * 3 / 4 - 2, 0)), i;
for (i = 0; i < s.length; i += 4) {
var j = i * 3 / 4, c1 = dec[s[i]], c2 = dec[s[i+1]], c3 = dec[s[i+2]], c4 = dec[s[i+3]];
a[j] = (c1 << 2) | (c2 >> 4);
if (c3 >= 0) a[j+1] = ((c2 & 15) << 4) | (c3 >> 2);
if (c4 >= 0) a[j+2] = ((c3 & 3) << 6) | c4;
}
return a;
};
ss.getAssemblies = function ss$getAssemblies() {
return Object.keys(ss.__assemblies).map(function(n) { return ss.__assemblies[n]; });
};
ss.isNullOrUndefined = function ss$isNullOrUndefined(o) {
return (o === null) || (o === undefined);
};
ss.isValue = function ss$isValue(o) {
return (o !== null) && (o !== undefined);
};
ss.referenceEquals = function ss$referenceEquals(a, b) {
return ss.isValue(a) ? a === b : !ss.isValue(b);
};
ss.mkdict = function ss$mkdict() {
var a = (arguments.length != 1 ? arguments : arguments[0]);
var r = {};
for (var i = 0; i < a.length; i += 2) {
r[a[i]] = a[i + 1];
}
return r;
};
ss.clone = function ss$clone(t, o) {
return o ? t.$clone(o) : o;
}
ss.coalesce = function ss$coalesce(a, b) {
return ss.isValue(a) ? a : b;
};
ss.isDate = function ss$isDate(obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
};
ss.isArray = function ss$isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
ss.isTypedArrayType = function ss$isTypedArrayType(type) {
return ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray'].indexOf(ss.getTypeFullName(type)) >= 0;
};
ss.isArrayOrTypedArray = function ss$isArray(obj) {
return ss.isArray(obj) || ss.isTypedArrayType(ss.getInstanceType(obj));
};
ss.getHashCode = function ss$getHashCode(obj) {
if (!ss.isValue(obj))
throw new ss_NullReferenceException('Cannot get hash code of null');
else if (typeof(obj.getHashCode) === 'function')
return obj.getHashCode();
else if (typeof(obj) === 'boolean') {
return obj ? 1 : 0;
}
else if (typeof(obj) === 'number') {
var s = obj.toExponential();
s = s.substr(0, s.indexOf('e'));
return parseInt(s.replace('.', ''), 10) & 0xffffffff;
}
else if (typeof(obj) === 'string') {
var res = 0;
for (var i = 0; i < obj.length; i++)
res = (res * 31 + obj.charCodeAt(i)) & 0xffffffff;
return res;
}
else if (ss.isDate(obj)) {
return obj.valueOf() & 0xffffffff;
}
else {
return ss.defaultHashCode(obj);
}
};
ss.defaultHashCode = function ss$defaultHashCode(obj) {
return obj.$__hashCode__ || (obj.$__hashCode__ = (Math.random() * 0x100000000) | 0);
};
ss.equals = function ss$equals(a, b) {
if (!ss.isValue(a))
throw new ss_NullReferenceException('Object is null');
else if (a !== ss && typeof(a.equals) === 'function')
return a.equals(b);
if (ss.isDate(a) && ss.isDate(b))
return a.valueOf() === b.valueOf();
else if (typeof(a) === 'function' && typeof(b) === 'function')
return ss.delegateEquals(a, b);
else if (ss.isNullOrUndefined(a) && ss.isNullOrUndefined(b))
return true;
else
return a === b;
};
ss.compare = function ss$compare(a, b) {
if (!ss.isValue(a))
throw new ss_NullReferenceException('Object is null');
else if (typeof(a) === 'number' || typeof(a) === 'string' || typeof(a) === 'boolean')
return ss.isValue(b) ? (a < b ? -1 : (a > b ? 1 : 0)) : 1;
else if (ss.isDate(a))
return ss.isValue(b) ? ss.compare(a.valueOf(), b.valueOf()) : 1;
else
return a.compareTo(b);
};
ss.equalsT = function ss$equalsT(a, b) {
if (!ss.isValue(a))
throw new ss_NullReferenceException('Object is null');
else if (typeof(a) === 'number' || typeof(a) === 'string' || typeof(a) === 'boolean')
return a === b;
else if (ss.isDate(a))
return a.valueOf() === b.valueOf();
else
return a.equalsT(b);
};
ss.staticEquals = function ss$staticEquals(a, b) {
if (!ss.isValue(a))
return !ss.isValue(b);
else
return ss.isValue(b) ? ss.equals(a, b) : false;
};
ss.shallowCopy = function ss$shallowCopy(source, target) {
var keys = Object.keys(source);
for (var i = 0, l = keys.length; i < l; i++) {
var k = keys[i];
target[k] = source[k];
}
};
ss.isLower = function ss$isLower(c) {
var s = String.fromCharCode(c);
return s === s.toLowerCase() && s !== s.toUpperCase();
};
ss.isUpper = function ss$isUpper(c) {
var s = String.fromCharCode(c);
return s !== s.toLowerCase() && s === s.toUpperCase();
};
if (typeof(window) == 'object') {
// Browser-specific stuff that could go into the Web assembly, but that assembly does not have an associated JS file.
if (!window.Element) {
// IE does not have an Element constructor. This implementation should make casting to elements work.
window.Element = function() {};
window.Element.isInstanceOfType = function(instance) { return instance && typeof instance.constructor === 'undefined' && typeof instance.tagName === 'string'; };
}
window.Element.__typeName = 'Element';
if (!window.XMLHttpRequest) {
window.XMLHttpRequest = function() {
var progIDs = [ 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP' ];
for (var i = 0; i < progIDs.length; i++) {
try {
var xmlHttp = new ActiveXObject(progIDs[i]);
return xmlHttp;
}
catch (ex) {
}
}
return null;
};
}
ss.parseXml = function(markup) {
try {
if (DOMParser) {
var domParser = new DOMParser();
return domParser.parseFromString(markup, 'text/xml');
}
else {
var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ];
for (var i = 0; i < progIDs.length; i++) {
var xmlDOM = new ActiveXObject(progIDs[i]);
xmlDOM.async = false;
xmlDOM.loadXML(markup);
xmlDOM.setProperty('SelectionLanguage', 'XPath');
return xmlDOM;
}
}
}
catch (ex) {
}
return null;
};
}
///////////////////////////////////////////////////////////////////////////////
// Object Extensions
ss.clearKeys = function ss$clearKeys(d) {
for (var n in d) {
if (d.hasOwnProperty(n))
delete d[n];
}
};
ss.keyExists = function ss$keyExists(d, key) {
return d[key] !== undefined;
};
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','constructor'],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
ss.getKeyCount = function ss$getKeyCount(d) {
return Object.keys(d).length;
};
///////////////////////////////////////////////////////////////////////////////
// Type System Implementation
ss.__genericCache = {};
ss._makeGenericTypeName = function ss$_makeGenericTypeName(genericType, typeArguments) {
var result = genericType.__typeName;
for (var i = 0; i < typeArguments.length; i++)
result += (i === 0 ? '[' : ',') + '[' + ss.getTypeFullName(typeArguments[i]) + ']';
result += ']';
return result;
};
ss.makeGenericType = function ss$makeGenericType(genericType, typeArguments) {
var name = ss._makeGenericTypeName(genericType, typeArguments);
return ss.__genericCache[name] || genericType.apply(null, typeArguments);
};
ss.registerGenericClassInstance = function ss$registerGenericClassInstance(instance, genericType, typeArguments, members, baseType, interfaceTypes) {
var name = ss._makeGenericTypeName(genericType, typeArguments);
ss.__genericCache[name] = instance;
instance.__typeName = name;
instance.__genericTypeDefinition = genericType;
instance.__typeArguments = typeArguments;
ss.initClass(instance, genericType.__assembly, members, baseType(), interfaceTypes());
};
ss.registerGenericInterfaceInstance = function ss$registerGenericInterfaceInstance(instance, genericType, typeArguments, members, baseInterfaces) {
var name = ss._makeGenericTypeName(genericType, typeArguments);
ss.__genericCache[name] = instance;
instance.__typeName = name;
instance.__genericTypeDefinition = genericType;
instance.__typeArguments = typeArguments;
ss.initInterface(instance, genericType.__assembly, members, baseInterfaces());
};
ss.isGenericTypeDefinition = function ss$isGenericTypeDefinition(type) {
return type.__isGenericTypeDefinition || false;
};
ss.getGenericTypeDefinition = function ss$getGenericTypeDefinition(type) {
return type.__genericTypeDefinition || null;
};
ss.getGenericParameterCount = function ss$getGenericParameterCount(type) {
return type.__typeArgumentCount || 0;
};
ss.getGenericArguments = function ss$getGenericArguments(type) {
return type.__typeArguments || null;
};
ss.setMetadata = function ss$_setMetadata(type, metadata) {
if (metadata.members) {
for (var i = 0; i < metadata.members.length; i++) {
var m = metadata.members[i];
m.typeDef = type;
if (m.adder) m.adder.typeDef = type;
if (m.remover) m.remover.typeDef = type;
if (m.getter) m.getter.typeDef = type;
if (m.setter) m.setter.typeDef = type;
}
}
type.__metadata = metadata;
if (metadata.variance) {
type.isAssignableFrom = function(source) {
var check = function(target, type) {
if (type.__genericTypeDefinition === target.__genericTypeDefinition && type.__typeArguments.length == target.__typeArguments.length) {
for (var i = 0; i < target.__typeArguments.length; i++) {
var v = target.__metadata.variance[i], t = target.__typeArguments[i], s = type.__typeArguments[i];
switch (v) {
case 1: if (!ss.isAssignableFrom(t, s)) return false; break;
case 2: if (!ss.isAssignableFrom(s, t)) return false; break;
default: if (s !== t) return false;
}
}
return true;
}
return false;
};
if (source.__interface && check(this, source))
return true;
var ifs = ss.getInterfaces(source);
for (var i = 0; i < ifs.length; i++) {
if (ifs[i] === this || check(this, ifs[i]))
return true;
}
return false;
};
}
}
ss.initClass = function ss$initClass(ctor, asm, members, baseType, interfaces) {
ctor.__class = true;
ctor.__assembly = asm;
if (!ctor.__typeArguments)
asm.__types[ctor.__typeName] = ctor;
if (baseType && baseType !== Object) {
var f = function(){};
f.prototype = baseType.prototype;
ctor.prototype = new f();
ctor.prototype.constructor = ctor;
}
ss.shallowCopy(members, ctor.prototype);
if (interfaces)
ctor.__interfaces = interfaces;
};
ss.initGenericClass = function ss$initGenericClass(ctor, asm, typeArgumentCount) {
ctor.__class = true;
ctor.__assembly = asm;
asm.__types[ctor.__typeName] = ctor;
ctor.__typeArgumentCount = typeArgumentCount;
ctor.__isGenericTypeDefinition = true;
};
ss.initInterface = function ss$initInterface(ctor, asm, members, baseInterfaces) {
ctor.__interface = true;
ctor.__assembly = asm;
if (!ctor.__typeArguments)
asm.__types[ctor.__typeName] = ctor;
if (baseInterfaces)
ctor.__interfaces = baseInterfaces;
ss.shallowCopy(members, ctor.prototype);
ctor.isAssignableFrom = function(type) { return ss.contains(ss.getInterfaces(type), this); };
};
ss.initGenericInterface = function ss$initGenericClass(ctor, asm, typeArgumentCount) {
ctor.__interface = true;
ctor.__assembly = asm;
asm.__types[ctor.__typeName] = ctor;
ctor.__typeArgumentCount = typeArgumentCount;
ctor.__isGenericTypeDefinition = true;
};
ss.initEnum = function ss$initEnum(ctor, asm, members, namedValues) {
ctor.__enum = true;
ctor.__assembly = asm;
asm.__types[ctor.__typeName] = ctor;
ss.shallowCopy(members, ctor.prototype);
ctor.getDefaultValue = ctor.createInstance = function() { return namedValues ? null : 0; };
ctor.isInstanceOfType = function(instance) { return typeof(instance) == (namedValues ? 'string' : 'number'); };
};
ss.getBaseType = function ss$getBaseType(type) {
if (type === Object || type.__interface) {
return null;
}
else if (Object.getPrototypeOf) {
return Object.getPrototypeOf(type.prototype).constructor;
}
else {
var p = type.prototype;
if (Object.prototype.hasOwnProperty.call(p, 'constructor')) {
try {
var ownValue = p.constructor;
delete p.constructor;
return p.constructor;
}
finally {
p.constructor = ownValue;
}
}
return p.constructor;
}
};
ss.getTypeFullName = function ss$getTypeFullName(type) {
return type.__typeName || type.name || (type.toString().match(/^\s*function\s*([^\s(]+)/) || [])[1] || 'Object';
};
ss.getTypeQName = function ss$getTypeFullName(type) {
return ss.getTypeFullName(type) + (type.__assembly ? ', ' + type.__assembly.name : '');
};
ss.getTypeName = function ss$getTypeName(type) {
var fullName = ss.getTypeFullName(type);
var bIndex = fullName.indexOf('[');
var nsIndex = fullName.lastIndexOf('.', bIndex >= 0 ? bIndex : fullName.length);
return nsIndex > 0 ? fullName.substr(nsIndex + 1) : fullName;
};
ss.getTypeNamespace = function ss$getTypeNamespace(type) {
var fullName = ss.getTypeFullName(type);
var bIndex = fullName.indexOf('[');
var nsIndex = fullName.lastIndexOf('.', bIndex >= 0 ? bIndex : fullName.length);
return nsIndex > 0 ? fullName.substr(0, nsIndex) : '';
};
ss.getTypeAssembly = function ss$getTypeAssembly(type) {
if (ss.contains([Date, Number, Boolean, String, Function, Array], type))
return ss;
else
return type.__assembly || null;
};
ss._getAssemblyType = function ss$_getAssemblyType(asm, name) {
var result = [];
if (asm.__types) {
return asm.__types[name] || null;
}
else {
var a = name.split('.');
for (var i = 0; i < a.length; i++) {
asm = asm[a[i]];
if (!ss.isValue(asm))
return null;
}
if (typeof asm !== 'function')
return null;
return asm;
}
};
ss.getAssemblyTypes = function ss$getAssemblyTypes(asm) {
var result = [];
if (asm.__types) {
for (var t in asm.__types) {
if (asm.__types.hasOwnProperty(t))
result.push(asm.__types[t]);
}
}
else {
var traverse = function(s, n) {
for (var c in s) {
if (s.hasOwnProperty(c))
traverse(s[c], c);
}
if (typeof(s) === 'function' && ss.isUpper(n.charCodeAt(0)))
result.push(s);
};
traverse(asm, '');
}
return result;
};
ss.createAssemblyInstance = function ss$createAssemblyInstance(asm, typeName) {
var t = ss.getType(typeName, asm);
return t ? ss.createInstance(t) : null;
};
ss.getInterfaces = function ss$getInterfaces(type) {
if (type.__interfaces)
return type.__interfaces;
else if (type === Date || type === Number)
return [ ss_IEquatable, ss_IComparable, ss_IFormattable ];
else if (type === Boolean || type === String)
return [ ss_IEquatable, ss_IComparable ];
else if (type === Array || ss.isTypedArrayType(type))
return [ ss_IEnumerable, ss_ICollection, ss_IList ];
else
return [];
};
ss.isInstanceOfType = function ss$isInstanceOfType(instance, type) {
if (ss.isNullOrUndefined(instance))
return false;
if (typeof(type.isInstanceOfType) === 'function')
return type.isInstanceOfType(instance);
return ss.isAssignableFrom(type, ss.getInstanceType(instance));
};
ss.isAssignableFrom = function ss$isAssignableFrom(target, type) {
return target === type || (typeof(target.isAssignableFrom) === 'function' && target.isAssignableFrom(type)) || type.prototype instanceof target;
};
ss.isClass = function Type$isClass(type) {
return (type.__class == true || type === Array || type === Function || type === RegExp || type === String || type === Error || type === Object);
};
ss.isEnum = function Type$isEnum(type) {
return !!type.__enum;
};
ss.isFlags = function Type$isFlags(type) {
return type.__metadata && type.__metadata.enumFlags || false;
};
ss.isInterface = function Type$isInterface(type) {
return !!type.__interface;
};
ss.safeCast = function ss$safeCast(instance, type) {
if (type === true)
return instance;
else if (type === false)
return null;
else
return ss.isInstanceOfType(instance, type) ? instance : null;
};
ss.cast = function ss$cast(instance, type) {
if (instance === null || typeof(instance) === 'undefined')
return instance;
else if (type === true || (type !== false && ss.isInstanceOfType(instance, type)))
return instance;
throw new ss_InvalidCastException('Cannot cast object to type ' + ss.getTypeFullName(type));
};
ss.getInstanceType = function ss$getInstanceType(instance) {
if (!ss.isValue(instance))
throw new ss_NullReferenceException('Cannot get type of null');
// NOTE: We have to catch exceptions because the constructor
// cannot be looked up on native COM objects
try {
return instance.constructor;
}
catch (ex) {
return Object;
}
};
ss._getType = function (typeName, asm, re) {
var outer = !re;
re = re || /[[,\]]/g;
var last = re.lastIndex, m = re.exec(typeName), tname, targs = [];
if (m) {
tname = typeName.substring(last, m.index);
switch (m[0]) {
case '[':
if (typeName[m.index + 1] != '[')
return null;
for (;;) {
re.exec(typeName);
var t = ss._getType(typeName, global, re);
if (!t)
return null;
targs.push(t);
m = re.exec(typeName);
if (m[0] === ']')
break;
else if (m[0] !== ',')
return null;
}
m = re.exec(typeName);
if (m && m[0] === ',') {
re.exec(typeName);
if (!(asm = ss.__assemblies[(re.lastIndex > 0 ? typeName.substring(m.index + 1, re.lastIndex - 1) : typeName.substring(m.index + 1)).trim()]))
return null;
}
break;
case ']':
break;
case ',':
re.exec(typeName);
if (!(asm = ss.__assemblies[(re.lastIndex > 0 ? typeName.substring(m.index + 1, re.lastIndex - 1) : typeName.substring(m.index + 1)).trim()]))
return null;
break;
}
}
else {
tname = typeName.substring(last);
}
if (outer && re.lastIndex)
return null;
var t = ss._getAssemblyType(asm, tname.trim());
return targs.length ? ss.makeGenericType(t, targs) : t;
}
ss.getType = function ss$getType(typeName, asm) {
return typeName ? ss._getType(typeName, asm || global) : null;
};
ss.getDefaultValue = function ss$getDefaultValue(type) {
if (typeof(type.getDefaultValue) === 'function')
return type.getDefaultValue();
else if (type === Boolean)
return false;
else if (type === Date)
return new Date(0);
else if (type === Number)
return 0;
return null;
};
ss.createInstance = function ss$createInstance(type) {
if (typeof(type.createInstance) === 'function')
return type.createInstance();
else if (type === Boolean)
return false;
else if (type === Date)
return new Date(0);
else if (type === Number)
return 0;
else if (type === String)
return '';
else
return new type();
};
ss.applyConstructor = function ss$applyConstructor(constructor, args) {
var f = function() {
constructor.apply(this, args);
};
f.prototype = constructor.prototype;
return new f();
};
ss.getAttributes = function ss$getAttributes(type, attrType, inherit) {
var result = [];
if (inherit) {
var b = ss.getBaseType(type);
if (b) {
var a = ss.getAttributes(b, attrType, true);
for (var i = 0; i < a.length; i++) {
var t = ss.getInstanceType(a[i]);
if (!t.__metadata || !t.__metadata.attrNoInherit)
result.push(a[i]);
}
}
}
if (type.__metadata && type.__metadata.attr) {
for (var i = 0; i < type.__metadata.attr.length; i++) {
var a = type.__metadata.attr[i];
if (attrType == null || ss.isInstanceOfType(a, attrType)) {
var t = ss.getInstanceType(a);
if (!t.__metadata || !t.__metadata.attrAllowMultiple) {
for (var j = result.length - 1; j >= 0; j--) {
if (ss.isInstanceOfType(result[j], t))
result.splice(j, 1);
}
}
result.push(a);
}
}
}
return result;
};
ss.getMembers = function ss$getMembers(type, memberTypes, bindingAttr, name, params) {
var result = [];
if ((bindingAttr & 72) == 72 || (bindingAttr & 6) == 4) {
var b = ss.getBaseType(type);
if (b)
result = ss.getMembers(b, memberTypes & ~1, bindingAttr & (bindingAttr & 64 ? 255 : 247) & (bindingAttr & 2 ? 251 : 255), name, params);
}
var f = function(m) {
if ((memberTypes & m.type) && (((bindingAttr & 4) && !m.isStatic) || ((bindingAttr & 8) && m.isStatic)) && (!name || m.name === name)) {
if (params) {
if ((m.params || []).length !== params.length)
return;
for (var i = 0; i < params.length; i++) {
if (params[i] !== m.params[i])
return;
}
}
result.push(m);
}
};
if (type.__metadata && type.__metadata.members) {
for (var i = 0; i < type.__metadata.members.length; i++) {
var m = type.__metadata.members[i];
f(m);
for (var j = 0; j < 4; j++) {
var a = ['getter','setter','adder','remover'][j];
if (m[a])
f(m[a]);
}
}
}
if (bindingAttr & 256) {
while (type) {
var r = [];
for (var i = 0; i < result.length; i++) {
if (result[i].typeDef === type)
r.push(result[i]);
}
if (r.length > 1)
throw new ss_AmbiguousMatchException('Ambiguous match');
else if (r.length === 1)
return r[0];
type = ss.getBaseType(type);
}
return null;
}
return result;
};
ss.midel = function ss$midel(mi, target, typeArguments) {
if (mi.isStatic && !!target)
throw new ss_ArgumentException('Cannot specify target for static method');
else if (!mi.isStatic && !target)
throw new ss_ArgumentException('Must specify target for instance method');
var method;
if (mi.fget) {
method = function() { return (mi.isStatic ? mi.typeDef : this)[mi.fget]; };
}
else if (mi.fset) {
method = function(v) { (mi.isStatic ? mi.typeDef : this)[mi.fset] = v; };
}
else {
method = mi.def || (mi.isStatic || mi.sm ? mi.typeDef[mi.sname] : target[mi.sname]);
if (mi.tpcount) {
if (!typeArguments || typeArguments.length !== mi.tpcount)
throw new ss_ArgumentException('Wrong number of type arguments');
method = method.apply(null, typeArguments);
}
else {
if (typeArguments && typeArguments.length)
throw new ss_ArgumentException('Cannot specify type arguments for non-generic method');
}
if (mi.exp) {
var _m1 = method;
method = function () { return _m1.apply(this, Array.prototype.slice.call(arguments, 0, arguments.length - 1).concat(arguments[arguments.length - 1])); };
}
if (mi.sm) {
var _m2 = method;
method = function() { return _m2.apply(null, [this].concat(Array.prototype.slice.call(arguments))); };
}
}
return ss.mkdel(target, method);
};
ss.invokeCI = function ss$invokeCI(ci, args) {
if (ci.exp)
args = args.slice(0, args.length - 1).concat(args[args.length - 1]);
if (ci.def)
return ci.def.apply(null, args);
else if (ci.sm)
return ci.typeDef[ci.sname].apply(null, args);
else
return ss.applyConstructor(ci.sname ? ci.typeDef[ci.sname] : ci.typeDef, args);
};
ss.fieldAccess = function ss$fieldAccess(fi, obj) {
if (fi.isStatic && !!obj)
throw new ss_ArgumentException('Cannot specify target for static field');
else if (!fi.isStatic && !obj)
throw new ss_ArgumentException('Must specify target for instance field');
obj = fi.isStatic ? fi.typeDef : obj;
if (arguments.length === 3)
obj[fi.sname] = arguments[2];
else
return obj[fi.sname];
};
///////////////////////////////////////////////////////////////////////////////
// IFormattable
var ss_IFormattable = function IFormattable$() { };
ss_IFormattable.__typeName = 'ss.IFormattable';
ss.IFormattable = ss_IFormattable;
ss.initInterface(ss_IFormattable, ss, { format: null });
ss.format = function ss$format(obj, fmt) {
if (typeof(obj) === 'number')
return ss.formatNumber(obj, fmt);
else if (ss.isDate(obj))
return ss.formatDate(obj, fmt);
else
return obj.format(fmt);
};
///////////////////////////////////////////////////////////////////////////////
// IComparable
var ss_IComparable = function IComparable$() { };
ss_IComparable.__typeName = 'ss.IComparable';
ss.IComparable = ss_IComparable;
ss.initInterface(ss_IComparable, ss, { compareTo: null });
///////////////////////////////////////////////////////////////////////////////
// IEquatable
var ss_IEquatable = function IEquatable$() { };
ss_IEquatable.__typeName = 'ss.IEquatable';
ss.IEquatable = ss_IEquatable;
ss.initInterface(ss_IEquatable, ss, { equalsT: null });
///////////////////////////////////////////////////////////////////////////////
// Number Extensions
ss.formatNumber = function ss$formatNumber(num, format) {
if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) {
return num.toString();
}
return ss.netFormatNumber(num, format, ss_CultureInfo.invariantCulture.numberFormat);
};
ss.localeFormatNumber = function ss$localeFormatNumber(num, format) {
if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) {
return num.toLocaleString();
}
return ss.netFormatNumber(num, format, ss_CultureInfo.currentCulture.numberFormat);
};
ss._commaFormatNumber = function ss$_commaFormat(number, groups, decimal, comma) {
var decimalPart = null;
var decimalIndex = number.indexOf(decimal);
if (decimalIndex > 0) {
decimalPart = number.substr(decimalIndex);
number = number.substr(0, decimalIndex);
}
var negative = ss.startsWithString(number, '-');
if (negative) {
number = number.substr(1);
}
var groupIndex = 0;
var groupSize = groups[groupIndex];
if (number.length < groupSize) {
return (negative ? '-' : '') + (decimalPart ? number + decimalPart : number);
}
var index = number.length;
var s = '';
var done = false;
while (!done) {
var length = groupSize;
var startIndex = index - length;
if (startIndex < 0) {
groupSize += startIndex;
length += startIndex;
startIndex = 0;
done = true;
}
if (!length) {
break;
}
var part = number.substr(startIndex, length);
if (s.length) {
s = part + comma + s;
}
else {
s = part;
}
index -= length;
if (groupIndex < groups.length - 1) {
groupIndex++;
groupSize = groups[groupIndex];
}
}
if (negative) {
s = '-' + s;
}
return decimalPart ? s + decimalPart : s;
};
ss.netFormatNumber = function ss$netFormatNumber(num, format, numberFormat) {
var nf = (numberFormat && numberFormat.getFormat(ss_NumberFormatInfo)) || ss_CultureInfo.currentCulture.numberFormat;
var s = '';
var precision = -1;
if (format.length > 1) {
precision = parseInt(format.substr(1), 10);
}
var fs = format.charAt(0);
switch (fs) {
case 'd': case 'D':
s = parseInt(Math.abs(num)).toString();
if (precision != -1) {
s = ss.padLeftString(s, precision, 0x30);
}
if (num < 0) {
s = '-' + s;
}
break;
case 'x': case 'X':
s = parseInt(Math.abs(num)).toString(16);
if (fs == 'X') {
s = s.toUpperCase();
}
if (precision != -1) {
s = ss.padLeftString(s, precision, 0x30);
}
break;
case 'e': case 'E':
if (precision == -1) {
s = num.toExponential();
}
else {
s = num.toExponential(precision);
}
if (fs == 'E') {
s = s.toUpperCase();
}
break;
case 'f': case 'F':
case 'n': case 'N':
if (precision == -1) {
precision = nf.numberDecimalDigits;
}
s = num.toFixed(precision).toString();
if (precision && (nf.numberDecimalSeparator != '.')) {
var index = s.indexOf('.');
s = s.substr(0, index) + nf.numberDecimalSeparator + s.substr(index + 1);
}
if ((fs == 'n') || (fs == 'N')) {
s = ss._commaFormatNumber(s, nf.numberGroupSizes, nf.numberDecimalSeparator, nf.numberGroupSeparator);
}
break;
case 'c': case 'C':
if (precision == -1) {
precision = nf.currencyDecimalDigits;
}
s = Math.abs(num).toFixed(precision).toString();
if (precision && (nf.currencyDecimalSeparator != '.')) {
var index = s.indexOf('.');
s = s.substr(0, index) + nf.currencyDecimalSeparator + s.substr(index + 1);
}
s = ss._commaFormatNumber(s, nf.currencyGroupSizes, nf.currencyDecimalSeparator, nf.currencyGroupSeparator);
if (num < 0) {
s = ss.formatString(nf.currencyNegativePattern, s);
}
else {
s = ss.formatString(nf.currencyPositivePattern, s);
}
break;
case 'p': case 'P':
if (precision == -1) {
precision = nf.percentDecimalDigits;
}
s = (Math.abs(num) * 100.0).toFixed(precision).toString();
if (precision && (nf.percentDecimalSeparator != '.')) {
var index = s.indexOf('.');
s = s.substr(0, index) + nf.percentDecimalSeparator + s.substr(index + 1);
}
s = ss._commaFormatNumber(s, nf.percentGroupSizes, nf.percentDecimalSeparator, nf.percentGroupSeparator);
if (num < 0) {
s = ss.formatString(nf.percentNegativePattern, s);
}
else {
s = ss.formatString(nf.percentPositivePattern, s);
}
break;
}
return s;
};
///////////////////////////////////////////////////////////////////////////////
// String Extensions
ss.netSplit = function ss$netSplit(s, strings, limit, options) {
var re = new RegExp(strings.map(ss.regexpEscape).join('|'), 'g'), res = [], m, i;
for (i = 0;; i = re.lastIndex) {
if (m = re.exec(s)) {
if (options !== 1 || m.index > i) {
if (res.length === limit - 1) {
res.push(s.substr(i));
return res;
}
else
res.push(s.substring(i, m.index));
}
}
else {
if (options !== 1 || i !== s.length)
res.push(s.substr(i));
return res;
}
}
};
ss.compareStrings = function ss$compareStrings(s1, s2, ignoreCase) {
if (!ss.isValue(s1))
return ss.isValue(s2) ? -1 : 0;
if (!ss.isValue(s2))
return 1;
if (ignoreCase) {
if (s1) {
s1 = s1.toUpperCase();
}
if (s2) {
s2 = s2.toUpperCase();
}
}
s1 = s1 || '';
s2 = s2 || '';
if (s1 == s2) {
return 0;
}
if (s1 < s2) {
return -1;
}
return 1;
};
ss.endsWithString = function ss$endsWithString(s, suffix) {
if (!suffix.length) {
return true;
}
if (suffix.length > s.length) {
return false;
}
return (s.substr(s.length - suffix.length) == suffix);
};
ss._formatString = function ss$_formatString(format, values, useLocale) {
if (!ss._formatRE) {
ss._formatRE = /\{\{|\}\}|\{[^\}\{]+\}/g;
}
return format.replace(ss._formatRE,
function(m) {
if (m === '{{' || m === '}}')
return m.charAt(0);
var index = parseInt(m.substr(1), 10);
var value = values[index + 1];
if (ss.isNullOrUndefined(value)) {
return '';
}
if (ss.isInstanceOfType(value, ss_IFormattable)) {
var formatSpec = null;
var formatIndex = m.indexOf(':');
if (formatIndex > 0) {
formatSpec = m.substring(formatIndex + 1, m.length - 1);
}
return ss.format(value, formatSpec);
}
else {
return useLocale ? value.toLocaleString() : value.toString();
}
});
};
ss.formatString = function String$format(format) {
return ss._formatString(format, arguments, /* useLocale */ false);
};
ss.stringFromChar = function ss$stringFromChar(ch, count) {
var s = ch;
for (var i = 1; i < count; i++) {
s += ch;
}
return s;
};
ss.htmlDecode = function ss$htmlDecode(s) {
return s.replace(/&([^;]+);/g, function(_, e) {
if (e[0] === '#')
return String.fromCharCode(parseInt(e.substr(1), 10));
switch (e) {
case 'quot': return '"';
case 'apos': return "'";
case 'amp': return '&';
case 'lt': return '<';
case 'gt': return '>';
default : return '&' + e + ';';
}
});
};
ss.htmlEncode = function ss$htmlEncode(s) {
return s.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
};
ss.jsEncode = function ss$jsEncode(s, q) {
s = s.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\"');
return q ? '"' + s + '"' : s;
};
ss.indexOfAnyString = function ss$indexOfAnyString(s, chars, startIndex, count) {
var length = s.length;
if (!length) {
return -1;
}
chars = String.fromCharCode.apply(null, chars);
startIndex = startIndex || 0;
count = count || length;
var endIndex = startIndex + count - 1;
if (endIndex >= length) {
endIndex = length - 1;
}
for (var i = startIndex; i <= endIndex; i++) {
if (chars.indexOf(s.charAt(i)) >= 0) {
return i;
}
}
return -1;
};
ss.insertString = function ss$insertString(s, index, value) {
if (!value) {
return s;
}
if (!index) {
return value + s;
}
var s1 = s.substr(0, index);
var s2 = s.substr(index);
return s1 + value + s2;
};
ss.isNullOrEmptyString = function ss$isNullOrEmptyString(s) {
return !s || !s.length;
};
ss.lastIndexOfAnyString = function ss$lastIndexOfAnyString(s, chars, startIndex, count) {
var length = s.length;
if (!length) {
return -1;
}
chars = String.fromCharCode.apply(null, chars);
startIndex = startIndex || length - 1;
count = count || length;
var endIndex = startIndex - count + 1;
if (endIndex < 0) {
endIndex = 0;
}
for (var i = startIndex; i >= endIndex; i--) {
if (chars.indexOf(s.charAt(i)) >= 0) {
return i;
}
}
return -1;
};
ss.localeFormatString = function ss$localeFormatString(format) {
return ss._formatString(format, arguments, /* useLocale */ true);
};
ss.padLeftString = function ss$padLeftString(s, totalWidth, ch) {
if (s.length < totalWidth) {
ch = String.fromCharCode(ch || 0x20);
return ss.stringFromChar(ch, totalWidth - s.length) + s;
}
return s;
};
ss.padRightString = function ss$padRightString(s, totalWidth, ch) {
if (s.length < totalWidth) {
ch = String.fromCharCode(ch || 0x20);
return s + ss.stringFromChar(ch, totalWidth - s.length);
}
return s;
};
ss.removeString = function ss$removeString(s, index, count) {
if (!count || ((index + count) > this.length)) {
return s.substr(0, index);
}
return s.substr(0, index) + s.substr(index + count);
};
ss.replaceAllString = function ss$replaceAllString(s, oldValue, newValue) {
newValue = newValue || '';
return s.split(oldValue).join(newValue);
};
ss.startsWithString = function ss$startsWithString(s, prefix) {
if (!prefix.length) {
return true;
}
if (prefix.length > s.length) {
return false;
}
return (s.substr(0, prefix.length) == prefix);
};
if (!String.prototype.trim) {
String.prototype.trim = function String$trim() {
return ss.trimStartString(ss.trimEndString(this));
};
}
ss.trimEndString = function ss$trimEndString(s, chars) {
return s.replace(chars ? new RegExp('[' + String.fromCharCode.apply(null, chars) + ']+$') : /\s*$/, '');
};
ss.trimStartString = function ss$trimStartString(s, chars) {
return s.replace(chars ? new RegExp('^[' + String.fromCharCode.apply(null, chars) + ']+') : /^\s*/, '');
};
ss.trimString = function ss$trimString(s, chars) {
return ss.trimStartString(ss.trimEndString(s, chars), chars);
};
ss.lastIndexOfString = function ss$lastIndexOfString(s, search, startIndex, count) {
var index = s.lastIndexOf(search, startIndex);
return (index < (startIndex - count + 1)) ? -1 : index;
};
ss.indexOfString = function ss$indexOfString(s, search, startIndex, count) {
var index = s.indexOf(search, startIndex);
return ((index + search.length) <= (startIndex + count)) ? index : -1;
};
///////////////////////////////////////////////////////////////////////////////
// Math Extensions
ss.divRem = function ss$divRem(a, b, result) {
var remainder = a % b;
result.$ = remainder;
return (a - remainder) / b;
};
ss.round = function ss$round(n, d, rounding) {
var m = Math.pow(10, d || 0);
n *= m;
var sign = (n > 0) | -(n < 0);
if (n % 1 === 0.5 * sign) {
var f = Math.floor(n);
return (f + (rounding ? (sign > 0) : (f % 2 * sign))) / m;
}
return Math.round(n) / m;
};
///////////////////////////////////////////////////////////////////////////////
// IFormatProvider
var ss_IFormatProvider = function IFormatProvider$() { };
ss_IFormatProvider.__typeName = 'ss.IFormatProvider';
ss.IFormatProvider = ss_IFormatProvider;
ss.initInterface(ss_IFormatProvider, ss, { getFormat: null });
///////////////////////////////////////////////////////////////////////////////
// NumberFormatInfo
var ss_NumberFormatInfo = function NumberFormatInfo$() {
};
ss_NumberFormatInfo.__typeName = 'ss.NumberFormatInfo';
ss.NumberFormatInfo = ss_NumberFormatInfo;
ss.initClass(ss_NumberFormatInfo, ss, {
getFormat: function NumberFormatInfo$getFormat(type) {
return (type === ss_NumberFormatInfo) ? this : null;
}
}, null, [ss_IFormatProvider]);
ss_NumberFormatInfo.invariantInfo = new ss_NumberFormatInfo();
ss.shallowCopy({
naNSymbol: 'NaN',
negativeSign: '-',
positiveSign: '+',
negativeInfinitySymbol: '-Infinity',
positiveInfinitySymbol: 'Infinity',
percentSymbol: '%',
percentGroupSizes: [3],
percentDecimalDigits: 2,
percentDecimalSeparator: '.',
percentGroupSeparator: ',',
percentPositivePattern: 0,
percentNegativePattern: 0,
currencySymbol: '$',
currencyGroupSizes: [3],
currencyDecimalDigits: 2,
currencyDecimalSeparator: '.',
currencyGroupSeparator: ',',
currencyNegativePattern: 0,
currencyPositivePattern: 0,
numberGroupSizes: [3],
numberDecimalDigits: 2,
numberDecimalSeparator: '.',
numberGroupSeparator: ','
}, ss_NumberFormatInfo.invariantInfo);
///////////////////////////////////////////////////////////////////////////////
// DateTimeFormatInfo
var ss_DateTimeFormatInfo = function DateTimeFormatInfo$() {
};
ss_DateTimeFormatInfo.__typeName = 'ss.DateTimeFormatInfo';
ss.DateTimeFormatInfo = ss_DateTimeFormatInfo;
ss.initClass(ss_DateTimeFormatInfo, ss, {
getFormat: function DateTimeFormatInfo$getFormat(type) {
return type === ss_DateTimeFormatInfo ? this : null;
}
}, null, [ss_IFormatProvider]);
ss_DateTimeFormatInfo.invariantInfo = new ss_DateTimeFormatInfo();
ss.shallowCopy({
amDesignator: 'AM',
pmDesignator: 'PM',
dateSeparator: '/',
timeSeparator: ':',
gmtDateTimePattern: 'ddd, dd MMM yyyy HH:mm:ss \'GMT\'',
universalDateTimePattern: 'yyyy-MM-dd HH:mm:ssZ',
sortableDateTimePattern: 'yyyy-MM-ddTHH:mm:ss',
dateTimePattern: 'dddd, MMMM dd, yyyy h:mm:ss tt',
longDatePattern: 'dddd, MMMM dd, yyyy',
shortDatePattern: 'M/d/yyyy',
longTimePattern: 'h:mm:ss tt',
shortTimePattern: 'h:mm tt',
firstDayOfWeek: 0,
dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
shortDayNames: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
minimizedDayNames: ['Su','Mo','Tu','We','Th','Fr','Sa'],
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December',''],
shortMonthNames: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','']
}, ss_DateTimeFormatInfo.invariantInfo);
///////////////////////////////////////////////////////////////////////////////
// Stopwatch
var ss_Stopwatch = function Stopwatch$() {
this._stopTime = 0;
this._startTime = 0;
this.isRunning = false;
};
ss_Stopwatch.startNew = function Stopwatch$startNew() {
var s = new ss_Stopwatch();
s.start();
return s;
};
if (typeof(window) !== 'undefined' && window.performance && window.performance.now) {
ss_Stopwatch.frequency = 1e6;
ss_Stopwatch.isHighResolution = true;
ss_Stopwatch.getTimestamp = function() { return Math.round(window.performance.now() * 1000); };
}
else if (typeof(process) !== 'undefined' && process.hrtime) {
ss_Stopwatch.frequency = 1e9;
ss_Stopwatch.isHighResolution = true;
ss_Stopwatch.getTimestamp = function() { var hr = process.hrtime(); return hr[0] * 1e9 + hr[1]; };
}
else {
ss_Stopwatch.frequency = 1e3;
ss_Stopwatch.isHighResolution = false;
ss_Stopwatch.getTimestamp = function() { return new Date().valueOf(); };
}
ss_Stopwatch.__typeName = 'ss.Stopwatch';
ss.Stopwatch = ss_Stopwatch;
ss.initClass(ss_Stopwatch, ss, {
reset: function Stopwatch$reset() {
this._stopTime = this._startTime = ss_Stopwatch.getTimestamp();
this.isRunning = false;
},
ticks: function Stopwatch$ticks() {
return (this.isRunning ? ss_Stopwatch.getTimestamp() : this._stopTime) - this._startTime;
},
milliseconds: function Stopwatch$milliseconds() {
return Math.round(this.ticks() / ss_Stopwatch.frequency * 1000);
},
timeSpan: function Stopwatch$timeSpan() {
return new ss_TimeSpan(this.milliseconds() * 10000);
},
start: function Stopwatch$start() {
if (this.isRunning)
return;
this._startTime = ss_Stopwatch.getTimestamp();
this.isRunning = true;
},
stop: function Stopwatch$stop() {
if (!this.isRunning)
return;
this._stopTime = ss_Stopwatch.getTimestamp();
this.isRunning = false;
},
restart: function Stopwatch$restart() {
this.isRunning = false;
this.start();
}
});
///////////////////////////////////////////////////////////////////////////////
// Array Extensions
ss._flatIndex = function ss$_flatIndex(arr, indices) {
if (indices.length != (arr._sizes ? arr._sizes.length : 1))
throw new ss_ArgumentException('Invalid number of indices');
if (indices[0] < 0 || indices[0] >= (arr._sizes ? arr._sizes[0] : arr.length))
throw new ss_ArgumentException('Index 0 out of range');
var idx = indices[0];
if (arr._sizes) {
for (var i = 1; i < arr._sizes.length; i++) {
if (indices[i] < 0 || indices[i] >= arr._sizes[i])
throw new ss_ArgumentException('Index ' + i + ' out of range');
idx = idx * arr._sizes[i] + indices[i];
}
}
return idx;
};
ss.arrayGet2 = function ss$arrayGet2(arr, indices) {
var idx = ss._flatIndex(arr, indices);
var r = arr[idx];
return typeof r !== 'undefined' ? r : arr._defvalue;
};
ss.arrayGet = function ss$arrayGet(arr) {
return ss.arrayGet2(arr, Array.prototype.slice.call(arguments, 1));
}
ss.arraySet2 = function ss$arraySet2(arr, value, indices) {
var idx = ss._flatIndex(arr, indices);
arr[idx] = value;
};
ss.arraySet = function ss$arraySet() {
return ss.arraySet2(arguments[0], arguments[arguments.length - 1], Array.prototype.slice.call(arguments, 1, arguments.length - 1));
};
ss.arrayRank = function ss$arrayRank(arr) {
return arr._sizes ? arr._sizes.length : 1;
};
ss.arrayLength = function ss$arrayLength(arr, dimension) {
if (dimension >= (arr._sizes ? arr._sizes.length : 1))
throw new ss_ArgumentException('Invalid dimension');
return arr._sizes ? arr._sizes[dimension] : arr.length;
};
ss.arrayExtract = function ss$arrayExtract(arr, start, count) {
if (!ss.isValue(count)) {
return arr.slice(start);
}
return arr.slice(start, start + count);
};
ss.arrayAddRange = function ss$arrayAddRange(arr, items) {
if (items instanceof Array) {
arr.push.apply(arr, items);
}
else {
var e = ss.getEnumerator(items);
try {
while (e.moveNext()) {
ss.add(arr, e.current());
}
}
finally {
if (ss.isInstanceOfType(e, ss_IDisposable)) {
ss.cast(e, ss_IDisposable).dispose();
}
}
}
};
ss.arrayClone = function ss$arrayClone(arr) {
if (arr.length === 1) {
return [arr[0]];
}
else {
return Array.apply(null, arr);
}
};
ss.arrayPeekFront = function ss$arrayPeekFront(arr) {
if (arr.length)
return arr[0];
throw new ss_InvalidOperationException('Array is empty');
};
ss.arrayPeekBack = function ss$arrayPeekBack(arr) {
if (arr.length)
return arr[arr.length - 1];
throw new ss_InvalidOperationException('Array is empty');
};
ss.indexOfArray = function ss$indexOfArray(arr, item, startIndex) {
startIndex = startIndex || 0;
for (var i = startIndex; i < arr.length; i++) {
if (ss.staticEquals(arr[i], item)) {
return i;
}
}
return -1;
}
ss.arrayInsertRange = function ss$arrayInsertRange(arr, index, items) {
if (items instanceof Array) {
if (index === 0) {
arr.unshift.apply(arr, items);
}
else {
for (var i = 0; i < items.length; i++) {
arr.splice(index + i, 0, items[i]);
}
}
}
else {
var e = ss.getEnumerator(items);
try {
while (e.moveNext()) {
arr.insert(index, e.current());
index++;
}
}
finally {
if (ss.isInstanceOfType(e, ss_IDisposable)) {
ss.cast(e, ss_IDisposable).dispose();
}
}
}
};
if (!Array.prototype.map) {
Array.prototype.map = function Array$map(callback, instance) {
var length = this.length;
var mapped = new Array(length);
for (var i = 0; i < length; i++) {
if (i in this) {
mapped[i] = callback.call(instance, this[i], i, this);
}
}
return mapped;
};
}
ss.arrayRemoveRange = function ss$arrayRemoveRange(arr, index, count) {
arr.splice(index, count);
};
if (!Array.prototype.some) {
Array.prototype.some = function Array$some(callback, instance) {
var length = this.length;
for (var i = 0; i < length; i++) {
if (i in this && callback.call(instance, this[i], i, this)) {
return true;
}
}
return false;
};
}
ss.arrayFromEnumerable = function ss$arrayFromEnumerable(enm) {
if (!ss.isValue(enm))
return null;
var e = ss.getEnumerator(enm), r = [];
try {
while (e.moveNext())
r.push(e.current());
}
finally {
e.dispose();
}
return r;
};
ss.multidimArray = function ss$multidimArray(defvalue, sizes) {
var arr = [];
arr._defvalue = defvalue;
arr._sizes = [arguments[1]];
var length = arguments[1];
for (var i = 2; i < arguments.length; i++) {
length *= arguments[i];
arr._sizes[i - 1] = arguments[i];
}
arr.length = length;
return arr;
};
ss.repeat = function ss$repeat(value, count) {
var result = [];
for (var i = 0; i < count; i++)
result.push(value);
return result;
};
ss.arrayFill = function ss$arrayFill(dst, val, index, count) {
if (index < 0 || count < 0 || (index + count) > dst.length)
throw new ss_ArgumentException();
if (Array.prototype.fill) {
dst.fill(val, index, index + count);
}
else {
while (--count >= 0)
dst[index + count] = val;
}
};
ss.arrayCopy = function ss$arrayCopy(src, spos, dst, dpos, len) {
if (spos < 0 || dpos < 0 || len < 0)
throw new ss_ArgumentOutOfRangeException();
if (len > (src.length - spos) || len > (dst.length - dpos))
throw new ss_ArgumentException();
if (spos < dpos && src === dst) {
while (--len >= 0)
dst[dpos + len] = src[spos + len];
}
else {
for (var i = 0; i < len; i++)
dst[dpos + i] = src[spos + i];
}
}
///////////////////////////////////////////////////////////////////////////////
// Date Extensions
ss.utcNow = function ss$utcNow() {
var d = new Date();
return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
};
ss.toUTC = function ss$toUniversalTime(d) {
return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
};
ss.fromUTC = function ss$toLocalTime(d) {
return new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
};
ss.today = function ss$today() {
var d = new Date();
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
ss.formatDate = function ss$formatDate(date, format) {
if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) {
return date.toString();
}
if (format == 'id') {
return date.toDateString();
}
if (format == 'it') {
return date.toTimeString();
}
return ss._netFormatDate(date, format, false);
};
ss.localeFormatDate = function ss$localeFormatDate(date, format) {
if (ss.isNullOrUndefined(format) || (format.length == 0) || (format == 'i')) {
return date.toLocaleString();
}
if (format == 'id') {
return date.toLocaleDateString();
}
if (format == 'it') {
return date.toLocaleTimeString();
}
return ss._netFormatDate(date, format, true);
};
ss._netFormatDate = function ss$_netFormatDate(dt, format, useLocale) {
var dtf = useLocale ? ss_CultureInfo.currentCulture.dateTimeFormat : ss_CultureInfo.invariantCulture.dateTimeFormat;
if (format.length == 1) {
switch (format) {
case 'f': format = dtf.longDatePattern + ' ' + dtf.shortTimePattern; break;
case 'F': format = dtf.dateTimePattern; break;
case 'd': format = dtf.shortDatePattern; break;
case 'D': format = dtf.longDatePattern; break;
case 't': format = dtf.shortTimePattern; break;
case 'T': format = dtf.longTimePattern; break;
case 'g': format = dtf.shortDatePattern + ' ' + dtf.shortTimePattern; break;
case 'G': format = dtf.shortDatePattern + ' ' + dtf.longTimePattern; break;
case 'R': case 'r':
dtf = ss_CultureInfo.InvariantCulture.dateTimeFormat;
format = dtf.gmtDateTimePattern;
break;
case 'u': format = dtf.universalDateTimePattern; break;
case 'U':
format = dtf.dateTimePattern;
dt = new Date(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate(),
dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
break;
case 's': format = dtf.sortableDateTimePattern; break;
}
}
if (format.charAt(0) == '%') {
format = format.substr(1);
}
if (!Date._formatRE) {
Date._formatRE = /'.*?[^\\]'|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g;
}
var re = Date._formatRE;
var sb = new ss_StringBuilder();
re.lastIndex = 0;
while (true) {
var index = re.lastIndex;
var match = re.exec(format);
sb.append(format.slice(index, match ? match.index : format.length));
if (!match) {
break;
}
var fs = match[0];
var part = fs;
switch (fs) {
case 'dddd':
part = dtf.dayNames[dt.getDay()];
break;
case 'ddd':
part = dtf.shortDayNames[dt.getDay()];
break;
case 'dd':
part = ss.padLeftString(dt.getDate().toString(), 2, 0x30);
break;
case 'd':
part = dt.getDate();
break;
case 'MMMM':
part = dtf.monthNames[dt.getMonth()];
break;
case 'MMM':
part = dtf.shortMonthNames[dt.getMonth()];
break;
case 'MM':
part = ss.padLeftString((dt.getMonth() + 1).toString(), 2, 0x30);
break;
case 'M':
part = (dt.getMonth() + 1);
break;
case 'yyyy':
part = dt.getFullYear();
break;
case 'yy':
part = ss.padLeftString((dt.getFullYear() % 100).toString(), 2, 0x30);
break;
case 'y':
part = (dt.getFullYear() % 100);
break;
case 'h': case 'hh':
part = dt.getHours() % 12;
if (!part) {
part = '12';
}
else if (fs == 'hh') {
part = ss.padLeftString(part.toString(), 2, 0x30);
}
break;
case 'HH':
part = ss.padLeftString(dt.getHours().toString(), 2, 0x30);
break;
case 'H':
part = dt.getHours();
break;
case 'mm':
part = ss.padLeftString(dt.getMinutes().toString(), 2, 0x30);
break;
case 'm':
part = dt.getMinutes();
break;
case 'ss':
part = ss.padLeftString(dt.getSeconds().toString(), 2, 0x30);
break;
case 's':
part = dt.getSeconds();
break;
case 't': case 'tt':
part = (dt.getHours() < 12) ? dtf.amDesignator : dtf.pmDesignator;
if (fs == 't') {
part = part.charAt(0);
}
break;
case 'fff':
part = ss.padLeftString(dt.getMilliseconds().toString(), 3, 0x30);
break;
case 'ff':
part = ss.padLeftString(dt.getMilliseconds().toString(), 3).substr(0, 2);
break;
case 'f':
part = ss.padLeftString(dt.getMilliseconds().toString(), 3).charAt(0);
break;
case 'z':
part = dt.getTimezoneOffset() / 60;
part = ((part >= 0) ? '-' : '+') + Math.floor(Math.abs(part));
break;
case 'zz': case 'zzz':
part = dt.getTimezoneOffset() / 60;
part = ((part >= 0) ? '-' : '+') + Math.floor(ss.padLeftString(Math.abs(part)).toString(), 2, 0x30);
if (fs == 'zzz') {
part += dtf.timeSeparator + Math.abs(ss.padLeftString(dt.getTimezoneOffset() % 60).toString(), 2, 0x30);
}
break;
default:
if (part.charAt(0) == '\'') {
part = part.substr(1, part.length - 2).replace(/\\'/g, '\'');
}
break;
}
sb.append(part);
}
return sb.toString();
};
ss._parseExactDate = function ss$_parseExactDate(val, format, provider, utc) {
provider = (provider && provider.getFormat(ss_DateTimeFormatInfo)) || ss_CultureInfo.currentCulture.dateTimeFormat;
var AM = provider.amDesignator, PM = provider.pmDesignator;
var _isInteger = function(val) {
var digits="1234567890";
for (var i=0; i < val.length; i++) {
if (digits.indexOf(val.charAt(i))==-1) {
return false;
}
}
return true;
};
var _getInt = function(str,i,minlength,maxlength) {
for (var x=maxlength; x>=minlength; x--) {
var token=str.substring(i,i+x);
if (token.length < minlength) {
return null;
}
if (_isInteger(token)) {
return token;
}
}
return null;
};
val = val + "";
format = format + "";
var i_val = 0;
var i_format = 0;
var c = "";
var token = "";
var year = 0, month = 1, date = 1, hh = 0, mm = 0, _ss = 0, ampm = "";
while (i_format < format.length) {
// Get next token from format string
c = format.charAt(i_format);
token = "";
while ((format.charAt(i_format) == c) && (i_format < format.length)) {
token += format.charAt(i_format++);
}
// Extract contents of value based on format token
if (token=="yyyy" || token=="yy" || token=="y") {
if (token == "yyyy")
year = _getInt(val, i_val, 4, 4);
if (token == "yy")
year = _getInt(val, i_val, 2, 2);
if (token == "y")
year = _getInt(val, i_val, 2, 4);
if (year == null)
return null;
i_val += year.length;
if (year.length == 2) {
if (year > 30) {
year = 1900 + (year-0);
}
else {
year = 2000 + (year-0);
}
}
}
else if (token == "MM" || token == "M") {
month = _getInt(val, i_val, token.length, 2);
if (month == null || (month < 1) || (month > 12))
return null;
i_val += month.length;
}
else if (token=="dd"||token=="d") {
date = _getInt(val, i_val, token.length, 2);
if (date == null || (date < 1) || (date > 31))
return null;
i_val += date.length;
}
else if (token=="hh"||token=="h") {
hh = _getInt(val, i_val, token.length, 2);
if (hh == null || (hh < 1) || (hh > 12))
return null;
i_val += hh.length;
}
else if (token=="HH"||token=="H") {
hh = _getInt(val, i_val, token.length, 2);
if (hh == null || (hh < 0) || (hh > 23))
return null;
i_val += hh.length;
}
else if (token == "mm" || token == "m") {
mm = _getInt(val, i_val, token.length, 2);
if (mm == null || (mm < 0) || (mm > 59))
return null;
i_val += mm.length;
}
else if (token == "ss" || token == "s") {
_ss = _getInt(val, i_val, token.length, 2);
if (_ss == null || (_ss < 0) || (_ss > 59))
return null;
i_val += _ss.length;
}
else if (token == "t") {
if (val.substring(i_val, i_val + 1).toLowerCase() == AM.charAt(0).toLowerCase())
ampm = AM;
else if (val.substring(i_val, i_val + 1).toLowerCase() == PM.charAt(0).toLowerCase())
ampm = PM;
else
return null;
i_val += 1;
}
else if (token == "tt") {
if (val.substring(i_val, i_val + 2).toLowerCase() == AM.toLowerCase())
ampm = AM;
else if (val.substring(i_val,i_val+2).toLowerCase() == PM.toLowerCase())
ampm = PM;
else
return null;
i_val += 2;
}
else {
if (val.substring(i_val, i_val + token.length) != token)
return null;
else
i_val += token.length;
}
}
// If there are any trailing characters left in the value, it doesn't match
if (i_val != val.length)
return null;
// Is date valid for month?
if (month == 2) {
// Check for leap year
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { // leap year
if (date > 29)
return null;
}
else if (date > 28)
return null;
}
if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
if (date > 30) {
return null;
}
}
// Correct hours value
if (hh < 12 && ampm == PM) {
hh = hh - 0 + 12;
}
else if (hh > 11 && ampm == AM) {
hh -= 12;
}
if (utc)
return new Date(Date.UTC(year, month - 1, date, hh, mm, _ss));
else
return new Date(year, month - 1, date, hh, mm, _ss);
};
ss.parseExactDate = function ss$parseExactDate(val, format, provider) {
return ss._parseExactDate(val, format, provider, false);
};
ss.parseExactDateUTC = function ss$parseExactDateUTC(val, format, provider) {
return ss._parseExactDate(val, format, provider, true);
};
///////////////////////////////////////////////////////////////////////////////
// Function Extensions
ss._delegateContains = function ss$_delegateContains(targets, object, method) {
for (var i = 0; i < targets.length; i += 2) {
if (targets[i] === object && targets[i + 1] === method) {
return true;
}
}
return false;
};
ss._mkdel = function ss$_mkdel(targets) {
var delegate = function() {
if (targets.length == 2) {
return targets[1].apply(targets[0], arguments);
}
else {
var clone = ss.arrayClone(targets);
for (var i = 0; i < clone.length; i += 2) {
if (ss._delegateContains(targets, clone[i], clone[i + 1])) {
clone[i + 1].apply(clone[i], arguments);
}
}
return null;
}
};
delegate._targets = targets;
return delegate;
};
ss.mkdel = function ss$mkdel(object, method) {
if (!object) {
return method;
}
if (typeof method === 'string') {
method = object[method];
}
return ss._mkdel([object, method]);
};
ss.delegateCombine = function ss$delegateCombine(delegate1, delegate2) {
if (!delegate1) {
if (!delegate2._targets) {
return ss.mkdel(null, delegate2);
}
return delegate2;
}
if (!delegate2) {
if (!delegate1._targets) {
return ss.mkdel(null, delegate1);
}
return delegate1;
}
var targets1 = delegate1._targets ? delegate1._targets : [null, delegate1];
var targets2 = delegate2._targets ? delegate2._targets : [null, delegate2];
return ss._mkdel(targets1.concat(targets2));
};
ss.delegateRemove = function ss$delegateRemove(delegate1, delegate2) {
if (!delegate1 || (delegate1 === delegate2)) {
return null;
}
if (!delegate2) {
return delegate1;
}
var targets = delegate1._targets;
var object = null;
var method;
if (delegate2._targets) {
object = delegate2._targets[0];
method = delegate2._targets[1];
}
else {
method = delegate2;
}
for (var i = 0; i < targets.length; i += 2) {
if ((targets[i] === object) && (targets[i + 1] === method)) {
if (targets.length == 2) {
return null;
}
var t = ss.arrayClone(targets);
t.splice(i, 2);
return ss._mkdel(t);
}
}
return delegate1;
};
ss.delegateEquals = function ss$delegateEquals(a, b) {
if (a === b)
return true;
if (!a._targets && !b._targets)
return false;
var ta = a._targets || [null, a], tb = b._targets || [null, b];
if (ta.length != tb.length)
return false;
for (var i = 0; i < ta.length; i++) {
if (ta[i] !== tb[i])
return false;
}
return true;
};
ss.delegateClone = function ss$delegateClone(source) {
return source._targets ? ss._mkdel(source._targets) : function() { return source.apply(this, arguments); };
};
ss.thisFix = function ss$thisFix(source) {
return function() {
var x = [this];
for(var i = 0; i < arguments.length; i++)
x.push(arguments[i]);
return source.apply(source, x);
};
};
ss.getInvocationList = function ss$getInvocationList(delegate) {
if (!delegate._targets)
return [delegate];
var result = [];
for (var i = 0; i < delegate._targets.length; i += 2)
result.push(ss.mkdel(delegate._targets[i], delegate._targets[i + 1]));
return result;
};
///////////////////////////////////////////////////////////////////////////////
// RegExp Extensions
ss.regexpEscape = function ss$regexpEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
///////////////////////////////////////////////////////////////////////////////
// Debug Extensions
ss.Debug = global.Debug || function() {};
ss.Debug.__typeName = 'Debug';
if (!ss.Debug.writeln) {
ss.Debug.writeln = function Debug$writeln(text) {
if (global.console) {
if (global.console.debug) {
global.console.debug(text);
return;
}
else if (global.console.log) {
global.console.log(text);
return;
}
}
else if (global.opera &&
global.opera.postError) {
global.opera.postError(text);
return;
}
}
};
ss.Debug._fail = function Debug$_fail(message) {
ss.Debug.writeln(message);
debugger;
};
ss.Debug.assert = function Debug$assert(condition, message) {
if (!condition) {
message = 'Assert failed: ' + message;
if (confirm(message + '\r\n\r\nBreak into debugger?')) {
ss.Debug._fail(message);
}
}
};
ss.Debug.fail = function Debug$fail(message) {
ss.Debug._fail(message);
};
///////////////////////////////////////////////////////////////////////////////
// Enum
var ss_Enum = function Enum$() {
};
ss_Enum.__typeName = 'ss.Enum';
ss.Enum = ss_Enum;
ss.initClass(ss_Enum, ss, {});
ss_Enum.parse = function Enum$parse(enumType, s) {
var values = enumType.prototype;
if (!ss.isFlags(enumType)) {
for (var f in values) {
if (f === s) {
return values[f];
}
}
}
else {
var parts = s.split('|');
var value = 0;
var parsed = true;
for (var i = parts.length - 1; i >= 0; i--) {
var part = parts[i].trim();
var found = false;
for (var f in values) {
if (f === part) {
value |= values[f];
found = true;
break;
}
}
if (!found) {
parsed = false;
break;
}
}
if (parsed) {
return value;
}
}
throw new ss_ArgumentException('Invalid Enumeration Value');
};
ss_Enum.toString = function Enum$toString(enumType, value) {
var values = enumType.prototype;
if (!ss.isFlags(enumType) || (value === 0)) {
for (var i in values) {
if (values[i] === value) {
return i;
}
}
throw new ss_ArgumentException('Invalid Enumeration Value');
}
else {
var parts = [];
for (var i in values) {
if (values[i] & value) {
ss.add(parts, i);
}
}
if (!parts.length) {
throw new ss_ArgumentException('Invalid Enumeration Value');
}
return parts.join(' | ');
}
};
ss_Enum.getValues = function Enum$getValues(enumType) {
var parts = [];
var values = enumType.prototype;
for (var i in values) {
if (values.hasOwnProperty(i))
parts.push(values[i]);
}
return parts;
};
///////////////////////////////////////////////////////////////////////////////
// CultureInfo
var ss_CultureInfo = function CultureInfo$(name, numberFormat, dateTimeFormat) {
this.name = name;
this.numberFormat = numberFormat;
this.dateTimeFormat = dateTimeFormat;
};
ss_CultureInfo.__typeName = 'ss.CultureInfo';
ss.CultureInfo = ss_CultureInfo;
ss.initClass(ss_CultureInfo, ss, {
getFormat: function CultureInfo$getFormat(type) {
switch (type) {
case ss_NumberFormatInfo: return this.numberFormat;
case ss_DateTimeFormatInfo: return this.dateTimeFormat;
default: return null;
}
}
}, null, [ss_IFormatProvider]);
ss_CultureInfo.invariantCulture = new ss_CultureInfo('en-US', ss_NumberFormatInfo.invariantInfo, ss_DateTimeFormatInfo.invariantInfo);
ss_CultureInfo.currentCulture = ss_CultureInfo.invariantCulture;
///////////////////////////////////////////////////////////////////////////////
// IEnumerator
var ss_IEnumerator = function IEnumerator$() { };
ss_IEnumerator.__typeName = 'ss.IEnumerator';
ss.IEnumerator = ss_IEnumerator;
ss.initInterface(ss_IEnumerator, ss, { current: null, moveNext: null, reset: null }, [ss_IDisposable]);
///////////////////////////////////////////////////////////////////////////////
// IEnumerable
var ss_IEnumerable = function IEnumerable$() { };
ss_IEnumerable.__typeName = 'ss.IEnumerable';
ss.IEnumerable = ss_IEnumerable;
ss.initInterface(ss_IEnumerable, ss, { getEnumerator: null });
ss.getEnumerator = function ss$getEnumerator(obj) {
return obj.getEnumerator ? obj.getEnumerator() : new ss_ArrayEnumerator(obj);
};
///////////////////////////////////////////////////////////////////////////////
// ICollection
var ss_ICollection = function ICollection$() { };
ss_ICollection.__typeName = 'ss.ICollection';
ss.ICollection = ss_ICollection;
ss.initInterface(ss_ICollection, ss, { get_count: null, add: null, clear: null, contains: null, remove: null });
ss.count = function ss$count(obj) {
return obj.get_count ? obj.get_count() : obj.length;
};
ss.add = function ss$add(obj, item) {
if (obj.add)
obj.add(item);
else if (ss.isArray(obj))
obj.push(item);
else
throw new ss_NotSupportedException();
};
ss.clear = function ss$clear(obj) {
if (obj.clear)
obj.clear();
else if (ss.isArray(obj))
obj.length = 0;
else
throw new ss_NotSupportedException();
};
ss.remove = function ss$remove(obj, item) {
if (obj.remove)
return obj.remove(item);
else if (ss.isArray(obj)) {
var index = ss.indexOf(obj, item);
if (index >= 0) {
obj.splice(index, 1);
return true;
}
return false;
}
else
throw new ss_NotSupportedException();
};
ss.contains = function ss$contains(obj, item) {
if (obj.contains)
return obj.contains(item);
else
return ss.indexOf(obj, item) >= 0;
};
///////////////////////////////////////////////////////////////////////////////
// TimeSpan
var ss_TimeSpan = function TimeSpan$(ticks) {
this.ticks = ticks || 0;
};
ss_TimeSpan.getDefaultValue = ss_TimeSpan.createInstance = function TimeSpan$default() {
return new ss_TimeSpan(0);
};
ss_TimeSpan.__typeName = 'ss.TimeSpan';
ss.TimeSpan = ss_TimeSpan;
ss.initClass(ss_TimeSpan, ss, {
compareTo: function TimeSpan$compareTo(other) {
return this.ticks < other.ticks ? -1 : (this.ticks > other.ticks ? 1 : 0);
},
equals: function TimeSpan$equals(other) {
return ss.isInstanceOfType(other, ss_TimeSpan) && other.ticks === this.ticks;
},
equalsT: function TimeSpan$equalsT(other) {
return other.ticks === this.ticks;
},
toString: function TimeSpan$toString() {
var d = function(s, n) { return ss.padLeftString(s + '', n || 2, 48); };
var ticks = this.ticks;
var result = '';
if (Math.abs(ticks) >= 864000000000) {
result += d((ticks / 864000000000) | 0) + '.';
ticks %= 864000000000;
}
result += d(ticks / 36000000000 | 0) + ':';
ticks %= 36000000000;
result += d(ticks / 600000000 | 0) + ':';
ticks %= 600000000;
result += d(ticks / 10000000 | 0);
ticks %= 10000000;
if (ticks > 0)
result += '.' + d(ticks, 7);
return result;
}
}, null, [ss_IComparable, ss_IEquatable]);
ss_TimeSpan.__class = false;
///////////////////////////////////////////////////////////////////////////////
// IEqualityComparer
var ss_IEqualityComparer = function IEqualityComparer$() { };
ss_IEqualityComparer.__typeName = 'ss.IEqualityComparer';
ss.IEqualityComparer = ss_IEqualityComparer;
ss.initInterface(ss_IEqualityComparer, ss, { areEqual: null, getObjectHashCode: null });
///////////////////////////////////////////////////////////////////////////////
// IComparer
var ss_IComparer = function IComparer$() { };
ss_IComparer.__typeName = 'ss.IComparer';
ss.IComparer = ss_IComparer;
ss.initInterface(ss_IComparer, ss, { compare: null });
///////////////////////////////////////////////////////////////////////////////
// Nullable
ss.unbox = function ss$unbox(instance) {
if (!ss.isValue(instance))
throw new ss_InvalidOperationException('Nullable object must have a value.');
return instance;
};
var ss_Nullable$1 = function Nullable$1$(T) {
var $type = function() {
};
$type.isInstanceOfType = function(instance) {
return ss.isInstanceOfType(instance, T);
};
ss.registerGenericClassInstance($type, ss_Nullable$1, [T], {}, function() { return null; }, function() { return []; });
return $type;
};
ss_Nullable$1.__typeName = 'ss.Nullable$1';
ss.Nullable$1 = ss_Nullable$1;
ss.initGenericClass(ss_Nullable$1, ss, 1);
ss_Nullable$1.eq = function Nullable$eq(a, b) {
return !ss.isValue(a) ? !ss.isValue(b) : (a === b);
};
ss_Nullable$1.ne = function Nullable$eq(a, b) {
return !ss.isValue(a) ? ss.isValue(b) : (a !== b);
};
ss_Nullable$1.le = function Nullable$le(a, b) {
return ss.isValue(a) && ss.isValue(b) && a <= b;
};
ss_Nullable$1.ge = function Nullable$ge(a, b) {
return ss.isValue(a) && ss.isValue(b) && a >= b;
};
ss_Nullable$1.lt = function Nullable$lt(a, b) {
return ss.isValue(a) && ss.isValue(b) && a < b;
};
ss_Nullable$1.gt = function Nullable$gt(a, b) {
return ss.isValue(a) && ss.isValue(b) && a > b;
};
ss_Nullable$1.sub = function Nullable$sub(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a - b : null;
};
ss_Nullable$1.add = function Nullable$add(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a + b : null;
};
ss_Nullable$1.mod = function Nullable$mod(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a % b : null;
};
ss_Nullable$1.div = function Nullable$divf(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a / b : null;
};
ss_Nullable$1.mul = function Nullable$mul(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a * b : null;
};
ss_Nullable$1.band = function Nullable$band(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a & b : null;
};
ss_Nullable$1.bor = function Nullable$bor(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a | b : null;
};
ss_Nullable$1.bxor = function Nullable$xor(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a ^ b : null;
};
ss_Nullable$1.shl = function Nullable$shl(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a << b : null;
};
ss_Nullable$1.srs = function Nullable$srs(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a >> b : null;
};
ss_Nullable$1.sru = function Nullable$sru(a, b) {
return ss.isValue(a) && ss.isValue(b) ? a >>> b : null;
};
ss_Nullable$1.and = function Nullable$and(a, b) {
if (a === true && b === true)
return true;
else if (a === false || b === false)
return false;
else
return null;
};
ss_Nullable$1.or = function Nullable$or(a, b) {
if (a === true || b === true)
return true;
else if (a === false && b === false)
return false;
else
return null;
};
ss_Nullable$1.xor = function Nullable$xor(a, b) {
return ss.isValue(a) && ss.isValue(b) ? !!(a ^ b) : null;
};
ss_Nullable$1.not = function Nullable$not(a) {
return ss.isValue(a) ? !a : null;
};
ss_Nullable$1.neg = function Nullable$neg(a) {
return ss.isValue(a) ? -a : null;
};
ss_Nullable$1.pos = function Nullable$pos(a) {
return ss.isValue(a) ? +a : null;
};
ss_Nullable$1.cpl = function Nullable$cpl(a) {
return ss.isValue(a) ? ~a : null;
};
ss_Nullable$1.lift1 = function Nullable$lift1(f, o) {
return ss.isValue(o) ? f(o) : null;
};
ss_Nullable$1.lift2 = function Nullable$lift2(f, a, b) {
return ss.isValue(a) && ss.isValue(b) ? f(a, b) : null;
};
ss_Nullable$1.liftcmp = function Nullable$liftcmp(f, a, b) {
return ss.isValue(a) && ss.isValue(b) ? f(a, b) : false;
};
ss_Nullable$1.lifteq = function Nullable$lifteq(f, a, b) {
var va = ss.isValue(a), vb = ss.isValue(b);
return (!va && !vb) || (va && vb && f(a, b));
};
ss_Nullable$1.liftne = function Nullable$liftne(f, a, b) {
var va = ss.isValue(a), vb = ss.isValue(b);
return (va !== vb) || (va && f(a, b));
};
///////////////////////////////////////////////////////////////////////////////
// IList
var ss_IList = function IList$() { };
ss_IList.__typeName = 'ss.IList';
ss.IList = ss_IList;
ss.initInterface(ss_IList, ss, { get_item: null, set_item: null, indexOf: null, insert: null, removeAt: null }, [ss_ICollection, ss_IEnumerable]);
ss.getItem = function ss$getItem(obj, index) {
return obj.get_item ? obj.get_item(index) : obj[index];
}
ss.setItem = function ss$setItem(obj, index, value) {
obj.set_item ? obj.set_item(index, value) : (obj[index] = value);
}
ss.indexOf = function ss$indexOf(obj, item) {
if (ss.isArrayOrTypedArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (ss.staticEquals(obj[i], item)) {
return i;
}
}
return -1;
}
else
return obj.indexOf(item);
};
ss.insert = function ss$insert(obj, index, item) {
if (obj.insert)
obj.insert(index, item);
else if (ss.isArray(obj))
obj.splice(index, 0, item);
else
throw new ss_NotSupportedException();
};
ss.removeAt = function ss$removeAt(obj, index) {
if (obj.removeAt)
obj.removeAt(index);
else if (ss.isArray(obj))
obj.splice(index, 1);
else
throw new ss_NotSupportedException();
};
///////////////////////////////////////////////////////////////////////////////
// IDictionary
var ss_IDictionary = function IDictionary$() { };
ss_IDictionary.__typeName = 'ss.IDictionary';
ss.IDictionary = ss_IDictionary;
ss.initInterface(ss_IDictionary, ss, { get_item: null, set_item: null, get_keys: null, get_values: null, containsKey: null, add: null, remove: null, tryGetValue: null }, [ss_IEnumerable]);
///////////////////////////////////////////////////////////////////////////////
// Int32
var ss_Int32 = function Int32$() { };
ss_Int32.__typeName = 'ss.Int32';
ss.Int32 = ss_Int32;
ss.initClass(ss_Int32, ss, {}, Object, [ ss_IEquatable, ss_IComparable, ss_IFormattable ]);
ss_Int32.__class = false;
ss_Int32.isInstanceOfType = function Int32$isInstanceOfType(instance) {
return typeof(instance) === 'number' && isFinite(instance) && Math.round(instance, 0) == instance;
};
ss_Int32.getDefaultValue = ss_Int32.createInstance = function Int32$getDefaultValue() {
return 0;
};
ss_Int32.div = function Int32$div(a, b) {
if (!ss.isValue(a) || !ss.isValue(b)) return null;
if (b === 0) throw new ss_DivideByZeroException();
return ss_Int32.trunc(a / b);
};
ss_Int32.trunc = function Int32$trunc(n) {
return ss.isValue(n) ? (n > 0 ? Math.floor(n) : Math.ceil(n)) : null;
};
ss_Int32.tryParse = function Int32$tryParse(s, result, min, max) {
result.$ = 0;
if (!/^[+-]?[0-9]+$/.test(s))
return 0;
var n = parseInt(s, 10);
if (n < min || n > max)
return false;
result.$ = n;
return true;
};
///////////////////////////////////////////////////////////////////////////////
// MutableDateTime
var ss_JsDate = function JsDate$() { };
ss_JsDate.__typeName = 'ss.JsDate';
ss.JsDate = ss_JsDate;
ss.initClass(ss_JsDate, ss, {}, Object, [ ss_IEquatable, ss_IComparable ]);
ss_JsDate.createInstance = function JsDate$createInstance() {
return new Date();
};
ss_JsDate.isInstanceOfType = function JsDate$isInstanceOfType(instance) {
return instance instanceof Date;
};
///////////////////////////////////////////////////////////////////////////////
// ArrayEnumerator
var ss_ArrayEnumerator = function ArrayEnumerator$(array) {
this._array = array;
this._index = -1;
};
ss_ArrayEnumerator.__typeName = 'ss.ArrayEnumerator';
ss.ArrayEnumerator = ss_ArrayEnumerator;
ss.initClass(ss_ArrayEnumerator, ss, {
moveNext: function ArrayEnumerator$moveNext() {
this._index++;
return (this._index < this._array.length);
},
reset: function ArrayEnumerator$reset() {
this._index = -1;
},
current: function ArrayEnumerator$current() {
if (this._index < 0 || this._index >= this._array.length)
throw 'Invalid operation';
return this._array[this._index];
},
dispose: function ArrayEnumerator$dispose() {
}
}, null, [ss_IEnumerator, ss_IDisposable]);
///////////////////////////////////////////////////////////////////////////////
// ObjectEnumerator
var ss_ObjectEnumerator = function ObjectEnumerator$(o) {
this._keys = Object.keys(o);
this._index = -1;
this._object = o;
};
ss_ObjectEnumerator.__typeName = 'ss.ObjectEnumerator';
ss.ObjectEnumerator = ss_ObjectEnumerator;
ss.initClass(ss_ObjectEnumerator, ss, {
moveNext: function ObjectEnumerator$moveNext() {
this._index++;
return (this._index < this._keys.length);
},
reset: function ObjectEnumerator$reset() {
this._index = -1;
},
current: function ObjectEnumerator$current() {
if (this._index < 0 || this._index >= this._keys.length)
throw new ss_InvalidOperationException('Invalid operation');
var k = this._keys[this._index];
return { key: k, value: this._object[k] };
},
dispose: function ObjectEnumerator$dispose() {
}
}, null, [ss_IEnumerator, ss_IDisposable]);
///////////////////////////////////////////////////////////////////////////////
// EqualityComparer
var ss_EqualityComparer = function EqualityComparer$() {
};
ss_EqualityComparer.__typeName = 'ss.EqualityComparer';
ss.EqualityComparer = ss_EqualityComparer;
ss.initClass(ss_EqualityComparer, ss, {
areEqual: function EqualityComparer$areEqual(x, y) {
return ss.staticEquals(x, y);
},
getObjectHashCode: function EqualityComparer$getObjectHashCode(obj) {
return ss.isValue(obj) ? ss.getHashCode(obj) : 0;
}
}, null, [ss_IEqualityComparer]);
ss_EqualityComparer.def = new ss_EqualityComparer();
///////////////////////////////////////////////////////////////////////////////
// Comparer
var ss_Comparer = function Comparer$(f) {
this.f = f;
};
ss_Comparer.__typeName = 'ss.Comparer';
ss.Comparer = ss_Comparer;
ss.initClass(ss_Comparer, ss, {
compare: function Comparer$compare(x, y) {
return this.f(x, y);
}
}, null, [ss_IComparer]);
ss_Comparer.def = new ss_Comparer(function Comparer$defaultCompare(a, b) {
if (!ss.isValue(a))
return !ss.isValue(b)? 0 : -1;
else if (!ss.isValue(b))
return 1;
else
return ss.compare(a, b);
});
///////////////////////////////////////////////////////////////////////////////
// Dictionary
var ss_$DictionaryCollection = function $DictionaryCollection$(dict, isKeys) {
this._dict = dict;
this._isKeys = isKeys;
};
var ss_Dictionary$2 = function Dictionary$2$(TKey, TValue) {
var $type = function(o, cmp) {
this.countField = 0;
this.buckets = {};
this.comparer = cmp || ss_EqualityComparer.def;
if (ss.isInstanceOfType(o, ss_IDictionary)) {
var e = ss.getEnumerator(o);
try {
while (e.moveNext()) {
var c = e.current();
this.add(c.key, c.value);
}
}
finally {
if (ss.isInstanceOfType(e, ss_IDisposable)) {
ss.cast(e, ss_IDisposable).dispose();
}
}
}
else if (o) {
var keys = Object.keys(o);
for (var i = 0; i < keys.length; i++) {
this.add(keys[i], o[keys[i]]);
}
}
};
ss.registerGenericClassInstance($type, ss_Dictionary$2, [TKey, TValue], {
_setOrAdd: function(key, value, add) {
var hash = this.comparer.getObjectHashCode(key);
var entry = { key: key, value: value };
if (this.buckets.hasOwnProperty(hash)) {
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.comparer.areEqual(array[i].key, key)) {
if (add)
throw new ss_ArgumentException('Key ' + key + ' already exists.');
array[i] = entry;
return;
}
}
array.push(entry);
} else {
this.buckets[hash] = [entry];
}
this.countField++;
},
add: function(key, value) {
this._setOrAdd(key, value, true);
},
set_item: function(key, value) {
this._setOrAdd(key, value, false);
},
_get: function(key) {
var hash = this.comparer.getObjectHashCode(key);
if (this.buckets.hasOwnProperty(hash)) {
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
var entry = array[i];
if (this.comparer.areEqual(entry.key, key))
return entry.value !== undefined ? entry.value : null;
}
}
return undefined;
},
get_item: function(key) {
var v = this._get(key);
if (v === undefined)
throw new ss_KeyNotFoundException('Key ' + key + ' does not exist.');
return v;
},
tryGetValue: function(key, value) {
var v = this._get(key);
if (v !== undefined) {
value.$ = v;
return true;
}
else {
value.$ = ss.getDefaultValue(TValue);
return false;
}
},
containsKey: function(key) {
var hash = this.comparer.getObjectHashCode(key);
if (!this.buckets.hasOwnProperty(hash))
return false;
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.comparer.areEqual(array[i].key, key))
return true;
}
return false;
},
clear: function() {
this.countField = 0;
this.buckets = {};
},
remove: function(key) {
var hash = this.comparer.getObjectHashCode(key);
if (!this.buckets.hasOwnProperty(hash))
return false;
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.comparer.areEqual(array[i].key, key)) {
array.splice(i, 1);
if (array.length == 0) delete this.buckets[hash];
this.countField--;
return true;
}
}
return false;
},
get_count: function() {
return this.countField;
},
_getEnumerator: function(projector) {
var bucketKeys = Object.keys(this.buckets), bucketIndex = -1, arrayIndex;
return new ss_IteratorBlockEnumerator(function() {
if (bucketIndex < 0 || arrayIndex >= (this.buckets[bucketKeys[bucketIndex]].length - 1)) {
arrayIndex = -1;
bucketIndex++;
}
if (bucketIndex >= bucketKeys.length)
return false;
arrayIndex++;
return true;
}, function() { return projector(this.buckets[bucketKeys[bucketIndex]][arrayIndex]); }, null, this);
},
get_keys: function() {
return new ss_$DictionaryCollection(this, true);
},
get_values: function() {
return new ss_$DictionaryCollection(this, false);
},
getEnumerator: function() {
return this._getEnumerator(function(e) { return e; });
}
}, function() { return null; }, function() { return [ ss_IDictionary, ss_IEnumerable ]; });
return $type;
};
ss_Dictionary$2.__typeName = 'ss.Dictionary$2';
ss.Dictionary$2 = ss_Dictionary$2;
ss.initGenericClass(ss_Dictionary$2, ss, 2);
ss_$DictionaryCollection.__typeName = 'ss.$DictionaryCollection';
ss.$DictionaryCollection = ss_$DictionaryCollection;
ss.initClass(ss_$DictionaryCollection, ss, {
get_count: function $DictionaryCollection$get_count() {
return this._dict.get_count();
},
contains: function $DictionaryCollection$contains(v) {
if (this._isKeys) {
return this._dict.containsKey(v);
}
else {
for (var e in this._dict.buckets) {
if (this._dict.buckets.hasOwnProperty(e)) {
var bucket = this._dict.buckets[e];
for (var i = 0; i < bucket.length; i++) {
if (this._dict.comparer.areEqual(bucket[i].value, v))
return true;
}
}
}
return false;
}
},
getEnumerator: function $DictionaryCollection$getEnumerator(v) {
return this._dict._getEnumerator(this._isKeys ? function(e) { return e.key; } : function(e) { return e.value; });
},
add: function $DictionaryCollection$add(v) {
throw new ss_InvalidOperationException('Collection is read-only');
},
clear: function $DictionaryCollection$clear() {
throw new ss_InvalidOperationException('Collection is read-only');
},
remove: function $DictionaryCollection$remove() {
throw new ss_InvalidOperationException('Collection is read-only');
}
}, null, [ss_IEnumerable, ss_ICollection]);
///////////////////////////////////////////////////////////////////////////////
// IDisposable
var ss_IDisposable = function IDisposable$() { };
ss_IDisposable.__typeName = 'ss.IDisposable';
ss.IDisposable = ss_IDisposable;
ss.initInterface(ss_IDisposable, ss, { dispose: null });
///////////////////////////////////////////////////////////////////////////////
// StringBuilder
var ss_StringBuilder = function StringBuilder$(s) {
this._parts = (ss.isValue(s) && s != '') ? [s] : [];
this.length = ss.isValue(s) ? s.length : 0;
}
ss_StringBuilder.__typeName = 'ss.StringBuilder';
ss.StringBuilder = ss_StringBuilder;
ss.initClass(ss_StringBuilder, ss, {
append: function StringBuilder$append(o) {
if (ss.isValue(o)) {
var s = o.toString();
ss.add(this._parts, s);
this.length += s.length;
}
return this;
},
appendChar: function StringBuilder$appendChar(c) {
return this.append(String.fromCharCode(c));
},
appendLine: function StringBuilder$appendLine(s) {
this.append(s);
this.append('\r\n');
return this;
},
appendLineChar: function StringBuilder$appendLineChar(c) {
return this.appendLine(String.fromCharCode(c));
},
clear: function StringBuilder$clear() {
this._parts = [];
this.length = 0;
},
toString: function StringBuilder$toString() {
return this._parts.join('');
}
});
///////////////////////////////////////////////////////////////////////////////
// Random
var ss_Random = function Random$(seed) {
var _seed = (seed === undefined) ? parseInt(Date.now() % 2147483648) : parseInt(Math.abs(seed));
this.inext = 0;
this.inextp = 21;
this.seedArray = new Array(56);
for(var i = 0; i < 56; i++)
this.seedArray[i] = 0;
_seed = 161803398 - _seed;
if (_seed < 0)
_seed += 2147483648;
this.seedArray[55] = _seed;
var mk = 1;
for (var i = 1; i < 55; i++) {
var ii = (21 * i) % 55;
this.seedArray[ii] = mk;
mk = _seed - mk;
if (mk < 0)
mk += 2147483648;
_seed = this.seedArray[ii];
}
for (var j = 1; j < 5; j++) {
for (var k = 1; k < 56; k++) {
this.seedArray[k] -= this.seedArray[1 + (k + 30) % 55];
if (this.seedArray[k] < 0)
this.seedArray[k] += 2147483648;
}
}
};
ss_Random.__typeName = 'ss.Random';
ss.Random = ss_Random;
ss.initClass(ss_Random, ss, {
next: function Random$next() {
return this.sample() * 2147483648 | 0;
},
nextMax: function Random$nextMax(max) {
return this.sample() * max | 0;
},
nextMinMax: function Random$nextMinMax(min, max) {
return (this.sample() * (max - min) + min) | 0;
},
nextBytes: function Random$nextBytes(bytes) {
for (var i = 0; i < bytes.length; i++)
bytes[i] = (this.sample() * 256) | 0;
},
nextDouble: function Random$nextDouble() {
return this.sample();
},
sample: function Random$sample() {
if (++this.inext >= 56)
this.inext = 1;
if (++this.inextp >= 56)
this.inextp = 1;
var retVal = this.seedArray[this.inext] - this.seedArray[this.inextp];
if (retVal < 0)
retVal += 2147483648;
this.seedArray[this.inext] = retVal;
return retVal * (1.0 / 2147483648);
}
});
///////////////////////////////////////////////////////////////////////////////
// EventArgs
var ss_EventArgs = function EventArgs$() {
}
ss_EventArgs.__typeName = 'ss.EventArgs';
ss.EventArgs = ss_EventArgs;
ss.initClass(ss_EventArgs, ss, {});
ss_EventArgs.Empty = new ss_EventArgs();
///////////////////////////////////////////////////////////////////////////////
// Exception
var ss_Exception = function Exception$(message, innerException) {
this._message = message || 'An error occurred.';
this._innerException = innerException || null;
this._error = new Error();
}
ss_Exception.__typeName = 'ss.Exception';
ss.Exception = ss_Exception;
ss.initClass(ss_Exception, ss, {
get_message: function Exception$get_message() {
return this._message;
},
get_innerException: function Exception$get_innerException() {
return this._innerException;
},
get_stack: function Exception$get_stack() {
return this._error.stack;
}
});
ss_Exception.wrap = function Exception$wrap(o) {
if (ss.isInstanceOfType(o, ss_Exception)) {
return o;
}
else if (o instanceof TypeError) {
// TypeError can either be 'cannot read property blah of null/undefined' (proper NullReferenceException), or it can be eg. accessing a non-existent method of an object.
// As long as all code is compiled, they should with a very high probability indicate the use of a null reference.
return new ss_NullReferenceException(o.message, new ss_JsErrorException(o));
}
else if (o instanceof RangeError) {
return new ss_ArgumentOutOfRangeException(null, o.message, new ss_JsErrorException(o));
}
else if (o instanceof Error) {
return new ss_JsErrorException(o);
}
else {
return new ss_Exception(o.toString());
}
};
////////////////////////////////////////////////////////////////////////////////
// NotImplementedException
var ss_NotImplementedException = function NotImplementedException$(message, innerException) {
ss_Exception.call(this, message || 'The method or operation is not implemented.', innerException);
};
ss_NotImplementedException.__typeName = 'ss.NotImplementedException';
ss.NotImplementedException = ss_NotImplementedException;
ss.initClass(ss_NotImplementedException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// NotSupportedException
var ss_NotSupportedException = function NotSupportedException$(message, innerException) {
ss_Exception.call(this, message || 'Specified method is not supported.', innerException);
};
ss_NotSupportedException.__typeName = 'ss.NotSupportedException';
ss.NotSupportedException = ss_NotSupportedException;
ss.initClass(ss_NotSupportedException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// AggregateException
var ss_AggregateException = function AggregateException$(message, innerExceptions) {
this.innerExceptions = ss.isValue(innerExceptions) ? ss.arrayFromEnumerable(innerExceptions) : [];
ss_Exception.call(this, message || 'One or more errors occurred.', this.innerExceptions.length ? this.innerExceptions[0] : null);
};
ss_AggregateException.__typeName = 'ss.AggregateException';
ss.AggregateException = ss_AggregateException;
ss.initClass(ss_AggregateException, ss, {
flatten: function AggregateException$flatten() {
var inner = [];
for (var i = 0; i < this.innerExceptions.length; i++) {
var e = this.innerExceptions[i];
if (ss.isInstanceOfType(e, ss_AggregateException)) {
inner.push.apply(inner, e.flatten().innerExceptions);
}
else {
inner.push(e);
}
}
return new ss_AggregateException(this._message, inner);
}
}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// PromiseException
var ss_PromiseException = function PromiseException(args, message, innerException) {
ss_Exception.call(this, message || (args.length && args[0] ? args[0].toString() : 'An error occurred'), innerException);
this.arguments = ss.arrayClone(args);
};
ss_PromiseException.__typeName = 'ss.PromiseException';
ss.PromiseException = ss_PromiseException;
ss.initClass(ss_PromiseException, ss, {
get_arguments: function PromiseException$get_arguments() {
return this._arguments;
}
}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// JsErrorException
var ss_JsErrorException = function JsErrorException$(error, message, innerException) {
ss_Exception.call(this, message || error.message, innerException);
this.error = error;
};
ss_JsErrorException.__typeName = 'ss.JsErrorException';
ss.JsErrorException = ss_JsErrorException;
ss.initClass(ss_JsErrorException, ss, {
get_stack: function Exception$get_stack() {
return this.error.stack;
}
}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// ArgumentException
var ss_ArgumentException = function ArgumentException$(message, paramName, innerException) {
ss_Exception.call(this, message || 'Value does not fall within the expected range.', innerException);
this.paramName = paramName || null;
};
ss_ArgumentException.__typeName = 'ss.ArgumentException';
ss.ArgumentException = ss_ArgumentException;
ss.initClass(ss_ArgumentException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// ArgumentNullException
var ss_ArgumentNullException = function ArgumentNullException$(paramName, message, innerException) {
if (!message) {
message = 'Value cannot be null.';
if (paramName)
message += '\nParameter name: ' + paramName;
}
ss_ArgumentException.call(this, message, paramName, innerException);
};
ss_ArgumentNullException.__typeName = 'ss.ArgumentNullException';
ss.ArgumentNullException = ss_ArgumentNullException;
ss.initClass(ss_ArgumentNullException, ss, {}, ss_ArgumentException);
////////////////////////////////////////////////////////////////////////////////
// ArgumentNullException
var ss_ArgumentOutOfRangeException = function ArgumentOutOfRangeException$(paramName, message, innerException, actualValue) {
if (!message) {
message = 'Value is out of range.';
if (paramName)
message += '\nParameter name: ' + paramName;
}
ss_ArgumentException.call(this, message, paramName, innerException);
this.actualValue = actualValue || null;
};
ss_ArgumentOutOfRangeException.__typeName = 'ss.ArgumentOutOfRangeException';
ss.ArgumentOutOfRangeException = ss_ArgumentOutOfRangeException;
ss.initClass(ss_ArgumentOutOfRangeException, ss, {}, ss_ArgumentException);
////////////////////////////////////////////////////////////////////////////////
// FormatException
var ss_FormatException = function FormatException$(message, innerException) {
ss_Exception.call(this, message || 'Invalid format.', innerException);
};
ss_FormatException.__typeName = 'ss.FormatException';
ss.FormatException = ss_FormatException;
ss.initClass(ss_FormatException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// DivideByZeroException
var ss_DivideByZeroException = function DivideByZeroException$(message, innerException) {
ss_Exception.call(this, message || 'Division by 0.', innerException);
};
ss_DivideByZeroException.__typeName = 'ss.DivideByZeroException';
ss.DivideByZeroException = ss_DivideByZeroException;
ss.initClass(ss_DivideByZeroException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// InvalidCastException
var ss_InvalidCastException = function InvalidCastException$(message, innerException) {
ss_Exception.call(this, message || 'The cast is not valid.', innerException);
};
ss_InvalidCastException.__typeName = 'ss.InvalidCastException';
ss.InvalidCastException = ss_InvalidCastException;
ss.initClass(ss_InvalidCastException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// InvalidOperationException
var ss_InvalidOperationException = function InvalidOperationException$(message, innerException) {
ss_Exception.call(this, message || 'Operation is not valid due to the current state of the object.', innerException);
};
ss_InvalidOperationException.__typeName = 'ss.InvalidOperationException';
ss.InvalidOperationException = ss_InvalidOperationException;
ss.initClass(ss_InvalidOperationException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// NullReferenceException
var ss_NullReferenceException = function NullReferenceException$(message, innerException) {
ss_Exception.call(this, message || 'Object is null.', innerException);
};
ss_NullReferenceException.__typeName = 'ss.NullReferenceException';
ss.NullReferenceException = ss_NullReferenceException;
ss.initClass(ss_NullReferenceException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// KeyNotFoundException
var ss_KeyNotFoundException = function KeyNotFoundException$(message, innerException) {
ss_Exception.call(this, message || 'Key not found.', innerException);
};
ss_KeyNotFoundException.__typeName = 'ss.KeyNotFoundException';
ss.KeyNotFoundException = ss_KeyNotFoundException;
ss.initClass(ss_KeyNotFoundException, ss, {}, ss_Exception);
////////////////////////////////////////////////////////////////////////////////
// InvalidOperationException
var ss_AmbiguousMatchException = function AmbiguousMatchException$(message, innerException) {
ss_Exception.call(this, message || 'Ambiguous match.', innerException);
};
ss_AmbiguousMatchException.__typeName = 'ss.AmbiguousMatchException';
ss.AmbiguousMatchException = ss_AmbiguousMatchException;
ss.initClass(ss_AmbiguousMatchException, ss, {}, ss_Exception);
///////////////////////////////////////////////////////////////////////////////
// IteratorBlockEnumerable
var ss_IteratorBlockEnumerable = function IteratorBlockEnumerable$(getEnumerator, $this) {
this._getEnumerator = getEnumerator;
this._this = $this;
};
ss_IteratorBlockEnumerable.__typeName = 'ss.IteratorBlockEnumerable';
ss.IteratorBlockEnumerable = ss_IteratorBlockEnumerable;
ss.initClass(ss_IteratorBlockEnumerable, ss, {
getEnumerator: function IteratorBlockEnumerable$getEnumerator() {
return this._getEnumerator.call(this._this);
}
}, null, [ss_IEnumerable]);
///////////////////////////////////////////////////////////////////////////////
// IteratorBlockEnumerator
var ss_IteratorBlockEnumerator = function IteratorBlockEnumerator$(moveNext, getCurrent, dispose, $this) {
this._moveNext = moveNext;
this._getCurrent = getCurrent;
this._dispose = dispose;
this._this = $this;
};
ss_IteratorBlockEnumerator.__typeName = 'ss.IteratorBlockEnumerator';
ss.IteratorBlockEnumerator = ss_IteratorBlockEnumerator;
ss.initClass(ss_IteratorBlockEnumerator, ss, {
moveNext: function IteratorBlockEnumerator$moveNext() {
try {
return this._moveNext.call(this._this);
}
catch (ex) {
if (this._dispose)
this._dispose.call(this._this);
throw ex;
}
},
current: function IteratorBlockEnumerator$current() {
return this._getCurrent.call(this._this);
},
reset: function IteratorBlockEnumerator$reset() {
throw new ss_NotSupportedException('Reset is not supported.');
},
dispose: function IteratorBlockEnumerator$dispose() {
if (this._dispose)
this._dispose.call(this._this);
}
}, null, [ss_IEnumerator, ss_IDisposable]);
///////////////////////////////////////////////////////////////////////////////
// Lazy
var ss_Lazy = function Lazy$(valueFactory) {
this._valueFactory = valueFactory;
this.isValueCreated = false;
};
ss_Lazy.__typeName = 'ss.Lazy';
ss.Lazy = ss_Lazy;
ss.initClass(ss_Lazy, ss, {
value: function Lazy$value() {
if (!this.isValueCreated) {
this._value = this._valueFactory();
delete this._valueFactory;
this.isValueCreated = true;
}
return this._value;
}
});
///////////////////////////////////////////////////////////////////////////////
// Task
var ss_Task = function Task$(action, state) {
this._action = action;
this._state = state;
this.exception = null;
this.status = 0;
this._thens = [];
this._result = null;
};
ss_Task.delay = function Task$delay(delay) {
var tcs = new ss_TaskCompletionSource();
setTimeout(function() {
tcs.setResult(0);
}, delay);
return tcs.task;
};
ss_Task.fromResult = function Task$fromResult(result) {
var t = new ss_Task();
t.status = 5;
t._result = result;
return t;
};
ss_Task.run = function Task$run(f) {
var tcs = new ss_TaskCompletionSource();
setTimeout(function() {
try {
tcs.setResult(f());
}
catch (e) {
tcs.setException(ss_Exception.wrap(e));
}
}, 0);
return tcs.task;
};
ss_Task.whenAll = function Task$whenAll(tasks) {
var tcs = new ss_TaskCompletionSource();
if (tasks.length === 0) {
tcs.setResult([]);
}
else {
var result = new Array(tasks.length), remaining = tasks.length, cancelled = false, exceptions = [];
for (var i = 0; i < tasks.length; i++) {
(function(i) {
tasks[i].continueWith(function(t) {
switch (t.status) {
case 5:
result[i] = t.getResult();
break;
case 6:
cancelled = true;
break;
case 7:
ss.arrayAddRange(exceptions, t.exception.innerExceptions);
break;
default:
throw new ss_InvalidOperationException('Invalid task status ' + t.status);
}
if (--remaining === 0) {
if (exceptions.length > 0)
tcs.setException(exceptions);
else if (cancelled)
tcs.setCanceled();
else
tcs.setResult(result);
}
});
})(i);
}
}
return tcs.task;
};
ss_Task.whenAny = function Task$whenAny(tasks) {
if (!tasks.length)
throw new ss_ArgumentException('Must wait for at least one task', 'tasks');
var tcs = new ss_TaskCompletionSource();
for (var i = 0; i < tasks.length; i++) {
tasks[i].continueWith(function(t) {
switch (t.status) {
case 5:
tcs.trySetResult(t);
break;
case 6:
tcs.trySetCanceled();
break;
case 7:
tcs.trySetException(t.exception.innerExceptions);
break;
default:
throw new ss_InvalidOperationException('Invalid task status ' + t.status);
}
});
}
return tcs.task;
};
ss_Task.fromDoneCallback = function Task$fromDoneCallback(t, i, m) {
var tcs = new ss_TaskCompletionSource(), args;
if (typeof(i) === 'number') {
args = Array.prototype.slice.call(arguments, 3);
if (i < 0)
i += args.length + 1;
}
else {
args = Array.prototype.slice.call(arguments, 2);
m = i;
i = args.length;
}
var cb = function(v) {
tcs.setResult(v);
};
args = args.slice(0, i).concat(cb, args.slice(i));
t[m].apply(t, args);
return tcs.task;
};
ss_Task.fromPromise = function Task$fromPromise(p, f) {
var tcs = new ss_TaskCompletionSource();
if (typeof(f) === 'number')
f = (function(i) { return function() { return arguments[i >= 0 ? i : (arguments.length + i)]; }; })(f);
else if (typeof(f) !== 'function')
f = function() { return Array.prototype.slice.call(arguments, 0); };
p.then(function() {
tcs.setResult(typeof(f) === 'function' ? f.apply(null, arguments) : null);
}, function() {
tcs.setException(new ss_PromiseException(Array.prototype.slice.call(arguments, 0)));
});
return tcs.task;
};
ss_Task.fromNode = function Task$fromNode(t, f, m) {
var tcs = new ss_TaskCompletionSource(), args;
if (typeof(f) === 'function') {
args = Array.prototype.slice.call(arguments, 3);
}
else {
args = Array.prototype.slice.call(arguments, 2);
m = f;
f = function() { return arguments[0]; };
}
var cb = function(e) {
if (e)
tcs.setException(ss_Exception.wrap(e));
else
tcs.setResult(f.apply(null, Array.prototype.slice.call(arguments, 1)));
};
args.push(cb);
t[m].apply(t, args);
return tcs.task;
};
ss_Task.__typeName = 'ss.Task';
ss.Task = ss_Task;
ss.initClass(ss_Task, ss, {
continueWith: function Task$continueWith(continuation) {
var tcs = new ss_TaskCompletionSource();
var _this = this;
var fn = function() {
try {
tcs.setResult(continuation(_this));
}
catch (e) {
tcs.setException(ss_Exception.wrap(e));
}
};
if (this.isCompleted()) {
setTimeout(fn, 0);
}
else {
this._thens.push(fn);
}
return tcs.task;
},
start: function Task$start() {
if (this.status !== 0)
throw new ss_InvalidOperationException('Task was already started.');
var _this = this;
this.status = 3;
setTimeout(function() {
try {
var result = _this._action(_this._state);
delete _this._action;
delete _this._state;
_this._complete(result);
}
catch (e) {
_this._fail(new ss_AggregateException(null, [ss_Exception.wrap(e)]));
}
}, 0);
},
_runCallbacks: function Task$_runCallbacks() {
for (var i = 0; i < this._thens.length; i++)
this._thens[i](this);
delete this._thens;
},
_complete: function Task$_complete(result) {
if (this.isCompleted())
return false;
this._result = result;
this.status = 5;
this._runCallbacks();
return true;
},
_fail: function Task$_fail(exception) {
if (this.isCompleted())
return false;
this.exception = exception;
this.status = 7;
this._runCallbacks();
return true;
},
_cancel: function Task$_cancel() {
if (this.isCompleted())
return false;
this.status = 6;
this._runCallbacks();
return true;
},
isCanceled: function Task$isCanceled() {
return this.status === 6;
},
isCompleted: function Task$isCompleted() {
return this.status >= 5;
},
isFaulted: function Task$isFaulted() {
return this.status === 7;
},
_getResult: function Task$_getResult(await) {
switch (this.status) {
case 5:
return this._result;
case 6:
throw new ss_InvalidOperationException('Task was cancelled.');
case 7:
throw await ? this.exception.innerExceptions[0] : this.exception;
default:
throw new ss_InvalidOperationException('Task is not yet completed.');
}
},
getResult: function Task$getResult() {
return this._getResult(false);
},
getAwaitedResult: function Task$getAwaitedResult() {
return this._getResult(true);
},
dispose: function Task$dispose() {
}
}, null, [ss_IDisposable]);
////////////////////////////////////////////////////////////////////////////////
// TaskStatus
var ss_TaskStatus = function() {
};
ss_TaskStatus.__typeName = 'ss.TaskStatus';
ss.TaskStatus = ss_TaskStatus;
ss.initEnum(ss_TaskStatus, ss, { created: 0, running: 3, ranToCompletion: 5, canceled: 6, faulted: 7 });
///////////////////////////////////////////////////////////////////////////////
// TaskCompletionSource
var ss_TaskCompletionSource = function TaskCompletionSource$() {
this.task = new ss_Task();
this.task.status = 3;
};
ss_TaskCompletionSource.__typeName = 'ss.TaskCompletionSource';
ss.TaskCompletionSource = ss_TaskCompletionSource;
ss.initClass(ss_TaskCompletionSource, ss, {
setCanceled: function TaskCompletionSource$setCanceled() {
if (!this.task._cancel())
throw new ss_InvalidOperationException('Task was already completed.');
},
setResult: function TaskCompletionSource$setResult(result) {
if (!this.task._complete(result))
throw new ss_InvalidOperationException('Task was already completed.');
},
setException: function TaskCompletionSource$setException(exception) {
if (!this.trySetException(exception))
throw new ss_InvalidOperationException('Task was already completed.');
},
trySetCanceled: function TaskCompletionSource$trySetCanceled() {
return this.task._cancel();
},
trySetResult: function TaskCompletionSource$setResult(result) {
return this.task._complete(result);
},
trySetException: function TaskCompletionSource$setException(exception) {
if (ss.isInstanceOfType(exception, ss_Exception))
exception = [exception];
return this.task._fail(new ss_AggregateException(null, exception));
}
});
///////////////////////////////////////////////////////////////////////////////
// CancelEventArgs
var ss_CancelEventArgs = function CancelEventArgs$() {
ss_EventArgs.call(this);
this.cancel = false;
}
ss_CancelEventArgs.__typeName = 'ss.CancelEventArgs';
ss.CancelEventArgs = ss_CancelEventArgs;
ss.initClass(ss_CancelEventArgs, ss, {}, ss_EventArgs);
///////////////////////////////////////////////////////////////////////////////
// Guid
var ss_Guid = function Guid$() {
};
ss_Guid.$valid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ig;
ss_Guid.$split = /^(.{8})(.{4})(.{4})(.{4})(.{12})$/;
ss_Guid.empty = '00000000-0000-0000-0000-000000000000';
ss_Guid.$rng = new ss_Random();
ss_Guid.__typeName = 'ss.Guid';
ss.Guid = ss_Guid;
ss.initClass(ss_Guid, ss, {}, Object, [ ss_IEquatable, ss_IComparable ]);
ss_Guid.__class = false;
ss_Guid.isInstanceOfType = function Guid$isInstanceOfType(instance) {
return typeof(instance) === 'string' && instance.match(ss_Guid.$valid);
};
ss_Guid.getDefaultValue = ss_Guid.createInstance = function Guid$default() {
return ss_Guid.empty;
};
ss_Guid.parse = function Guid$parse(uuid, format) {
var r = {};
if (ss_Guid.tryParse(uuid, format, r))
return r.$;
throw new ss_FormatException('Unable to parse UUID');
};
ss_Guid.tryParse = function Guid$tryParse(uuid, format, r) {
r.$ = ss_Guid.empty;
if (!ss.isValue(uuid)) throw new ss_ArgumentNullException('uuid');
if (!format) {
var m = /^[{(]?([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})[)}]?$/ig.exec(uuid);
if (m) {
r.$ = m.slice(1).join('-').toLowerCase();
return true;
}
}
else {
if (format === 'N') {
var m = ss_Guid.$split.exec(uuid);
if (!m)
return false;
uuid = m.slice(1).join('-');
}
else if (format === 'B' || format === 'P') {
var b = format === 'B';
if (uuid[0] !== (b ? '{' : '(') || uuid[uuid.length - 1] !== (b ? '}' : ')'))
return false;
uuid = uuid.substr(1, uuid.length - 2);
}
if (uuid.match(ss_Guid.$valid)) {
r.$ = uuid.toLowerCase();
return true;
}
}
return false;
};
ss_Guid.format = function Guid$format(uuid, format) {
switch (format) {
case 'N': return uuid.replace(/-/g, '');
case 'B': return '{' + uuid + '}';
case 'P': return '(' + uuid + ')';
default : return uuid;
}
}
ss_Guid.fromBytes = function Guid$fromBytes(b) {
if (!b || b.length !== 16)
throw new ss_ArgumentException('b', 'Must be 16 bytes');
var s = b.map(function(x) { return ss.formatNumber(x & 0xff, 'x2'); }).join('');
return ss_Guid.$split.exec(s).slice(1).join('-');
}
ss_Guid.newGuid = function Guid$newGuid() {
var a = Array(16);
ss_Guid.$rng.nextBytes(a);
a[6] = a[6] & 0x0f | 0x40;
a[8] = a[8] & 0xbf | 0x80;
return ss_Guid.fromBytes(a);
};
ss_Guid.getBytes = function Guid$getBytes(uuid) {
var a = Array(16);
var s = uuid.replace(/-/g, '');
for (var i = 0; i < 16; i++) {
a[i] = parseInt(s.substr(i * 2, 2), 16);
}
return a;
};
if (global.ss) {
for (var n in ss) {
if (ss.hasOwnProperty(n))
global.ss[n] = ss[n];
}
}
else {
global.ss = ss;
}
})(global);
|
/*
Copyright 2013, KISSY UI Library v1.40dev
MIT Licensed
build time: Aug 15 00:00
*/
/*
Combined processedModules by KISSY Module Compiler:
resizable/plugin/proxy
*/
/**
* resize proxy plugin for resizable.
* same with dd/plugin/proxy
* @ignore
* @author yiminghe@gmail.com
*/
KISSY.add('resizable/plugin/proxy', function (S, Base, Node) {
var $ = Node.all,
PROXY_EVENT = '.-ks-proxy' + S.now();
return Base.extend({
pluginId: 'resizable/plugin/proxy',
pluginInitializer: function (resizable) {
var self = this,
hideNodeOnResize = self.get('hideNodeOnResize');
function start() {
var node = self.get('node'),
dragNode = resizable.get('node');
// cache proxy node
if (!self.get('proxyNode')) {
if (typeof node === 'function') {
node = node(resizable);
self.set('proxyNode', node);
}
} else {
node = self.get('proxyNode');
}
node.show();
dragNode.parent().append(node);
node.css({
left: dragNode.css('left'),
top: dragNode.css('top'),
width: dragNode.width(),
height: dragNode.height()
});
if (hideNodeOnResize) {
dragNode.css('visibility', 'hidden');
}
}
function beforeResize(e) {
// prevent resizable node to resize
e.preventDefault();
self.get('proxyNode').css(e.region);
}
function end() {
var node = self.get('proxyNode'),
dragNode = resizable.get('node');
dragNode.css({
left: node.css('left'),
top: node.css('top'),
width: node.width(),
height: node.height()
});
if (self.get('destroyOnEnd')) {
node.remove();
self.set('proxyNode', 0);
} else {
node.hide();
}
if (hideNodeOnResize) {
dragNode.css('visibility', '');
}
}
resizable['on']('resizeStart' + PROXY_EVENT, start)
['on']('beforeResize' + PROXY_EVENT, beforeResize)
['on']('resizeEnd' + PROXY_EVENT, end);
},
pluginDestructor: function (resizable) {
resizable['detach'](PROXY_EVENT);
}
},{
ATTRS: {
/**
* how to get the proxy node.
* default clone the node itself deeply.
* @cfg {Function} node
*/
/**
* @ignore
*/
node: {
value: function (resizable) {
return $('<div class="' + resizable.get('prefixCls') +
'resizable-proxy"></div>');
}
},
/**
* Current proxy node.
* @type {KISSY.NodeList}
* @property proxyNode
*/
/**
* @ignore
*/
proxyNode: {
},
/**
* whether hide original node when resize proxy.
* Defaults to: false
* @cfg {Boolean} hideNodeOnResize
*/
/**
* @ignore
*/
hideNodeOnResize: {
value: false
},
/**
* destroy the proxy node at the end of this drag.
* default false
* @cfg {Boolean} destroyOnEnd
*/
/**
* @ignore
*/
destroyOnEnd: {
value: false
}
}
});
}, {
requires: ['base', 'node']
});
|
import {createStore, compose, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import commonMiddleware from '../middlewares/common';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools
function configureStoreProd(initialState) {
const middlewares = [
// Add other middleware on this line...
commonMiddleware,
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunk
];
return createStore(rootReducer, initialState, composeEnhancers(
applyMiddleware(...middlewares)
)
);
}
function configureStoreDev(initialState) {
const middlewares = [
// Add other middleware on this line...
commonMiddleware,
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunk
];
const store = createStore(rootReducer, initialState, composeEnhancers(
applyMiddleware(...middlewares)
)
);
return store;
}
const configureStore = process.env.NODE_ENV === 'production' ? configureStoreProd : configureStoreDev;
export default configureStore;
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var prices = require('./routes/prices');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/v1', index);
app.use('/api/v1/prices', prices);
// Avoid 304
app.disable('etag');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// 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;
|
/* eslint-disable id-match, id-length, no-undef, camelcase */
import PianoConfig from '../src/example-config.js';
import ReactI13nPiano from '../src/index';
import chai from 'chai';
import spies from 'chai-spies';
chai.use(spies).should();
mocha.setup({ globals: [ 'tp', 'init', 'jQuery*', 'setAdblockerCookie', 'script' ] });
describe('PianoPlugin is a i13n plugin for Piano', () => {
describe('ensureScriptHasLoaded', () => {
it('calls loadExternalScript if it was passed', () => {
window.tp = [];
const loadExternalScript = chai.spy(() => Promise.resolve());
const plugin = new ReactI13nPiano({ ...PianoConfig, loadExternalScript });
plugin.ensureScriptHasLoaded();
loadExternalScript.should.have.been.called.exactly(1);
});
});
describe('piano plugin', () => {
it('window.tp.experience.execute() is called with specific properties',
() => {
const TrackedApp = new ReactI13nPiano(PianoConfig);
TrackedApp.updateTinypass = chai.spy(() => Promise.resolve());
return TrackedApp.pageview().then(() => {
TrackedApp.updateTinypass.should.have.been.called.exactly(1);
const pianoTp = window.tp;
pianoTp.should.have.property('aid', 'M3UZnikdix');
pianoTp.should.have.property('customPageUrl', 'http://www.economist.com');
pianoTp.should.have.property('endpoint', 'https://sandbox.tinypass.com/api/v3');
});
});
});
describe('customEvent', () => {
it('it calls ensureScriptHasLoaded and updateTinypass', (done) => {
window.tp = {
setCustomVariable: () => null,
setPageURL: () => null,
push: () => null,
};
const plugin = new ReactI13nPiano({ ...PianoConfig });
plugin.ensureScriptHasLoaded = chai.spy(() => Promise.resolve());
const payload = {
example: 'test',
};
plugin.updateTinypass = chai.spy();
plugin.generatePayload = chai.spy();
plugin.customEvent(payload, 'pageview').then(() => {
plugin.ensureScriptHasLoaded.should.have.been.called.exactly(1);
plugin.updateTinypass.should.have.been.called.exactly(1);
plugin.generatePayload.should.have.been.called.exactly(1);
plugin.generatePayload.should.have.been.called.with(payload, 'pageview');
done();
})
.catch((error) => {
done(error);
});
});
});
describe('pageview', () => {
it('calls customEvent', () => {
window.tp = [];
const plugin = new ReactI13nPiano({ ...PianoConfig });
plugin.customEvent = chai.spy();
plugin.pageview({
example: 'test',
});
plugin.customEvent.should.have.been.called.exactly(1);
});
});
describe('userinformationchange', () => {
it('calls customEvent with an additional parameter', () => {
window.tp = [];
const plugin = new ReactI13nPiano({ ...PianoConfig });
plugin.customEvent = chai.spy();
const payload = {
example: 'test',
};
plugin.userinformationchange(payload);
plugin.customEvent.should.have.been.called.exactly(1);
plugin.customEvent.should.have.been.called.with(payload, 'userinformationchange');
});
});
});
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'horizontalrule', 'az', {
toolbar: 'Sərhəd xətti yarat'
} );
|
import FeatureBaseRenderer from '../../../../../gene/internal/renderer/features/drawing/featureBaseRenderer';
import {ColorProcessor, PixiTextSize} from '../../../../../../utilities';
import drawStrandDirection, {getStrandArrowSize} from '../../../../../gene/internal/renderer/features/drawing/strandDrawing';
const Math = window.Math;
export default class BedItemFeatureRenderer extends FeatureBaseRenderer {
get strandIndicatorConfig(): undefined {
return this.config && this.config.bed && this.config.bed.strand
? this.config.bed.strand
: super.strandIndicatorConfig;
}
analyzeBoundaries(feature, viewport) {
const boundaries = super.analyzeBoundaries(feature, viewport);
let descriptionLabelSize = {height: 0, width: 0};
let labelSize = {height: 0, width: 0};
if (feature.name && feature.name !== '.') {
labelSize = PixiTextSize.getTextSize(feature.name, this.config.bed.label);
}
if (feature.description && feature.description.length < this.config.bed.description.maximumDisplayLength) {
descriptionLabelSize = PixiTextSize.getTextSize(feature.description, this.config.bed.description.label);
}
if (boundaries.rect) {
boundaries.rect.x2 = Math.max(boundaries.rect.x2, boundaries.rect.x1 + labelSize.width);
if (boundaries.rect.x2 - boundaries.rect.x1 < descriptionLabelSize.width) {
descriptionLabelSize.height = 0;
}
boundaries.rect.y2 = 2 * this.config.bed.margin + this.config.bed.height + labelSize.height + descriptionLabelSize.height;
}
return boundaries;
}
_getFeatureColor(feature, state) {
if (state && state.color && !feature.rgb) {
return state.color;
}
let color = this.config.bed.defaultColor;
const oneByte = 256;
if (feature.rgb) {
color = feature.rgb[0] * oneByte * oneByte + feature.rgb[1] * oneByte + feature.rgb[2];
}
return color;
}
render(feature, viewport, graphicsObj, labelContainer, dockableElementsContainer, attachedElementsContainer, position) {
super.render(feature, viewport, graphicsObj, labelContainer, dockableElementsContainer, attachedElementsContainer, position);
const {
graphics,
hoveredGraphics
} = graphicsObj || {};
const pixelsInBp = viewport.factor;
const yStart = position.y;
let labelHeight = 0;
let labelWidth = 0;
if (feature.name && feature.name !== '.') {
const label = this.labelsManager
? this.labelsManager.getLabel(feature.name, this.config.bed.label)
: undefined;
if (label) {
label.x = Math.round(position.x);
label.y = Math.round(position.y);
dockableElementsContainer.addChild(label);
labelHeight = label.height;
labelWidth = label.width;
this.registerLabel(label, position, {end: feature.endIndex, start: feature.startIndex});
}
}
if (feature.description && feature.description.length < this.config.bed.description.maximumDisplayLength) {
const descriptionLabelWidth = PixiTextSize.getTextSize(feature.description, this.config.bed.description.label).width;
if (descriptionLabelWidth < position.width) {
const descriptionLabel = this.labelsManager
? this.labelsManager.getLabel(feature.description, this.config.bed.description.label)
: undefined;
if (descriptionLabel) {
descriptionLabel.x = Math.round(position.x);
descriptionLabel.y = Math.round(position.y + labelHeight);
dockableElementsContainer.addChild(descriptionLabel);
this.registerLabel(descriptionLabel, {
x: position.x,
y: Math.round(position.y + labelHeight)
}, {
end: feature.endIndex,
start: feature.startIndex
});
position.y += descriptionLabel.height;
}
}
}
position.y += labelHeight;
this.registerFeaturePosition(feature, {
x1: viewport.project.brushBP2pixel(feature.startIndex) - pixelsInBp / 2,
x2: Math.max(viewport.project.brushBP2pixel(feature.endIndex) + pixelsInBp / 2, position.x + labelWidth),
y1: yStart,
y2: position.y + this.config.bed.height
});
const color = this._getFeatureColor(feature, this.track ? this.track.state : undefined);
let structureToDisplay = null;
for (let i = 0; i < feature.structures.length; i++) {
const width = viewport.convert.brushBP2pixel(feature.structures[i].length);
if (width > 1) {
structureToDisplay = feature.structures[i].structure;
break;
}
}
const startX = viewport.project.brushBP2pixel(feature.startIndex) - pixelsInBp / 2;
let endX = viewport.project.brushBP2pixel(feature.endIndex) + pixelsInBp / 2;
if (
feature.hasOwnProperty('strand') &&
/^(positive|negative)$/i.test(feature.strand) &&
this.shouldRenderStrandIndicatorInsteadOfGraphics(startX, endX)
) {
endX = startX +
getStrandArrowSize(this.config.bed.strand.arrow.height).width +
this.config.bed.strand.arrow.margin * 4;
const arrowConfig = {
...this.config.bed.strand.arrow,
mode: 'fill',
height: this.config.bed.strand.arrow.height + 2 * this.config.bed.strand.arrow.margin
};
this.updateTextureCoordinates(
{
x: startX,
y: position.y + this.config.bed.margin
});
drawStrandDirection(
feature.strand,
{
centerY: position.y + this.config.bed.margin + this.config.bed.height / 2,
height: this.config.bed.height,
width: endX - startX,
x: startX
},
graphics,
color,
arrowConfig,
1,
::this.updateTextureCoordinates
);
drawStrandDirection(
feature.strand,
{
centerY: position.y + this.config.bed.margin + this.config.bed.height / 2,
height: this.config.bed.height,
width: endX - startX,
x: startX
},
hoveredGraphics,
ColorProcessor.darkenColor(color),
arrowConfig,
1,
::this.updateTextureCoordinates
);
} else {
if (!structureToDisplay) {
structureToDisplay = feature.structures[feature.structures.length - 1].structure; // minimized mode
}
const maxViewportsOnScreen = 3;
for (let i = 0; i < structureToDisplay.length; i++) {
const block = structureToDisplay[i];
if (block.isEmpty) {
graphics.beginFill(color, 0);
graphics.lineStyle(1, color, 1);
const x1 = Math.min(
Math.max(viewport.project.brushBP2pixel(block.startIndex) - pixelsInBp / 2, -viewport.canvasSize),
2.0 * viewport.canvasSize
);
const x2 = Math.max(
Math.min(viewport.project.brushBP2pixel(block.endIndex) + pixelsInBp / 2, 2 * viewport.canvasSize),
-viewport.canvasSize
);
graphics.moveTo(x1, position.y + this.config.bed.margin + this.config.bed.height / 2);
graphics.lineTo(x2, position.y + this.config.bed.margin + this.config.bed.height / 2);
graphics.endFill();
hoveredGraphics.beginFill(ColorProcessor.darkenColor(color), 0);
hoveredGraphics.lineStyle(1, ColorProcessor.darkenColor(color), 1);
hoveredGraphics.moveTo(x1, position.y + this.config.bed.margin + this.config.bed.height / 2);
hoveredGraphics.lineTo(x2, position.y + this.config.bed.margin + this.config.bed.height / 2);
hoveredGraphics.endFill();
this.updateTextureCoordinates(
{
x: x1,
y: position.y + this.config.bed.margin + this.config.bed.height / 2
});
if (block.hasOwnProperty('strand')) {
drawStrandDirection(
block.strand,
{
centerY: position.y + this.config.bed.margin + this.config.bed.height / 2,
height: this.config.bed.height,
width: Math.min(x2 - x1, maxViewportsOnScreen * viewport.canvasSize),
x: x1
},
graphics,
color,
this.config.bed.strand.arrow,
1,
::this.updateTextureCoordinates
);
drawStrandDirection(
block.strand,
{
centerY: position.y + this.config.bed.margin + this.config.bed.height / 2,
height: this.config.bed.height,
width: Math.min(x2 - x1, maxViewportsOnScreen * viewport.canvasSize),
x: x1
},
hoveredGraphics,
ColorProcessor.darkenColor(color),
this.config.bed.strand.arrow,
1,
::this.updateTextureCoordinates
);
}
} else {
graphics.beginFill(color, 1);
graphics.lineStyle(0, color, 0);
const start = Math.min(
Math.max(viewport.project.brushBP2pixel(block.startIndex) - pixelsInBp / 2, -viewport.canvasSize),
2.0 * viewport.canvasSize
);
const end = Math.max(
Math.min(viewport.project.brushBP2pixel(block.endIndex) + pixelsInBp / 2, 2 * viewport.canvasSize),
-viewport.canvasSize
);
graphics.drawRect(
start,
position.y + this.config.bed.margin,
Math.max(1, end - start),
this.config.bed.height
);
graphics.endFill();
hoveredGraphics.beginFill(ColorProcessor.darkenColor(color), 1);
hoveredGraphics.lineStyle(0, ColorProcessor.darkenColor(color), 0);
hoveredGraphics.drawRect(
start,
position.y + this.config.bed.margin,
Math.max(1, end - start),
this.config.bed.height
);
hoveredGraphics.endFill();
this.updateTextureCoordinates(
{
x: start,
y: position.y + this.config.bed.margin
});
if (block.hasOwnProperty('strand')) {
const white = 0xFFFFFF;
drawStrandDirection(
block.strand,
{
centerY: position.y + this.config.bed.margin + this.config.bed.height / 2,
height: this.config.bed.height,
width: Math.min(end - start, maxViewportsOnScreen * viewport.canvasSize),
x: start
},
graphics,
white,
this.config.bed.strand.arrow,
1,
::this.updateTextureCoordinates
);
drawStrandDirection(
block.strand,
{
centerY: position.y + this.config.bed.margin + this.config.bed.height / 2,
height: this.config.bed.height,
width: Math.min(end - start, maxViewportsOnScreen * viewport.canvasSize),
x: start
},
hoveredGraphics,
white,
this.config.bed.strand.arrow,
1,
::this.updateTextureCoordinates
);
}
}
}
}
}
}
|
(function(){
var pluginName = 'qqvideo';
CKEDITOR.plugins.add(pluginName, {
lang:'zh-cn',
onLoad: function(){
},
beforeInit: function(editor){
},
init: function(editor) {
var lang = editor.lang[pluginName];
editor.addCommand(pluginName, new CKEDITOR.dialogCommand(pluginName));
editor.ui.addButton(pluginName, {
label: lang.button.label,
command: pluginName,
icon: this.path + 'images/icon.png'
});
CKEDITOR.dialog.add(pluginName, this.path + 'dialogs/qqvideo.js');
},
afterInit: function(editor){
}
});
})(); |
var nomnoml = nomnoml || {};
var JDLParser = module.exports;
nomnoml.parse = function (source){
function onlyCompilables(line){
var ok = line[0] !== '#' && line[0] !== '/' && line[0] !== '*'
return ok ? line.replace(/\/\/[^\n\r]*/mg, '') : ''
}
var isDirective = function (line){ return line.text[0] === '#' }
var lines = source.split('\n').map(function (s, i){
return {text: s.trim(), index: i }
})
var pureDirectives = _.filter(lines, isDirective)
var directives = _.object(pureDirectives.map(function (line){
try {
var tokens = line.text.substring(1).split(':')
return [tokens[0].trim(), tokens[1].trim()]
}
catch (e) {
throw new Error('line ' + (line.index + 1))
}
}))
var pureDiagramCode = _.map(_.pluck(lines, 'text'), onlyCompilables).join('\n').trim()
var ast = nomnoml.transformParseIntoSyntaxTree(nomnoml.intermediateParse(pureDiagramCode))
ast.directives = directives
return ast
}
nomnoml.intermediateParse = function (source){
return nomnoml.convertToNomnoml(JDLParser.parse(source));
}
nomnoml.convertToNomnoml = function(JDLObj){
var parts = [], enumParts = []
var required = function (line){ return line.key === 'required' }
var isRequired = function (validations) {
return _.filter(validations, required).length > 0
}
var setEnumRelation = function (a, part) {
var enumPart = _.filter(enumParts, function (e){
return e.id === a.type
});
if(enumPart.length > 0){
parts.push({
assoc: '->',
start: part,
end: enumPart[0],
startLabel: '',
endLabel: ''
})
}
}
var getCardinality = function (cardinality) {
switch (cardinality) {
case 'one-to-many':
return '1-*'
case 'one-to-one':
return '1-1'
case 'many-to-one':
return '*-1'
case 'many-to-many':
return '*-*'
default:
return '1-*'
}
}
var setParts = function (entity, isEnum) {
var attrs = []
if(isEnum){
_.each(entity.values, function (a) {
attrs.push(a)
})
} else {
_.each(entity.body, function (a) {
attrs.push(a.name + ': ' + a.type + (isRequired(a.validations) ? '*' : ''))
})
}
return {
type: isEnum ? 'ENUM' : 'CLASS',
id: entity.name,
parts:[
[entity.name],
attrs
]
}
}
_.each(JDLObj.enums, function (p){
if (p.name){ // is an enum
var part = setParts(p, true)
parts.push(part)
enumParts.push(part)
}
})
_.each(JDLObj.entities, function (p){
if (p.name){ // is a classifier
var part = setParts(p)
parts.push(part)
_.each(p.body, function (a) {
setEnumRelation(a, part)
})
}
})
_.each(JDLObj.relationships, function (p){
parts.push({
assoc: '->',
start: setParts(p.from),
end: setParts(p.to),
startLabel: p.from.injectedfield ? p.from.injectedfield : '',
endLabel: (getCardinality(p.cardinality) + ' ' + (p.to.injectedfield ? p.to.injectedfield : ''))
})
})
return parts;
}
nomnoml.transformParseIntoSyntaxTree = function (entity){
var relationId = 0
function transformCompartment(parts){
var lines = []
var rawClassifiers = []
var relations = []
_.each(parts, function (p){
if (typeof p === 'string')
lines.push(p)
if (p.assoc){ // is a relation
rawClassifiers.push(p.start)
rawClassifiers.push(p.end)
relations.push({
id: relationId++,
assoc: p.assoc,
start: p.start.parts[0][0],
end: p.end.parts[0][0],
startLabel: p.startLabel,
endLabel: p.endLabel
})
}
if (p.parts){ // is a classifier
rawClassifiers.push(p)
}
})
var allClassifiers = _.map(rawClassifiers, transformItem)
var noDuplicates = _.map(_.groupBy(allClassifiers, 'name'), function (cList){
return _.max(cList, function (c){ return c.compartments.length })
})
return nomnoml.Compartment(lines, noDuplicates, relations)
}
function transformItem(entity){
if (typeof entity === 'string')
return entity
if (_.isArray(entity))
return transformCompartment(entity)
if (entity.parts){
var compartments = _.map(entity.parts, transformCompartment)
return nomnoml.Classifier(entity.type, entity.id, compartments)
}
return undefined
}
return transformItem(entity)
}
|
import fp from 'lodash/fp'
import HTMLElementAttributes from 'html-element-attributes/index.json'
import jsdom from 'jsdom'
import bail from 'bail'
import fs from 'fs'
import { join } from 'path'
import svgTags from 'svg-tags'
import htmlTags from 'html-tags'
const htmlAttributeListTitleSelector = 'h2:contains("All Supported HTML Attributes")'
const svgAttributeListTitleSelector = 'h2:contains("All Supported SVG Attributes")'
const reactDomElementDocUrl = 'https://facebook.github.io/react/docs/dom-elements.html'
const jQueryScriptUrl = 'http://code.jquery.com/jquery.js'
const attributeListParentNodeSelector = '.highlight'
const attributeFileName = 'react-html-attributes.json'
const crawledHTMLAttributesFileName = 'crawled-react-html-attributes.test.json'
const crawledSVGAttributesFileName = 'crawled-react-svg-attributes.test.json'
const HTMLElementsFileName = 'crawled-react-html-elements.test.json'
const SVGElementSFileName = 'crawled-react-svg-elements.test.json'
// These are attributes that are not crawled from the above website and copied
// directly from that site.
const reactHtmlAttributesCopied = {
'*': [
'dangerouslySetInnerHTML',
'suppressContentEditableWarning',
'itemProp',
'itemScope',
'itemType',
'itemRef',
'itemID',
'security',
'unselectable',
'about',
'datatype',
'inlist',
'prefix',
'property',
'resource',
'typeof',
'vocab',
],
input: [
'onChange',
'defaultValue',
'defaultChecked',
'autoCapitalize',
'autoCorrect',
'results',
'autoSave',
],
textarea: [
'value',
'onChange',
'defaultValue',
'autoCapitalize',
'autoCorrect',
],
select: [
'value',
'onChange',
'defaultValue',
],
link: [
'color',
],
svg: [
'color',
'height',
'width',
],
}
function getList(jQuery, listTitleSelector) {
const titleNode = jQuery(listTitleSelector)
const listNode = titleNode.nextAll(attributeListParentNodeSelector).first()
return listNode.text().replace(/\n/g, ' ').trim().split(' ')
}
function writeJSONToFile(fileName, object) {
fs.writeFile(
join(__dirname, 'src', fileName),
`${JSON.stringify(object, 0, 2)}\n`,
bail,
)
}
jsdom.env(
reactDomElementDocUrl,
[jQueryScriptUrl],
(err, pageWindow) => {
bail(err)
const jQuery = pageWindow.$
const reactSVGAttributesCrawled = getList(
jQuery, svgAttributeListTitleSelector,
)
const reactHtmlAttributesCrawled = getList(
jQuery, htmlAttributeListTitleSelector,
)
const reactHtmlAttributesFull = fp.pipe([
// Get rid of normal HTML attributes that React doesn't support
fp.mapValues(attributes => fp.intersection(reactHtmlAttributesCrawled)(attributes)),
fp.set('svg', reactSVGAttributesCrawled),
// Add supported attributes copied from the site
fp.mapValues.convert({ cap: false })((attributes, tagName) => (
fp.uniq(attributes.concat(reactHtmlAttributesCopied[tagName] || []))
)),
// Pull all the included crawled attributes and put the rest labelled
// as being React specific into the global attributes
(reactHtmlAttributes) => {
const reactSpecificAttributes = fp.reduce(
(result, value) => fp.pullAll(value)(result),
[].concat(reactHtmlAttributesCrawled),
)(fp.omit(['svg'])(reactHtmlAttributes))
return fp.set(
'*',
reactHtmlAttributes['*'].concat(reactSpecificAttributes),
)(reactHtmlAttributes)
},
fp.mapValues(fp.sortBy(fp.identity)),
fp.pickBy(attributes => !fp.isEmpty(attributes)),
])(HTMLElementAttributes)
const reactHtmlAttributesAndTags = fp.pipe([
fp.set('elements', { html: [], svg: [] }),
fp.set('elements.html', htmlTags),
fp.set('elements.svg', svgTags),
])(reactHtmlAttributesFull)
const jsonFilesToWrite = {
[attributeFileName]: reactHtmlAttributesAndTags,
[crawledHTMLAttributesFileName]: reactHtmlAttributesCrawled,
[crawledSVGAttributesFileName]: reactSVGAttributesCrawled,
[HTMLElementsFileName]: htmlTags,
[SVGElementSFileName]: svgTags,
}
Object.keys(jsonFilesToWrite).forEach((fileName) => {
writeJSONToFile(fileName, jsonFilesToWrite[fileName])
})
},
)
|
let createCalculator = require('../add-or-subtract').createCalculator;
let expect = require('chai').expect;
describe("createCalculator() - Simple adding and subtracting calculations", function() {
let calc;
beforeEach(function() {
calc = createCalculator();
});
it('should return 10 for add(10)', function() {
calc.add(10);
expect(calc.get()).to.be.equal(10)
});
it('should return -10 for subtract(10)', function() {
calc.subtract(10);
expect(calc.get()).to.be.equal(-10)
});
it('should return 5 for add(10) and then subtract(5)', function() {
calc.add(10);
calc.subtract(5);
expect(calc.get()).to.be.equal(5)
});
it('should return 10 for 2 x add(10) and then 2x subtract(5)', function() {
calc.add(10);
calc.add(10);
calc.subtract(5);
calc.subtract(5);
expect(calc.get()).to.be.equal(10)
});
it('add should work correctly with strings', function() {
calc.add('10');
expect(calc.get()).to.be.equal(10)
});
it('subtract should work correctly with strings', function() {
calc.subtract('10');
expect(calc.get()).to.be.equal(-10)
});
it('initial value should be 0', function() {
expect(calc.get()).to.be.equal(0)
});
}); |
var assert = require('assert'),
mongoose = require('mongoose'),
mockgoose = require('mockgoose'),
Request, Mapping;
// in-memory mongoose for model testing
mockgoose(mongoose, true);
Request = require('../../lib/models/request');
Mapping = require('../../lib/models/mapping');
exports.it_should_require_all_required_fields = function(done){
var req = new Request({
method : 'get'
});
req.save(function(err){
assert.ok(err);
return done();
});
};
exports.it_should_reject_invalid_methods = function(done){
var req = new Request({
method : 'DOESNTEXIST',
url : 'http://www.google.ie'
});
req.save(function(err){
assert.ok(err);
return done();
});
};
exports.it_should_capitalise_methods = function(done){
var method = 'get',
req = new Request({
method : 'get',
url : 'http://www.google.ie'
});
req.save(function(err, createRes){
assert.ok(!err);
assert.ok(createRes);
assert.ok(createRes.method === method.toUpperCase());
return done();
});
};
exports.it_should_create_requests_with_a_mapping = function(done){
var mapping = new Mapping({
type : "object",
fields : [
{
type : "number",
from : "foo",
to : "bar"
}
]
});
return mapping.save(function(err, savedMapping){
assert.ok(!err, 'Unable to create simple mapping: ' + err);
var mappingId = savedMapping._id;
var req = new Request({
method : 'get',
url : 'http://www.google.ie',
mapping : mappingId,
mountPath : '/'
});
req.save(function(err){
assert.ok(!err);
return done();
});
});
};
|
var should = require('should');
var is = require('../index.js');
describe('lat', () => {
it('should work with a number type (positive integer)', () => {
is(37, 'lat').should.be.a.Boolean().and.be.true();
});
it('should work with a number type (negative integer)', () => {
is(-37, 'lat').should.be.a.Boolean().and.be.true();
});
it('should work with a number type (positive float)', () => {
is(37.4418834, 'lat').should.be.a.Boolean().and.be.true();
});
it('should work with a number type (negative float)', () => {
is(-37.4418834, 'lat').should.be.a.Boolean().and.be.true();
});
it('should fail with a number type (> 90)', () => {
is(90.01, 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with a number type (< -90)', () => {
is(-90.01, 'lat').should.be.a.Boolean().and.be.false();
});
it('should work with a string type (> 0)', () => {
is('50.123', 'lat').should.be.a.Boolean().and.be.true();
});
it('should work with a string type (< 0)', () => {
is('-50.123', 'lat').should.be.a.Boolean().and.be.true();
});
it('should fail with a string type (empty)', () => {
is('', 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with an array type', () => {
is([], 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with an object type', () => {
is({}, 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with a boolean type', () => {
is(true, 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with a regexp type', () => {
is(new RegExp(''), 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with a function type', () => {
is(function () {}, 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with a date type', () => {
is(new Date(), 'lat').should.be.a.Boolean().and.be.false();
});
it('should fail with a NaN type', () => {
is(0 / 0, 'lat').should.be.a.Boolean().and.be.false();
});
});
|
// ------------------------------------------------------------------
//
// Nodejs module that provides the server-side game model.
//
// ------------------------------------------------------------------
'use strict';
let present = require('present');
let Player = require('./player');
let NetworkIds = require('../shared/network-ids');
let Queue = require('../shared/queue.js');
const UPDATE_RATE_MS = 100; // How often to update the game model
let quit = false;
let activeClients = {};
let inputQueue = Queue.create();
//------------------------------------------------------------------
//
// Process the network inputs we have received since the last time
// the game loop was processed.
//
//------------------------------------------------------------------
function processInput() {
//
// Double buffering on the queue so we don't asynchronously receive inputs
// while processing.
let processMe = inputQueue;
inputQueue = Queue.create();
while (!processMe.empty) {
let input = processMe.dequeue();
let client = activeClients[input.clientId];
client.lastMessageId = input.message.id;
switch (input.message.type) {
case NetworkIds.INPUT_MOVE:
client.player.move(input.message.elapsedTime);
break;
case NetworkIds.INPUT_ROTATE_LEFT:
client.player.rotateLeft(input.message.elapsedTime);
break;
case NetworkIds.INPUT_ROTATE_RIGHT:
client.player.rotateRight(input.message.elapsedTime);
break;
}
}
}
//------------------------------------------------------------------
//
// Update the simulation of the game.
//
//------------------------------------------------------------------
function update(elapsedTime) {
for (let id in activeClients) {
activeClients[id].player.update(elapsedTime);
}
}
//------------------------------------------------------------------
//
// Send state of the game to any connected clients.
//
//------------------------------------------------------------------
function updateClients(elapsedTime) {
for (let clientId in activeClients) {
let client = activeClients[clientId];
let update = {
clientId: clientId,
lastMessageId: client.lastMessageId,
direction: client.player.direction,
center: client.player.center,
updateWindow: elapsedTime
};
if (client.player.reportUpdate) {
client.socket.emit(NetworkIds.UPDATE_SELF, update);
//
// Notify all other connected clients about every
// other connected client status...but only if they are updated.
for (let otherId in activeClients) {
if (otherId !==clientId) {
activeClients[otherId].socket.emit(NetworkIds.UPDATE_OTHER, update);
}
}
}
}
for (let clientId in activeClients) {
activeClients[clientId].player.reportUpdate = false;
}
}
//------------------------------------------------------------------
//
// Server side game loop
//
//------------------------------------------------------------------
function gameLoop(currentTime, elapsedTime) {
processInput();
update(elapsedTime);
updateClients(elapsedTime);
if (!quit) {
setTimeout(() => {
let now = present();
gameLoop(now, now - currentTime);
}, UPDATE_RATE_MS);
}
}
//------------------------------------------------------------------
//
// Get the socket.io server up and running so it can begin
// collecting inputs from the connected clients.
//
//------------------------------------------------------------------
function initializeSocketIO(httpServer) {
let io = require('socket.io')(httpServer);
//------------------------------------------------------------------
//
// Notifies the already connected clients about the arrival of this
// new client. Plus, tell the newly connected client about the
// other players already connected.
//
//------------------------------------------------------------------
function notifyConnect(socket, newPlayer) {
for (let clientId in activeClients) {
let client = activeClients[clientId];
if (newPlayer.clientId !== clientId) {
//
// Tell existing about the newly connected player
client.socket.emit(NetworkIds.CONNECT_OTHER, {
clientId: newPlayer.clientId,
direction: newPlayer.direction,
center: newPlayer.center,
size: newPlayer.size,
rotateRate: newPlayer.rotateRate,
speed: newPlayer.speed,
});
//
// Tell the new player about the already connected player
socket.emit(NetworkIds.CONNECT_OTHER, {
clientId: client.player.clientId,
direction: client.player.direction,
center: client.player.center,
size: client.player.size,
rotateRate: client.player.rotateRate,
speed: client.player.speed,
});
}
}
}
//------------------------------------------------------------------
//
// Notifies the already connected clients about the disconnect of
// another client.
//
//------------------------------------------------------------------
function notifyDisconnect(playerId) {
for (let clientId in activeClients) {
let client = activeClients[clientId];
if (playerId !== clientId) {
client.socket.emit(NetworkIds.DISCONNECT_OTHER, {
clientId: playerId
});
}
}
}
//------------------------------------------------------------------
//
// A new connection (browser) was made. Create a new player at the server
// and send that information to the newly connected client. After
// doing that, also want to notify all other currently connected
// clients of the new player.
//
//------------------------------------------------------------------
io.on('connection', function(socket) {
console.log(`Connection established: ${socket.id}`);
//
// Create an entry in our list of connected clients
let newPlayer = Player.create();
newPlayer.clientId = socket.id;
activeClients[socket.id] = {
socket: socket,
player: newPlayer
};
socket.emit(NetworkIds.CONNECT_ACK, {
direction: newPlayer.direction,
center: newPlayer.center,
size: newPlayer.size,
rotateRate: newPlayer.rotateRate,
speed: newPlayer.speed
});
socket.on(NetworkIds.INPUT, function(data) {
inputQueue.enqueue({
clientId: socket.id,
message: data,
});
});
socket.on('disconnect', function() {
delete activeClients[socket.id];
notifyDisconnect(socket.id);
});
// Notify the other already connected clients of this new player
notifyConnect(socket, newPlayer);
});
}
//------------------------------------------------------------------
//
// Entry point to get the game started.
//
//------------------------------------------------------------------
function initialize(httpServer) {
initializeSocketIO(httpServer);
gameLoop(present(), 0);
}
//------------------------------------------------------------------
//
// Public function that allows the game simulation and processing to
// be terminated.
//
//------------------------------------------------------------------
function terminate() {
this.quit = true;
}
module.exports.initialize = initialize;
|
const chai = require('chai');
const expect = chai.expect;
const Timer = require('../../lib/timer');
describe('Timer', () => {
it('exist', () => {
expect(Timer).to.exist;
});
it('runs', () => {
const timer = new Timer(() => {}, 0);
expect(timer.running).to.be.true;
});
it('triggers callback', (callback) => {
const timer = new Timer(() => {
expect(timer.running).to.be.false;
expect(true).to.be.true;
callback();
}, 0);
});
it('can be paused', () => {
const timer = new Timer((callback) => {
expect(timer.running).to.be.false;
expect(false).to.be.true;
callback();
}, 0);
timer.pause();
});
it('can be resumed', (callback) => {
const timer = new Timer(() => {
expect(true).to.be.true;
callback();
}, 0);
timer.pause();
timer.resume();
});
it('can be cancelled', () => {
const timer = new Timer((callback) => {
expect(timer.running).to.be.false;
expect(false).to.be.true;
callback();
}, 0);
timer.cancel();
});
it('can be restarted', (callback) => {
const timer = new Timer(() => {
expect(true).to.be.true;
callback();
}, 0);
timer.cancel();
timer.reset();
});
});
|
'use strict';
/**
* Tests for 'filter' module.
*/
const expect = require('chai').expect;
const MetadataFilter = require('../../core/content/filter');
/**
* Test data is an array of objects. Each object must contain
* three fields: 'description', 'source' and 'expected'.
*
* 'description' is a test description used by 'it' function.
* 'source' is an function argument that used to test function.
* 'expected' is an expected value of function result.
*/
const FILTER_NULL_DATA = [{
description: 'should not call filter function for null source',
source: null,
expected: null
}, {
description: 'should not call filter function for empty source',
source: '',
expected: ''
}];
/**
* Test data for testing Trim filter.
* @type {Array}
*/
const TRIM_TEST_DATA = [{
description: 'should do nothing with clean string',
source: 'Track Title',
expected: 'Track Title'
}, {
description: 'should trim whitespaces',
source: ' Track Metafield ',
expected: 'Track Metafield'
}, {
description: 'should trim trailing whitespaces',
source: 'Track Metafield ',
expected: 'Track Metafield'
}, {
description: 'should trim leading whitespaces',
source: ' Track Metafield',
expected: 'Track Metafield'
}];
/**
* Test data for testing Youtube filter.
* @type {Array}
*/
const YOUTUBE_TEST_DATA = [{
description: 'should do nothing with clean string',
source: 'Track Title',
expected: 'Track Title'
}, {
description: 'should trim whitespaces',
source: ' Track Title ',
expected: 'Track Title'
}, {
description: 'should trim leading whitespaces',
source: ' Track Title',
expected: 'Track Title'
}, {
description: 'should trim trailing whitespaces',
source: 'Track Title ',
expected: 'Track Title'
}, {
description: 'should remove leftovers after e.g. (official video)',
source: 'Track Title ( )',
expected: 'Track Title'
}, {
description: 'should remove empty leftovers after e.g. (official video)',
source: 'Track Title ()',
expected: 'Track Title'
}, {
description: 'should remove "HD" string',
source: 'Track Title HD',
expected: 'Track Title'
}, {
description: 'should remove "HQ" string',
source: 'Track Title HQ',
expected: 'Track Title'
}, {
description: 'should extract title from single quotes',
source: '\'Track Title\'',
expected: 'Track Title'
}, {
description: 'should extract title from double quotes',
source: '"Track Title" whatever',
expected: 'Track Title'
}, {
description: 'should remove .avi extension',
source: 'Track Title.avi',
expected: 'Track Title'
}, {
description: 'should remove .wmv extension',
source: 'Track Title.wmv',
expected: 'Track Title'
}, {
description: 'should remove .mpg extension',
source: 'Track Title.mpg',
expected: 'Track Title'
}, {
description: 'should remove .flv extension',
source: 'Track Title.flv',
expected: 'Track Title'
}, {
description: 'should remove .mpeg extension',
source: 'Track Title.mpeg',
expected: 'Track Title'
}, {
description: 'should remove "**NEW**" string',
source: 'Track Title **NEW**',
expected: 'Track Title'
}, {
description: 'should remove "[whatever]" string',
source: 'Track Title [Official Video]',
expected: 'Track Title'
}, {
description: 'should remove "Video" string',
source: 'Track Title Video',
expected: 'Track Title'
}, {
description: 'should remove "Music Video" string',
source: 'Track Title Music Video',
expected: 'Track Title'
}, {
description: 'should remove "Official Video" string',
source: 'Track Title Official Video',
expected: 'Track Title'
}, {
description: 'should remove "Official Music Video" string',
source: 'Track Title Official Music Video',
expected: 'Track Title'
}, {
description: 'should remove "Audio" string',
source: 'Track Title Audio',
expected: 'Track Title'
}, {
description: 'should remove "Music Audio" string',
source: 'Track Title Music Audio',
expected: 'Track Title'
}, {
description: 'should remove "Official Audio" string',
source: 'Track Title Official Audio',
expected: 'Track Title'
}, {
description: 'should remove "Official Music Audio" string',
source: 'Track Title Official Music Audio',
expected: 'Track Title'
}, {
description: 'should remove "(official)" string',
source: 'Track Title (Official)',
expected: 'Track Title'
}, {
description: 'should remove "(oficial)" string',
source: 'Track Title (Oficial)',
expected: 'Track Title'
}, {
description: 'should remove "offizielles Video" string',
source: 'Track Title offizielles Video',
expected: 'Track Title'
}, {
description: 'should remove "video clip officiel" string',
source: 'Track Title video clip officiel',
expected: 'Track Title'
}, {
description: 'should remove "video clip" string',
source: 'Track Title video clip',
expected: 'Track Title'
}, {
description: 'should remove "vid\u00E9o clip" string',
source: 'Track Title vid\u00E9o clip',
expected: 'Track Title'
}, {
description: 'should remove "(YYYY)" string',
source: 'Track Title (2348)',
expected: 'Track Title'
}, {
description: 'should remove "(Whatever version)" string',
source: 'Track Title (Super Cool Version)',
expected: 'Track Title'
}, {
description: 'should remove "(Lyric Video)" string',
source: 'Track Title (Lyric Video)',
expected: 'Track Title'
}, {
description: 'should remove "(Whatever Lyric Video)" string',
source: 'Track Title (Official Lyric Video)',
expected: 'Track Title'
}, {
description: 'should remove "(Lyrics Video)" string',
source: 'Track Title (Lyrics Video)',
expected: 'Track Title'
}, {
description: 'should remove "(Whatever Lyrics Video)" string',
source: 'Track Title (OFFICIAL LYRICS VIDEO)',
expected: 'Track Title'
}, {
description: 'should remove "(Official Track Stream)" string',
source: 'Track Title (Official Track Stream)',
expected: 'Track Title'
}, {
description: 'should remove leading colon',
source: ':Track Title',
expected: 'Track Title'
}, {
description: 'should remove leading semicolon',
source: ';Track Title',
expected: 'Track Title'
}, {
description: 'should remove leading dash',
source: '-Track Title',
expected: 'Track Title'
}, {
description: 'should remove leading double quote',
source: '"Track Title',
expected: 'Track Title'
}, {
description: 'should remove trailing colon',
source: 'Track Title:',
expected: 'Track Title'
}, {
description: 'should remove trailing semicolon',
source: 'Track Title;',
expected: 'Track Title'
}, {
description: 'should remove trailing dash',
source: 'Track Title-',
expected: 'Track Title'
}, {
description: 'should remove trailing double quote',
source: 'Track Title"',
expected: 'Track Title'
}];
/**
* Test data for testing Remastered filter.
* @type {Array}
*/
const REMASTERED_TEST_DATA = [{
description: 'should do nothing with clean string',
source: 'Track Title',
expected: 'Track Title'
}, {
description: 'should remove "- Remastered" string',
source: 'Track Title - Remastered',
expected: 'Track Title'
}, {
description: 'should remove "(YYYY - Remaster)" string',
source: 'Track Title (2011 - Remaster)',
expected: 'Track Title'
}, {
description: 'should remove "- Remastered YYYY" string',
source: 'Track Title - Remastered 2015',
expected: 'Track Title'
}, {
description: 'should remove "(Remastered YYYY)" string',
source: 'Track Title (Remastered 2009)',
expected: 'Track Title'
}, {
description: 'should remove "[YYYY - Remaster]" string',
source: 'Track Title [2011 - Remaster]',
expected: 'Track Title'
}, {
description: 'should remove "- YYYY - Remaster" string',
source: 'Track Title - 2011 - Remaster',
expected: 'Track Title'
}, {
description: 'should remove "(Live / Remastered)" string',
source: 'Track Title (Live / Remastered)',
expected: 'Track Title'
}, {
description: 'should remove "- Live / Remastered" string',
source: 'Track Title - Live / Remastered',
expected: 'Track Title'
}, {
description: 'should remove "- YYYY Digital Remaster" string',
source: 'Track Title - 2001 Digital Remaster',
expected: 'Track Title'
}, {
description: 'should remove "- YYYY Remastered Version" string',
source: 'Track Title - 2011 Remastered Version',
expected: 'Track Title'
}];
/**
* Test data for testing 'MetadataFilter.decodeHtmlEntities' function.
* @type {Array}
*/
const DECODE_HTML_ENTITIES_TEST_DATA = [{
description: 'should do nothing with clean string',
source: 'Can\'t Kill Us',
expected: 'Can\'t Kill Us'
}, {
description: 'should decode HTML entity',
source: 'Can't Kill Us',
expected: 'Can\'t Kill Us'
}, {
description: 'should decode HTML entity',
source: 'Can`t Kill Us',
expected: 'Can`t Kill Us'
}, {
description: 'should decode ampersand symbol',
source: 'Artist 1 & Artist 2',
expected: 'Artist 1 & Artist 2'
}, {
description: 'should not decode invalid HTML entity',
source: 'Artist 1 &#xzz; Artist 2',
expected: 'Artist 1 &#xzz; Artist 2'
}];
/**
* Test data for testing 'MetadataFilter.removeZeroWidth' function.
* @type {Array}
*/
const REMOVE_ZERO_WIDTH_TEST_DATA = [{
description: 'should do nothing with clean string',
source: 'Track Metafield',
expected: 'Track Metafield'
}, {
description: 'should remove zero-width characters',
source: 'Str\u200Ding\u200B',
expected: 'String'
}, {
description: 'should remove trailing zero-width characters',
source: 'String\u200C',
expected: 'String'
}, {
description: 'should remove leading zero-width characters',
source: '\u200DString',
expected: 'String'
}];
/**
* Filters data is an array of objects. Each object must contain
* four fields: 'description', 'filter', 'fields' and 'testData'.
*
* 'description' is a test description used by 'it' function.
* 'filter' is an filter instance.
* 'fields' is an array of song fields to be filtered.
* 'testData' contains test data used to test filter.
*/
const FILTERS_DATA = [{
description: 'Base filter',
filter: new MetadataFilter({ all: shouldNotBeCalled }),
fields: ['artist', 'track', 'album'],
testData: FILTER_NULL_DATA,
}, {
description: 'Trim filter',
filter: MetadataFilter.getTrimFilter(),
fields: ['artist', 'track', 'album'],
testData: TRIM_TEST_DATA,
}, {
description: 'Youtube filter',
filter: MetadataFilter.getYoutubeFilter(),
fields: ['track'],
testData: YOUTUBE_TEST_DATA,
}, {
description: 'Remastered filter',
filter: MetadataFilter.getRemasteredFilter(),
fields: ['track', 'album'],
testData: REMASTERED_TEST_DATA,
}, {
description: 'removeZeroWidth',
filter: new MetadataFilter({ all: MetadataFilter.removeZeroWidth }),
fields: ['artist', 'track', 'album'],
testData: REMOVE_ZERO_WIDTH_TEST_DATA,
}, {
description: 'decodeHtmlEntities',
filter: new MetadataFilter({ all: MetadataFilter.decodeHtmlEntities }),
fields: ['artist', 'track', 'album'],
testData: DECODE_HTML_ENTITIES_TEST_DATA,
}];
/**
* Test filter object.
* @param {Object} filter MetadataFilter instance
* @param {Array} fields Array of fields to be filtered
* @param {Array} testData Array of test data
*/
function testFilter(filter, fields, testData) {
let filterFunctions = {
artist: filter.filterArtist.bind(filter),
track: filter.filterTrack.bind(filter),
album: filter.filterAlbum.bind(filter)
};
for (let field of fields) {
let filterFunction = filterFunctions[field];
describe(`${field} field`, function() {
for (let data of testData) {
let { description, source, expected } = data;
it(description, function() {
expect(expected).to.be.equal(filterFunction(source));
});
}
});
}
}
/**
* Function that should not be called.
* @throws {Error} if is called
*/
function shouldNotBeCalled() {
throw new Error('This function should not be called');
}
/**
* Run all tests.
*/
function runTests() {
for (let data of FILTERS_DATA) {
let { description, filter, fields, testData } = data;
describe(description, function() {
testFilter(filter, fields, testData);
});
}
}
module.exports = runTests;
|
/**
* User.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
attributes: {
uid: {
type: 'string'
},
name: {
type: 'string'
},
email: {
type: 'string'
},
first_name: {
type: 'string'
},
last_name: {
type: 'string'
},
customer_id: {
type: 'string'
}
}
};
|
/*
Form related utilities module
*/
var _ = require('lodash'),
/*
A field object is this structure:
{
// Any attributes, eg: id, etc. (optional)
name: "", // Name of the field (optional)
options: [], // Any options, for selectboxes, etc (optional)
meta: {} // Any other attributes, eg: label, placeholder, etc.
}
These will be used in the construction in the template.
Any other attributes can be passed through, and used for
other things, eg: validation, etc, and won't be rendered
as an attribute ...
*/
applyField = function(field, name, translateFunc) {
field.meta = field.meta || {};
field.name = name;
// Grab any attributes that are assigned directly on the field object
_.forOwn(field, function(value, key) {
if(key !== "meta" && key !== "options") {
field[key] = value;
}
});
// Merge fields with their translations
tmp = translateFunc(name + 'Field');
if(typeof tmp == "object") {
field.meta = _.merge(field.meta || {}, tmp);
}
// Merge ID based translations
tmp = translateFunc(name + 'Field_' + field.id);
if(typeof tmp == "object") {
field.meta = _.merge(field.meta, tmp);
}
// Merge options with translations
if(field.options) {
field.options = field.options;
_.forOwn(field.options, function(optValue, optIndex){
// Merge options with their translations
tmp = translateFunc(name + 'Field_' + optValue.id);
if(typeof tmp == "object") {
field.options[optIndex].meta = field.options[optIndex].meta || {};
field.options[optIndex].meta = _.merge(field.options[optIndex].meta, tmp);
}
});
}
return field;
};
module.exports = {
// TODO: Finish creating form mappings translation for sequelizejs
// model - need to test with more elaborate models.
// Note: we do this so we are loosely coupled to sequelize
// optional: formName, in case we want to prefix field names
// where there might be more than one form on the page
sequelizeModelToForm: function(model, formName) {
var o = {}, tmp, validators;
_.forOwn(model.rawAttributes, function(value, key){
validators = (value.validate)? value.validate: null;
tmp = {
// Set the name, optionally prefixing
name: (formName)? formName + "_" + key: key,
// Set the value
value: model.dataValues? model.dataValues[key]: undefined,
// Any meta data
meta: {
required: (value.allowNull == false),
validate: validators
}
};
// Set the data-validate attribute
if(validators) {
tmp['data-validate'] = JSON.stringify(validators).split('"').join('"');
}
o[key] = tmp;
});
return o;
},
// Populate a sequelize model from a form
// TODO: We need this when a formName is specified
formToSequelizeModel: function(model, data, formName) {
// TODO: use form name to gather the data
return model.build(data);
},
// Creates a form object, resolving
// translated field labels, hints, etc, via
// the passed in translation function
//
// TODO: For production - Caching - should be able to load the form
// from cache based on language, and just update the values.
form: function(fields, translateFunc){
// Set names and translated items
_.forOwn(fields, function(value, name){
var tmp, isArr;
// Allow a list of fields to be passed through
if(_.isArray(value)) {
// Process the fields
fields[name] = [];
_.forOwn(value, function(field) {
fields[name].push(applyField(field, name, translateFunc));
})
} else {
fields[name] = applyField(value, name, translateFunc);
}
});
return fields;
}
}; |
var url = 'http://localhost:3000',
request = require('superagent'),
moment = require('moment'),
user = {
username: 'smalik',
password: '12345'
},
authToken, userId;
var document1 = {
title: 'Area of Triangle',
content: 'This is obtained from the base and height. Get half of' +
' the base and multiply by the height to get the area.'
},
doc1id,
document2 = {
title: 'Cone',
content: 'Has a circular base and a pointed top. It is a third of a ' +
'cylinder'
},
doc2id,
document3 = {
title: 'Perimeter of Rectangle',
content: 'Obtained by summing the length and width and doubling the result.'
},
doc3id,
document4 = {
title: 'Cylinder',
content: 'Volume obtained using area of base multiplied by the height.'
},
doc4id;
describe('Document', function() {
it('validates that one has to be authenticated to access documents ' +
'(GET /api/documents)',
function(done) {
request
.get(url + '/api/documents')
.end(function(err, res) {
expect(typeof res.body).toBe('object');
expect(res.status).toEqual(403);
expect(res.body.success).toEqual(false);
expect(res.body.message).toBe('No token provided!');
done();
});
});
});
describe('Document tests requiring authentication', function() {
// perform login function first
beforeEach(function login(done) {
request
.post(url + '/api/users/login')
.send(user)
.end(function(err, res) {
userId = res.body.id;
authToken = res.body.token;
done();
});
});
it('validates that a document is created by a user logged in ' +
'(POST /api/documents)',
function(done) {
request
.post(url + '/api/documents')
.set('x-access-token', authToken)
.send(document1)
.end(function(err, res) {
doc1id = res.body._id;
expect(res.status).toEqual(200);
expect(typeof res.body).toBe('object');
expect(res.body._id).toBeDefined();
expect(res.body.title).toEqual(document1.title);
expect(res.body.content).toBe(document1.content);
done();
});
});
it('validates that a document is created by a user logged in ' +
'(POST /api/documents)',
function(done) {
request
.post(url + '/api/documents')
.set('x-access-token', authToken)
.send(document2)
.end(function(err, res) {
doc2id = res.body._id;
expect(res.status).toEqual(200);
expect(typeof res.body).toBe('object');
expect(res.body._id).toBeDefined();
expect(res.body.title).toEqual(document2.title);
expect(res.body.content).toBe(document2.content);
done();
});
});
it('validates that one has to be authenticated to access documents ' +
'(GET /api/documents)',
function(done) {
request
.get(url + '/api/documents')
.set('x-access-token', authToken)
.end(function(err, res) {
expect(res.status).toEqual(200);
expect(typeof res.body).toBe('object');
expect(res.body.length).toBeGreaterThan(0);
expect(res.body[res.body.length - 1].title).toEqual(document2.title);
expect(res.body[res.body.length - 1].content).toEqual(document2
.content);
done();
});
});
it('validates that all documents, limited by a specified number ' +
'and ordered by published date, that can be accessed by a ' +
'role USER, are returned when getAllDocumentsByRoleUser is called',
function(done) {
request
.get(url + '/api/documents/user')
.set('x-access-token', authToken)
.end(function(err, res) {
var itemOne = res.body[0];
var itemLast = res.body[res.body.length - 1];
expect(res.status).toEqual(200);
expect(itemLast.dateCreated).toEqual(itemOne.dateCreated);
done();
});
});
it('validates that all documents, limited by a specified number, that were' +
' published on a certain date, are returned when getAllDocumentsByDate ' +
'is called',
function(done) {
request
.get(url + '/api/documents/date')
.set('x-access-token', authToken)
.end(function(err, res) {
expect(res.status).toEqual(200);
expect(res.body.length).toBeGreaterThan(1);
expect(res.body[0].dateCreated).toContain(moment(new Date())
.format('YYYY-MM-DD'));
expect(true).toBe(true);
done();
});
});
});
// tests for administrator documents
describe('Administrator Documents', function() {
beforeEach(function logout(done) {
request
.get('http://localhost:3000/api/users/logout')
.set('x-access-token', authToken)
.end(function() {
authToken = '';
done();
});
});
// login the administrator
beforeEach(function loginAdmin(done) {
request
.post(url + '/api/users/login')
.send({
username: 'Sonnie',
password: '12345'
})
.end(function(err, res) {
userId = res.body.id;
authToken = res.body.token;
done();
});
});
it('validates that a document is created by a admin logged in ' +
'(POST /api/documents)',
function(done) {
request
.post(url + '/api/documents')
.set('x-access-token', authToken)
.send(document3)
.end(function(err, res) {
doc3id = res.body._id;
expect(res.status).toEqual(200);
expect('Content-Type', 'json', done);
expect(typeof res.body).toBe('object');
expect(res.body._id).toBeDefined();
expect(res.body.title).toEqual(document3.title);
expect(res.body.content).toBe(document3.content);
done();
});
});
it('validates that a document is created by a admin logged in ' +
'(POST /api/documents)',
function(done) {
request
.post(url + '/api/documents')
.set('x-access-token', authToken)
.send(document4)
.end(function(err, res) {
doc4id = res.body._id;
expect(res.status).toEqual(200);
expect(typeof res.body).toBe('object');
expect(res.body._id).toBeDefined();
expect(res.body.title).toEqual(document4.title);
expect(res.body.content).toBe(document4.content);
done();
});
});
it('validates that all documents, limited by a specified number ' +
'and ordered by published date, that can be accessed by a role ' +
'ADMINISTRATOR, are returned when ' +
'getAllDocumentsByRoleAdministrator is called',
function(done) {
request
.get(url + '/api/documents/admin')
.set('x-access-token', authToken)
.end(function(err, res) {
var lastItem = res.body[res.body.length - 1];
var firstItem = res.body[res.body.length - 2];
expect(res.status).toEqual(200);
expect(lastItem.dateCreated).toEqual(firstItem.dateCreated);
expect(true).toBe(true);
done();
});
});
it('validates that any users document can be updated by an ' +
'Administrator (PUT /api/documents)/:id',
function(done) {
request
.put(url + '/api/documents/' + doc1id)
.set('x-access-token', authToken)
.send({
title: 'Frodo',
content: 'A character in LOTR.'
})
.end(function(err, res) {
expect(res.status).toBe(200);
expect(typeof res.body).toEqual('object');
expect(res.body.success).toBe(true);
expect(res.body.message).toBe('Successfully updated Document!');
done();
});
});
it('validates that any users document can be deleted by an ' +
'Administrator (DELETE /api/documents)/:id',
function(done) {
request
.del(url + '/api/documents/' + doc2id)
.set('x-access-token', authToken)
.end(function(err, res) {
expect(res.status).toEqual(200);
expect(typeof res.body).toBe('object');
expect(res.body.message.title).toBe(document2.title);
expect(res.body.message.content).toBe(document2.content);
done();
});
});
});
// tests for manipulating documents access
describe('Document tests requiring authentication', function() {
// logout first
beforeEach(function logout(done) {
request
.get('http://localhost:3000/api/users/logout')
.set('x-access-token', authToken)
.end(function() {
authToken = '';
done();
});
});
// perform login function first
beforeEach(function login(done) {
request
.post(url + '/api/users/login')
.send({
username: 'tn',
password: '12345'
})
.end(function(err, res) {
userId = res.body.id;
authToken = res.body.token;
done();
});
});
it('validates that a document can only be updated by the creator or an ' +
'Administrator (PUT /api/documents/:id)',
function(done) {
request
.put(url + '/api/documents/' + doc1id)
.set('x-access-token', authToken)
.send({
title: 'Frodo',
content: 'A character in LOTR.'
})
.end(function(err, res) {
expect(res.status).toBe(403);
expect(typeof res.body).toBe('object');
expect(res.body.message).toBe('Forbidden to update this document.');
done();
});
});
it('validates that a document can only be deleted by the creator or an ' +
'Administrator (DELETE /api/documents/:id)',
function(done) {
request
.del(url + '/api/documents/' + doc1id)
.set('x-access-token', authToken)
.end(function(err, res) {
expect(res.status).toEqual(403);
expect(typeof res.body).toBe('object');
expect(res.body.message).toBe('Forbidden to delete this document.');
done();
});
});
});
|
import qb from 'orbit/query/builder';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/concat';
import '../../rxjs/add/operator/matching';
import RecordsObservable from './records-observable';
export default class HasManyObservable extends Observable {
constructor(subscribe, cache, record, relationship) {
super(subscribe);
this.cache = cache;
this.record = record;
this.relationship = relationship;
}
lift(operator) {
const observable = new HasManyObservable();
observable.source = this;
observable.operator = operator;
observable.cache = this.cache;
observable.record = this.record;
observable.relationship = this.relationship;
return observable;
}
relationshipChanges() {
return this.map(operation => {
const relatedRecord = operation.relatedRecord;
switch (operation.op) {
case 'addToHasMany': return { op: 'addRecord', record: relatedRecord };
case 'removeFromHasMany': return { op: 'removeRecord', record: relatedRecord };
default: throw new Error(`relatedRecords operator does not support: ${operation.op}`);
}
});
}
relatedRecords({ initial = false } = {}) {
let relatedRecords = this.map(() => this._fetchRelatedRecords());
if (initial) {
relatedRecords = relatedRecords.startWith(this._fetchRelatedRecords());
}
return RecordsObservable.fromObservable(relatedRecords, this.cache);
}
_fetchRelatedRecords() {
const resultSet = this.cache.query(qb.relatedRecords(this.record, this.relationship));
const resultArray = Object.keys(resultSet).map(id => resultSet[id]);
return resultArray;
}
static fromObservable(observable, cache, record, relationship) {
const patches = observable.matching({ record: { type: record.type, id: record.id }, op: ['addToHasMany', 'removeFromHasMany'], relationship });
const subscribe = patches.subscribe.bind(patches);
return new HasManyObservable(subscribe, cache, record, relationship);
}
}
|
describe('util', function(){
describe('Ticker', function(){
var ticker, tickObj;
beforeEach('init Ticker', function(){
ticker = new Hilo.Ticker(60);
tickObj = {
tickNum:0,
tick:function(){
this.tickNum ++;
}
};
});
afterEach('destroy Ticker', function(){
ticker.stop();
});
it('addTick & removeTick', function(){
ticker._tick();
tickObj.tickNum.should.equal(0);
//addTick
ticker.addTick(tickObj);
ticker._tick();
tickObj.tickNum.should.equal(1);
ticker._tick();
tickObj.tickNum.should.equal(2);
//removeTick
ticker.removeTick(tickObj);
ticker._tick();
tickObj.tickNum.should.equal(2);
});
it('tick time', function(done){
var startTime;
ticker.addTick({
tick:function(){
if(!startTime){
startTime = Date.now();
}
else{
try{
(Date.now() - startTime).should.be.within(11, 21);
done();
}
catch(e){
done(e);
}
}
}
});
ticker.start();
});
});
describe('TextureAtlas', function(){
var fishImage;
beforeEach('load image', function(done){
utils.loadImage('images/fish.png', function(img){
fishImage = img;
done();
});
});
it('new', function(){
var texture = new Hilo.TextureAtlas({
image: fishImage,
width: 174,
height: 1512,
frames: {
frameWidth: 174,
frameHeight: 126,
numFrames: 12
},
sprites: {
fish: {from:0, to:7}
}
});
var spriteFrames = texture.getSprite('fish');
spriteFrames.length.should.equal(8);
var firstFrame = spriteFrames[0], endFrame = spriteFrames[7];
firstFrame.rect[1].should.equal(0);
endFrame.rect[1].should.equal(882);
});
it('createSpriteFrames', function(){
var spriteFrames = Hilo.TextureAtlas.createSpriteFrames("swim", "0-7", fishImage, 174, 126, true);
spriteFrames.length.should.equal(8);
var firstFrame = spriteFrames[0], endFrame = spriteFrames[7];
firstFrame.name.should.equal('swim');
endFrame.next.should.equal('swim');
firstFrame.rect[1].should.equal(0);
endFrame.rect[1].should.equal(882);
});
});
}); |
'use strict'
var opbeat = require('opbeat').start()
var fs = require('fs')
var http = require('http')
var handlebars = require('handlebars')
var afterAll = require('after-all')
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
var tmpl = handlebars.compile(fs.readFileSync('index.handlebars').toString())
var BUCKET = process.env.AWS_S3_BUCKET || 'printbin'
var names = {}
var server = http.createServer(function (req, res) {
if (req.method !== 'GET') {
res.writeHead(405, { Allow: 'GET' })
res.end()
return
} else if (req.url !== '/') {
res.statusCode = 404
res.end()
return
}
fetchDocuments(function (err, docs) {
if (err) {
opbeat.captureError(err)
res.statusCode = 500
res.end()
return
}
var html = tmpl({ docs: docs })
res.writeHead(200, {
'Content-Length': Buffer.byteLength(html),
'Content-Type': 'text/html'
})
res.end(html)
})
})
server.listen(process.env.PORT, function () {
console.log('Server listening on port', server.address().port)
})
function fetchDocuments (cb) {
fetchKeys(function (err, keys) {
if (err) return cb(err)
var next = afterAll(function (err) {
if (err) return cb(err)
cb(null, docs)
})
var docs = keys.map(function (key) {
var doc = { key: key, name: names[key] }
if (!doc.name) {
console.log('Caching document name for %s...', key)
var done = next()
var params = { Bucket: BUCKET, Key: key }
s3.headObject(params, function (err, data) {
if (err) return done(err)
doc.name = names[key] = data.Metadata.name || key
done()
})
}
return doc
})
})
}
function fetchKeys (cb) {
s3.listObjects({ Bucket: BUCKET }, function (err, data) {
if (err) return cb(err)
var keys = data.Contents
.sort(function (a, b) {
return b.LastModified.getTime() - a.LastModified.getTime()
})
.map(function (obj) {
return obj.Key
})
cb(null, keys)
})
}
|
'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module,
favicon = require('serve-favicon'),
express = require('express');
var System = new Module('system');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
System.register(function(app, auth, database) {
//We enable routing. By default the Package Object is passed to the routes
System.routes(app, auth, database);
System.aggregateAsset('css', 'common.css');
// The middleware in config/express will run before this code
// Set views path, template engine and default layout
app.set('views', __dirname + '/server/views');
// Setting the favicon and static folder
app.use(favicon(__dirname + '/public/assets/img/favicon.ico'));
// Adding robots and humans txt
app.use(express.static(__dirname + '/public/assets/static'));
app.use(express.static(__dirname + '/public/assets/img'));
return System;
});
|
var nodemailer = require('nodemailer'); // email sender
function exports.sendEmail = function(to, text){
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'example@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'Web Prosumer',
to: to,
subject: 'Medidas alcanzadas',
text: text
};
transporter.sendMail(mailOptions, function(error, info){
if (error){
console.log(error);
} else {
console.log("Email sent");
}
});
};
|
// Wait till the browser is ready to render the game (avoids glitches)
window.requestAnimationFrame(function () {
var manager = new GameManager(8, KeyboardInputManager, HTMLActuator);
});
|
function solve(args) {
let newArr = [];
for (let i = 0; i < args.length; i++) {
let temp = args[i].split(' ');
index = temp[0];
value = temp[1];
if (index == "add") {
newArr.push(value);
}
if (index == "remove") {
newArr.splice(value, 1);
}
}
for (var j = 0; j < newArr.length; j++) {
console.log(newArr[j]);
}
}
solve([
'add 3',
'add 5',
'add 7']);
|
/*global jasmine*/
(function () {
'use strict';
var jasmineEnv = jasmine.getEnv(),
htmlReporter;
jasmineEnv.updateInterval = 1000;
htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
window.onload = function () {
jasmineEnv.execute();
};
}()); |
"use strict";
var toggleClass_1 = require("./toggleClass");
var moveElement = function (elementToMove) {
return function _moveElement(elementBeingDragged, event, details) {
var initialClientX = details.initialClientX, initialClientY = details.initialClientY, lastClientX = details.lastClientX, lastClientY = details.lastClientY, newClientX = details.newClientX, newClientY = details.newClientY;
var el = elementToMove;
var bounds = el.getBoundingClientRect();
var left = bounds.left, top = bounds.top;
var dx = newClientX - lastClientX;
var dy = newClientY - lastClientY;
el.style.right = "auto";
el.style.bottom = "auto";
el.style.left = (left + dx) + 'px';
el.style.top = (top + dy) + 'px';
};
};
exports.dragActions = {
move: moveElement,
};
function draggable(el, callback) {
var enabled = true;
var isDragging = false;
var initialClientX = 0, initialClientY = 0;
var lastClientX = 0, lastClientY = 0;
var mouseDownListener = function (e) {
if (!enabled)
return;
isDragging = true;
lastClientX = initialClientX = e.clientX;
lastClientY = initialClientY = e.clientY;
var dragListener = function (e) {
if (!enabled || !isDragging)
return;
e.preventDefault();
var newClientX = e.clientX, newClientY = e.clientY;
callback(el, e, { initialClientX: initialClientX, initialClientY: initialClientY, lastClientX: lastClientX, lastClientY: lastClientY, newClientX: newClientX, newClientY: newClientY });
lastClientX = newClientX;
lastClientY = newClientY;
};
var doneDragging = function (e) {
isDragging = false;
document.removeEventListener("mousemove", dragListener);
document.removeEventListener("mouseup", doneDragging);
};
document.addEventListener("mousemove", dragListener);
document.addEventListener("mouseup", doneDragging);
};
toggleClass_1.addClass("draggable")(el);
el.addEventListener("mousedown", mouseDownListener);
return function () { return el.removeEventListener("mousedown", mouseDownListener); };
}
exports.draggable = draggable;
//# sourceMappingURL=draggable.js.map |
// The admin bar module implements Apostrophe's admin bar at the top of the screen. Any module
// can register a button (or more than one) for this bar by calling the `add` method of this
// module. Buttons can also be grouped into dropdown menus and restricted to those with
// particular permissions. [apostrophe-pieces](../apostrophe-pieces/index.html) automatically
// takes advantage of this module.
//
// On the browser side there are also conveniences to implement jQuery handlers for these
// menu items.
var _ = require('lodash');
module.exports = {
alias: 'adminBar',
// Push the assets and the browser call to create the browser-side singleton
// that provides `apos.adminBar.link`. Most server-side initialization happens
// in `self.modulesReady` rather than here.
afterConstruct: function(self) {
self.pushAssets();
},
construct: function(self, options) {
self.items = [];
self.groups = [];
self.groupLabels = {};
// Add an item to the admin bar.
//
// The name argument becomes the value of the `data-apos-admin-bar-item`
// attribute of the admin bar item.
//
// `permission` should be a permission name such as `admin`
// (the user must be a full admin) or `edit-apostrophe-event`
// (the user can create events and edit their own). If
// `permission` is null then being logged in is
// good enough to see the item. (Securing your actual routes that
// respond to these items is up to you.)
//
// Usually just one admin bar item per module makes sense, so it's
// common to pass `self.__meta.name` (the module's name) as the name argument.
//
// For example, the pieces module does this:
//
// ```
// self.apos.adminBar.add(self.__meta.name, self.pluralLabel, 'edit')
// ```
//
// If you have an `events` module that subclasses pieces, then this
// creates an admin bar item with a data-apos-admin-item="events" attribute.
//
// Browser side, you can call `apos.adminBar.link('item-name', function() { ...})`
// to conveniently set up an event handler that fires when this button is clicked.
// Or, if you wish to create an ordinary link, you can pass the `href` option
// as part of the `options` object (fourth argument).
//
// You can use the `after` option to specify an admin bar item name
// this item should appear immediately following.
self.add = function(name, label, permission, options) {
var index;
var item = {
name: name,
label: label,
permission: permission,
options: options || {}
};
if (options && options.after) {
index = _.findIndex(self.items, { name: options.after });
if (index !== -1) {
self.items.splice(index + 1, 0, item);
return;
}
}
self.items.push(item);
};
// Group several menu items together in the interface (currently
// implemented as a dropdown menu). If `items` is an array of menu
// item names, then the group's label is the same as the label of
// the first item. If you wish the label to differ from the label
// of the first item, instead pass an object with a `label` property
// and an `items` property.
self.group = function(items) {
self.groups.push(items);
};
self.addHelpers({
// Render the admin bar. If the user is not able to see any items,
// nothing is rendered
output: function() {
// Find the subset of admin bar items this user is permitted to see
var user = self.apos.templates.contextReq.user;
if (!user) {
return '';
}
var permissions = (user && user._permissions) || {};
var items = _.filter(self.items, function(item) {
if (!item.permission) {
// Being logged in is good enough to see this
return true;
}
return self.apos.permissions.can(self.apos.templates.contextReq, item.permission);
});
if (!items.length) {
return '';
}
// Find the combined items and group them up into menus.
// groupedItems becomes an array that mixes standalone
// admin bar items with menus.
groupedItems = [];
var menu = false;
_.each(items, function(item, i) {
if (menu) {
// We are already building up a grouped menu, but stop doing that
// if this next item isn't part of it
if (item.menuLeader === menu.leader.name) {
menu.items.push(item);
return;
} else {
menu = false;
}
}
// Only build a menu if there are at least two items after filtering
// for permissions
if ((item.menuLeader === item.name) && (items[i + 1] && items[i + 1].menuLeader === item.name)) {
menu = {
menu: true,
items: [ item ],
leader: item,
label: self.groupLabels[item.name] || item.label
};
groupedItems.push(menu);
} else {
groupedItems.push(item);
}
});
return self.partial('adminBar', { items: groupedItems });
}
});
// Like the assets module, we wait as long as humanly possible
// to lock down the list of admin bar items, so that other modules
// can bicker amongst themselves even during the `modulesReady` stage.
// When we get to `afterInit`, we can no longer wait! Order and
// group the admin bar items.
self.afterInit = function() {
self.orderItems();
self.groupItems();
};
// Implement the `order` option. This insertion sort results
// in putting everything otherwise unspecified at the end, as desired.
// Items with the `last: true` option are moved to the end before the
// explicit order is applied.
//
// Called by `afterInit`
self.orderItems = function() {
// Items with a preference to go last go last...
var moving = [];
while (true) {
var moveIndex = _.findIndex(self.items, function(item) {
return item.options.last;
});
if (moveIndex === -1) {
break;
}
moving.push(self.items[moveIndex]);
self.items.splice(moveIndex, 1);
}
self.items = self.items.concat(moving);
// ... But then explicit order kicks in
_.each(self.options.order || [], function(name) {
var item = _.find(self.items, { name: name });
if (item) {
self.items = [ item ].concat(_.filter(self.items, function(item) {
return item.name !== name;
}));
}
});
};
// Marks items that have been grouped via the `groups` option — or via
// `group` calls from modules, combined with the `addGroups` option —
// with a `menuLeader` property and ensures that the items in a group
// are consecutive in the order. We'll figure out the final menus at
// render time so we can handle it properly if an individual
// user only sees one of them, etc. Called by `afterInit`
self.groupItems = function() {
// Implement the groups and addGroups options. Mark the grouped items with a
// `menuLeader` property.
_.each(self.options.groups || self.groups.concat(self.options.addGroups || []), function(group) {
var first = group[0];
if (group.label) {
self.groupLabels[group.items[0]] = group.label;
group = group.items;
}
_.each(group, function(name, groupIndex) {
var item = _.find(self.items, { name: name });
if (item) {
item.menuLeader = group[0];
} else {
return;
}
// Make sure the submenu items wind up following the leader
// in self.items in the appropriate order
if (name !== item.menuLeader) {
var indexLeader = _.findIndex(self.items, { name: item.menuLeader });
if (indexLeader === -1) {
throw new Error('Admin bar grouping error: no match for ' + item.menuLeader + ' in menu item ' + item.name);
}
var indexMe = _.findIndex(self.items, { name: name });
if (indexMe !== (indexLeader + groupIndex)) {
// Swap ourselves into the right position following our leader
if (indexLeader + groupIndex < indexMe) {
indexMe++;
}
self.items.splice(indexLeader + groupIndex, 0, item);
self.items.splice(indexMe, 1);
}
}
});
});
};
self.pushAssets = function() {
self.pushAsset('script', 'user', { when: 'user' });
options.browser = options.browser || {};
self.apos.push.browserCall('user', 'apos.create(?, ?)', self.__meta.name, options.browser);
};
}
};
|
import updateModel from '../actions/updateModel';
export default [
updateModel
];
|
var primitivemap = require('./../primitivemap')
var m = new primitivemap.StringStringMap()
m.put('hello', 'world')
console.log('hello ' + m.get('hello'))
m.put(undefined,undefined)
var lookup = {}
var deleted = {}
for(var i=0;i<100000;++i){
var k = 'key_'+i
var v = 'value_'+i+'_'+Math.random()
lookup[k] = v
m.put(k,v)
if(Math.random() < .2){
deleted[k] = true
m.rm(k)
}
}
Object.keys(lookup).forEach(function(key){
var mv = m.get(key)
var lv = lookup[key]
if(deleted[key]){
if(mv != null) throw new Error('not deleted properly: ' + key)
}else{
if(mv !== lv){
throw new Error('mismatch ' + mv + '|'+lv)
}
}
})
console.log('ok')
|
angular.module('jdFontselect.app', ['jdFontselect']).run(function($rootScope) {
$rootScope.header = '"Underdog", fantasy, "google"';
$rootScope.content = '"Open Sans", sans-serif, "google"';
$rootScope.footer = '"Mate", serif, "google"';
}).config(["jdfsCuratedFontsProvider", function (jdfsCuratedFontsProvider) {
jdfsCuratedFontsProvider.setCuratedFontKeys(['websafe.timesnewroman', 'google.alef']);
}])
angular.bootstrap(document, ['jdFontselect.app']);
|
'use strict';
var gulp = require('gulp'),
// require for gulp-tasks folder
requireDir = require('require-dir');
requireDir('gulp-tasks'); |
var expect = require('chai').expect;
describe('random-natural', function () {
var randomNatural = require('../../');
it('randomNatural()', function () {
expect(randomNatural()).to.be.a('number');
});
it('randomNatural({ max: 2 })', function () {
expect(randomNatural({ max: 2 })).to.be.oneOf([0, 1, 2]);
});
it('randomNatural({ min: 2, max: 10 })', function () {
expect(randomNatural({ min: 2, max: 10 })).to.be.within(2, 10);
});
it('randomNatural({ min: 10, max: 2 })', function () {
expect(randomNatural({ min: 10, max: 2 })).to.be.within(2, 10);
});
it('randomNatural({ min: "2", max: "10" })', function () {
expect(randomNatural({ min: "2", max: "10" })).to.be.within(2, 10);
});
it('randomNatural({ min: "abc", max: { a: 1 } })', function () {
expect(randomNatural({ min: "abc", max: { a: 1 } })).to.be.a('number');
});
it('randomNatural({ min: 0, max: 0 }) should always be 0', function () {
expect(randomNatural({ min: 0, max: 0 })).to.equal(0);
});
it('randomNatural({ min: 1, max: 1, inspected: true }) should always be 1', function () {
expect(randomNatural({ min: 1, max: 1, inspected: true })).to.equal(1);
});
it('randomNatural({ min: -1, max: -1 }) should always be 0', function () {
expect(randomNatural({ min: -1, max: -1 })).to.equal(0);
});
it('randomNatural({ min: 0, max: -1 }) should always be 0', function () {
expect(randomNatural({ min: 0, max: -1 })).to.equal(0);
});
it('randomNatural({ min: -1, max: 0 }) should always be 0', function () {
expect(randomNatural({ min: -1, max: 0 })).to.equal(0);
});
});
|
module.exports = function($stateProvider) {
$stateProvider
.state('app.userProfile', {
url: '/user/:id/profile',
templateUrl: 'js/user/profile/user-profile.html',
controller: 'UserProfileController',
controllerAs: 'vm',
data: {
requiresLogin: true,
pageTitle: 'Profile'
}
});
};
|
angular.module('app')
.directive('fieldZoom', function () {
return {
restrict: 'E',
scope : {
field: '='
},
require : ['^form'],
template: '<div class="field-aria-container">' +
'<div ng-if="field.$viewValue" class="field-aria">{{placeholder}}</div>' +
'</div>',
link: fz_link
}
});
var fz_link = function (scope, el, attr, form) {
scope.placeholder = attr.text;
};
|
const log = require('./log');
function shareFirst(path) {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
}
function maxAgeInvalid(maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
if (this.local) {
if (maxAge === undefined) {
if ((typeof this.remote === 'object') &&
this.remote.connected && this.remote.online) {
maxAge = 2*this.getSyncInterval();
} else {
log('Not setting default maxAge, because remote is offline or not connected');
maxAge = false;
}
}
if (maxAgeInvalid(maxAge)) {
return Promise.reject('Argument \'maxAge\' must be false or a number');
}
return this.local.get(path, maxAge, this.sync.queueGetRequest.bind(this.sync));
} else {
return this.remote.get(path);
}
},
put: function (path, body, contentType) {
if (shareFirst.bind(this)(path)) {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));
}
else if (this.local) {
return this.local.put(path, body, contentType);
} else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));
}
},
'delete': function (path) {
if (this.local) {
return this.local.delete(path);
} else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.delete(path));
}
},
_wrapBusyDone: function (result) {
var self = this;
this._emit('wire-busy');
return result.then(function (r) {
self._emit('wire-done', { success: true });
return Promise.resolve(r);
}, function (err) {
self._emit('wire-done', { success: false });
return Promise.reject(err);
});
}
};
module.exports = SyncedGetPutDelete;
|
// Global Variables
// Meetup.com API Key for Steve Kornahrens
var MeetupKey = "6a3426d1c7d3565234713b22683948"
//Variables needed for Data Gathering and Looping
var GroupEventPairs = {}
var CategoryData = []
var EventData = []
var DateArray
var StartDate
var EndDate
var SetDates
var ZipCity
var ZipCodeChosen = $("#CityFinder").val()
$(document).ready(function() {
window['moment-range'].extendMoment(moment)
// Makes two function calls immediately when document.ready, one to populate Category List and the other to create Tech Event List for 80203
CreateCategoryList()
CreateEvents(34, 80203)
$("#CityFinder").keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
ZipCodeChosen = $("#CityFinder").val()
IsValidZipCode(ZipCodeChosen)
}
})
$("#Categories").change(function() {
ZipCodeChosen = $("#CityFinder").val()
IsValidZipCode(ZipCodeChosen)
})
// Checks if zip entered by user is valid, runs CreateEvents if valid is true
function IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip)
if (isValid) {
$("#ZipError").empty()
var CategoryChosen = $("#Categories").val()
CreateEvents(CategoryChosen, zip)
}
else {
$("#ZipError").text('Sorry, but that\'s an invalid Zip Code')
}
}
// Creates the list of current Event Categories available on Meetup.com
// Called immediately when document is loaded
function CreateCategoryList() {
$.ajax({
method: "GET",
url: "https://galvanize-cors-proxy.herokuapp.com/https://api.meetup.com/2/categories/?key=" + MeetupKey
})
.then(function(GetCategoryData) {
CategoryData.push(GetCategoryData.results)
})
.then(function () {
CategoryData[0].forEach((Category) => {
$('#Categories').append(new Option(Category.sort_name, Category.id))
})
$("#Categories").val("34")
})
}
// Function Called on Document.ready, Zip Code change, and Event Category change
// Creates Event List, changes " "'s Upcoming Events to zip's city, and creates date range based of range from EventData index 0 to last index
function CreateEvents(Category, Zipcode) {
//Clears Events and EventData for Get Call
$("#EventList").empty()
EventData = []
$("#OneSecFindingResults").removeClass("hide")
$.when(
$.ajax({
method: "GET",
url: "https://galvanize-cors-proxy.herokuapp.com/https://api.meetup.com/2/open_events?&sign=true&photo-host=public&zip="+ Zipcode + "&country=United%20States&city=Denver&state=CO&category=" + Category + "&time=,1w&radius=10&key=" + MeetupKey
}),
$.ajax({
method: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json?address="+ Zipcode + "&sensor=true"
})
)
.then(function (GetEventData, GetZipCity) {
EventData.push(GetEventData[0].results)
ZipCity = GetZipCity[0].results[0].address_components[2].long_name
var CategoryTitle = $("#Categories").find(":selected").text()
if (EventData[0].length == 0) {
throw new Error("Sorry no upcoming " + CategoryTitle + " Events found for " + ZipCity)
}
})
.then(function(){
$('#CityEventTitle').text(ZipCity + "'s Upcoming Events")
})
//Creates an array of Dates from first array index to last array index
.then(function () {
$("#OneSecFindingResults").addClass("hide")
var count = 0
StartDate = new Date(EventData[0][0].time)
EndDate = new Date(EventData[0][EventData[0].length - 1].time)
RangeOfDates = moment.range(StartDate, EndDate)
DateArray = Array.from(RangeOfDates.by('day'))
DateArray.map(m => m.format('DD'))
DateArray.forEach((datefound) => {
var DateToSet = moment(datefound._d).format("dddd, MMMM Do")
var DayCount = "Day" + count
$('#EventList').append(`
<div id=${DayCount} class="animated fadeInLeft DateAdded">
<h2 class="SetDate">${DateToSet}</h2>
</div>
`)
count++
})
SetDates = $(".SetDate")
})
.then(function () {
var EventCount = 0
EventData[0].forEach((EventFound) => {
Array.from(SetDates).forEach((datefound) => {
// DateToSet = moment(datefound._d).format("dddd, MMMM Do")
if (moment(EventFound.time).format("dddd, MMMM Do") === datefound.innerHTML) {
//Convert Event's Time to usable format
var Time = moment(EventFound.time).format("h:mma")
//if statement to check if the EventFound contains a venue key
var EventLoc
if (!EventFound.venue) {
EventLoc = "Location Not Selected"
} else {
EventLoc = EventFound.venue.name
}
$(datefound).parent().append(`
<a class="EventLink" href="${EventFound.event_url}" target="_blank">
<div id="Event${EventCount}" class="Event animated fadeInLeft">
<div class="EventLeft">
<p class="EventTimeDate">${Time}</p>
</div>
<div class="EventRight">
<h4 class="EventName">${EventFound.name}</h4>
<h4 class="GroupName">${EventFound.group.name}</h4>
<h5 class="EventLocation">${EventLoc}</h5>
</div>
</div>
</a>
`)
// use below for icon link
// <i class="material-icons NTicon">open_in_new</i>
//Creates Object Key Event# with array value Group Name and Event ID numbers for each event
GroupEventPairs["Event" + EventCount] = []
GroupEventPairs["Event" + EventCount].push(EventFound.group.urlname)
GroupEventPairs["Event" + EventCount].push(EventFound.id)
EventCount++
}
})
})
})
.then(function() {
var DateAdd = $('.DateAdded')
Array.from(DateAdd).forEach((datefound) => {
if($(datefound).children().length < 2) {
$(datefound).append(`
<h5 class="NoEvent">No Events Today.</h5>`)
}
})
})
.catch(function (error) {
$("#OneSecFindingResults").addClass("hide")
$("#CityEventTitle").text(error.message)
})
}
//Event Listener for Hightlighting Events
$('#EventList').on('mouseenter', '.Event', function() {
$(this).toggleClass("EventHovered");
});
$('#EventList').on('mouseleave', '.Event', function() {
$(this).toggleClass("EventHovered");
});
})
|
const fs = require('fs-extra')
const gulp = require('gulp')
const handlebars = require('handlebars')
const autoprefixer = require('gulp-autoprefixer')
const clean = require('gulp-clean-css')
const connect = require('gulp-connect')
const sass = require('gulp-sass')
gulp.task('connect', () =>
connect.server({
livereload: true,
root: 'public'
})
)
gulp.task('livereload', () => gulp.src('./public/**/*').pipe(connect.reload()))
gulp.task('watch', () => {
gulp.watch('./src/stylesheets/*.scss', ['stylesheets'])
gulp.watch('./src/data.json', ['templates'])
gulp.watch('./src/templates/*.hbs', ['templates'])
gulp.watch('./public/**/*', ['livereload'])
})
gulp.task('dev', ['connect', 'watch', 'default'])
gulp.task('stylesheets', () =>
gulp
.src('./src/stylesheets/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(clean())
.pipe(gulp.dest('./public/assets/css/'))
.pipe(connect.reload())
)
gulp.task('templates', async () => {
const load = name =>
new Promise(resolve => {
fs.readFile(
`./src/templates/${name}.hbs`,
{
encoding: 'utf8'
},
(err, template) => {
resolve({
name: name,
template: template
})
}
)
})
const data = await fs.readJson('src/data.json')
const templates = ['footer', 'header', 'main', 'nav'].map(name =>
fs
.readFile(`src/templates/${name}.hbs`, 'utf8')
.then(template => handlebars.registerPartial(name, template))
)
await Promise.all(templates)
const layout = await fs.readFile('src/templates/layout.hbs', 'utf8')
const template = handlebars.compile(layout)
const html = template(data)
await fs.outputFile('public/index.html', html)
connect.reload()
})
gulp.task('default', ['stylesheets', 'templates'])
|
var SchemaObject = require('node-schema-object');
var NotEmptyString = require('./NotEmptyString');
var Resource = new SchemaObject(
{
id: NotEmptyString,
text: NotEmptyString,
amount: Number,
maxAmount: Number,
usable: Boolean,
requirement: String
}
);
module.exports = Resource; |
export function isLoadSuccess (state) {
let comp = state.app.globalData.components;
comp = comp == undefined ? 0 : comp;
return state.app.loadedCompNum == comp.length ;
} |
const sec = 1000;
const min = 60 * sec;
export const GAME_INACTIVE_TIMEOUT = 30 * sec;
export const GAME_EXPIRE_TIMEOUT = 15 * min;
export const ACTION_STATS_FLUSH_INTERVAL = 5 * sec;
export const ACTION_STATS_FLUSH_DELAY = 1 * sec;
|
/*
* $Id: MooEditable.js 68 2008-11-13 16:00:18Z tjleahy.jr@gmail.com $
*
* The MIT License
*
* Copyright (c) 2007, 2008 Lim Chee Aun <cheeaun@gmail.com>
*
* 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.
*/
/**
* MooEditable.js
* MooEditable class for contentEditable-capable browsers
*
* @package MooEditable
* @subpackage Core
* @author Lim Chee Aun <cheeaun@gmail.com>
* @author Marc Fowler <marc.fowler@defraction.net>
* @author Radovan Lozej <http://xrado.hopto.org/>
* @author mindplay.dk <http://www.mindplay.dk/>
* @author T.J. Leahy <tjleahy.jr [at] gmail [dot] com>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @link http://code.google.com/p/mooeditable/
* @since 1.0
* @version $Revision: 8 $
* @credits Most code is based on Stefan's work "Safari Supports Content Editing!"
* <http://www.xs4all.nl/~hhijdra/stefan/ContentEditable.html>
* Main reference from Peter-Paul Koch's "execCommand compatibility" research
* <http://www.quirksmode.org/dom/execCommand.html>
* Some ideas inspired by TinyMCE <http://tinymce.moxiecode.com/>
* Some functions inspired by Inviz's "Most tiny wysiwyg you ever seen"
* <http://forum.mootools.net/viewtopic.php?id=746>,
* <http://forum.mootools.net/viewtopic.php?id=5740>
* Some regex from Cameron Adams's widgEditor
* <http://themaninblue.com/experiment/widgEditor/>
* Some code from Juan M Martinez's jwysiwyg, the WYSIWYG jQuery Plugin
* <http://projects.bundleweb.com.ar/jWYSIWYG/>,
* <http://code.google.com/p/jwysiwyg/>
* Some reference from MoxieForge's PunyMCE
* <http://code.google.com/p/punymce/>
* IE support referring Robert Bredlau's "Rich Text Editing" part 1 and 2 articles
* <http://www.rbredlau.com/drupal/node/6>
* Tango icons from the Tango Desktop Project
* <http://tango.freedesktop.org/>
* Additional tango icons from Tango OpenOffice set by Jimmacs
* <http://www.gnome-look.org/content/show.php/Tango+OpenOffice?content=54799>
*/
var MooEditable = new Class({
Implements: [Events, Options],
options:{
toolbar: true,
cleanup: true,
paragraphise: true,
xhtml : true,
semantics : true,
buttons: 'bold,italic,underline,strikethrough,|,insertunorderedlist,insertorderedlist,indent,outdent,|,undo,redo,|,createlink,unlink,|,urlimage,|,toggleview',
mode: 'icons'
},
initialize: function(el,options) {
this.setOptions(options);
this.textarea = el;
this.build();
},
build: function() {
var self = this;
// Build the container
this.container = new Element('div',{
'id': (this.textarea.id) ? this.textarea.id+'-container' : null,
'class': 'mooeditable-container',
'styles': {
'width': this.textarea.getSize().x,
'margin': this.textarea.getStyle('margin')
}
});
// Put textarea inside container
this.container.wraps(this.textarea);
// Fix IE bug, refer "IE/Win Inherited Margins on Form Elements" <http://positioniseverything.net/explorer/inherited_margin.html>
if(Browser.Engine.trident) new Element('span').wraps(this.textarea);
// Build the iframe
var pads = this.textarea.getStyle('padding').split(' ');
pads = pads.map(function(p) { return (p == 'auto') ? 0 : p.toInt(); });
this.iframe = new IFrame({
'class': 'mooeditable-iframe',
'styles': {
'width': this.textarea.getStyle('width').toInt() + pads[1] + pads[3],
'height': this.textarea.getStyle('height').toInt() + pads[0] + pads[2],
'border-color': this.textarea.getStyle('border-color'),
'border-width': this.textarea.getStyle('border-width'),
'border-style': this.textarea.getStyle('border-style')
}
});
this.textarea.setStyles({
'margin': 0,
'display': 'none',
'resize': 'none', // disable resizable textareas in Safari
'outline': 'none' // disable focus ring in Safari
});
this.iframe.inject(this.container, 'top');
// contentWindow and document references
this.win = this.iframe.contentWindow;
this.doc = this.win.document;
// Build the content of iframe
var documentTemplate = '\
<html style="cursor: text; height: 100%">\
<head>' + (this.options.cssPath ? "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.options.cssPath + "\" />" : "") + '</head>\
<body id=\"editable\"' + (this.options.cssClass ? " class=\"" + this.options.cssClass + "\"" : "") + ' style="font-family: sans-serif; border: 0">'+
this.doCleanup(this.textarea.get('value')) +
'</body>\
</html>\
';
this.doc.open();
this.doc.write(documentTemplate);
this.doc.close();
// Turn on Design Mode
// IE fired load event twice if designMode is set
(Browser.Engine.trident) ? this.doc.body.contentEditable = true : this.doc.designMode = 'On';
// Assign view mode
this.mode = 'iframe';
// Update the event for textarea's corresponding labels
if (this.textarea.id) $$('label[for="'+this.textarea.id+'"]').addEvent('click', function(e) {
if(self.mode == 'iframe') {
e = new Event(e).stop();
self.focus();
}
});
// Update & cleanup content before submit
this.form = this.textarea.getParent('form');
if (this.form) this.form.addEvent('submit',function() {
if(self.mode=='iframe') self.saveContent();
});
// document.window for IE, for new Document code below
if (Browser.Engine.trident) this.doc.window = this.win;
// Mootoolize document and body
if (!this.doc.$family) new Document(this.doc);
$(this.doc.body);
this.doc.addEvents({
'keypress': this.keyListener.bind(this),
'keydown': this.enterListener.bind(this)
});
this.textarea.addEvent('keypress', this.keyListener.bind(this));
var styleCSS = function() {
// styleWithCSS, not supported in IE and Opera
if (!['trident', 'presto'].contains(Browser.Engine.name)) self.execute('styleWithCSS', false, false);
self.doc.removeEvent('focus', styleCSS);
}
this.doc.addEvent('focus', styleCSS);
// make images selectable and draggable in Safari
if (Browser.Engine.webkit) this.doc.addEvent('click', function(e){
var el = e.target;
if (el.get('tag') == 'img') self.selectNode(el);
});
if (this.options.toolbar) {
this.buildToolbar();
this.doc.addEvents({
'keyup': this.checkStates.bind(this),
'mouseup': this.checkStates.bind(this)
});
}
this.selection = new MooEditable.Selection(this);
},
buildToolbar: function() {
var self = this;
this.toolbar = new Element('div',{ 'class': 'mooeditable-toolbar' }).inject(this.iframe, 'before');
this.keys = [];
var buttons = [];
var toolbarButtons = this.options.buttons.split(',');
toolbarButtons.each(function(command, idx) {
var b;
if (command == '|') b = new Element('span',{ 'class': 'toolbar-separator' });
else{
b = new Element('button',{
'class': command+'-button toolbar-button',
'title': MooEditable.Actions[command]['title'] + ((MooEditable.Actions[command]['shortcut']) ? ' ( Ctrl+' + MooEditable.Actions[command]['shortcut'].toUpperCase() + ' )' : ''),
'events': {
'click': function(e) {
e.stop();
if (!this.hasClass('disabled') ) {
self.focus();
self.action(command);
if (self.mode == 'iframe') self.checkStates();
}
},
'mousedown': function(e) { e.stop(); }
}
});
// apply toolbar mode
b.addClass(MooEditable.Actions[command]['mode'] || self.options.mode);
// add hover effect for IE
if(Browser.Engine.trident) b.addEvents({
'mouseenter': function(e) { this.addClass('hover'); },
'mouseleave': function(e) { this.removeClass('hover'); }
});
// shortcuts
var key = MooEditable.Actions[command]['shortcut'];
if (key) self.keys[key] = b;
b.set('text', MooEditable.Actions[command]['title']);
buttons.push(b);
}
b.inject(self.toolbar);
});
this.toolbarButtons = new Elements(buttons);
},
keyListener: function(e) {
if (e.control && this.keys[e.key]) {
e.stop();
this.keys[e.key].fireEvent('click', e);
}
},
insertBreak : function(e) {
if (!Browser.Engine.trident) return true;
var r = this.selection.getRange();
var node = this.selection.getNode();
if (node.get('tag') != 'li') {
if (r) {
this.selection.insertContent("<br class='mooeditable-skip'>");
this.selection.collapse(false);
}
e.stop();
}
},
enterListener: function(e) {
if (e.key == 'enter') {
if (this.options.paragraphise && e.shift) {
this.insertBreak(e);
}
else if (this.options.paragraphise) {
if (Browser.Engine.gecko || Browser.Engine.webkit) {
var node = this.selection.getNode();
if (node.get('tag') != 'li') this.execute('insertparagraph');
}
}
//make IE insert <br> instead of <p></p>
else {
this.insertBreak(e);
}
}
},
focus: function() {
(this.mode=='iframe' ? this.win : this.textarea).focus();
return this;
},
action: function(command) {
var action = MooEditable.Actions[command];
var args = action.arguments || [];
if (action.command)
($type(action.command) == 'function') ? action.command.attempt(args, this) : this.execute(action.command, false, args);
else
this.execute(command, false, args);
},
execute: function(command, param1, param2) {
if (!this.busy) {
this.busy = true;
this.doc.execCommand(command, param1, param2);
this.saveContent();
this.busy = false;
}
return false;
},
toggleView: function() {
if (this.mode == 'textarea') {
this.mode = 'iframe';
this.iframe.setStyle('display', '');
this.setContent(this.textarea.value);
this.enableToolbar();
this.textarea.setStyle('display', 'none');
} else {
this.saveContent();
this.mode = 'textarea';
this.textarea.setStyle('display', '');
this.disableToolbar('toggleview');
this.iframe.setStyle('display', 'none');
}
// toggling from textarea to iframe needs the delay to get focus working
(function() { this.focus(); }).bind(this).delay(10);
return this;
},
disableToolbar: function(b) {
this.toolbarButtons.each(function(item) {
(!item.hasClass(b+'-button')) ? item.addClass('disabled').set('opacity', 0.4) : item.addClass('onActive');
});
return this;
},
enableToolbar: function() {
this.toolbarButtons.removeClass('disabled').removeClass('onActive').set('opacity', 1);
return this;
},
getContent: function() {
return this.doCleanup(this.doc.getElementById('editable').innerHTML);
},
setContent: function(newContent) {
(function() {
$(this.doc.getElementById('editable')).set('html', newContent);
}).bind(this).delay(1); // dealing with Adobe AIR's webkit bug
return this;
},
saveContent: function() {
if(this.mode == 'iframe') this.textarea.set('value', this.getContent());
return this;
},
checkStates: function() {
MooEditable.Actions.each(function(action, command) {
var button = this.toolbarButtons.filter('.' + command + '-button');
if (!button) return;
button.removeClass('active');
if (action.tags) {
var el = this.selection.getNode();
if (el) do {
if ($type(el) != 'element') break;
if (action.tags.contains(el.tagName.toLowerCase()))
button.addClass('active');
}
while (el = el.parentNode);
}
if(action.css) {
var el = this.selection.getNode();
if (el) do {
if ($type(el) != 'element') break;
for (var prop in action.css)
if ($(el).getStyle(prop).contains(action.css[prop]))
button.addClass('active');
}
while (el = el.parentNode);
}
}.bind(this));
},
cleanup: function(source) {
if(!this.options.cleanup) return source.trim();
// Webkit cleanup
source = source.replace(/<br class\="webkit-block-placeholder">/gi, "<br />");
source = source.replace(/<span class="Apple-style-span">(.*)<\/span>/gi, '$1');
source = source.replace(/ class="Apple-style-span"/gi, '');
source = source.replace(/<span style="">/gi, '');
// Remove padded paragraphs
source = source.replace(/<p>\s*<br ?\/?>\s*<\/p>/gi, '<p>\u00a0</p>');
source = source.replace(/<p>( |\s)*<\/p>/gi, '<p>\u00a0</p>');
if (!this.options.semantics) {
source = source.replace(/\s*<br ?\/?>\s*<\/p>/gi, '</p>');
}
// Replace improper BRs (only if XHTML : true)
if (this.options.xhtml) {
source = source.replace(/<br>/gi, "<br />");
}
if (this.options.semantics) {
//remove divs from <li>
if (Browser.Engine.trident) {
source = source.replace(/<li>\s*<div>(.+?)<\/div><\/li>/g, '<li>$1</li>');
}
//remove stupid apple divs
if (Browser.Engine.webkit) {
source = source.replace(/^([\w\s]+.*?)<div>/i, '<p>$1</p><div>');
source = source.replace(/<div>(.+?)<\/div>/ig, '<p>$1</p>');
}
//<p> tags around a list will get moved to after the list
if (['gecko', 'presto','webkit'].contains(Browser.Engine.name)) {
//not working properly in safari?
source = source.replace(/<p>[\s\n]*(<(?:ul|ol)>.*?<\/(?:ul|ol)>)(.*?)<\/p>/ig, '$1<p>$2</p>');
source = source.replace(/<\/(ol|ul)>\s*(?!<(?:p|ol|ul|img).*?>)((?:<[^>]*>)?\w.*)$/g, '</$1><p>$2</p>');
}
source = source.replace(/<br[^>]*><\/p>/g, '</p>'); //remove <br>'s that end a paragraph here.
source = source.replace(/<p>\s*(<img[^>]+>)\s*<\/p>/ig, '$1\n'); //if a <p> only contains <img>, remove the <p> tags
//format the source
source = source.replace(/<p([^>]*)>(.*?)<\/p>(?!\n)/g, '<p$1>$2</p>\n'); //break after paragraphs
source = source.replace(/<\/(ul|ol|p)>(?!\n)/g, '</$1>\n'); //break after </p></ol></ul> tags
source = source.replace(/><li>/g, '>\n\t<li>'); //break and indent <li>
source = source.replace(/([^\n])<\/(ol|ul)>/g, '$1\n</$2>'); //break before </ol></ul> tags
source = source.replace(/([^\n])<img/ig, '$1\n<img'); //move images to their own line
source = source.replace(/^\s*$/g, ''); //delete empty lines in the source code (not working in opera)
}
// Remove leading and trailing BRs
source = source.replace(/<br ?\/?>$/gi, '');
source = source.replace(/^<br ?\/?>/gi, '');
// Remove useless BRs
source = source.replace(/><br ?\/?>/gi, '>');
// Remove BRs right before the end of blocks
source = source.replace(/<br ?\/?>\s*<\/(h1|h2|h3|h4|h5|h6|li|p)/gi, '</$1');
// Semantic conversion
source = source.replace(/<span style="font-weight: bold;">(.*)<\/span>/gi, '<strong>$1</strong>');
source = source.replace(/<span style="font-style: italic;">(.*)<\/span>/gi, '<em>$1</em>');
source = source.replace(/<b(?!r)[^>]*>(.*?)<\/b[^>]*>/gi, '<strong>$1</strong>')
source = source.replace(/<i[^>]*>(.*?)<\/i[^>]*>/gi, '<em>$1</em>')
source = source.replace(/<u(?!l)[^>]*>(.*?)<\/u[^>]*>/gi, '<span style="text-decoration: underline;">$1</span>')
// Replace uppercase element names with lowercase
source = source.replace(/<[^> ]*/g, function(match){return match.toLowerCase();});
// Replace uppercase attribute names with lowercase
source = source.replace(/<[^>]*>/g, function(match){
match = match.replace(/ [^=]+=/g, function(match2){return match2.toLowerCase();});
return match;
});
// Put quotes around unquoted attributes
source = source.replace(/<[^>]*>/g, function(match){
match = match.replace(/( [^=]+=)([^"][^ >]*)/g, "$1\"$2\"");
return match;
});
//make img tags xhtml compatable
// if (this.options.xhtml) {
// source = source.replace(/(<(?:img|input)[^/>]*)>/g, '$1 />');
// }
//remove double <p> tags and empty <p> tags
source = source.replace(/<p>(?:\s*)<p>/g, '<p>');
source = source.replace(/<\/p>\s*<\/p>/g, '</p>');
source = source.replace(/<p>\W*<\/p>/g, '');
// Final trim
source = source.trim();
return source;
},
doCleanup : function(source) {
do {
var oSource = source;
source = this.cleanup(source);
} while (source != oSource);
return source;
}
});
MooEditable.Selection = new Class({
initialize: function(editor) {
this.win = editor.win;
this.doc = editor.doc;
},
getSelection: function() {
return (this.win.getSelection) ? this.win.getSelection() : this.doc.selection;
},
getRange: function() {
var s = this.getSelection();
if (!s) return null;
try {
return s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : null);
} catch (e) {
// IE bug when used in frameset
return this.doc.body.createTextRange();
}
},
setRange: function(range) {
if (range.select) $try(function(){
range.select();
});
else {
var s = this.getSelection();
if (s.addRange) {
s.removeAllRanges();
s.addRange(range);
}
}
},
selectNode: function(node, collapse) {
var r = this.getRange();
var s = this.getSelection();
if (r.moveToElementText) $try(function(){
r.moveToElementText(node);
r.select();
});
else if (s.addRange) {
collapse ? r.selectNodeContents(node) : r.selectNode(node);
s.removeAllRanges();
s.addRange(r);
} else
s.setBaseAndExtent(node, 0, node, 1);
return node;
},
isCollapsed: function() {
var r = this.getRange();
if (r.item) return false;
return r.boundingWidth == 0 || this.getSelection().isCollapsed;
},
collapse: function(toStart) {
var r = this.getRange();
var s = this.getSelection();
if (r.select) {
r.collapse(toStart);
r.select();
}
else
toStart ? s.collapseToStart() : s.collapseToEnd();
},
getContent: function() {
var r = this.getRange();
var body = new Element('body');
if (this.isCollapsed()) return '';
if (r.cloneContents) body.appendChild(r.cloneContents());
else if ($defined(r.item) || $defined(r.htmlText)) body.set('html', r.item ? r.item(0).outerHTML : r.htmlText);
else body.set('html', r.toString());
var content = body.get('html');
return content;
},
getText : function() {
var r = this.getRange();
var s = this.getSelection();
return this.isCollapsed() ? '' : r.text || s.toString();
},
getNode: function() {
var r = this.getRange();
if (!Browser.Engine.trident) {
var el = null;
if (r) {
el = r.commonAncestorContainer;
// Handle selection a image or other control like element such as anchors
if (!r.collapsed)
if (r.startContainer == r.endContainer)
if (r.startOffset - r.endOffset < 2)
if (r.startContainer.hasChildNodes())
el = r.startContainer.childNodes[r.startOffset];
while ($type(el) != 'element') el = el.parentNode;
}
return el;
}
return r.item ? r.item(0) : r.parentElement();
},
insertContent: function(content) {
var r = this.getRange();
if (r.insertNode) {
r.deleteContents();
r.insertNode(r.createContextualFragment(content));
}
else {
// Handle text and control range
if (r.pasteHTML) r.pasteHTML(content);
else r.item(0).outerHTML = content;
}
}
});
MooEditable.Actions = new Hash({
bold: { title: 'Bold', shortcut: 'b', tags: ['b','strong'], css: {'font-weight':'bold'} },
italic: { title: 'Italic', shortcut: 'i', tags: ['i','em'], css: {'font-style':'italic'} },
underline: { title: 'Underline', shortcut: 'u', tags: ['u'], css: {'text-decoration':'underline'} },
strikethrough: { title: 'Strikethrough', shortcut: 's', tags: ['s','strike'], css: {'text-decoration':'line-through'} },
insertunorderedlist: { title: 'Unordered List', tags: ['ul'] },
insertorderedlist: { title: 'Ordered List', tags: ['ol'] },
indent: { title: 'Indent', tags: ['blockquote'] },
outdent: { title: 'Outdent' },
undo: { title: 'Undo', shortcut: 'z' },
redo: { title: 'Redo', shortcut: 'y' },
unlink: { title: 'Remove Hyperlink' },
createlink: {
title: 'Add Hyperlink',
shortcut: 'l',
tags: ['a'],
command: function() {
if (this.selection.getSelection() == '')
MooEditable.Dialogs.alert(this, 'createlink', 'Please select the text you wish to hyperlink.');
else
MooEditable.Dialogs.prompt(this, 'createlink', 'Enter url','http://', function(url) {
this.execute('createlink', false, url.trim());
}.bind(this));
}
},
urlimage: {
title: 'Add Image',
shortcut: 'm',
command: function() {
MooEditable.Dialogs.prompt(this, 'urlimage', 'Enter image url','http://', function(url) {
this.execute("insertimage", false, url.trim());
}.bind(this));
}
},
toggleview: {
title: 'Toggle View',
shortcut: 't',
command: function() { this.toggleView(); }
}
});
MooEditable.Dialogs = new Hash({
alert: function(me, el, str) {
// Adds the alert bar
if (!me.alertbar) {
me.alertbar = new Element('div', { 'class': 'alertbar dialog-toolbar' });
me.alertbar.inject(me.toolbar, 'after');
me.alertbar.strLabel = new Element('span', { 'class': 'alertbar-label' });
me.alertbar.okButton = new Element('button', {
'class': 'alertbar-ok input-button',
'text': 'OK',
'events': {
'click': function(e) {
e.stop();
me.alertbar.setStyle('display','none');
me.enableToolbar();
me.doc.removeEvents('mousedown');
}
}
});
new Element('div').adopt(me.alertbar.strLabel, me.alertbar.okButton).inject(me.alertbar);
}
else if (me.alertbar.getStyle('display') == 'none') me.alertbar.setStyle('display', '');
me.alertbar.strLabel.set('text', str);
me.alertbar.okButton.focus();
me.doc.addEvent('mousedown', function(e) { e.stop(); });
me.disableToolbar(el);
},
prompt: function(me, el, q, a, fn) {
me.range = me.selection.getRange(); // store the range
// Adds the prompt bar
if (!me.promptbar) {
me.promptbar = new Element('div', { 'class': 'promptbar dialog-toolbar' });
me.promptbar.inject(me.toolbar, 'after');
me.promptbar.qLabel = new Element('label', {
'class': 'promptbar-label',
'for': 'promptbar-'+me.container.uid
});
me.promptbar.aInput = new Element('input', {
'class': 'promptbar-input input-text',
'id': 'promptbar-'+me.container.uid,
'type': 'text'
});
me.promptbar.okButton = new Element('button', {
'class': 'promptbar-ok input-button',
'text': 'OK'
});
me.promptbar.cancelButton = new Element('button', {
'class': 'promptbar-cancel input-button',
'text': 'Cancel',
'events': {
'click': function(e) {
e.stop();
me.promptbar.setStyle('display','none');
me.enableToolbar();
me.doc.removeEvents('mousedown');
}
}
});
new Element('div').adopt(me.promptbar.qLabel, me.promptbar.aInput, me.promptbar.okButton, me.promptbar.cancelButton).inject(me.promptbar);
}
else if (me.promptbar.getStyle('display') == 'none') me.promptbar.setStyle('display', '');
// Update the fn for the OK button event (memory leak?)
me.promptbar.okButton.addEvent('click', function(e){
e.stop();
me.selection.setRange(me.range);
fn(me.promptbar.aInput.value);
me.promptbar.setStyle('display','none');
me.enableToolbar();
me.doc.removeEvents('mousedown');
this.removeEvents('click');
});
// Set the label and input
me.promptbar.qLabel.set('text', q);
me.promptbar.aInput.set('value', a);
me.promptbar.aInput.focus();
// Disables iframe and toolbar
me.doc.addEvent('mousedown', function(e) { e.stop(); });
me.disableToolbar(el);
}
});
Element.Properties.mooeditable = {
get : function() {
return this.retrieve('mooeditable');
},
set : function(options) {
var temp = new MooEditable(this, options);
this.store('mooeditable', temp);
return temp;
}
}
Element.implement({
mooEditable: function(options) {
return this.set('mooeditable', options);
}
}); |
(function () {
'use strict';
var module = angular.module('np.common', []);
module.factory('np.common.requestFactory', [
'$log', '$q', '$http',
function (console, Q, http) {
return function (config) {
return function (method, path, data, params) {
var req = {
method: method,
url: config.endpoint + path,
headers: {Accept: 'application/json'}
//withCredentials: true
};
if (method == 'GET' || method == 'DELETE') {
req.params = data;
} else {
req.headers['Content-Type'] = 'application/json;charset=utf8';
req.data = data;
req.params = params;
}
//if (config.authorization) {
// req.headers.Authorization = 'Bearer ' + SHA1(key + secret + nonce) + nonce
//}
return http(req).then(function (res) {
console.log('***request ', req.method, req.url, 'ok:', res.status);
return res.data;
}, function (res) {
console.log('***request ', req.method, req.url, 'err:', res.status);
var error = (res.data && res.data.status) ? res.data : {
status: res.status,
message: String(res.data)
};
return Q.reject(error);
});
};
};
}
]);
}());
|
"use strict";
const {EventEmitter} = require('events');
const dface = require('dface');
const {format} = require('util');
const WebSocket = require('ws');
const errors = require('./errors');
const PROTOCOL_VERSION_ARRAY = [1, 0];
const PROTOCOL_VERSION = '1.0';
class VertexSocket extends EventEmitter {
static connect(config = {}) {
return new Promise((resolve, reject) => {
config.port = config.port || 65535;
config.host = dface(config.host) || '127.0.0.1';
config.protocol = config.protocol || 'ws';
const url = format('%s://%s:%s', config.protocol, config.host, config.port);
const socket = new WebSocket(url, config.protocols, config.options);
const vertexSocket = new VertexSocket(socket, config);
const onError = error => {
vertexSocket.removeListener('connected', onConnected);
reject(error);
};
const onConnected = () => {
vertexSocket.removeListener('error', onError);
resolve(vertexSocket);
};
vertexSocket.once('error', onError);
vertexSocket.once('connect', onConnected);
});
}
constructor(socket, config = {}) {
super();
this._socket = socket;
this._config = config;
this._sequence = 0;
this._waiting = {};
this._onErrorListener = this._onError.bind(this);
this._onOpenListener = this._onOpen.bind(this);
this._onCloseListener = this._onClose.bind(this);
this._onMessageListener = this._onMessage.bind(this);
this._onPingListener = this._onPing.bind(this);
this._onPongListener = this._onPong.bind(this);
socket.on('error', this._onErrorListener);
socket.on('open', this._onOpenListener);
socket.on('close', this._onCloseListener);
socket.on('message', this._onMessageListener);
socket.on('ping', this._onPingListener);
socket.on('pong', this._onPongListener);
}
address() {
try {
return this._socket._socket.address();
} catch (e) {
/* gone after the socket is closed */
}
}
remoteAddress() {
try {
return {
address: this._socket._socket.remoteAddress,
family: this._socket._socket.remoteFamily,
port: this._socket._socket.remotePort
}
} catch (e) {
/* gone after the socket is closed */
}
}
close(code = 1001, message = 'going away') {
if (!this._socket) return;
if (!code) code = 1001;
this._socket.close(code, message);
}
terminate(error) {
if (!this._socket) return;
if (error) this.emit('error', error);
this._socket.terminate();
}
pause() {
if (!this._socket) return;
return this._socket.pause();
}
resume() {
if (!this._socket) return;
return this._socket.resume();
}
ping(data) {
if (!this._socket) return;
// this._socket.ping.apply(this._socket, arguments);
this._socket.ping(data);
}
send(data, timeout) {
return new Promise((resolve, reject) => {
if (!this._socket || this._socket.readyState != WebSocket.OPEN) {
return reject(new errors.VertexSocketClosedError('Cannot write'));
}
const sequence = this._nextSequence();
const ts = Date.now();
const meta = {
seq: sequence,
ts: ts
};
let encoded;
try {
encoded = this._encode(data, meta);
}
catch (error) {
return reject(error);
}
this._waiting[sequence] = {
resolve: resolve,
reject: reject,
ts: ts
};
if (timeout && typeof timeout == 'number') {
this._waiting[sequence].timeout = setTimeout(() => {
this._waiting[sequence].reject(
new errors.VertexSocketTimeoutError('Ack timeout', meta)
);
delete this._waiting[sequence];
}, timeout);
}
this._socket.send(encoded);
if (meta.buffer) this._socket.send(data);
});
}
_onError(error) {
this.emit('error', error);
}
_onOpen() {
this.emit('connect');
}
_onClose(code, message) {
if (code == 1003) this.emit('error', new errors.VertexSocketDataError(message));
this.emit('close', code, message);
if (!this._socket) return;
this._socket.removeListener('error', this._onErrorListener);
this._socket.removeListener('open', this._onOpenListener);
this._socket.removeListener('close', this._onCloseListener);
this._socket.removeListener('message', this._onMessageListener);
this._socket.removeListener('ping', this._onPingListener);
this._socket.removeListener('pong', this._onPongListener);
delete this._socket;
Object.keys(this._waiting).forEach(sequence => {
clearTimeout(this._waiting[sequence].timeout);
this._waiting[sequence].reject(
new errors.VertexSocketClosedError('Closed while awaiting ack', {
seq: parseInt(sequence),
ts: this._waiting[sequence].ts
})
);
delete this._waiting[sequence];
});
}
_onMessage(message, detail) {
let version, meta, data;
if (detail.binary) {
meta = this._waitingMeta;
meta.len = detail.buffer.length;
data = message;
delete this._waitingMeta;
}
else {
try {
let dataPosition = message.indexOf('[');
version = message.substring(0, dataPosition).split('.');
if (version[0] != PROTOCOL_VERSION_ARRAY[0]) {
throw new Error('Protocol mismatch');
}
[meta, data] = JSON.parse(message.substring(dataPosition));
}
catch (error) {
try {
this.emit('error', new errors.VertexSocketDataError(error.toString(), this.remoteAddress()));
}
catch (e) {
/* in case of no error handler */
}
this.close(1003, error.toString());
return;
}
if (!meta || typeof meta.seq !== 'number') {
try {
this.emit('error', new errors.VertexSocketDataError('Missing meta', this.remoteAddress()));
}
catch (e) {
/* in case of no error handler */
}
this.close(1003, 'Missing meta');
return;
}
meta.len = detail.buffer.length;
if (meta.ack || meta.nak) {
if (!this._waiting[meta.seq]) {
try {
this.emit('error', new errors.VertexSocketReplyError('Stray ack or nak', {meta: meta, data: data}));
}
catch (e) {
/* in case of no error handler */
}
return;
}
clearTimeout(this._waiting[meta.seq].timeout);
if (meta.nak) {
this._waiting[meta.seq].reject(this._format(meta, data));
delete this._waiting[meta.seq];
return;
}
this._waiting[meta.seq].resolve(this._format(meta, data));
delete this._waiting[meta.seq];
return;
}
if (meta.buffer) {
this._waitingMeta = meta;
return;
}
}
let replies, tags = 0;
let replyFn = (tag, promise) => {
if (typeof promise == 'undefined') {
promise = tag;
tag = tags++;
}
replies = replies || {};
replies[tag] = promise;
};
try {
this.emit('data', data, meta, replyFn);
}
catch (error) {
/* unhandled error in one of on('data') handlers, server will now crash, no ACK, no NAK */
throw error;
}
let response = {meta: meta}; // allows for insertion of 3rd party meta by on'data' handler
if (!replies) {
this._sendAck(response);
return;
}
this._reply(replies)
.then(replies => {
if (replies.nak) {
return this._sendNak(response.meta, replies.error || replies.nak);
}
response.data = {};
Object.keys(replies).forEach(key => response.data[key] = replies[key]);
this._sendAck(response);
})
.catch(error => this._sendNak(response.meta, error))
}
_onPing(data, detail) {
this.emit('ping', data /*, detail */);
}
_onPong(data, detail) {
this.emit('pong', data /*, detail */);
}
// _onDrain() {
// this.emit('drain');
// }
_encode(data, meta) {
if (Buffer.isBuffer(data)) {
meta.buffer = true;
return PROTOCOL_VERSION + JSON.stringify([meta]);
}
if (typeof data !== 'undefined') {
return PROTOCOL_VERSION + JSON.stringify([meta, data]);
}
return PROTOCOL_VERSION + JSON.stringify([meta]);
}
_nextSequence() {
if (this._sequence >= 4294967295) this._sequence = 0;
return this._sequence++;
}
_reply(replies) {
return new Promise((resolve, reject) => {
let processed = {};
let keys = Object.keys(replies);
let error;
keys.forEach(key => {
if (error) return;
let value = replies[key];
if (Buffer.isBuffer(value)) {
error = new errors.VertexSocketRemoteEncodeError('Cannot send buffer in reply');
return reject(error);
}
if (value instanceof Promise == false) {
processed[key] = value;
delete replies[key];
if (Object.keys(replies).length == 0) {
resolve(processed);
}
return;
}
value
.then(result => {
if (Buffer.isBuffer(result)) {
error = new errors.VertexSocketRemoteEncodeError('Cannot send buffer in reply');
return reject(error);
}
processed[key] = result;
delete replies[key];
if (Object.keys(replies).length == 0) {
resolve(processed);
}
})
.catch(error => {
delete replies[key];
processed[key] = this._fromError(error);
if (Object.keys(replies).length == 0) {
resolve(processed);
}
});
});
});
}
_sendAck(response) {
response.meta.ack = true;
let encoded;
try {
// encoded = JSON.stringify(response);
encoded = this._encode(response.data, response.meta);
}
catch (error) {
return this._sendNak(response.meta,
new errors.VertexSocketRemoteEncodeError(error.toString())
);
}
this._socket.send(encoded);
}
_sendNak(meta, error) {
try {
delete meta.ack;
meta.nak = true;
this._socket.send(this._encode(this._fromError(error), meta));
} catch (e) {
/* unlikely */
}
}
_format(meta, data) {
let formatted = data || {};
if (typeof formatted.meta == 'undefined') {
Object.defineProperty(formatted, 'meta', {
value: meta,
writable: true
});
}
if (formatted.meta.nak) {
let error = this._toError(formatted);
error.meta = formatted.meta;
return error;
}
Object.keys(formatted).forEach(key => {
if (!formatted[key]._error) return;
formatted[key] = this._toError(formatted[key]);
});
return formatted;
}
_fromError(error) {
if (!error) return {_error: true};
let serialised = {
_error: true,
name: error.name,
message: error.message
};
Object.keys(error).forEach(key => serialised[key] = error[key]);
return serialised;
}
_toError(error) {
if (!error) return new Error();
error.name = error.name || 'Error';
if (error.name.match(/^VertexSocket/)) {
if (errors[error.name]) {
let e = new errors[error.name](error.message);
Object.keys(error).forEach(key => e[key] = error[key]);
return e;
}
}
let e = new Error(error.message || 'Nak');
Object.keys(error).forEach(key => e[key] = error[key]);
return e;
}
}
module.exports = VertexSocket;
|
import * as assert from 'assert';
import * as OV from '../../source/engine/main.js';
export default function suite ()
{
function ImportFilesWithImporter (importer, files, callbacks)
{
let settings = new OV.ImportSettings ();
importer.ImportFiles (files, OV.FileSource.File, settings, {
onFilesLoaded : function () {
},
onImportSuccess : function (importResult) {
callbacks.success (importer, importResult);
},
onImportError : function (importError) {
callbacks.error (importer, importError);
}
});
}
function ImportFiles (files, callbacks)
{
let importer = new OV.Importer ();
ImportFilesWithImporter (importer, files, callbacks);
}
describe ('Importer Test', function () {
it ('Empty File List', function (done) {
let files = [];
ImportFiles (files, {
success : function (importer, importResult) {
assert.fail ();
},
error : function (importer, importError) {
assert.strictEqual (importError.code, OV.ImportErrorCode.NoImportableFile);
done ();
}
});
});
it ('Not existing file', function (done) {
let files = [
new FileObject ('', 'obj/missing.obj')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.fail ();
},
error : function (importer, importError) {
assert.strictEqual (importError.code, OV.ImportErrorCode.FailedToLoadFile);
assert.strictEqual (importError.mainFile, 'missing.obj');
done ();
}
});
});
it ('Not importable file', function (done) {
let files = [
new FileObject ('', 'wrong.ext')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.fail ();
},
error : function (importer, importError) {
assert.strictEqual (importError.code, OV.ImportErrorCode.NoImportableFile);
done ();
}
});
});
it ('Wrong file', function (done) {
let files = [
new FileObject ('', '3ds/wrong.3ds')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.fail ();
},
error : function (importer, importError) {
assert.strictEqual (importError.code, OV.ImportErrorCode.ImportFailed);
assert.strictEqual (importError.mainFile, 'wrong.3ds');
done ();
}
});
});
it ('Single file', function (done) {
let files = [
new FileObject ('', 'obj/single_triangle.obj')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['single_triangle.obj']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Multiple files', function (done) {
let files = [
new FileObject ('', 'obj/cube_with_materials.obj'),
new FileObject ('', 'obj/cube_with_materials.mtl'),
new FileObject ('', 'obj/cube_texture.png')
]
let theImporter = new OV.Importer ();
ImportFilesWithImporter (theImporter, files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl', 'cube_texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Missing files', function (done) {
let files = [];
files.push (new FileObject ('', 'obj/cube_with_materials.obj'));
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj']);
assert.deepStrictEqual (importResult.missingFiles, ['cube_with_materials.mtl']);
files.push (new FileObject ('', 'obj/cube_with_materials.mtl'));
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl']);
assert.deepStrictEqual (importResult.missingFiles, ['cube_texture.png']);
files.push (new FileObject ('', 'obj/cube_texture.png'));
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl', 'cube_texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
},
error : function (importer, importError) {
assert.fail ();
}
});
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Missing texture multiple times', function (done) {
let files = [
new FileObject ('', 'obj/two_materials_same_texture.obj'),
new FileObject ('', 'obj/two_materials_same_texture.mtl'),
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['two_materials_same_texture.obj', 'two_materials_same_texture.mtl']);
assert.deepStrictEqual (importResult.missingFiles, ['texture.png']);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Append Missing files', function (done) {
let theImporter = new OV.Importer ();
ImportFilesWithImporter (theImporter, [new FileObject ('', 'obj/cube_with_materials.obj')], {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj']);
assert.deepStrictEqual (importResult.missingFiles, ['cube_with_materials.mtl']);
ImportFilesWithImporter (theImporter, [new FileObject ('', 'obj/cube_with_materials.mtl')], {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl']);
assert.deepStrictEqual (importResult.missingFiles, ['cube_texture.png']);
ImportFilesWithImporter (theImporter, [new FileObject ('', 'obj/cube_texture.png')], {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl', 'cube_texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
},
error : function (importer, importError) {
assert.fail ();
}
});
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Reuse importer', function (done) {
let files1 = [
new FileObject ('', 'obj/cube_with_materials.obj'),
new FileObject ('', 'obj/cube_with_materials.mtl'),
new FileObject ('', 'obj/cube_texture.png')
]
let files2 = [
new FileObject ('', 'obj/single_triangle.obj')
];
let theImporter = new OV.Importer ();
ImportFilesWithImporter (theImporter, files1, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl', 'cube_texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
ImportFilesWithImporter (theImporter, files2, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['single_triangle.obj']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Default color', function (done) {
let files = [
new FileObject ('', 'stl/single_triangle.stl')
];
let theImporter = new OV.Importer ();
let settings = new OV.ImportSettings ();
settings.defaultColor = new OV.Color (200, 0, 0);
theImporter.ImportFiles (files, OV.FileSource.File, settings, {
onFilesLoaded : function () {
},
onImportSuccess : function (importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['single_triangle.stl']);
assert.deepStrictEqual (importResult.missingFiles, []);
let material = importResult.model.GetMaterial (0);
assert.deepStrictEqual (material.color, new OV.Color (200, 0, 0));
done ();
},
onImportError : function (importError) {
assert.fail ();
}
});
});
it ('Zip file', function (done) {
let files = [
new FileObject ('', 'zip/cube_four_instances.zip')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_four_instances.3ds', 'texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Zip file with Folders', function (done) {
let files = [
new FileObject ('', 'zip/cube_four_instances_folders.zip')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_four_instances.3ds', 'texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
});
it ('Multiple Zip Files', function (done) {
let files = [
new FileObject ('', 'zip/cube_with_materials_notexture.zip'),
new FileObject ('', 'zip/textures.zip')
];
ImportFiles (files, {
success : function (importer, importResult) {
assert.ok (!OV.IsModelEmpty (importResult.model));
assert.deepStrictEqual (importResult.usedFiles, ['cube_with_materials.obj', 'cube_with_materials.mtl', 'cube_texture.png']);
assert.deepStrictEqual (importResult.missingFiles, []);
done ();
},
error : function (importer, importError) {
assert.fail ();
}
});
});
});
}
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const loaderFlag = "LOADER_EXECUTION";
const webpackOptionsFlag = "WEBPACK_OPTIONS";
exports.cutOffByFlag = (stack, flag) => {
stack = stack.split("\n");
for (let i = 0; i < stack.length; i++) {
if (stack[i].includes(flag)) {
stack.length = i;
}
}
return stack.join("\n");
};
exports.cutOffLoaderExecution = stack =>
exports.cutOffByFlag(stack, loaderFlag);
exports.cutOffWebpackOptions = stack =>
exports.cutOffByFlag(stack, webpackOptionsFlag);
exports.cutOffMultilineMessage = (stack, message) => {
stack = stack.split("\n");
message = message.split("\n");
return stack
.reduce(
(acc, line, idx) =>
line.includes(message[idx]) ? acc : acc.concat(line),
[]
)
.join("\n");
};
exports.cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if (nextLine === -1) {
return stack === message ? "" : stack;
} else {
const firstLine = stack.substr(0, nextLine);
return firstLine === message ? stack.substr(nextLine + 1) : stack;
}
};
exports.cleanUp = (stack, message) => {
stack = exports.cutOffLoaderExecution(stack);
stack = exports.cutOffMessage(stack, message);
return stack;
};
exports.cleanUpWebpackOptions = (stack, message) => {
stack = exports.cutOffWebpackOptions(stack);
stack = exports.cutOffMultilineMessage(stack, message);
return stack;
};
|
;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
//var hermite = require("cubic-hermite");
// constructor
function Curve(r, nodeLoc1, nodeVel1, nodeLoc2, nodeVel2, delta) {
// data
nodeVel1.normalize();
nodeVel2.normalize();
this.radius = r;
this.length = Math.sqrt(Math.pow(nodeLoc1.x - nodeLoc2.x, 2) + Math.pow(nodeLoc1.y - nodeLoc2.y, 2) + Math.pow(nodeLoc1.z - nodeLoc2.z, 2));
this.p = [nodeLoc1.x, nodeLoc1.y, nodeLoc1.z, nodeVel1.x, nodeVel1.y, nodeVel1.z, nodeLoc2.x, nodeLoc2.y, nodeLoc2.z, nodeVel2.x, nodeVel2.y, nodeVel2.z];
this.geometry = [];;
this.system;
this.delta = delta/this.length;
this.addSphereGeometry();
}
// functions
Curve.prototype.getXYZPointAlongLength = function(xi) {
//var point = hermite([this.p[0],this.p[1],this.p[2]],[this.p[3],this.p[4],this.p[5]],[this.p[6],this.p[7],this.p[8]],[this.p[9],this.p[10],this.p[11]], xi);
var a = this.length;
var pos = new THREE.Vector3(0,0,0);
pos.x = (1 - 3 * xi * xi + 2 * Math.pow(xi, 3)) * this.p[0] + a * (xi - 2 * xi * xi + Math.pow(xi, 3)) * this.p[3] + (3 * xi * xi - 2 * Math.pow(xi, 3)) * this.p[6] + a * (-xi * xi + Math.pow(xi, 3)) * this.p[9];
pos.y = (1 - 3 * xi * xi + 2 * Math.pow(xi, 3)) * this.p[1] + a * (xi - 2 * xi * xi + Math.pow(xi, 3)) * this.p[4] + (3 * xi * xi - 2 * Math.pow(xi, 3)) * this.p[7] + a * (-xi * xi + Math.pow(xi, 3)) * this.p[10];
pos.z = (1 - 3 * xi * xi + 2 * Math.pow(xi, 3)) * this.p[2] + a * (xi - 2 * xi * xi + Math.pow(xi, 3)) * this.p[5] + (3 * xi * xi - 2 * Math.pow(xi, 3)) * this.p[8] + a * (-xi * xi + Math.pow(xi, 3)) * this.p[11];
return pos;//new THREE.Vector3(point[0],point[1],point[2]);
}
Curve.prototype.addSphereGeometry = function() {
// create the beam's material
var material = new THREE.MeshLambertMaterial({color: 0xCC0000});
for(var xi=0;xi<1;xi=xi+this.delta) {
// set up the sphere vars
var segments = 12, rings = 12;
// create a new mesh with sphere geometry -
var sphere = new THREE.Mesh(new THREE.SphereGeometry(this.radius, segments, rings),material);
sphere.position = this.getXYZPointAlongLength(xi);
this.geometry.push(sphere);
}
}
Curve.prototype.checkCollision_nsquared = function(curve) {
var index1 = -1;
var index2 = -2;
var d2min = 10000000;
for(var i=0;i<this.geometry.length;i++)
{
var nodeLoc1 = this.geometry[i].position;
for(var j=0;j<curve.geometry.length;j++)
{
var nodeLoc2 = curve.geometry[j].position;
var d2 = Math.pow(nodeLoc1.x - nodeLoc2.x, 2) + Math.pow(nodeLoc1.y - nodeLoc2.y, 2) + Math.pow(nodeLoc1.z - nodeLoc2.z, 2);
if(d2<d2min)
{
d2min = d2;
index1 = i;
index2 = j;
}
}
}
var material = new THREE.LineBasicMaterial({color: 0xFFFF00});
var geometry = new THREE.Geometry();
geometry.vertices.push(this.getXYZPointAlongLength(index1/this.geometry.length));
geometry.vertices.push(curve.getXYZPointAlongLength(index2/curve.geometry.length));
var line = new THREE.Line(geometry, material);
this.system.scene.add(line);
}
Curve.prototype.checkCollision_sphere = function(curve) {
// requires that the curves have the same cross-sectional radius!
//var nbp = require("n-body-pairs")(3, 1000);
var initNBP = require("n-body-pairs")
//var collisions = [];
var points = [];
for(var i=0;i<this.geometry.length;i++)
{
points.push([this.geometry[i].position.x,this.geometry[i].position.y,this.geometry[i].position.z]);
}
for(var i=0;i<curve.geometry.length;i++)
{
points.push([curve.geometry[i].position.x,curve.geometry[i].position.y,curve.geometry[i].position.z]);
}
var nbp = initNBP(3)
//Report all pairs of points which are within 1.5 units of eachother
var pairs = []
nbp(points, this.radius, function(i,j,d2) {
//console.log("Overlap ("+i+","+j+") Distance=", Math.sqrt(d2), "Positions=", points[i], points[j])
pairs.push([Math.min(i,j), Math.max(i,j), Math.sqrt(d2)])
})
pairs.sort()
for(var i=0;i<pairs.length;i++)
{
if(pairs[i][0]<this.geometry.length && pairs[i][1] >= this.geometry.length)
{
console.log("Overlap ("+pairs[i][0]+","+pairs[i][1]+") Distance=", pairs[i][2], "Positions=", points[i], points[j])
}
}
//return collisions;
}
Curve.prototype.checkCollision_opt = function(curve) {
// requires that the curves have the same cross-sectional radius!
var mathopt = require('mathopt');
var curve1 = this;
var curve2 = curve;
var dist2 = function(xi1, xi2) {
var nodeLoc1 = curve1.getXYZPointAlongLength(xi1);
var nodeLoc2 = curve2.getXYZPointAlongLength(xi2);
var d2 = Math.pow(nodeLoc1.x - nodeLoc2.x, 2) + Math.pow(nodeLoc1.y - nodeLoc2.y, 2) + Math.pow(nodeLoc1.z - nodeLoc2.z, 2);
if(xi1>1||xi1<0||xi2>1||xi2<0) d2 = 10000;
return d2;
}
console.log('Minimum found at ', mathopt.basicPSO(dist2));
var material = new THREE.LineBasicMaterial({color: 0x0000ff});
var geometry = new THREE.Geometry();
geometry.vertices.push(this.getXYZPointAlongLength(mathopt.basicPSO(dist2)[0]));
geometry.vertices.push(curve.getXYZPointAlongLength(mathopt.basicPSO(dist2)[1]));
var line = new THREE.Line(geometry, material);
this.system.scene.add(line);
}
Curve.prototype.doTimeStep = function() {
// these curves are static and cannot move (nothing to do in the time loop)
}
module.exports = Curve;
},{"mathopt":2,"n-body-pairs":3}],2:[function(require,module,exports){
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window).
root.mathopt = factory();
}
}(this, function () {
var euclideanLength = function(x) {
var v = 0;
for(var i = x.length; i--;) {
v += x[i] * x[i];
}
return Math.sqrt(v);
};
var copy = function(from, to, n) {
while(n--){
to[n] = from[n];
}
};
var vectorize = function(f) {
return function(x) {
return f.apply(null, x);
};
};
return {
basicPSO: function(f, options) {
var iteration, iterationLoop, result, allIdle, i, j, best, v, p, pbest, c, cbest;
// Normalize arguments.
options = options || {};
options.oniteration = options.oniteration || function(i, p, v, pbest, best, cb) {
cb && setTimeout(cb, 0);
};
options.onstop = options.onstop || null;
options.inertia = options.inertia || 0.7298;
options.localAcceleration = options.localAcceleration || 2.9922/2;
options.globalAcceleration = options.globalAcceleration || 2.9922/2;
options.particles = options.particles || 20;
options.idleSpeed = options.idleSpeed || 0.01;
if(!options.dimensions) {
options.dimensions = f.length;
f = vectorize(f);
}
if(!options.initialPosition) {
options.initialPosition = [];
for(i = options.dimensions; i--;) {
options.initialPosition.push(0);
}
}
// Initialize state.
p = new Array(options.particles);
pbest = p.slice(0);
v = p.slice(0);
cbest = p.slice(0);
best = 0;
for(i = p.length; i--;) {
p[i] = options.initialPosition.slice(0);
v[i] = [];
for(j = options.dimensions; j--;) {
v[i].push(2 * Math.random());
}
pbest[i] = p[i].slice(0);
cbest[i] = f(p[i]);
if(cbest[i] < cbest[best]) {
best = i;
}
}
// Find result.
result = pbest[best].slice(0);
result.iterations = 0;
iteration = function() {
result.iterations++;
allIdle = true;
for(i = options.particles; i--;) {
for(j = options.dimensions; j--;) {
v[i][j] = options.inertia * v[i][j] +
options.localAcceleration * Math.random() * (pbest[i][j] - p[i][j]) +
options.globalAcceleration * Math.random() * (pbest[best][j] - p[i][j]);
p[i][j] += v[i][j];
}
if(euclideanLength(v[i]) > options.idleSpeed) {
allIdle = false;
}
c = f(p[i]);
if(c < cbest[i]) {
cbest[i] = c;
copy(p[i], pbest[i], options.dimensions);
if(c < cbest[best]) {
best = i;
}
}
}
};
allIdle = false;
if(options.onstop) {
iterationLoop = function() {
if(allIdle) {
copy(pbest[best], result, options.dimensions);
result.value = cbest[best];
options.onstop(result);
} else {
options.oniteration(result.iterations, p, v, pbest, best, function() {
iteration();
iterationLoop();
});
}
};
iterationLoop();
} else {
while(!allIdle) {
options.oniteration(result.iterations, p, v, pbest, best);
iteration();
}
copy(pbest[best], result, options.dimensions);
result.value = cbest[best];
return result;
}
}
};
}));
},{}],3:[function(require,module,exports){
"use strict"
function Storage(max_points, dimension) {
this.coordinates = new Array(dimension)
this.points = new Array(dimension)
for(var i=0; i<dimension; ++i) {
this.coordinates[i] = new Int32Array(max_points<<dimension)
this.points[i] = new Float64Array(max_points<<dimension)
}
this.indices = new Int32Array(max_points<<dimension)
}
Storage.prototype.resize = function(max_points) {
var dimension = this.coordinates.length
for(var i=0; i<dimension; ++i) {
this.coordinates[i] = new Int32Array(max_points<<dimension)
this.points[i] = new Float64Array(max_points<<dimension)
}
this.indices = new Int32Array(max_points<<dimension)
}
Storage.prototype.size = function() {
return this.indices >> this.coordinates.length
}
Storage.prototype.move = function(p, q) {
var coords = this.coordinates
, points = this.points
, indices = this.indices
, dimension = coords.length
, a, b, k
for(k=0; k<dimension; ++k) {
a = coords[k]
a[p] = a[q]
b = points[k]
b[p] = b[q]
}
indices[p] = indices[q]
}
Storage.prototype.load = function(scratch, i) {
var coords = this.coordinates
, points = this.points
for(var k=0, d=coords.length; k<d; ++k) {
scratch[k] = coords[k][i]|0
scratch[k+d+1] = +points[k][i]
}
scratch[d] = this.indices[i]|0
}
Storage.prototype.store = function(i, scratch) {
var coords = this.coordinates
, points = this.points
for(var k=0, d=coords.length; k<d; ++k) {
coords[k][i] = scratch[k]
points[k][i] = scratch[k+d+1]
}
this.indices[i] = scratch[d]
}
Storage.prototype.swap = function(i, j) {
var coords = this.coordinates
var points = this.points
var ind = this.indices
var t, a, b
for(var k=0, d=coords.length; k<d; ++k) {
a = coords[k]
t = a[i]
a[i] = a[j]
a[j] = t
b = points[k]
t = b[i]
b[i] = b[j]
b[j] = t
}
t = ind[i]
ind[i] = ind[j]
ind[j] = t
}
Storage.prototype.compare = function(i,j) {
var coords = this.coordinates
for(var k=0, d=coords.length; k<d; ++k) {
var a = coords[k]
, s = a[i] - a[j]
if(s) { return s }
}
return this.indices[i] - this.indices[j]
}
Storage.prototype.compareNoId = function(i,j) {
var coords = this.coordinates
for(var k=0, d=coords.length-1; k<d; ++k) {
var a = coords[k]
, s = a[i] - a[j]
if(s) { return s }
}
return coords[d][i] - coords[d][j]
}
Storage.prototype.compareS = function(i, scratch) {
var coords = this.coordinates
for(var k=0, d=coords.length; k<d; ++k) {
var s = coords[k][i] - scratch[k]
if(s) { return s }
}
return this.indices[i] - scratch[d]
}
/*
Modified from this: http://stackoverflow.com/questions/8082425/fastest-way-to-sort-32bit-signed-integer-arrays-in-javascript
*/
Storage.prototype.sort = function(n) {
var coords = this.coordinates
var points = this.points
var indices = this.indices
var dimension = coords.length|0
var stack = []
var sp = -1
var left = 0
var right = n - 1
var i, j, k, d, swap = new Array(2*dimension+1), a, b, p, q, t
for(i=0; i<dimension; ++i) {
swap[i] = 0|0
}
swap[dimension] = 0|0
for(i=0; i<dimension; ++i) {
swap[dimension+1+i] = +0.0
}
while(true) {
if(right - left <= 25){
for(j=left+1; j<=right; j++) {
for(k=0; k<dimension; ++k) {
swap[k] = coords[k][j]|0
swap[k+dimension+1] = +points[k][j]
}
swap[dimension] = indices[j]|0
i = j-1;
lo_loop:
while(i >= left) {
for(k=0; k<dimension; ++k) {
d = coords[k][i] - swap[k]
if(d < 0) {
break lo_loop
} if(d > 0) {
break
}
}
p = i+1
q = i--
for(k=0; k<dimension; ++k) {
a = coords[k]
a[p] = a[q]
b = points[k]
b[p] = b[q]
}
indices[p] = indices[q]
}
this.store(i+1, swap)
}
if(sp == -1) break;
right = stack[sp--];
left = stack[sp--];
} else {
var median = (left + right) >> 1;
i = left + 1;
j = right;
this.swap(median, i)
if(this.compare(left, right) > 0) {
this.swap(left, right)
} if(this.compare(i, right) > 0) {
this.swap(i, right)
} if(this.compare(left, i) > 0) {
this.swap(left, i)
}
this.load(swap, i)
while(true){
ii_loop:
while(true) {
++i
for(k=0; k<dimension; ++k) {
d = coords[k][i] - swap[k]
if(d > 0) {
break ii_loop
} if(d < 0) {
continue ii_loop
}
}
if(indices[i] >= swap[dimension]) {
break
}
}
jj_loop:
while(true) {
--j
for(k=0; k<dimension; ++k) {
d = coords[k][j] - swap[k]
if(d < 0) {
break jj_loop
} if(d > 0) {
continue jj_loop
}
}
if(indices[j] <= swap[dimension]) {
break
}
}
if(j < i) break;
for(k=0; k<dimension; ++k) {
a = coords[k]
t = a[i]
a[i] = a[j]
a[j] = t
b = points[k]
t = b[i]
b[i] = b[j]
b[j] = t
}
t = indices[i]
indices[i] = indices[j]
indices[j] = t
}
this.move(left+1, j)
this.store(j, swap)
if(right - i + 1 >= j - left){
stack[++sp] = i;
stack[++sp] = right;
right = j - 1;
}else{
stack[++sp] = left;
stack[++sp] = j - 1;
left = i;
}
}
}
}
Storage.prototype.hashPoints = function(points, bucketSize, radius) {
var floor = Math.floor
, coords = this.coordinates
, spoints = this.points
, indices = this.indices
, count = points.length|0
, dimension = coords.length|0
, dbits = (1<<dimension)|0
, ptr = 0
for(var i=0; i<count; ++i) {
var t = ptr
, p = points[i]
, cross = 0
for(var j=0; j<dimension; ++j) {
var ix = floor(p[j]/bucketSize)
coords[j][ptr] = ix
spoints[j][ptr] = p[j]
if(bucketSize*(ix+1) <= p[j]+2*radius) {
cross += (1<<j)
}
}
indices[ptr++] = i
cross = ~cross
for(var j=1; j<dbits; ++j) {
if(j & cross) {
continue
}
for(var k=0; k<dimension; ++k) {
var c = coords[k]
c[ptr] = c[t]+((j>>>k)&1)
spoints[k][ptr] = p[k]
}
indices[ptr++] = i
}
}
return ptr
}
Storage.prototype.computePairs = function(cellCount, bucketSize, radius, cb) {
var floor = Math.floor
, coords = this.coordinates
, points = this.points
, indices = this.indices
, dimension = coords.length|0
, ptr = 0
, r2 = 4 * radius * radius
, i, j, k, l
, a, b, pa, pb, d, d2, ac, bc
for(i=0; i<cellCount;) {
for(j=i+1; j<cellCount; ++j) {
if(this.compareNoId(i, j) !== 0) {
break
}
a = indices[j]
k_loop:
for(k=i; k<j; ++k) {
b = indices[k]
d2 = 0.0
for(l=0; l<dimension; ++l) {
ac = points[l][j]
bc = points[l][k]
if(ac > bc) {
if(coords[l][i] !== floor(ac/bucketSize)) {
continue k_loop
}
} else if(coords[l][i] !== floor(bc/bucketSize)) {
continue k_loop
}
d = ac - bc
d2 += d * d
if(d2 > r2) {
continue k_loop
}
}
if(cb(a, b, d2)) {
return
}
}
}
i = j
}
}
function createNBodyDataStructure(dimension, num_points) {
dimension = (dimension|0) || 2
var grid = new Storage(num_points||1024, dimension)
function findPairs(points, radius, cb) {
var count = points.length|0
var cellCount = count<<dimension
if(grid.size() < cellCount) {
grid.resize(count)
}
var bucketSize = 4*radius
var nc = grid.hashPoints(points, bucketSize, radius)
grid.sort(nc)
grid.computePairs(nc, bucketSize, radius, cb)
}
Object.defineProperty(findPairs, "capacity", {
get: function() {
return grid.size()
},
set: function(n_capacity) {
grid.resize(n_points)
return grid.size()
}
})
return findPairs
}
module.exports = createNBodyDataStructure
},{}],4:[function(require,module,exports){
// constructor
function Sphere(r, rho, pos) {
// data
this.radius = r;
this.density = rho;
this.position = pos;
this.velocity = new THREE.Vector3( 0, 0, 0 );
this.acceleration = new THREE.Vector3( 0, 0, 0 );
this.force = new THREE.Vector3( 0, 0, 0 );
this.E = 2.0e7;
this.nu = 0.3;
// create the sphere's material
var sphereMaterial = new THREE.MeshLambertMaterial({color: 0xCC0000});
// set up the sphere vars
var segments = 6, rings = 6;
// create a new mesh with sphere geometry -
var sphere = new THREE.Mesh(new THREE.SphereGeometry(this.radius, segments, rings),sphereMaterial);
sphere.geometry.dynamic = true;
//sphere.geometry.verticesNeedUpdate = true;
//sphere.geometry.normalsNeedUpdate = true;
sphere.position = pos;
this.geometry = [];
this.geometry.push(sphere);
this.system;
}
// functions
Sphere.prototype.doTimeStep = function() {
// check to see if the sphere hit the ground
var groundPenetration = this.system.groundHeight-(this.position.y-this.radius);
if(groundPenetration>0) {
var sigma = (1-this.nu*this.nu)/this.E;
var K = 4.0/(3.0*(sigma+sigma))*Math.sqrt(this.radius*this.radius/(this.radius+this.radius));
var n = 1.5;
// determine damping
var b = 10;
var v = this.velocity;
var normal = new THREE.Vector3( 0, 1, 0 );
var damping = new THREE.Vector3( 0, 0, 0 );
damping.x = -b * normal.x * normal.x * v.x - b * normal.x * normal.y * v.y - b * normal.x * normal.z * v.z;
damping.y = -b * normal.x * normal.y * v.x - b * normal.y * normal.y * v.y - b * normal.y * normal.z * v.z;
damping.z = -b * normal.x * normal.z * v.x - b * normal.y * normal.z * v.y - b * normal.z * normal.z * v.z;
var vct = new THREE.Vector3( 0, 0, 0 );
vct.x = v.x - (normal.x * v.x + normal.y * v.y + normal.z * v.z) * normal.x;
vct.y = v.y - (normal.x * v.x + normal.y * v.y + normal.z * v.z) * normal.y;
vct.z = v.z - (normal.x * v.x + normal.y * v.y + normal.z * v.z) * normal.z;
vct.normalize();
var mu = 0;//.25;
var groundForce = K*Math.pow(groundPenetration,n)*(normal.y+mu*vct.y)-damping.y;
this.force.y+=groundForce;
console.log(sigma);
console.log(groundForce);
}
var mass = 4*this.density*this.r*this.r*this.r*Math.PI/3;
this.acceleration.x = this.force.x/mass+this.system.gravity.x;
this.acceleration.y = this.force.y/mass+this.system.gravity.y;
this.acceleration.z = this.force.z/mass+this.system.gravity.z;
this.velocity.x += this.acceleration.x*this.system.timeStep;
this.velocity.y += this.acceleration.y*this.system.timeStep;
this.velocity.z += this.acceleration.z*this.system.timeStep;
this.position.x += this.velocity.x*this.system.timeStep;
this.position.y += this.velocity.y*this.system.timeStep;
this.position.z += this.velocity.z*this.system.timeStep;
this.geometry.position = this.position;
this.force.y = 0;
//console.log(this.position);
}
module.exports = Sphere;
},{}],5:[function(require,module,exports){
// constructor
function System(timeStep,groundHeight,scene,shadows) {
// data
this.groundHeight = groundHeight;
this.time = 0;
this.timeIndex = 0;
this.timeStep = timeStep;
this.objects = [];
this.scene = scene;
this.drawGround(this.groundHeight);
this.gravity = new THREE.Vector3( 0, -9.81, 0 );
this.shadows = shadows;
}
// functions
System.prototype.add = function(object) {
object.system = this;
this.objects.push(object);
for(var i=0;i<object.geometry.length;i++)
{
if(this.shadows) object.geometry[i].castShadow = true;
this.scene.add(object.geometry[i]);
}
}
System.prototype.doTimeStep = function() {
for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
this.objects[i].doTimeStep();
}
this.time += this.timeStep;
this.timeIndex++;
}
System.prototype.drawGround = function() {
var ground = new THREE.Mesh(
new THREE.PlaneGeometry( 30, 30 ),
new THREE.MeshLambertMaterial({ color: 0x33CC33 })
);
// PlaneGeometry is created along YZ axis, rotate -90 degrees
// around the X axis so it lays flat and pointing up
ground.rotation.x = -0.5*Math.PI;
ground.receiveShadow = true;
this.scene.add( ground );
}
module.exports = System;
},{}],6:[function(require,module,exports){
var System = require("../system.js");
var Sphere = require("../sphere.js");
var Curve = require("../curve.js");
var mySystem; // CREATE THE SYSTEM!
var shadows = 1;
var sphere;
var camera, scene, renderer;
var geometry, material, mesh;
var controls,time = Date.now();
var objects = [];
var ray;
var blocker = document.getElementById( 'blocker' );
var instructions = document.getElementById( 'instructions' );
// http://www.html5rocks.com/en/tutorials/pointerlock/intro/
var havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
if ( havePointerLock ) {
var element = document.body;
var pointerlockchange = function ( event ) {
if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) {
controls.enabled = true;
blocker.style.display = 'none';
} else {
controls.enabled = false;
blocker.style.display = '-webkit-box';
blocker.style.display = '-moz-box';
blocker.style.display = 'box';
instructions.style.display = '';
}
}
var pointerlockerror = function ( event ) {
instructions.style.display = '';
}
// Hook pointer lock state change events
document.addEventListener( 'pointerlockchange', pointerlockchange, false );
document.addEventListener( 'mozpointerlockchange', pointerlockchange, false );
document.addEventListener( 'webkitpointerlockchange', pointerlockchange, false );
document.addEventListener( 'pointerlockerror', pointerlockerror, false );
document.addEventListener( 'mozpointerlockerror', pointerlockerror, false );
document.addEventListener( 'webkitpointerlockerror', pointerlockerror, false );
instructions.addEventListener( 'click', function ( event ) {
instructions.style.display = 'none';
// Ask the browser to lock the pointer
element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
if ( /Firefox/i.test( navigator.userAgent ) ) {
var fullscreenchange = function ( event ) {
if ( document.fullscreenElement === element || document.mozFullscreenElement === element || document.mozFullScreenElement === element ) {
document.removeEventListener( 'fullscreenchange', fullscreenchange );
document.removeEventListener( 'mozfullscreenchange', fullscreenchange );
element.requestPointerLock();
}
}
document.addEventListener( 'fullscreenchange', fullscreenchange, false );
document.addEventListener( 'mozfullscreenchange', fullscreenchange, false );
element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen;
element.requestFullscreen();
} else {
element.requestPointerLock();
}
}, false );
} else {
instructions.innerHTML = 'Your browser doesn\'t seem to support Pointer Lock API';
}
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );
//camera.position = new THREE.Vector3( 30, 10, 30 );
//camera.lookAt(new THREE.Vector3( 0, 10, 0 );
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 0, 750 );
var light = new THREE.AmbientLight( 0x333333 );
scene.add( light );
var light = new THREE.DirectionalLight( 0xBBBBBB );//0xffffff, 1.5 );
light.position.set( 0, 10, 0 );
if(shadows) {
light.castShadow = true;
light.shadowCameraNear = 1;
light.shadowCameraFar = 100;
light.shadowCameraLeft = -50;
light.shadowCameraRight = 50;
light.shadowCameraTop = -50;
light.shadowCameraBottom = 50;
light.shadowBias = -.01;
//light.shadowCameraVisible = true;
}
scene.add( light );
controls = new THREE.PointerLockControls( camera );
scene.add( controls.getObject() );
ray = new THREE.Raycaster();
ray.ray.direction.set( 0, -1, 0 );
// create the system
mySystem = new System(.001,0,scene,shadows);
/*
/// DEMONSTRATE VISUALIZER
var ball = new Sphere( 1, 1, new THREE.Vector3( 20*Math.random()+3, 20*Math.random()+3, 20*Math.random()+3 ));
mySystem.add(ball);
/// DEMONSTRATE PARTICLE API
var ball;
for(var i=0;i<1000;i++)
{
ball = new Sphere( .1, 1, new THREE.Vector3( 20*Math.random()+3, 20*Math.random()+3, 20*Math.random()+3 ));
mySystem.add(ball);
}
/// DEMONSTRATE STRAIGHT CURVE
var radius = Math.random();
var curve0 = new Curve(radius, new THREE.Vector3(0,10,0), new THREE.Vector3(1,0,0) , new THREE.Vector3(20,10,0) , new THREE.Vector3(1,0,0), .01);
mySystem.add(curve0);
/// DEMONSTRATE CURVED BEAM
var radius = Math.random();
var curve1 = new Curve(radius, new THREE.Vector3(0,1,0), new THREE.Vector3(1,0,0) , new THREE.Vector3(20,20,0) , new THREE.Vector3(0,1,0), .01);
mySystem.add(curve1);
/// CHECK COLLISION DETECTION
var radius = Math.random();
var curve2 = new Curve(radius, new THREE.Vector3(0,0,0), new THREE.Vector3(1,0,0) , new THREE.Vector3(1,0,0) , new THREE.Vector3(1,0,0), .5);
var curve3 = new Curve(radius, new THREE.Vector3(0,0,0), new THREE.Vector3(0,1,0) , new THREE.Vector3(0,3,0) , new THREE.Vector3(0,1,0), 1.5);
mySystem.add(curve2);
mySystem.add(curve3);
//curve2.checkCollision_sphere(curve3);
//curve2.checkCollision_opt(curve3);
*/
/// CHECK RANDOM BEAMS IN COLLISION DETECTION
var radius = Math.random();
var curve4 = new Curve(radius, new THREE.Vector3(10*Math.random(),10*Math.random(),10*Math.random()), new THREE.Vector3(Math.random(),Math.random(),Math.random()) , new THREE.Vector3(10*Math.random(),10*Math.random(),10*Math.random()) , new THREE.Vector3(Math.random(),Math.random(),Math.random()), radius*.2);
var curve5 = new Curve(radius, new THREE.Vector3(10*Math.random(),10*Math.random(),10*Math.random()), new THREE.Vector3(Math.random(),Math.random(),Math.random()) , new THREE.Vector3(10*Math.random(),10*Math.random(),10*Math.random()) , new THREE.Vector3(Math.random(),Math.random(),Math.random()), radius*.2);
mySystem.add(curve4);
mySystem.add(curve5);
curve4.checkCollision_nsquared(curve5)
curve4.checkCollision_opt(curve5);
//
renderer = new THREE.WebGLRenderer();
if(shadows) renderer.shadowMapEnabled = true;
renderer.setClearColor( 0xffffff );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
mySystem.doTimeStep();
//console.log(mySystem.time);
requestAnimationFrame( animate );
controls.isOnObject( false );
ray.ray.origin.copy( controls.getObject().position );
ray.ray.origin.y -= 10;
var intersections = ray.intersectObjects( objects );
if ( intersections.length > 0 ) {
var distance = intersections[ 0 ].distance;
if ( distance > 0 && distance < 10 ) {
controls.isOnObject( true );
}
}
controls.update( Date.now() - time );
renderer.render( scene, camera );
time = Date.now();
}
},{"../curve.js":1,"../sphere.js":4,"../system.js":5}]},{},[6])
; |
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Menu, Icon } from 'antd'
import { fetchData } from '../actions/Sider'
import { Link } from 'react-router'
const SubMenu = Menu.SubMenu
const MenuItemGroup = Menu.ItemGroup
const mapStateToProps = (state, ownProps) => {
return {
siderData: state.SiderData
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
fetchData: () =>{
dispatch(fetchData())
}
}
}
class Sider extends Component {
static propTypes = {
fetchData: React.PropTypes.func.isRequired,
siderData: React.PropTypes.array.isRequired
}
constructor (props) {
super(props)
this.state = {
current: '1'
}
}
componentWillMount () {
this.props.fetchData()
}
handleClick (e) {
console.log('click ', e)
this.setState({
current: e.key
})
}
render () {
var subTag = 0
var itemTag = 0
var optionTag = 0
return (
<Menu onClick={this.handleClick.bind(this)}
defaultOpenKeys={['sub0', 'item0']}
selectedKeys={[this.state.current]}
mode='inline'
theme='dark'
>
{this.props.siderData.map((sub, index) => (
<SubMenu key={'sub' + subTag++} title={<span><Icon type={sub.icon || 'mail'} />
<span>{sub.title}</span></span>} >
{sub.children && sub.children.map((item, index) => {
if (item.type === 'group') {
return (<MenuItemGroup key={'item' + itemTag++} title={item.title}>
{item.children && item.children.map((option, index) => (
<Menu.Item key={'option' + optionTag++}><Link to={option.url}>{option.title}</Link></Menu.Item>
))}
</MenuItemGroup>)
} else if (item.type === 'drop') {
return (<SubMenu key={'item' + itemTag++} title={item.title}>
{item.children && item.children.map((option, index) => (
<Menu.Item key={'option' + optionTag++}><Link to={option.url}>{option.title}</Link></Menu.Item>
))}
</SubMenu>)
} else {
return (
<Menu.Item key={'option' + optionTag++}><Link to={item.url}>{item.title}</Link></Menu.Item>
)
}
})}
</SubMenu>
))}
</Menu>
)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Sider)
|
import test from 'blue-tape';
import animal from '../../../source/zoo/1-just-protos/animal';
// this test is about linking the new instance to a prototype and just setting
// the properties on it
test('animal speaks', (assert) => {
let actual;
let expected;
let instance = animal; // the proto itself
actual = instance.describe();
expected = 'animal with 0 legs';
assert.equal(actual, expected);
actual = instance.speak('Hello i am animal');
expected = 'Hello [sound] i [sound] am [sound] animal';
assert.equal(actual, expected);
assert.end();
});
test('lion speaks', (assert) => {
let actual;
let expected;
// just link the delegate prototye to new instance and augment with dynamic object extension
let instance = Object.create(animal);
instance.animalType = 'lion';
instance.legs = 4;
instance.sound = 'roar';
actual = instance.describe();
expected = 'lion with 4 legs';
assert.equal(actual, expected);
actual = instance.speak('I am a lion');
expected = 'I roar am roar a roar lion';
assert.equal(actual, expected);
assert.end();
});
test('tiger speaks', (assert) => {
let actual;
let expected;
let instance = Object.create(animal);
instance.animalType = 'tiger';
instance.legs = 4;
instance.sound = 'grrr';
actual = instance.describe();
expected = 'tiger with 4 legs';
assert.equal(actual, expected);
actual = instance.speak('Lions suck');
expected = 'Lions grrr suck';
assert.equal(actual, expected);
assert.end();
});
|
import compose from '../../utils/compose';
var ValueAPI = {
value: function(value) {
return this._getValue();
},
onChange: function(cb) {
return this._onChange(cb);
},
};
var Value = compose(function(props, computeFn) {
this.ctr = compose(ValueAPI, {
_props: props,
_computeFn: computeFn,
});
});
export default Value; |
'use strict';
var d3Hierarchy = require('d3-hierarchy');
var flipTree = require('./flip_tree');
module.exports = function partition(entry, size, opts) {
var flipX = opts.flipX;
var flipY = opts.flipY;
var swapXY = opts.packing === 'dice-slice';
var top = opts.pad[flipY ? 'bottom' : 'top'];
var left = opts.pad[flipX ? 'right' : 'left'];
var right = opts.pad[flipX ? 'left' : 'right'];
var bottom = opts.pad[flipY ? 'top' : 'bottom'];
var tmp;
if(swapXY) {
tmp = left;
left = top;
top = tmp;
tmp = right;
right = bottom;
bottom = tmp;
}
var result = d3Hierarchy
.treemap()
.tile(getTilingMethod(opts.packing, opts.squarifyratio))
.paddingInner(opts.pad.inner)
.paddingLeft(left)
.paddingRight(right)
.paddingTop(top)
.paddingBottom(bottom)
.size(
swapXY ? [size[1], size[0]] : size
)(entry);
if(swapXY || flipX || flipY) {
flipTree(result, size, {
swapXY: swapXY,
flipX: flipX,
flipY: flipY
});
}
return result;
};
function getTilingMethod(key, squarifyratio) {
switch(key) {
case 'squarify':
return d3Hierarchy.treemapSquarify.ratio(squarifyratio);
case 'binary':
return d3Hierarchy.treemapBinary;
case 'dice':
return d3Hierarchy.treemapDice;
case 'slice':
return d3Hierarchy.treemapSlice;
default: // i.e. 'slice-dice' | 'dice-slice'
return d3Hierarchy.treemapSliceDice;
}
}
|
/**
* Author: Jeff Whelpley
* Date: 2/13/14
*
* Unit test for the data manipulator
*/
var name = 'utils/obj.utils';
var taste = require('../../pancakes.taste.js')();
var objUtils = taste.flapjack(name);
describe('UNIT ' + name, function () {
describe('removeAllFieldsFromObj()', function () {
it('should remove all fields from data', function () {
var data = {
fld1: 'blah',
fld2: 'another',
arr1: [{
fld2: 'something',
fld3: 'one more'
}],
arr2: ['booyeah'],
someObj: {
fld2: 'another',
subObj: {
fld3: 'one',
fld2: 'two'
}
}
};
var fieldsToRemove = ['fld2', 'arr2'];
var expected = {
fld1: 'blah',
arr1: [{
fld3: 'one more'
}],
someObj: {
subObj: {
fld3: 'one'
}
}
};
objUtils.removeAllFieldsFromObj(data, fieldsToRemove);
data.should.deep.equal(expected);
});
});
describe('mapData()', function () {
it('return back the input object if params invalid', function () {
var data = { something: 'blah' };
var expected = { something: 'blah' };
var actual = objUtils.mapData(null, data) || {};
actual.should.deep.equal(expected);
});
it('should map data from one format to another', function () {
var map = { col1: 'some.thing.blah' };
var data = { col1: 'zoom'};
var expected = {
some: {
thing: {
blah: 'zoom'
}
}
};
var actual = objUtils.mapData(map, data) || {};
actual.should.deep.equal(expected);
});
});
describe('getNestedValue()', function () {
it('should return undefined if value does not exist', function () {
taste.should.not.exist(objUtils.getNestedValue());
});
it('should return undefined field not in data', function () {
var data = { foo: 'choo' };
var field = 'blah';
var actual = objUtils.getNestedValue(data, field);
taste.should.not.exist(actual);
});
it('should return default since no value', function () {
var data = { foo: 'choo' };
var field = 'blah';
var defaultValue = 'boochica';
var actual = objUtils.getNestedValue(data, field, defaultValue);
actual.should.equal(defaultValue);
});
it('should get a simple value', function () {
var data = { foo: 'choo' };
var field = 'foo';
var expected = 'choo';
var actual = objUtils.getNestedValue(data, field);
actual.should.equal(expected);
});
it('should get a nested value', function () {
var data = { foo: { choo: { zoo: 'yep' }} };
var field = 'foo.choo.zoo';
var expected = 'yep';
var actual = objUtils.getNestedValue(data, field);
actual.should.equal(expected);
});
});
describe('setNestedValue()', function () {
it('should set a basic value', function () {
var data = { foo: 3 };
var field = 'foo';
var val = 2;
objUtils.setNestedValue(data, field, val);
data.foo.should.equal(val);
});
it('should set a nested value', function () {
var data = { foo: { man: { choo: 3 }}};
var field = 'foo.man.choo';
var val = 2;
objUtils.setNestedValue(data, field, val);
data.foo.man.choo.should.equal(val);
});
it('should set a nested value that does not exist', function () {
var data = {};
var field = 'foo.man.choo';
var val = 2;
objUtils.setNestedValue(data, field, val);
data.foo.man.choo.should.equal(val);
});
});
describe('matchesCriteria()', function () {
it('should return true if no params', function () {
return objUtils.matchesCriteria().should.be.true;
});
it('should return false if the data does not match the simple criteria', function () {
var data = { foo: 'choo' };
var criteria = { blah: 'zoo' };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should return false if the data does not match the simple criteria 2', function () {
var data = { foo: 'choo' };
var criteria = { foo: 'soo' };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should return true if the data matches simple criteria', function () {
var data = { foo: 'choo' };
var criteria = { foo: 'choo' };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should return true if the data matches complex criteria', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { foo: 'choo', 'woo.boo': 'la' };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should return false if no data matches complex criteria', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { foo: 'choo', 'woo.boo': 'sss' };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should allow the not operand', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { foo: { '$ne' : 'la' } };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should allow the not operand with complex material', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { 'woo.boo': { '$ne' : 'zoo' } };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should not false positive with not operand', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { 'foo': { '$ne' : 'choo' } };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should not false positive with not operand w missing property', function () {
var data = { woo: { boo: 'la' }};
var criteria = { 'foo': { '$ne' : 'choo' } };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should AND values together', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { 'foo': 'choo', 'woo.boo': 'la' };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should AND values together and be false if multiple conditions not met', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { 'foo': 'choo', 'woo.boo': 'na' };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should AND values together and be true if multiple conditions met w negative', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { 'foo': { '$ne': 'zoo' }, 'woo.boo': 'la' };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
it('should AND values together and be false if multiple conditions not met w negative', function () {
var data = { foo: 'choo', woo: { boo: 'la' }};
var criteria = { 'foo': { '$ne': 'choo' }, 'woo.boo': 'la' };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should AND values together and be false if multiple conditions not met w negative', function () {
var data = {};
var criteria = { 'foo': { '$ne': 'choo' }, 'woo': 'la' };
return objUtils.matchesCriteria(data, criteria).should.be.false;
});
it('should match a string in an array', function () {
var data = { 'arr': ['foo', 'bar'] };
var criteria = { 'arr': 'foo' };
return objUtils.matchesCriteria(data, criteria).should.be.true;
});
});
}); |
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../coverage/hslayers-material'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
// Copyright (c) Dyoub Applications. All rights reserved.
// Licensed under MIT (https://github.com/dyoub/app/blob/master/LICENSE).
(function () {
function Service() { }
Service.prototype.create = function (max) {
var installments = [];
for (var installment = 1; installment <= max; installment++) {
installments.push(installment);
}
return installments;
};
angular.module('dyoub.app').service('Installment', [
Service
]);
})();
|
import React, { PropTypes } from 'react'
import SettingsList from './SettingsList'
import { parseVocabulary } from '../../common/Vocabulary'
export class Predictions extends React.Component {
static propTypes = {
token: PropTypes.string.isRequired,
state: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired
};
type = 'vocabularies';
addItem = (values) => {
return parseVocabulary(values)
.then((vocabulary) => {
this.props.actions.addItem(this.props.token, this.type, vocabulary);
});
};
deleteItem = (id, name) => {
this.props.actions.deleteItem(this.props.token, this.type, id, name);
};
editItem = (id, values) => {
const { state, token, actions } = this.props;
const item = state.items[id];
const isEditName = item.name !== values.name;
return parseVocabulary(values)
.then((vocabulary) => {
if (isEditName) {
actions.editItemName(token, this.type, id, vocabulary);
}
else {
actions.editItem(token, this.type, id, vocabulary);
}
});
};
render() {
let state = this.props.state;
return (
<div>
<SettingsList
state={state}
type={this.type}
actions={this.props.actions}
onAddItem={this.addItem}
onDeleteItem={this.deleteItem}
onEditItem={this.editItem}
/>
</div>
)
}
}
export default Predictions
|
var ctx=document.getElementById("cvs").getContext("2d");
var timercount=200;
var timerctx;
var chrmtx=new Array();
var keywait=false;
window.onload=(function(){
clck=new Audio("cggsys/audio/pingpong1.mp3");
buzzer=new Audio("cggsys/audio/buzzer.mp3");
alerm=new Audio("cggsys/audio/alerm.wav");
//vraminit();
document.onkeydown=getkeychr;
document.onkeyup=keyclr;
document.onmousedown=getmouse;
init();
timerctx=setInterval("routine();",timercount);
});
function settimer(t){
timercount=t;
}
function cleartimer(){
clearInterval(timerctx);
}
function peek(x,y){
//return chr;
}
function beep(mode){
switch(mode){
case 0:
buzzer.play();
break;
case 1:
clck.play();
break;
case 2:
alerm.play();
break;
default:
break;
}
}
function putc(chrcode,chrctx,cx,cy){
var i,j;
for(i=0;i<=chrctx[2]-1;i++){
for(j=0;j<=chrctx[1]-1;j++){
if(chrcode[i*chrctx[1]+j]==1){
ctx.fillRect((cx+j)*4,(cy+i)*4,4,4);
}
}
}
}
function color(cc){
switch(cc){
case 0:
ctx.fillStyle="rgb(0,0,0)";
break;
case 1:
ctx.fillStyle="rgb(0,0,255)";
break;
case 2:
ctx.fillStyle="rgb(255,0,0)";
break;
case 3:
ctx.fillStyle="rgb(255,0,255)";
break;
case 4:
ctx.fillStyle="rgb(0,255,0)";
break;
case 5:
ctx.fillStyle="rgb(0,255,255)";
break;
case 6:
ctx.fillStyle="rgb(255,255,0)";
break;
case 7:
ctx.fillStyle="rgb(255,255,255)";
break;
default:
break;
}
}
function cls(){
ctx.fillStyle="rgb(0,0,0)";
ctx.fillRect(0,0,640,420);
}
function getkeychr(ev){
evt=ev.which
keychr=String.fromCharCode(evt).toLowerCase();
if(evt==39){keychr="right";}
if(evt==37){keychr="left";}
if(evt==40){keychr="down";}
if(evt==38){keychr="up";}
if(evt==13){keychr="cr";keywait=false;}
if(!keywait){keyin(keychr);}
}
function getmouse(ev){
var keychr;
if(ev.pageX>320){keychr="right";}else{keychr="left";}
keyin(keychr);
}
function keyclr(){
keychr="";
}
function printw(str){
println(str);
keywait=true;
}
function setchrscreen(){
var i,j;
for(i=0;i<=19;i++){
for(j=0;j<=19;j++){
chrmtx[i*20+j]=0;
}
}
}
function setchrmode(){
}
function chrmove(){
}
function chrscreen(){
}
function scrollup(){
for (i=18 ; i>=0 ;i--){
for (j = 0 ;j<=19 ;j++){
chrmtx[(i+1)*20+j] = chrmtx[i*20+j];
}
}
for(i=0;i<=19;i++){
chrmtx[19*20+i]=0;
}
}
function scrolldown(){
for (i=0 ; i<=18 ;i++){
for (j = 0 ;j<=19 ;j++){
chrmtx[i*20+j] = chrmtx[(i+1)*20+j];
}
}
for(i=0;i<=19;i++){
chrmtx[i]=0;
}
}
function println(str){
ctx,fillStyle="rgb(255,255,255)";
ctx.font="16px 'MSSVbN'";
ctx.fillText(str,10,405);
} |
/*
* Copyright 2015. Author: Jeffrey Hing. All Rights Reserved.
*
* MIT License
*
* Unit tests for extendThis.js.
*/
'use strict';
var extend = require('extend-this');
describe('extendThis.js:', function() {
// Pet class
function Pet(name, color, type) {
this._name = name;
this._color = color;
this._type = type;
}
Pet.prototype.name = function() {
return this._name;
};
Pet.prototype.color = function() {
return this._color;
};
Pet.prototype.type = function() {
return this._type;
};
//----------------------------------
// String selector tests
//----------------------------------
describe('selecting properties with no string selector', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype);
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.name()).toBe('ralph');
expect(dog.color()).toBe('red');
expect(dog.type()).toBe('dog');
});
});
describe('selecting properties with string selector', function() {
function Dog() {
extend(this).withCall([Pet, 'ralph', 'red', 'dog'], '_color');
}
extend(Dog.prototype).with(Pet.prototype, 'color');
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.color()).toBe('red');
expect(dog.name).toBe(undefined);
expect(dog._name).toBe(undefined);
expect(dog.type).toBe(undefined);
expect(dog._type).toBe(undefined);
});
});
//----------------------------------
// Array selector tests
//----------------------------------
describe('selecting properties with array selector', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype, ['name', 'color', ['type']]);
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.name()).toBe('ralph');
expect(dog.color()).toBe('red');
expect(dog.type()).toBe('dog');
});
});
//----------------------------------
// Regular expression selector tests
//----------------------------------
describe('selecting properties with regex', function() {
function Dog() {
extend(this).withCall([Pet, 'ralph', 'red', 'dog'], /_color/);
}
extend(Dog.prototype).with(Pet.prototype, /color/);
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.color()).toBe('red');
expect(dog.name).toBe(undefined);
expect(dog._name).toBe(undefined);
expect(dog.type).toBe(undefined);
expect(dog._type).toBe(undefined);
});
});
describe('selecting properties with regexp and map', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype, /.*/, {
color: 'dogColor'
});
it('should mixin the correct properties', function() {
var dog = new Dog();
expect(dog.dogColor()).toBe('red');
expect(dog.name()).toBe('ralph');
expect(dog.type()).toBe('dog');
});
});
//----------------------------------
// Rename selector tests
//----------------------------------
describe('renaming properties with map', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype, {
color: 'dogColor',
name: 'dogName',
type: 'dogType'
});
it('should mixin the correct properties', function() {
var dog = new Dog();
expect(dog.dogColor()).toBe('red');
expect(dog.dogName()).toBe('ralph');
expect(dog.dogType()).toBe('dog');
});
});
describe('renaming properties with map and non-string value', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
it('should throw an illegal property error', function() {
var error = new Error('extendThis.js: Illegal argument: []: ' +
'Target property name is not a string.');
expect(function() {
extend(Dog.prototype).with(Pet.prototype, {
color: []
});
}).toThrow(error);
});
});
//----------------------------------
// Inlines filter tests
//----------------------------------
describe('selecting properties with inline filter', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype, function(filterContext) {
var map = {
name: 'dogName',
color: 'dogColor'
};
var targetKey = map[filterContext.sourceKey];
if (targetKey !== undefined) {
filterContext.targetKey = targetKey;
return true;
}
return false;
});
it('should mixin the correct properties', function() {
var dog = new Dog();
expect(dog.dogColor()).toBe('red');
expect(dog.dogName()).toBe('ralph');
expect(dog.dogType).toBe(undefined);
});
});
describe('selecting properties with multiple inline filters', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype,
function(filterContext) {
filterContext.targetKey += 'a';
return true;
},
function(filterContext) {
filterContext.targetKey += 'b';
return true;
}
);
var dog = new Dog();
it('should apply filters in the order they are added', function() {
expect(dog.colorab()).toBe('red');
expect(dog.nameab()).toBe('ralph');
expect(dog.typeab()).toBe('dog');
});
});
//----------------------------------
// Negation tests
//----------------------------------
describe('selecting properties with negation modifier', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype, '!color');
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.name()).toBe('ralph');
expect(dog.type()).toBe('dog');
expect(dog.color).toBe(undefined);
});
});
//----------------------------------
// Override tests
//----------------------------------
describe('selecting property that exists in target prototype', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
Dog.prototype.name = function() {};
it('should throw an override error', function() {
var error = new Error(
'extendThis.js: Property already exists: name in {}');
expect(function() {
extend(Dog.prototype).with(Pet.prototype);
}).toThrow(error);
});
});
describe('selecting property that exists in target', function() {
function Dog() {
this._name = 'fred';
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype);
it('should throw an override error', function() {
var error = new Error(
'extendThis.js: Property already exists: ' +
'_name in {"_name":"ralph"}');
expect(function() {
new Dog(); // eslint-disable-line no-new
}).toThrow(error);
});
});
describe('disabling override error using override modifier', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
Dog.prototype.name = function() {};
extend(Dog.prototype).with(Pet.prototype, /.*/, '#name');
it('should mixin the correct properties', function() {
var dog = new Dog();
expect(dog.color()).toBe('red');
expect(dog.name()).toBe('ralph');
expect(dog.type()).toBe('dog');
});
});
//----------------------------------
// Non-existant source property tests
//----------------------------------
describe('selecting non-existant source property', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
it('should throw a property not found error', function() {
var error = new Error('extendThis.js: Property not found: ' +
'cat in {}');
expect(function() {
extend(Dog.prototype).with(Pet.prototype, 'cat');
}).toThrow(error);
});
});
describe('selecting non existant property with negation', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
it('should throw a property not found error', function() {
var error = new Error('extendThis.js: Property not found: ' +
'cat in {}');
expect(function() {
extend(Dog.prototype).with(Pet.prototype, '!cat');
}).toThrow(error);
});
});
//----------------------------------
// Call tests
//----------------------------------
describe('calling constructor with non-array format', function() {
function Dog() {
extend(this).withCall(Pet, 'ralph', 'red', 'dog');
}
extend(Dog.prototype).with(Pet.prototype);
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.name()).toBe('ralph');
expect(dog.color()).toBe('red');
expect(dog.type()).toBe('dog');
});
});
describe('calling constructor with array format', function() {
function Dog() {
extend(this).withCall([Pet, 'ralph', 'red', 'dog'], '_color');
}
extend(Dog.prototype).with(Pet.prototype, 'color');
var dog = new Dog();
it('should mixin the correct property', function() {
expect(dog.color()).toBe('red');
expect(dog._color).toBe('red');
expect(dog.name).toBe(undefined);
expect(dog._name).toBe(undefined);
expect(dog.type).toBe(undefined);
expect(dog._type).toBe(undefined);
});
});
describe('calling prototype method from constructor', function() {
function Person(height) {
this.height(height);
}
Person.prototype.height = function(height) {
if (height !== undefined) {
this._height = height;
}
return this._height;
};
function Recruit() {
extend(this).withCall(Person, 5);
}
extend(Recruit.prototype).with(Person.prototype);
var recruit = new Recruit();
it('should succeed', function() {
expect(recruit.height()).toBe(5);
});
});
//----------------------------------
// Delegation tests
//----------------------------------
describe('Composing object with delegation', function() {
function Height(height) {
this.height = height; // non-function property
this._func = function() {}; // private function property;
}
function Dog() {
extend(this).withDelegate(new Pet('ralph', 'red', 'dog'));
extend(this).withDelegate(new Height(10));
}
var dog = new Dog();
it('should delegate to the correct methods', function() {
expect(dog.name()).toBe('ralph');
expect(dog.color()).toBe('red');
expect(dog.type()).toBe('dog');
});
it('should delegate to the correct objects', function() {
expect(dog.height).toBe(10);
});
it('should not include private properties', function() {
expect(dog._name).toBe(undefined);
expect(dog._color).toBe(undefined);
expect(dog._type).toBe(undefined);
expect(dog._func).toBe(undefined);
});
});
//----------------------------------
// Individual property tests.
//----------------------------------
describe('Adding individual property', function() {
function Dog() {
extend(this).with('owner', 'me');
}
var dog = new Dog();
it('should add the correct property', function() {
expect(dog.owner).toBe('me');
});
});
describe('Adding individual property without a value', function() {
function Dog() {
extend(this).with('owner');
}
it('should throw an illegal property error', function() {
var error = new Error('extendThis.js: Illegal argument: "owner": ' +
'Requires a single property value');
expect(function() {
new Dog(); // eslint-disable-line no-new
}).toThrow(error);
});
});
//----------------------------------
// Wrap extend function
//----------------------------------
describe('Wrapping other extend function', function() {
it('should call the other extend function', function() {
var source = {};
var target = {};
this.otherExtend = function() {};
spyOn(this, 'otherExtend');
extend.wrap(this.otherExtend);
extend(source, target);
expect(this.otherExtend).toHaveBeenCalledWith(source, target);
extend.wrap(null);
});
});
//----------------------------------
// Method function
//----------------------------------
describe('Adding a method', function() {
it('should return my method', function() {
var func = function() {};
extend.method('funcA', func);
expect(extend.method('funcA')).toBe(func);
extend.method('funcA', null);
});
});
//----------------------------------
// Selector function
//----------------------------------
describe('Adding a selector', function() {
it('should return my selector', function() {
var selector = function() {};
extend.selector('&', selector);
expect(extend.selector('&')).toBe(selector);
extend.selector('&', null);
});
});
//----------------------------------
// Object.defineProperty
//----------------------------------
describe('Merging property created with Object.defineProperty', function() {
var source = {};
Object.defineProperty(source, 'sound', {
enumerable: true,
get: function() {
return 'meow';
}
});
it('should still work', function() {
var target = {};
expect(source.sound).toBe('meow');
extend(target).with(source);
expect(target.sound).toBe('meow');
});
});
//----------------------------------
// Misc Tests.
//----------------------------------
describe('Calling method without a source object', function() {
function Dog() {
extend(this).with(function() {});
}
it('should throw an illegal property error', function() {
var error = new Error('extendThis.js: Illegal argument: undefined: ' +
'No source object found.');
expect(function() {
new Dog(); // eslint-disable-line no-new
}).toThrow(error);
});
});
describe('Stringifying object with cyclical dependency', function() {
function Dog() {
// Create object with cyclical dependency.
var source = {
value: true
};
source.self = source;
extend(this).with(source, '!foobar');
}
it('should succeed', function() {
var error = new Error('extendThis.js: Property not found: foobar in ' +
'{"value":true}');
expect(function() {
new Dog(); // eslint-disable-line no-new
}).toThrow(error);
});
});
});
|
var login = require('../index');
login({email: "ynmedia.test.004@gmail.com", password: "ynmedia123"}, function(err, account) {
if (err) {
console.log('onLogin', err);
return;
}
account.sendComment('cmt6', 1483435788651394, function(err, res) {
console.log('comment', err, res);
});
}); |
'use strict';
var path = require('path'),
util = require('util'),
lodash = require ('lodash'),
ngUtil = require('../../utils/componentUtil'),
ScriptBase = require('../../script-base.js');
var Generator = module.exports = function Generator() {
ScriptBase.apply(this, arguments);
};
util.inherits(Generator, ScriptBase);
Generator.prototype.prompting = function askFor() {
var self = this;
var done = this.async();
var prompts = this.modulePrompts;
this.prompt(prompts, function (props) {
self.scriptAppName = props.moduleName || self.scriptAppName;
self.dir = path.join(self.config.get('serviceDirectory'), lodash.kebabCase(props.moduleName));
self.newModule = props.newModuleName;
self.moduleName = props.moduleName;
done();
});
};
Generator.prototype.writing = function createFiles() {
this.updateModule(this.moduleName, this.newModule, 'service');
ngUtil.copyTemplates(this, 'service');
};
|
import gulp from "gulp";
import {spawn} from "child_process";
import hugoBin from "hugo-bin";
import gutil from "gulp-util";
import gulpif from "gulp-if";
import yargs from "yargs";
import postcss from "gulp-postcss";
import cssnext from "postcss-cssnext";
import cssnano from "gulp-cssnano";
import atImport from "postcss-import";
import atExtend from "postcss-extend";
import mqpacker from "css-mqpacker";
import sourcemaps from "gulp-sourcemaps";
import BrowserSync from "browser-sync";
import webpack from "webpack";
import webpackConfig from "./webpack.conf";
const browserSync = BrowserSync.create();
const argv = yargs.argv;
// Hugo arguments
const hugoArgsDefault = ["-d", "../dist", "-s", "site", "-v"];
const hugoArgsPreview = ["--baseUrl=/", "--cleanDestinationDir", "--buildDrafts", "--buildFuture"];
// Development tasks
gulp.task("hugo", (cb) => buildSite(cb));
gulp.task("hugo-preview", (cb) => buildSite(cb, hugoArgsPreview));
// Build/production tasks
gulp.task("build", ["css", "js"], (cb) => buildSite(cb, [], "production"));
gulp.task("build-preview", ["css", "js"], (cb) => buildSite(cb, hugoArgsPreview, "production"));
// Compile CSS with PostCSS
gulp.task("css", () => (
gulp.src("./src/css/*.css")
.pipe(gulpif(!argv.production, sourcemaps.init()))
.pipe(postcss(
[
atImport({from: "./src/css/main.css"}),
atExtend(),
cssnext(),
mqpacker()
]
))
.pipe(gulpif(!argv.production, sourcemaps.write()))
.pipe(gulpif(argv.production, cssnano()))
.pipe(gulp.dest("./site/static/css"))
.pipe(browserSync.stream())
));
// Compile Javascript
gulp.task("js", (cb) => {
const myConfig = Object.assign({}, webpackConfig);
webpack(myConfig, (err, stats) => {
if (err) throw new gutil.PluginError("webpack", err);
gutil.log("[webpack]", stats.toString({
colors: true,
progress: true
}));
browserSync.reload();
cb();
});
});
// Development server with browsersync
gulp.task("server", ["hugo-preview", "css", "js"], () => {
browserSync.init({
server: {
baseDir: "./dist",
},
host: 'happeatravels.test',
open: 'external'
});
gulp.watch("src/js/**/*.js", ["js"]);
gulp.watch("src/css/**/*.css", ["css"]);
gulp.watch("site/**/*", ["hugo-preview"]);
});
/**
* Run hugo and build the site
*/
function buildSite(cb, options, environment = "development") {
const args = options ? hugoArgsDefault.concat(options) : hugoArgsDefault;
process.env.NODE_ENV = environment;
return spawn(hugoBin, args, {stdio: "inherit"}).on("close", (code) => {
if (code === 0) {
browserSync.reload();
cb();
} else {
browserSync.notify("Hugo build failed :(");
cb("Hugo build failed");
}
});
}
|
import React, {Component, PropTypes} from 'react';
import {connectReduxForm} from 'redux-form';
import surveyValidation from '../validation/surveyValidation';
import mapProps from 'map-props';
function asyncValidator(data) {
// TODO: figure out a way to move this to the server. need an instance of ApiClient
if (!data.email) {
return Promise.resolve({valid: true});
}
return new Promise((resolve) => {
setTimeout(() => {
const errors = {valid: true};
if (~['bobby@gmail.com', 'timmy@microsoft.com'].indexOf(data.email)) {
errors.email = 'Email address already used';
errors.valid = false;
}
resolve(errors);
}, 1000);
});
}
@connectReduxForm('survey', ['name','email','occupation'], surveyValidation).async(asyncValidator, 'email')
export default
class SurveyForm extends Component {
static propTypes = {
asyncValidating: PropTypes.bool.isRequired,
data: PropTypes.object.isRequired,
dirty: PropTypes.bool.isRequired,
errors: PropTypes.object.isRequired,
handleBlur: PropTypes.func.isRequired,
handleChange: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired,
invalid: PropTypes.bool.isRequired,
isDirty: PropTypes.func.isRequired,
pristine: PropTypes.bool.isRequired,
touched: PropTypes.object.isRequired,
valid: PropTypes.bool.isRequired
}
render() {
const {
data: {name, email, occupation},
errors: {name: nameError, email: emailError, occupation: occupationError},
touched: {name: nameTouched, email: emailTouched, occupation: occupationTouched},
asyncValidating,
handleBlur,
handleChange,
handleSubmit,
isDirty,
valid,
invalid,
pristine,
dirty
} = this.props;
return (
<div>
<form className="form-horizontal" onSubmit={handleSubmit}>
<div className={'form-group' + (nameError && nameTouched ? ' has-error' : '')}>
<label htmlFor="name" className="col-sm-2">
Full Name
{isDirty('name') && <span>*</span>}
</label>
<div className="col-sm-10">
<input type="text"
className="form-control"
id="name"
value={name}
onChange={handleChange('name')}
onBlur={handleBlur('name')}/>
{nameError && nameTouched && <div className="text-danger">{nameError}</div>}
</div>
</div>
<div className={'form-group' + (emailError && emailTouched ? ' has-error' : '')}>
<label htmlFor="email" className="col-sm-2">
Email address
{isDirty('email') && <span>*</span>}
</label>
<div className="col-sm-10">
<input type="email"
className="form-control"
id="email"
value={email}
onChange={handleChange('email')}
onBlur={handleBlur('email')}/>
{emailError && emailTouched && <div className="text-danger">{emailError}</div>}
{asyncValidating && <div>Validating...</div>}
</div>
</div>
<div className={'form-group' + (occupationError && occupationTouched ? ' has-error' : '')}>
<label htmlFor="occupation" className="col-sm-2">
Occupation
{isDirty('occupation') && <span>*</span>}
</label>
<div className="col-sm-10">
<input type="text"
className="form-control"
id="occupation"
value={occupation}
onChange={handleChange('occupation')}
onBlur={handleBlur('occupation')}/>
{occupationError && occupationTouched && <div className="text-danger">{occupationError}</div>}
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button className="btn btn-success" onClick={handleSubmit}>
<i className="fa fa-paper-airplane"/> Submit
</button>
</div>
</div>
</form>
<h4>Props from redux-form</h4>
<table className="table table-striped">
<tbody>
<tr>
<th>Dirty</th>
<td className={dirty ? 'success' : 'danger'}>{dirty ? 'true' : 'false'}</td>
</tr>
<tr>
<th>Pristine</th>
<td className={pristine ? 'success' : 'danger'}>{pristine ? 'true' : 'false'}</td>
</tr>
<tr>
<th>Valid</th>
<td className={valid ? 'success' : 'danger'}>{valid ? 'true' : 'false'}</td>
</tr>
<tr>
<th>Invalid</th>
<td className={invalid ? 'success' : 'danger'}>{invalid ? 'true' : 'false'}</td>
</tr>
</tbody>
</table>
</div>
);
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fileService_1 = require("../services/fileService");
const logService_1 = require("../services/logService");
const directoryService_1 = require("../services/directoryService");
class Remove {
constructor() {
this._fileService = new fileService_1.FileService();
this._logService = new logService_1.LogService();
this._directoryService = new directoryService_1.DirectoryService();
}
removeFileFromCurrentDirectory(fileName) {
if (!this._fileService.getManifestFile('./')) {
this._logService.warning('Sorry, this is not a directory you can remove styles from or you may be missing parameters.');
}
else {
this.processFileRemoval('.', fileName);
}
}
removeFileFromSpecifiedDirectory(dir, fileName) {
let directoryName = this._directoryService.findDirectoryByName(dir);
if (directoryName) {
let pathToDirectory = this._directoryService.findDirectory(directoryName);
if (pathToDirectory) {
this.processFileRemoval(pathToDirectory, fileName);
}
else {
this._logService.warning("Sorry, the directory you specified was not found.");
}
}
else {
this._directoryService.promptForMissingDirectory()
.then(directory => this.removeFileFromSpecifiedDirectory(directory, fileName));
}
}
processFileRemoval(pathToDirectory, fileName) {
let extension = this._fileService.getFileExtension(pathToDirectory);
let fileToRemove = `_${fileName}.${extension}`;
let manifestFile = `${pathToDirectory}/${this._fileService.getManifestFile(pathToDirectory)}`;
this._fileService.removeFile(`${pathToDirectory}/${fileToRemove}`);
this._fileService.removeFileFromManifest(extension === 'sass' || extension === 'scss' ? fileName : fileToRemove, manifestFile);
}
}
exports.Remove = Remove;
|
const _ = require('lodash/object');
module.exports = {
remove(tids, options = {}) {
const method = 'tags/remove';
const params = { tids };
_.assign(params, _.pick(options, ['password']));
return { method, params };
},
save(tids, uid, options = {}) {
const method = 'tags/save';
const params = { tids, uid };
_.assign(params, _.pick(options, ['namespace', 'label', 'password']));
return { method, params };
},
add(uid, url, tag, options = {}) {
const method = 'tags/add';
const params = { uid, url };
_.assign(params, _.pick(tag, ['x', 'y', 'width', 'height']));
_.assign(params, _.pick(options, ['label', 'password']));
return { method, params };
},
get(options = {}) {
const method = 'tags/get';
const params = {};
_.assign(params,
_.pick(options, [
'urls',
'uids',
'pids',
'order',
'limit',
'together',
'filter',
'namespace',
])
);
return { method, params };
},
};
|
const Queue = require('./Queue');
class CircularQueue extends Queue {
getIndex(index) {
return index >= this.size ? (index % this.size) : index
}
find(index) {
return this.isEmpty ? null : this.items[this.getIndex(index)]
}
}
module.exports = CircularQueue;
|
/**
* @file san-mui/Button
* @author leon <ludafa@outlook.com>
*/
import {create} from '../common/util/cx';
import {TouchRipple} from '../Ripple';
import BaseButton from './Base';
import {DataTypes} from 'san';
const cx = create('button');
export default class Button extends BaseButton {
static components = {
'san-touch-ripple': TouchRipple
};
static template = `
<button
on-click="click($event)"
type="{{type}}"
class="{{computedClassName}}"
disabled="{{disabled}}">
<slot />
<san-touch-ripple san-if="!disabled" />
</button>
`;
static computed = {
computedClassName() {
return cx(this).build();
}
};
static dataTypes = {
type: DataTypes.string,
disabled: DataTypes.bool
};
initData() {
return {
type: 'button',
disabled: false
};
};
attached() {
// save the original href into originalHref and change current href according to disabled
if (this.data.get('href')) {
this.data.set('originalHref', this.data.get('href'));
if (this.data.get('disabled')) {
this.setHref('javascript:void(0);');
}
}
this.watch('disabled', val => {
if (val) {
this.setHref('javascript:void(0);');
return;
}
this.setHref(this.data.get('originalHref'));
});
};
setHref(hrefVal) {
this.data.set('href', hrefVal);
}
click(e) {
if (!this.data.get('disabled')) {
this.fire('click', e);
}
}
}
|
jQuery(document).ready(function(){var ua=window.navigator.userAgent,safari=ua.indexOf("Safari"),chrome=ua.indexOf("Chrome"),mobile=ua.indexOf("Mobile"),version=ua.substring(0,safari).substring(ua.substring(0,safari).lastIndexOf("/")+1);if(SafariPushParams.websitePushID===null){console.log("Website Push ID is missing");SafariPushParams.status="error";}else if(SafariPushParams.webServiceURL===null){console.log("Web Service URL is missing");SafariPushParams.status="error";}else if(chrome==-1&&mobile==-1&&safari>0&&parseInt(version,10)>=7){surrealroad_safaripush_checkPermission();}else{SafariPushParams.status="unsupported";}
surrealroad_safaripush_rendershortcodes(SafariPushParams.status);});function surrealroad_safaripush_checkPermission(){var pResult=window.safari.pushNotification.permission(SafariPushParams.websitePushID);SafariPushParams.status=pResult.permission;if(pResult.permission==='default'){surrealroad_safaripush_requestPermission();}
else if(pResult.permission==='granted'){SafariPushParams.token=pResult.deviceToken;}
else if(pResult.permission==='denied'){}}
function surrealroad_safaripush_requestPermission(){window.safari.pushNotification.requestPermission(SafariPushParams.webServiceURL,SafariPushParams.websitePushID,{"id":SafariPushParams.userID},surrealroad_safaripush_requestPermissionCallback);}
function surrealroad_safaripush_requestPermissionCallback(permission){if(permission.permission==='granted'){SafariPushParams.token=permission.deviceToken;}
else if(permission.permission==='denied'){}
SafariPushParams.status=permission.permission;surrealroad_safaripush_rendershortcode(SafariPushParams.status);}
function surrealroad_safaripush_rendershortcodes(status){var html="";switch(status){case'error':html=SafariPushParams.errorMsg;break;case'unsupported':html=SafariPushParams.unsupportedMsg;break;case'granted':html=SafariPushParams.grantedMsg;break;case'denied':html=SafariPushParams.deniedMsg;break;default:html=SafariPushParams.defaultMsg;}
jQuery(".safari-push-info").html(html);if(jQuery(".safari-push-count").is('*')){jQuery.ajax(SafariPushParams.webServiceURL+SafariPushParams.countEndpoint).success(function(pushcount){jQuery(".safari-push-count").html(pushcount);});}} |
'use strict';
var Route = (function(){
/**
* Variables
*/
var realPath = null,
currentPath = null,
currentRouteIndex = null,
_on = [{
event: 'change',
callback: function(){}
}];
/**
* events
* This object handles the registration and handling of events related to the Route object
*
* @type {Object}
*/
var events = {
register: function(){
var elems = document.getElementsByTagName('a');
for(var i = 0; i < elems.length; i++){
elems[i].addEventListener('click', events.linkClick);
}
},
linkClick: function(event){
if(event.target.getAttribute('target') !== '_blank')
event.preventDefault();
Route.change(event.target.getAttribute('href'));
}
};
/**
* build
* Append routes to the available paths array
*
* @param {String} path The path to append to the path list
* @param {Function} middleware The middle where function, if middleware isn't defined then its null
* @param {Function} callback The callback function
* @param {[Object]} options Options, not used right now, maybe for named routes in the future
* @return {undefined}
*/
function build(path, middleware, callback, options){
if(path[0] != '/')
path = '/'+path;
if(path[path.length-1] == '/')
path = path.slice(0, -1);
Route.paths.push({
path: path,
middleware: middleware,
callback: callback
});
}
/**
* getParams
* This function retrieves url params and appends it to the Route.data object
*
* @return {undefined}
*/
function getParams(){
if(window.location.search != ''){
var params = window.location.search.replace('?', '').split('&');
for(var i = 0; i < params.length; i++){
var key = decodeURI(params[i].split('=')[0]);
var value = decodeURI(params[i].split('=')[1]);
Route.data[key] = value;
}
}
}
/**
* pathConstructor
* Creates a defined route with variables and turns it into a usable route
*
* @param {Sring} path is a string of the route which needs to be formated
* @return {Object} contains the formatted route and a mapping of the variables in the route
*/
function pathConstructor(path){
path = path.split('/');
var rp = realPath.split('/');
var route = {
data: [],
path: '',
};
for(var i = 0; i < path.length; i++){
if(path[i][0] === ':'){
if(rp[i]){
Route.data[path[i].replace(':', '').replace('?', '')] = decodeURI(rp[i]);
route.data.push(decodeURIComponent(rp[i]));
path[i] = rp[i];
}
if(path[i].indexOf('?') > false)
path[i] = rp[i] || '';
}
}
path = path.join('/');
if(path[path.length-1] === '/')
path = path.slice(0, -1);
route.path = path;
return route;
}
/**
* find
* Find iterates over the registered routes and looks for matches
* if no route matches, the start look for routes with variables
*
* @return {undefined}
*/
function find(){
Route.data = {}; // reset old route data
getParams(); // check for params
if(!Route.paths)
return;
realPath = window.location.pathname;
if(realPath[realPath.length-1] == '/')
realPath = realPath.slice(0, -1);
for(var i = 0; i < Route.paths.length; i++){
if(!(Route.paths[i].path.indexOf(':') > false) && Route.paths[i].path === realPath){
// normal route
if(Route.paths[i].middleware()){
Route.paths[i].callback();
setCurrentRoute(i);
return Route;
}
}
}
// if no path matched check for paths with vars
checkForVars();
}
/**
* checkForVars
* Looks for routes with variables. If nothing matches then trigger Route.notFound()
*
* @return {undefined}
*/
function checkForVars(){
for(var i = 0; i < Route.paths.length; i++){
var route = Route.paths[i];
if((route.path.indexOf(':') > false)){
var r = pathConstructor(route.path);
if(r.path == realPath){
if(route.middleware()){
route.callback.apply(Route, r.data);
setCurrentRoute(i);
return Route;
}
}
}
}
Route.notFound();
}
/**
* setCurrentRoute
*
* @param {int} i the iteration of paths
*/
function setCurrentRoute(i){
currentRouteIndex = i;
currentPath = realPath;
Route.trigger('change');
events.register();
}
/**
* Route
* This is the visible object, to handle the routing
*
* @type {Object}
*/
var Route = {
paths: [],
data: {},
init: function(){
window.onpopstate = function(e){
find();
}.bind(this);
events.register();
find();
return true;
},
set: function(path, middleware, callback, options){
if(callback === undefined){
callback = middleware;
middleware = function(){ return true; };
}
build(path, middleware, callback, options);
},
group: function(prefix, middleware, routes){
routes = routes || (typeof middleware === 'object' ? middleware : prefix);
middleware = typeof middleware === 'function' ? middleware : (typeof prefix === 'function' ? prefix : function(){ return true; });
prefix = typeof prefix === 'function' ? '' : (typeof prefix === 'object' ? '' : prefix);
if(prefix[prefix.length-1] !== '/')
prefix += '/';
for(var route in routes){
if(route[0] === '/')
var r = prefix+route.substring(1);
else
var r = prefix+route;
this.set(r, middleware, routes[route]);
}
},
change: function(path, data){
path = this.validate(path);
if(window.location.hash)
path += window.location.hash;
window.history.pushState("","", path);
find();
for(var prop in data){
this.data[prop] = data[prop];
}
},
validate: function(path) {
// if(path === undefined)
// return throw new Error('The path is not valid');
if(path[0] !== '/')
path = '/'+path;
return path;
},
on: function(event, callback){
_on.push({ event: event, callback: callback });
return this;
},
off: function(event){
for(var i = 0, item; item = _on[i]; i++){
if(item.event === event){
delete _on[i];
}
}
return this;
},
trigger: function(event, data){
for(var i = 0, item; item = _on[i]; i++){
if(item.event === event){
item.callback(data);
}
}
},
current: function(options){
return currentPath;
},
notFound: function(){
console.warn('Router.js: Route is not defined...');
},
};
return Route;
}());
if(typeof module === "object" && typeof module.exports === "object"){
module.exports = Route;
}
|
import {
addToken as _addToken,
removeToken as _removeToken,
replaceTokenList as _replaceTokenList,
isValidToken as _isValidToken,
clearTokenList as _clearTokenList,
} from 'utils/tokenHelper';
import { Auth } from 'utils/api';
// Export
export const UPDATE_TOKEN = 'UPDATE_TOKEN';
export const addToken = () => {
const { activeProviders } = _addToken();
return {
type: UPDATE_TOKEN,
payload: { activeProviders },
};
};
export const removeToken = (provider) => {
Auth.revoke({ provider });
const { activeProviders } = _removeToken(provider);
return {
type: UPDATE_TOKEN,
payload: { activeProviders },
};
};
export const replaceTokenList = (_tokenList) => {
const { activeProviders } = _replaceTokenList(_tokenList);
return {
type: UPDATE_TOKEN,
payload: { activeProviders },
};
};
export const clearTokenIfTokenExpired = () => {
return dispatch => {
if (!_isValidToken()) {
const { activeProviders } = _clearTokenList();
dispatch({
type: UPDATE_TOKEN,
payload: { activeProviders },
});
}
};
};
|
'use strict';
var events = require('events');
var _ = require('underscore');
_.extend(exports, events.prototype); |
import EmberRouter from '@ember/routing/router'
import config from './config/environment'
const Router = EmberRouter.extend({
location : config.locationType,
rootURL : config.rootURL
})
Router.map(function () {
})
export default Router
|
var mem = new Uint8Array(30000);
var r = 0;
var buf = '';
var pc = [];
function putchar() { process.stdout.write(String.fromCharCode(mem[r]));}
function getchar() { if (buf.length == 0) return false; mem[r] = buf.charCodeAt(0); buf = buf.substring(1); return true; }
function main() {
mem[r]++; /* + */
r++; /* > */
mem[r]++; /* + */
mem[r]++; /* + */
r++; /* > */
r--; /* < */
r--; /* < */
r++; /* > */
while (mem[r]) { /* [ */
mem[r]--; /* - */
r--; /* < */
mem[r]++; /* + */
r++; /* > */
} /* ] */
r--; /* < */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
mem[r]++; /* + */
putchar(); /* . */
process.exit(0);
}
main();
|
function booWho(bool) {
return typeof bool === "boolean";
}
booWho(null); |
/* globals Swivel */
;(function() {
"use strict";
/**
* Bucket test suite
*/
describe("Bucket", function() {
var Bucket = Swivel.Bucket;
var FeatureMap = Swivel.FeatureMap;
var Behavior = Swivel.Behavior;
describe("enabled", function() {
it("should delegate to the injected FeatureMap", function() {
var featureMap = new FeatureMap({ Test : [6], "Test.version" : [6] });
var bucket = new Bucket(featureMap, 6);
var behavior = new Behavior("Test.version", function() {});
spyOn(featureMap, "enabled").and.callThrough();
expect(bucket.enabled(behavior)).toBe(true);
expect(featureMap.enabled).toHaveBeenCalledWith("Test.version", 6);
});
it("should equal the slug sent in the callback", function() {
var slug = "InvalidSlug";
var mapArray = {
"Test" : [1],
"Test.version" : [1],
"Test.version.a" : [1]
};
var map = new FeatureMap(mapArray);
var behavior = new Behavior(slug, function() {});
var bucket = new Bucket(map, 1, function (slugParam) {
expect(slug).toEqual(slugParam);
});
spyOn(map, "enabled").and.callThrough();
expect(bucket.enabled(behavior)).toBe(false);
expect(map.enabled).toHaveBeenCalledWith(slug, 1);
});
});
});
}());
|
'use strict';
define([
'jquery',
'underscore',
'view/widget/panel/panel',
'view/widget/body/body',
'view/widget/navigation/navigation',
], function ($, _, Panel, Body, Navigation) {
return Panel.extend({
initialize: function () {
Panel.prototype.initialize.call(this, {
id: 'menu-panel',
position: 'right',
positionFixed: true,
display: 'overlay',
body: new Body({
items: {
navigation: new Navigation({
activeState: false,
rows: [
{ dashboard: {text: '<i class="fa fa-list-ul"></i> Dashboard'} },
{ providers: {text: '<i class="fa fa-copyright"></i> Providers'} },
{ products: {text: '<i class="fa fa-database"></i> Products'} },
{ blocks: {text: '<i class="fa fa-th-large"></i> Blocks'} },
{ beds: {text: '<i class="fa fa-bars"></i> Beds'} },
{ crops: {text: '<i class="fa fa-crop"></i> Crops'} },
{ tasks: {text: '<i class="fa fa-tasks"></i> Tasks'} },
{ works: {text: '<i class="fa fa-wrench"></i> Works'} },
{ varieties: {text: '<i class="fa fa-pagelines"></i> Varieties'} },
{ poss: {text: '<i class="fa fa-truck"></i> Points of sale'} },
{ logout: {text: '<i class="fa fa-sign-out"></i> Logout'} },
],
events: {
click: function (route) {
this.redirect(route)
}.bind(this),
},
}),
},
}),
});
},
redirect: function (route) {
this.close().done(function() {
app.router.navigate(route);
}.bind(this));
},
});
}); |
import React, {useContext} from "react";
import SurveyRule from "../components/SurveyRule";
import SvgIcon from "../components/svg/SvgIcon";
import {isNumber, sameContents} from "../utils/generalUtils";
import {ProjectContext} from "./constants";
const getNextId = array => array.reduce((maxId, obj) => Math.max(maxId, obj.id), 0) + 1;
export const SurveyRuleDesign = () => {
const {setProjectDetails, surveyRules} = useContext(ProjectContext);
return (
<div id="survey-rule-design">
<SurveyRulesList
inDesignMode
setProjectDetails={setProjectDetails}
surveyRules={surveyRules}
/>
<SurveyRulesForm/>
</div>
);
};
export class SurveyRulesList extends React.Component {
deleteSurveyRule = ruleId => {
const newSurveyRules = this.props.surveyRules.filter(rule => rule.id !== ruleId);
this.props.setProjectDetails({surveyRules: newSurveyRules});
};
// TODO update the remove buttons with SVG
removeButton = ruleId => (
<button
className="btn btn-sm btn-outline-red mt-0 mr-3 mb-3"
onClick={() => this.deleteSurveyRule(ruleId)}
title="Delete Rule"
type="button"
>
<SvgIcon icon="trash" size="1.25rem"/>
</button>
);
renderRuleRow = r => {
const {inDesignMode} = this.props;
return (
<div key={r.id} style={{display: "flex", alignItems: "center"}}>
{inDesignMode && this.removeButton(r.id)}
<SurveyRule ruleOptions={r}/>
</div>
);
};
render() {
const {surveyRules} = this.props;
return (
<>
<h2>Rules</h2>
{(surveyRules || []).length > 0
? (
<div>{surveyRules.map(this.renderRuleRow)}</div>
) : <label className="ml-3">No rules have been created for this survey.</label>}
</>
);
}
}
class SurveyRulesForm extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedRuleType: "text-match"
};
}
render() {
const {selectedRuleType} = this.state;
return (
<div className="mt-3 d-flex justify-content-center">
<div style={{display: "flex", flexFlow: "column", width: "25rem"}}>
<h2>New Rule</h2>
<div className="form-group">
<label>Rule Type</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({selectedRuleType: e.target.value})}
value={selectedRuleType}
>
<option value="text-match">Text Regex Match</option>
<option value="numeric-range">Numeric Range</option>
<option value="sum-of-answers">Sum of Answers</option>
<option value="matching-sums">Matching Sums</option>
<option value="incompatible-answers">Incompatible Answers</option>
</select>
</div>
{{
"text-match": <TextMatchForm/>,
"numeric-range": <NumericRangeForm/>,
"sum-of-answers": <SumOfAnswersForm/>,
"matching-sums": <MatchingSumsForm/>,
"incompatible-answers": <IncompatibleAnswersForm/>
}[selectedRuleType]}
</div>
</div>
);
}
}
class TextMatchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
regex: "",
questionId: -1
};
}
addSurveyRule = () => {
const {surveyRules, surveyQuestions, setProjectDetails} = this.context;
const {questionId, regex} = this.state;
const conflictingRule = surveyRules.find(rule => rule.ruleType === "text-match"
&& rule.questionId === questionId);
const errorMessages = [
conflictingRule && "A text regex match rule already exists for this question. (Rule " + conflictingRule.id + ")",
questionId < 1 && "You must select a question.",
regex.length === 0 && "The regex string is missing."
].filter(m => m);
if (errorMessages.length > 0) {
alert(errorMessages.map(s => "- " + s).join("\n"));
} else {
setProjectDetails({
surveyRules: [...surveyRules, {
id: getNextId(surveyRules),
ruleType: "text-match",
questionId,
questionsText: [surveyQuestions.find(q => q.id === questionId).question],
regex
}]
});
}
};
render() {
const {questionId, regex} = this.state;
const availableQuestions = this.context.surveyQuestions
.filter(q => q.componentType === "input" && q.dataType === "text");
return availableQuestions.length > 0
? (
<>
<div className="form-group">
<label>Survey Question</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({questionId: Number(e.target.value)})}
value={questionId}
>
<option value={-1}>- Select Question -</option>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
</div>
<div className="form-group">
<label>Enter regular expression</label>
<input
className="form-control form-control-sm"
onChange={e => this.setState({regex: e.target.value})}
placeholder="Regular expression"
type="text"
value={regex}
/>
</div>
<div className="d-flex justify-content-end">
<input
className="btn btn-lightgreen"
onClick={this.addSurveyRule}
type="button"
value="Add Survey Rule"
/>
</div>
</>
) : <label>This rule requires a question of type input-text.</label>;
}
}
TextMatchForm.contextType = ProjectContext;
class NumericRangeForm extends React.Component {
constructor(props) {
super(props);
this.state = {
questionId: -1,
min: 0,
max: 0
};
}
addSurveyRule = () => {
const {surveyRules, surveyQuestions, setProjectDetails} = this.context;
const {questionId, min, max} = this.state;
const conflictingRule = surveyRules.find(rule => rule.ruleType === "numeric-range"
&& rule.questionId === questionId);
const errorMessages = [
conflictingRule && "A numeric range rule already exists for this question. (Rule " + conflictingRule.id + ")",
questionId < 1 && "You must select a question.",
(max <= min) && "Max must be larger than min."
].filter(m => m);
if (errorMessages.length > 0) {
alert(errorMessages.map(s => "- " + s).join("\n"));
} else {
setProjectDetails({
surveyRules: [...surveyRules, {
id: getNextId(surveyRules),
ruleType: "numeric-range",
questionId,
questionsText: [surveyQuestions.find(q => q.id === questionId).question],
min,
max
}]
});
}
};
render() {
const {questionId, min, max} = this.state;
const availableQuestions = this.context.surveyQuestions
.filter(q => q.componentType === "input" && q.dataType === "number");
return availableQuestions.length > 0
? (
<>
<div className="form-group">
<label>Survey Question</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({questionId: Number(e.target.value)})}
value={questionId}
>
<option value={-1}>- Select Question -</option>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
</div>
<div className="form-group">
<label>Enter minimum</label>
<input
className="form-control form-control-sm"
onChange={e => this.setState({min: Number(e.target.value)})}
placeholder="Minimum value"
type="number"
value={min}
/>
</div>
<div className="form-group">
<label>Enter maximum</label>
<input
className="form-control form-control-sm"
onChange={e => this.setState({max: Number(e.target.value)})}
placeholder="Maximum value"
type="number"
value={max}
/>
</div>
<div className="d-flex justify-content-end">
<input
className="btn btn-lightgreen"
onClick={this.addSurveyRule}
type="button"
value="Add Survey Rule"
/>
</div>
</>
) : <label>This rule requires a question of type input-number.</label>;
}
}
NumericRangeForm.contextType = ProjectContext;
class SumOfAnswersForm extends React.Component {
constructor(props) {
super(props);
this.state = {
validSum: 0,
questionIds: []
};
}
addSurveyRule = () => {
const {surveyRules, surveyQuestions, setProjectDetails} = this.context;
const {questionIds, validSum} = this.state;
const conflictingRule = surveyRules.find(rule => rule.ruleType === "sum-of-answers"
&& sameContents(questionIds, rule.questions));
const errorMessages = [
conflictingRule && "A sum of answers rule already exists for these questions. (Rule " + conflictingRule.id + ")",
(questionIds.length < 2) && "Sum of answers rule requires the selection of two or more questions.",
!isNumber(validSum) && "You must ender a valid sum number."
].filter(m => m);
if (errorMessages.length > 0) {
alert(errorMessages.map(s => "- " + s).join("\n"));
} else {
setProjectDetails({
surveyRules: [...surveyRules, {
id: getNextId(surveyRules),
ruleType: "sum-of-answers",
questions: questionIds,
questionsText: surveyQuestions
.filter(q => questionIds.includes(q.id))
.map(q => q.question),
validSum
}]
});
}
};
render() {
const {questionIds, validSum} = this.state;
const availableQuestions = this.context.surveyQuestions.filter(q => q.dataType === "number");
return availableQuestions.length > 1
? (
<>
<div className="form-group">
<label>Select survey question</label>
<select
className="form-control form-control-sm overflow-auto"
multiple="multiple"
onChange={e => this.setState({
questionIds: Array.from(e.target.selectedOptions, i => Number(i.value))
})}
value={questionIds}
>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
<small className="form-text text-muted">Hold ctrl/cmd and select multiple questions</small>
</div>
<div className="form-group">
<label>Enter valid sum</label>
<input
className="form-control form-control-sm"
onChange={e => this.setState({validSum: Number(e.target.value)})}
placeholder="Valid sum"
type="number"
value={validSum}
/>
</div>
<div className="d-flex justify-content-end">
<input
className="btn btn-lightgreen"
onClick={this.addSurveyRule}
type="button"
value="Add Survey Rule"
/>
</div>
</>
) : <label>There must be at least 2 number questions for this rule type.</label>;
}
}
SumOfAnswersForm.contextType = ProjectContext;
class MatchingSumsForm extends React.Component {
constructor(props) {
super(props);
this.state = {
questionSetIds1: [],
questionSetIds2: []
};
}
addSurveyRule = () => {
const {surveyRules, surveyQuestions, setProjectDetails} = this.context;
const {questionSetIds1, questionSetIds2} = this.state;
const conflictingRule = surveyRules.find(rule => rule.ruleType === "matching-sums"
&& sameContents(questionSetIds1, rule.questionSetIds1)
&& sameContents(questionSetIds2, rule.questionSetIds2));
const errorMessages = [
conflictingRule && "A matching sums rule already exists for these questions. (Rule " + conflictingRule.id + ")",
(questionSetIds1.length < 2 && questionSetIds2.length < 2)
&& "Matching sums rule requires that at least one of the question sets contain two or more questions.",
questionSetIds1.length === 0 && "You must select at least one question from the first set.",
questionSetIds2.length === 0 && "You must select at least one question from the second set.",
questionSetIds1.some(id => questionSetIds2.includes(id))
&& "Question set 1 and 2 cannot contain the same question."
].filter(m => m);
if (errorMessages.length > 0) {
alert(errorMessages.map(s => "- " + s).join("\n"));
} else {
setProjectDetails({
surveyRules: [...surveyRules, {
id: getNextId(surveyRules),
ruleType: "matching-sums",
questionSetIds1,
questionSetIds2,
questionSetText1: surveyQuestions
.filter(q => questionSetIds1.includes(q.id))
.map(q => q.question),
questionSetText2: surveyQuestions
.filter(q => questionSetIds2.includes(q.id))
.map(q => q.question)
}]
});
}
};
render() {
const {questionSetIds1, questionSetIds2} = this.state;
const availableQuestions = this.context.surveyQuestions.filter(q => q.dataType === "number");
return availableQuestions.length > 1
? (
<>
<div className="form-group">
<label>Select first question set</label>
<select
className="form-control form-control-sm overflow-auto"
multiple="multiple"
onChange={e => this.setState({
questionSetIds1: Array.from(e.target.selectedOptions, i => Number(i.value))
})}
value={questionSetIds1}
>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
<small className="form-text text-muted">Hold ctrl/cmd and select multiple questions</small>
</div>
<div className="form-group">
<label>Select second question set</label>
<select
className="form-control form-control-sm overflow-auto"
multiple="multiple"
onChange={e => this.setState({
questionSetIds2: Array.from(e.target.selectedOptions, i => Number(i.value))
})}
value={questionSetIds2}
>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
<small className="form-text text-muted">Hold ctrl/cmd and select multiple questions</small>
</div>
<div className="d-flex justify-content-end">
<input
className="btn btn-lightgreen"
onClick={this.addSurveyRule}
type="button"
value="Add Survey Rule"
/>
</div>
</>
) : <label>There must be at least 2 number questions for this rule type.</label>;
}
}
MatchingSumsForm.contextType = ProjectContext;
class IncompatibleAnswersForm extends React.Component {
constructor(props) {
super(props);
this.state = {
questionId1: -1,
questionId2: -1,
answerId1: -1,
answerId2: -1
};
}
checkPair = (q1, a1, q2, a2) => q1 === q2 && a1 === a2;
checkEquivalent = (q1, a1, q2, a2, q3, a3, q4, a4) =>
(this.checkPair(q1, a1, q3, a3) && this.checkPair(q2, a2, q4, a4))
|| (this.checkPair(q1, a1, q4, a4) && this.checkPair(q2, a2, q3, a3));
addSurveyRule = () => {
const {surveyRules, surveyQuestions, setProjectDetails} = this.context;
const {questionId1, answerId1, questionId2, answerId2} = this.state;
const conflictingRule = surveyRules.find(({question1, answer1, question2, answer2, ruleType}) => ruleType === "incompatible-answers"
&& this.checkEquivalent(
question1,
answer1,
question2,
answer2,
questionId1,
answerId1,
questionId2,
answerId2
));
const errorMessages = [
conflictingRule
&& "An incompatible answers rule already exists for these question / answer pairs. (Rule "
+ conflictingRule.id
+ ")",
(questionId1 === questionId2) && "You must select two different questions.",
questionId1 < 1 && "You must select a valid first question.",
questionId2 < 1 && "You must select a valid second question.",
(answerId1 < 1 || answerId2 < 1) && "You must select an answer for each question."
].filter(m => m);
if (errorMessages.length > 0) {
alert(errorMessages.map(s => "- " + s).join("\n"));
} else {
const q1 = surveyQuestions.find(q => q.id === questionId1);
const q2 = surveyQuestions.find(q => q.id === questionId2);
setProjectDetails({
surveyRules: [...surveyRules, {
id: getNextId(surveyRules),
ruleType: "incompatible-answers",
question1: questionId1,
question2: questionId2,
answer1: answerId1,
answer2: answerId2,
questionText1: q1.question,
questionText2: q2.question,
answerText1: q1.answers.find(a => a.id === answerId1).answer,
answerText2: q2.answers.find(a => a.id === answerId2).answer
}]
});
}
};
safeFindAnswers = questionId => {
const question = this.context.surveyQuestions.find(q => q.id === questionId);
const answers = question && question.answers;
return answers || [];
};
render() {
const {questionId1, answerId1, questionId2, answerId2} = this.state;
const availableQuestions = this.context.surveyQuestions.filter(q => q.componentType !== "input");
return availableQuestions.length > 1
? (
<>
<strong className="mb-2" style={{textAlign: "center"}}>Select the incompatible questions and answers</strong>
<div className="form-group">
<label>Question 1</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({
questionId1: Number(e.target.value),
answerId1: -1
})}
value={questionId1}
>
<option value="-1">- Select Question 1 -</option>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
</div>
<div className="form-group">
<label>Answer 1</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({answerId1: Number(e.target.value)})}
value={answerId1}
>
<option value="-1">- Select Answer 1 -</option>
{this.safeFindAnswers(questionId1).map(answer =>
<option key={answer.id} value={answer.id}>{answer.answer}</option>)}
</select>
</div>
<div className="form-group">
<label>Question 2</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({
questionId2: Number(e.target.value),
answerId2: -1
})}
value={questionId2}
>
<option value="-1">- Select Question 2 -</option>
{availableQuestions.map(question =>
<option key={question.id} value={question.id}>{question.question}</option>)}
</select>
</div>
<div className="form-group">
<label>Answer 2</label>
<select
className="form-control form-control-sm"
onChange={e => this.setState({answerId2: Number(e.target.value)})}
value={answerId2}
>
<option value="-1">- Select Answer 2 -</option>
{this.safeFindAnswers(questionId2).map(answer =>
<option key={answer.id} value={answer.id}>{answer.answer}</option>)}
</select>
</div>
<div className="d-flex justify-content-end">
<input
className="btn btn-lightgreen"
onClick={this.addSurveyRule}
type="button"
value="Add Survey Rule"
/>
</div>
</>
) : <label>There must be at least 2 questions where type is not input for this rule.</label>;
}
}
IncompatibleAnswersForm.contextType = ProjectContext;
|
// if change the 'printWidth' don't forget set same value:
// - for `max_line_length` in `.editorconfig`
// - for `max-len` rule in `eslint` config
module.exports = {
printWidth: 120,
singleQuote: true,
trailingComma: 'all',
};
|
$(function() {
var app_id = '184245778775374';
var scopes = 'email, public_profile, user_friends';
var btn_login = '<a href="#" id="login"><img src="../LOGO/face.png" width= "18%"></a>';
var div_session = "<div id='facebook-session'>"+
"<a href='#' id='logout' class='btn btn-danger'>DESLOGAR</a>"+
"</div>";
window.fbAsyncInit = function() {
FB.init({
appId : app_id,
status : true,
cookie : true,
xfbml : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response, function() {});
});
};
var statusChangeCallback = function(response, callback){
if (response.status === 'connected') {
getFacebookData();
} else {
callback(false);
}
}
var checkLoginState = function(callback) {
FB.getLoginStatus(function(response) {
callback(response);
});
}
var getFacebookData = function() {
FB.api('/me', function(response) {
$('#login').after(div_session);
$('#login').remove();
});
}
var facebookLogin = function() {
checkLoginState(function(data) {
if (data.status !== 'connected') {
FB.login(function(response) {
if (response.status === 'connected')
getFacebookData();
window.location = "https://rodrigogmartins.github.io/mov/feed.html";
}, {scope: scopes});
}
})
}
var facebookLogout = function() {
checkLoginState(function(data) {
if (data.status === 'connected') {
FB.logout(function(response) {
$('#facebook-session').before(btn_login);
$('#facebook-session').remove();
})
}
})
}
$(document).on('click', '#login', function(e) {
e.preventDefault();
facebookLogin();
})
$(document).on('click', '#logout', function(e) {
e.preventDefault();
return confirm("Quer mesmo deslogar?")?facebookLogout():false;
})
})
|
// @flow
import {
AUTH_ASAP,
AUTH_BASIC,
AUTH_BEARER,
AUTH_HAWK,
AUTH_OAUTH_1,
AUTH_OAUTH_2
} from '../common/constants';
import getOAuth2Token from './o-auth-2/get-token';
import getOAuth1Token from './o-auth-1/get-token';
import * as Hawk from 'hawk';
import jwtAuthentication from 'jwt-authentication';
import type { RequestAuthentication } from '../models/request';
import { getBasicAuthHeader } from './basic-auth/get-header';
import { getBearerAuthHeader } from './bearer-auth/get-header';
type Header = {
name: string,
value: string
};
export async function getAuthHeader(
requestId: string,
url: string,
method: string,
authentication: RequestAuthentication
): Promise<Header | null> {
if (authentication.disabled) {
return null;
}
if (authentication.type === AUTH_BASIC) {
const { username, password } = authentication;
return getBasicAuthHeader(username, password);
}
if (authentication.type === AUTH_BEARER) {
const { token, prefix } = authentication;
return getBearerAuthHeader(token, prefix);
}
if (authentication.type === AUTH_OAUTH_2) {
// HACK: GraphQL requests use a child request to fetch the schema with an
// ID of "{{request_id}}.graphql". Here we are removing the .graphql suffix and
// pretending we are fetching a token for the original request. This makes sure
// the same tokens are used for schema fetching. See issue #835 on GitHub.
const tokenId = requestId.match(/\.graphql$/) ? requestId.replace(/\.graphql$/, '') : requestId;
const oAuth2Token = await getOAuth2Token(tokenId, authentication);
if (oAuth2Token) {
const token = oAuth2Token.accessToken;
return _buildBearerHeader(token, authentication.tokenPrefix);
} else {
return null;
}
}
if (authentication.type === AUTH_OAUTH_1) {
const oAuth1Token = await getOAuth1Token(url, method, authentication);
if (oAuth1Token) {
return {
name: 'Authorization',
value: oAuth1Token.Authorization
};
} else {
return null;
}
}
if (authentication.type === AUTH_HAWK) {
const { id, key, algorithm } = authentication;
const header = Hawk.client.header(url, method, {
credentials: { id, key, algorithm }
});
return {
name: 'Authorization',
value: header.field
};
}
if (authentication.type === AUTH_ASAP) {
const { issuer, subject, audience, keyId, additionalClaims, privateKey } = authentication;
const generator = jwtAuthentication.client.create();
let claims = { iss: issuer, sub: subject, aud: audience };
let parsedAdditionalClaims;
try {
parsedAdditionalClaims = JSON.parse(additionalClaims || '{}');
} catch (err) {
throw new Error(`Unable to parse additional-claims: ${err}`);
}
if (parsedAdditionalClaims) {
if (typeof parsedAdditionalClaims !== 'object') {
throw new Error(
`additional-claims must be an object received: '${typeof parsedAdditionalClaims}' instead`
);
}
claims = Object.assign(parsedAdditionalClaims, claims);
}
const options = {
privateKey,
kid: keyId
};
return new Promise((resolve, reject) => {
generator.generateAuthorizationHeader(claims, options, (error, headerValue) => {
if (error) {
reject(error);
} else {
resolve({
name: 'Authorization',
value: headerValue
});
}
});
});
}
return null;
}
function _buildBearerHeader(accessToken, prefix) {
if (!accessToken) {
return null;
}
const name = 'Authorization';
const value = `${prefix || 'Bearer'} ${accessToken}`;
return { name, value };
}
|
//////////////////////////////////////////////
// TODO:
// put in CQ
// Mobile Events - test these
//////////////////////////////////////////////
if (typeof jQuery === "undefined") {
throw "This widget requires jquery module to be loaded";
}
(function($){
var widgetObj = {
options: {
viewportSel: '.viewport',
slideSel: '.slide',
slideContSel: '.photo-list',
activeClass: 'active',
prevClass: 'prev',
prevAltClass: 'prev-alt',
nextClass: 'next',
nextAltClass: 'next-alt',
useTouchEvents: true,
useNav: true,
navContSel: '.nav-bar',
navNextSel: '.slide-nav-next',
navPrevSel: '.slide-nav-prev',
captionBarSel: '.caption-bar',
automate: true, //have slider itterate on a timer
pauseInterval: 10000, //time in millisecionds between slides
slideSpeed: 800, //speed in milliseconds the slider moves
toSandbag: true,
height: 'max' //set height of carousel - based on largest image ("max"), smallest ("min"), or a value
},
//**********************//
// PRIVATE METHODS //
//**********************//
_create: function () {
},
_init: function() {
// -- Local Vars -- //
//get slides
this.slideArr = this.element.find(this.options.slideSel);
// -- Element Vars --//
this.viewport = this.element.find(this.options.viewportSel);
this.captionHolder = this.element.find(this.options.captionBarSel);
this.slideCont = this.element.find(this.options.slideContSel); //store slide container for simple moving
this.jqSlideArr = this._populateJQArr(this.slideArr); //populate a jquery array for faster classing
this.slidePhotoTimer = null; //timer to move playhead
this.isEnabled = true; //track if the slider is enabled
this.isSliding = false; //track if the slider is actively sliding
this.userStopped = false;
this.activeSlide = 0;
// -- Actions -- //
this._populateCaptionArr(this.jqSlideArr);
this.captionHolder.html(this.captionArr[this.activeSlide]);
var slideLen = this.slideArr.length;
if ( slideLen < 1 ) {
return false; // no slides
}
else if( slideLen<2 ) {
this._convertToImage();
} else {
// Set height of view panel
if (this.options.toSandbag) { this._setSizing( this.slideArr, this.slideCont ); }
//ensure we have enough slides for this to work (5)
this._checkSlideCount();
// set the first slide as active
this._setActiveSlide(this.activeSlide);
//bind buttons - next and back if enabled
if (this.options.useNav) {
this._bindNav();
}
//bind touch events if function is included and option is chosen
if (Modernizr.touch){
console.log('you have touch');
}
if (this.options.useTouchEvents ) {
this._bindTouch();
}
//if set to automate start the loop
if (this.options.automate ) {
this._automate();
}
}
},
_setSizing : function($arr, $container){
var self = this,
baseSize = 0,
$sandBagImg,
$toAppend;
switch (this.options.height) {
case 'max':
// find the tallest
$arr.each( function ( i ) {
var $this = $(this),
tempH = $this.outerHeight();
if ( tempH > baseSize ) {
baseSize = tempH;
$sandBagImg = $this;
}
} );
break;
case 'min':
// find the shortest
$arr.each( function ( i ) {
var $this = $(this),
tempH = $this.outerHeight();
baseSize = ( i == 0 ) ? tempH : baseSize;
if ( tempH <= baseSize && tempH != 0) {
baseSize = tempH;
$sandBagImg = $this;
}
} );
break;
default:
if ( typeof self.height === 'number' ) {
$sandBagImg = $($arr[0]).clone();
$sandBagImg.find('img').height( self.height );
} else {
//if self.height is not a valid value set it to min, and then run it
self.height = 'min';
self._setSizing();
return false;
}
break;
}
$toAppend = $sandBagImg.clone().addClass('sandbag');
//$toAppend = "<img class='sandbag' height='" + baseSize + "px' alt='sandbag image' src=''/>"
$container.after( $toAppend );
//set image positions to absolute and rely on the sandbag for sizing
$arr.each( function ( j ) {
var $this = $( this );
$this.find('img').css("position", "absolute");
$this.append( $toAppend.clone() );
} );
return self;
},
_populateCaptionArr: function ($slideArr) {
var i=0,
len = $slideArr.length;
this.captionArr = [];
for (; i<len; i++) {
this.captionArr.push( $slideArr[i].find(".caption").clone() );
}
},
_checkSlideCount: function () {
// if there are less than 5 items we need to dupliate the slide list
if(this.jqSlideArr.length<5) {
// go through each slide in the original slide array (the new array will gro expotentially otherwise)
var i = 0, len = this.slideArr.length;
for (; i<len; i++) {
// make a clone of the slide - mine are simple so i don't need to add a more complex clone
var clone = this.jqSlideArr[i].clone();
// add the slide to the DOM
this.slideCont.append(clone);
// add the slide to the slide array
this.jqSlideArr.push(clone);
};
// make the function recursive
this._checkSlideCount();
}
},
_bindNav: function () {
var self = this;
this.nextBtn = this.element.find(this.options.navNextSel);
this.prevBtn = this.element.find(this.options.navPrevSel);
this.nextBtn.on('click', function ( e ) {
e.preventDefault();
self.userStopped = true;
self._advanceSlides(1);
});
this.prevBtn.on('click', function ( e ) {
e.preventDefault();
self.userStopped = true;
self._advanceSlides(-1);
});
},
_bindTouch: function () {
var self = this;
ontouch(this.viewport[0], function(evt, dir, phase, swipetype, distance){
if (self.isSliding || !self.isEnabled) { return false }; // return if currently in a slide or disabled
if (phase == 'start'){ // on touchstart
self.isSliding = true; // set isSliding to preven other actions
self.listLeft = parseInt(this.viewport.css('margin-left')) || 0; // initialize ulLeft var with left position of UL
self.viewportWidth = this.viewport.width(); // store viewport width for faster processing
}
else if (phase == 'move' && (dir =='left' || dir =='right')){ // on touchmove and if moving left or right
var totaldist = distance + self.listLeft; // calculate new left position of UL based on movement of finger
var newPos = Math.min(totaldist, self.viewportWidth) + 'px'; // set gallery to new left position
this.viewport.css('margin-left', newPos); //adjust viewport width to new width
}
else if (phase == 'end'){ // on touchend
self.isSliding = false; // set to false in order to move items
if (swipetype == 'left'){ // if swipe left
self._advanceSlides(-1);
} else if (swipetype == 'right') { // if swipe right
self._advanceSlides(1);
} else { //not a swipe, reset to base position
self._advanceSlides(0);
}
}
}); // end ontouch
},
_automate: function () {
var self = this;
// set up timer
self._slideStart();
self.element.on( 'stop', function() {
window.clearInterval( self.slideTimer );
} );
self.element.on( 'mouseenter', function(){
$(this).trigger('stop');
});
self.element.on( 'mouseleave', function(){
if (!self.userStopped) {
self._slideStart();
}
});
return self;
},
_setActiveSlide: function (v) {
this._removeActiveClasses();
var prev = this._normalizeNum( v - 1 ),
prevalt = this._normalizeNum( v - 2 ),
next = this._normalizeNum( v + 1 ),
nextalt = this._normalizeNum( v + 2 );
this.activeSlide = v;
this.jqSlideArr[v].addClass(this.options.activeClass);
this.jqSlideArr[prev].addClass(this.options.prevClass);
this.jqSlideArr[prevalt].addClass(this.options.prevAltClass);
this.jqSlideArr[next].addClass(this.options.nextClass);
this.jqSlideArr[nextalt].addClass(this.options.nextAltClass);
},
_removeActiveClasses: function () {
this.slideCont.find('.'+this.options.activeClass).removeClass(this.options.activeClass);
this.slideCont.find('.'+this.options.prevClass).removeClass(this.options.prevClass);
this.slideCont.find('.'+this.options.prevAltClass).removeClass(this.options.prevAltClass);
this.slideCont.find('.'+this.options.nextClass).removeClass(this.options.nextClass);
this.slideCont.find('.'+this.options.nextAltClass).removeClass(this.options.nextAltClass);
},
_slideStart: function () {
var self = this;
self.slideTimer = window.setInterval( function() {
self._advanceSlides(1);
}, self.options.pauseInterval );
self.isEnabled = true;
},
_slideStop: function () {
window.clearInterval( this.slidePhotoTimer );
this.isEnabled = false;
},
_advanceSlides: function (v) {
// only trigger if enabled and not sliding
if (!this.isEnabled || this.isSliding) { return false; }
this.isSliding = true;
var self = this;
this.captionHolder.transition({"opacity": 0}, 200, function () {
self._transitionSlide(v);
});
},
_transitionSlide: function (v) {
var toMove = (-v * 100) + "%", //calc the move val in percent
self = this; // create a reference to this for inside the function
this.slideCont.transition({"margin-left": toMove}, this.options.slideSpeed, function () {
//reset slider and slides
self.slideCont.css("margin-left", 0);
var newActive = self._normalizeNum(self.activeSlide+v);
self._setActiveSlide(newActive);
self._changeCaption(newActive);
});
},
_changeCaption: function (v) {
var self = this;
this.captionHolder.html(this.captionArr[v]);
this.captionHolder.transition({"opacity": 1}, 200, function () {
self.isSliding = false;
});
},
_convertToImage: function () {
this.isEnabled = false;
this.jqSlideArr[0].addClass(this.options.activeClass);
this.captionHolder.html(this.captionArr[0]);
if (this.options.useNav) {
$(this.options.navContSel).hide();
}
},
/* ===== HELPER METHODS ===== */
_normalizeNum : function ( num ) {
//ensure num is always a valid number
var len = this.jqSlideArr.length,
num = ( num < 0 ) ? len + num : num,
num = ( num > len -1 ) ? num - len : num;
return num;
},
_populateJQArr : function ( arr ) {
var i=0, tempArr = [];
//populate an array of Jquery objects
for (; i<arr.length; i++) {
var $temp = $( arr[i] );
tempArr.push( $temp );
}
return tempArr;
},
//**********************//
// PUBLIC METHODS //
//**********************//
moveSlides: function (v) {
var toMove = (v) ? v : 1;
this._advanceSlides(v);
},
pauseSlides : function(){
this.element.trigger('stop');
return this;
},
disableSlides : function () {
this.element.trigger('stop');
this.isEnabled = false;
return this;
},
startSlides : function(){
this._slideStart();
this.isEnabled = true;
return this;
}
};
$.widget( 'ui.marqueeSlide', widgetObj );
/**
* Example
* $( '#myID' ).marqueeSlide();
**/
})(jQuery);
|
var byname, microdom;
if (typeof require !== "undefined") {
byname = require("../byname.js");
microdom = require('microdom');
} else {
byname = window.byname;
microdom = window.microdom;
}
var ok = function(a, msg) { if (!a) throw new Error(msg || "not ok"); };
describe('byname', function() {
describe('#byName', function() {
it('should return an array of found nodes', function() {
var dom = microdom('<a><b><c><d></d></c></b></a>');
var results = dom.byName('a');
ok(results.length === 1);
ok(results[0] === dom.child(0));
});
it('should return an empty array when no nodes are found', function() {
var dom = microdom('<a><b><c><d></d></c></b></a>');
var results = dom.byName('e');
ok(results.length === 0);
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.