code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/**
* replace
* @author sanshishen
* @email 1327653237@qq.com
* @date 2015-08-31 15:47:52
* @version 1.0.0
*/
/**
* myApp Module
*
* Description
*/
angular.module('myApp', [])
.directive('hello', function(){
// Runs during compile
return {
// name: '',
// priority: 1,
// terminal: true,
// scope: {}, // {} = isolate, true = child, false/undefined = no change
// controller: function($scope, $element, $attrs, $transclude) {},
// require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
template: '<div>Hello everyone!</div>',
// templateUrl: '',
replace: true,
// transclude: true,
// compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
link: function($scope, iElm, iAttrs, controller) {
}
};
}); | sanshishen/AngularJS | chapter005_directive/js/replace.js | JavaScript | mit | 958 |
/**
* Created by OmarCespedes on 16/09/2015.
*/
var Board = (function(){
var instance;
function init(){
//Private stuff
var board = [];
var row = [];
var MAX_Y = 0;
var MAX_X = 0;
function setMAX_X(value){
MAX_X = value
}
function setMAX_Y(value){
MAX_Y = value
}
function checkFreeCells(){
for(var i = 0 ; i < MAX_X ; i++){
for(var j = 0 ; j < MAX_Y ; j++){
if(board[i][j] == 0){
return true
}
}
}
return false
}
return {
//Public stuff
getMAX_X : function () {
return MAX_X
},
getMAX_Y : function () {
return MAX_Y
},
createBoard : function (height, width) {
var gameBoard = $('#gameBoard');
setMAX_X(height);
setMAX_Y(width);
gameBoard.css('height', (height + 1) * 30 + 3 * height);
gameBoard.css('width', (width + 1) * 30 + 3 * width);
//gameBoard.css('display','block');
for(var i = 1 ; i < height + 1 ; i++){
for(var j = 1 ; j < width + 1 ; j++){
var divEl = '<div id="' + i + "x" + j + 'y" class="floor"></div>';
gameBoard.append(divEl);
row.push(0);
}
board.push(row);
row = [];
}
},
getLogicArray : function () {
return board;
},
changeCellType: function (x, y, type){
var cellId = x + 'x' + y + 'y';
var cell = $('#' + cellId);
cell.removeClass();
cell.addClass(type);
},
generateRandomObstacles : function(number){
var randomX;
var randomY;
var cont = 0;
while(cont < number){
randomX = Math.round(Math.random() * 9);
randomY = Math.round(Math.random() * 9);
if(board[randomX][randomY] === 0){
this.changeCellType(randomX + 1, randomY + 1, 'obstacle');
board[randomX][randomY] = 1;
cont++;
}
}
},
generateRandomCoin : function(){
var randomX;
var randomY;
while(true){
randomX = Math.round(Math.random() * 9);
randomY = Math.round(Math.random() * 9);
if(board[randomX][randomY] === 0){
this.changeCellType(randomX + 1, randomY + 1, 'coin');
board[randomX][randomY] = 4;
break;
} else {
if(!checkFreeCells())
break
}
}
},
generateRandomChest : function(){
var randomX;
var randomY;
while(true){
randomX = Math.round(Math.random() * 9);
randomY = Math.round(Math.random() * 9);
if(board[randomX][randomY] === 0){
this.changeCellType(randomX + 1, randomY + 1, 'chest');
board[randomX][randomY] = 5;
break;
}
}
},
generateRandomFreePoint : function(){
var randomX;
var randomY;
while(true){
randomX = Math.round(Math.random() * 9);
randomY = Math.round(Math.random() * 9);
if(board[randomX][randomY] === 0){
return {x : randomX, y : randomY}
}
}
}
}
}
return {
getInstance : function(){
if(!instance){
instance = init();
}
return instance
}
};
})(); | omar234/GhostEscape | js/Board.js | JavaScript | mit | 4,352 |
{
var el = instance.document.getRef(nodeId);
if (el) {
return instance.document.fireEvent(el, type, e, domChanges);
}
return new Error('invalid element reference "' + nodeId + '"');
}
| stas-vilchik/bdd-ml | data/12505.js | JavaScript | mit | 198 |
var p = require('deployk-utils').path;
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var async = require('async');
var extend = require('config-extend');
var DeployEmitter = require('./Emitter');
var DeployContext = require('./Context');
var WatchWrapper = require('./../Rule/WatchWrapper');
var MirrorTree = require('../Mirror/MirrorTree');
var MirrorSync = require('../Mirror/MirrorSync');
var diffMirrorTree = require('../Mirror-Diff/diffMirrorTree');
var diffMirrorSync = require('../Mirror-Diff/diffMirrorSync');
var DeferEmitter = require('../Mirror-Diff/DeferEmitter');
var PathEmitter = require('../Mirror-Diff/PathEmitter');
var UntreeEmitter = require('../Mirror-Diff/UntreeEmitter');
var SharedEmitter = require('../Mirror-Diff/SharedEmitter');
var SharedTree = require('../Mirror-Diff/SharedTree');
module.exports = DeployProcess;
/**
* @param {Config}
* @param {LocalWrapper}
* @param {RemoteWrapper}
* @constructor
*/
function DeployProcess(config, local, remote)
{
var self = this;
EventEmitter.call(this);
/** @var {Config} */
this.config = config;
/** @var {LocalWrapper} */
this.local = local;
/** @var {RemoteWrapper} */
this.remote = remote;
this.remote.on('command', function(client, message) {
self.emit('command', client, message);
});
/** @var {boolean} */
this.aborted = false;
/** @var {SharedTree} */
this.sharedTree = new SharedTree();
/** @var {MirrorTree} */
this.mirrorTree;
/** @var {Array.<Object>} */
this.mirrorSyncList = [];
/** @var {DeployContext} */
this.context = new DeployContext(this);
this.context.on('start', function(message, done, total) {
self.emit('step', 'async: ' + done + '/' + total + (message ? '; Start: ' + message : ''));
});
this.context.on('end', function(message, done, total) {
self.emit('step', 'async: ' + done + '/' + total + (message ? '; Done: ' + message : ''));
});
/** @var {WatchWrapper} */
this.watchWrapper = new WatchWrapper(config.watchList, this.context.createContext());
/** @var {WatchWrapper} */
this.globWrapper = new WatchWrapper(config.globList, this.context.createContext());
};
util.inherits(DeployProcess, EventEmitter);
DeployProcess.prototype.abort = function(message)
{
this.aborted = message ? message : true;
};
DeployProcess.prototype.should = function(run)
{
var self = this;
return function(cb) {
if (self.aborted) {
cb(true);
} else {
run(cb);
}
};
};
DeployProcess.prototype.run = function(opts)
{
opts = extend({
dry: false,
setup: false
}, opts);
var self = this;
async.series([
this.should(function(cb) {
self.emit('step', '1/9:\tConnect to remote server.');
self.remote.connect(function(err) {
if (err) self.abort('Could not connect to remote server.');
cb();
})
}),
this.should(function(cb) {
self.mirrorTree = new MirrorTree(self.remote.walk('/'));
self.createMirrorTree();
self.createMirrorSyncList();
cb();
}),
this.should(function(cb) {
self.emit('step', '2/9:\tMirror project tree.');
self.mirrorTree.run(cb);
}),
this.should(function(cb) {
self.emit('step', '3/9:\tbefore events.')
self.config.eventList['before'].forEach(function(event) {
event.apply(self.context.createContext());
});
self.context.whenDone(function() {
cb();
});
}),
this.should(function(cb) {
self.emit('step', '4/9:\tGlob events');
self.local.glob(self.globWrapper.buildPatterns(), function(files) {
self.emit('step', '5/9:\tSynchronization loop.');
Object.keys(files).forEach(function(file) {
self.globWrapper.track(file);
});
cb();
});
}),
this.should(function(cb) {
self.runLoop(cb);
}),
this.should(function(cb) {
if (opts.dry) {
self.emit('step', '6/9:\tSkip setup.');
cb();
} else {
if (opts.setup) {
self.emit('step', '6/9:\tSetup project and deploy dirs.');
} else {
self.emit('step', '6/9:\tSetup deploy dirs.');
}
self.remote.setup(opts.setup, function(err) {
if (err && opts.setup) {
self.abort('Could not setup project and deploy dir.');
} else if (err) {
self.abort('Could not setup deploy dir. Project dir is probably missing, call setup to create ' + self.remote.basedir);
}
cb();
});
}
}),
this.should(function(cb) {
var emitter, defer = new DeferEmitter();
self.emit('step', '7/9:\tCalculate diffs between local and remote.');
emitter = defer;
emitter = new DeployEmitter(emitter, self.local, self.config.dirRights, self.config.fileRights);
diffMirrorTree(self.mirrorTree, emitter);
self.mirrorSyncList.forEach(function(sync) {
emitter = defer;
emitter = new DeployEmitter(emitter, self.local, self.config.dirRights, self.config.fileRights);
emitter = new SharedEmitter(emitter, self.sharedTree);
emitter = new PathEmitter(emitter, sync.remoteDir, sync.localDir);
diffMirrorSync(sync.from, sync.to, emitter);
});
self.emit('step', ' - \t\tPending: ' + defer.getLength() + ' commands.');
if (opts.dry) {
self.abort('Dry mode. Commands not executed.');
cb();
} else {
defer.emit(self.remote);
self.remote.whenDone(function() {
cb();
});
}
}),
this.should(function(cb) {
self.emit('step', '8/9:\tCommit changes into production.');
self.emit('step', ' - \t\tPending: ' + self.remote.getDelayedLength() + ' commands.');
self.remote.commit(function() {
cb();
});
}),
this.should(function(cb) {
self.emit('step', '9/9:\tbeforeend events.');
self.config.eventList['beforeend'].forEach(function(event) {
event.apply(self.context.createWaitContext());
});
self.context.whenDone(function() {
cb();
});
}),
], function(err) {
if (err===undefined) {
self.emit('success');
} else {
self.emit('abort', self.aborted);
}
self.emit('end');
})
};
/**
* @param {function}
*/
DeployProcess.prototype.runLoop = function(cb)
{
var self = this;
async.doWhilst(
function(cb) {
self.context.whenDone(function() {
var defer = new DeferEmitter();
var changes = self.context.purgeChanges();
var syncList = [].concat(self.mirrorSyncList);
async.whilst(
function() { return self.aborted===false && syncList.length>0; },
function(cb) {
var sync = syncList.shift();
if (changes===true) {
sync.from.prepare('', true);
sync.to.prepare('');
} else {
changes.local.forEach(function(local) {
if (local = sync.sync.localMonitored(local)) {
sync.from.prepare(local, true);
sync.to.prepare(local);
}
});
changes.remote.forEach(function(remote) {
if (remote = sync.sync.remoteMonitored(remote)) {
sync.from.prepare(remote, true);
sync.to.prepare(remote);
}
});
}
self.emit('step', ' - \t\tSync ' + sync.localDir + ' -> ' + sync.remoteDir);
async.parallel([
sync.from.run.bind(sync.from),
sync.to.run.bind(sync.to)
], function(err) {
var emitter = defer;
emitter = new DeployEmitter(emitter, self.local, self.config.dirRights, self.config.fileRights);
emitter = new PathEmitter(emitter, sync.remoteDir, sync.localDir);
emitter = new UntreeEmitter(emitter);
diffMirrorSync(sync.from, sync.to, emitter);
cb();
});
},
function() {
self.emit('step', ' - \t\tPending: ' + defer.getLength() + ' commands');
defer.emit({
emitOp: function(op, dest, source) {
if (op==='putFile' || op==='putContent') {
self.watchWrapper.track(source.getRelativePath());
}
}
});
cb();
}
);
});
},
function() { return self.aborted===false && !self.context.isFinished(); },
cb
);
};
/**
* @param {string}
* @param {function}
*/
DeployProcess.prototype.purge = function(path, cb)
{
var self = this;
async.parallel([
function(cb) {
self.mirrorTree.purge(path);
var syncList = [].concat(self.mirrorSyncList);
async.whilst(
function() { return syncList.length>0; },
function(cb) {
var sync = syncList.shift();
var remote;
if (remote = sync.sync.remoteMonitored(path)) {
sync.to.prepare(remote);
sync.to.run(function() {
sync.to.purgeTree(remote);
cb();
})
} else {
cb();
}
},
cb
);
},
function(cb) {
self.remote.walk('').stat(path, function(err, stat) {
if (!err) {
if (stat.isDirectory()) {
self.remote.deleteDir(path);
} else if (stat.isFile()) {
self.remote.deleteFile(path);
}
}
cb();
});
}
], cb);
}
/**
* @param {string}
*/
DeployProcess.prototype.touch = function(path)
{
this.local.touch(path);
};
/**
* @param {string}
* @param {string|Buffer}
* @param {function}
*/
DeployProcess.prototype.touchContent = function(path, content, cb)
{
var self = this;
this.local.walk('').stat(p.dirname(path), function(err, stat) {
if (stat && stat.isDirectory()) {
self.mirrorSyncList.forEach(function(sync) {
var local;
if (local = sync.sync.localMonitored(path)) {
sync.from.prepare(local, true);
sync.to.prepare(local);
}
});
} else {
self.mirrorSyncList.forEach(function(sync) {
if (sync.sync.localMonitored(path)) {
sync.from.prepare('', true);
sync.to.prepare('');
}
});
}
self.local.touchContent(path, content);
cb();
});
};
/**
* @param {function}
*/
DeployProcess.prototype.createMirrorTree = function()
{
this.config.ruleList.syncList.forEach(function(sync) {
this.mirrorTree.prepare(sync.remoteDir);
this.sharedTree.add(sync.remoteDir);
}, this);
this.config.ruleList.keepDir.forEach(function(dir) {
this.mirrorTree.prepare(dir, MirrorTree.TYPE_DIR);
this.sharedTree.add(dir);
}, this);
this.config.ruleList.keepSymlink.forEach(function(symlink) {
this.mirrorTree.prepare(symlink[0], MirrorTree.TYPE_SYMLINK, symlink[1]);
this.sharedTree.add(symlink[0]);
}, this);
};
DeployProcess.prototype.createMirrorSyncList = function()
{
this.config.ruleList.syncList.forEach(function(sync) {
this.mirrorSyncList.push({
sync: sync,
remoteDir: sync.remoteDir,
localDir: sync.localDir,
from: new MirrorSync(this.local.walk(sync.localDir), sync, this.config.ruleList),
to: new MirrorSync(this.remote.walk(sync.remoteDir), sync, this.config.ruleList)
});
}, this);
};
| aleskafka/deployk | lib/DeployProcess/DeployProcess.js | JavaScript | mit | 10,506 |
if(typeof(require) !== 'undefined'){
var helpers = require("./helpers").helpers;
var entity = require("./entity").entity;
}
var explosion = function(config){
helpers.apply(config, this);
this.color = this.color || "#FFF";
this.position = this.position || {x:0, y:0};
this.duration = 0;
this.modelIndex = 6;
this.subEntities = [];
for(var i = 0 ; i < 4 ; i++){
this.subEntities.push({
modelIndex: 6,
color: this.color,
position: this.position,
direction: 0
});
}
this.audioDone = false;
this.rect = {x: -5, y: -5, w: 10, h: 10};
};
explosion.prototype = new entity();
explosion.prototype.render = function(){
this.renderExplosion(this.duration, !this.audioDone);
this.audioDone = true;
};
explosion.prototype.renderExplosion = function(duration, sound){
if(sound){
audio.explosionAudio.play();
}
if(duration%2){
var currentPosition = { x: 0 - (4 * duration), y: 0 };
this.classicModel = [];
for(var i = 0 ; i < 4 ; i++){
var rectPos = helpers.rotate(currentPosition, {x:0, y:0}, i*90);
this.classicModel.push({x: -5 + rectPos.x, y: -5 + rectPos.y, w: 10, h: 10});
this.subEntities[i].position = {x: this.position.x + rectPos.x, y: this.position.y + rectPos.y};
}
this.classicModel.push(this.rect);
}
};
explosion.prototype.update = function(time){
this.duration++;
if(this.duration > 10){
this.finished = true;
for(var i = 0 ; i < 4 ; i++){
this.subEntities[i].finished = true;
}
}
};
explosion.prototype.getRemoteData = function(){
var result = null;
if(!this.remoteDataSend){
result = "4," + Math.ceil(this.position.x) + "," +
Math.ceil(this.position.y) + "," + this.duration + "," +
(this.audioDone ? "1" : "0") + "," +
(this.finished ? "1" : "0");
this.audioDone = true;
this.remoteDataSend = true;
}
return result;
};
explosion.prototype.renderRemoteData = function(remoteData, offset){
this.classicModel = remoteData[offset + 3] === "1" ? this.rectsRight : this.rectsLeft;
this.position = {x:parseFloat(remoteData[offset + 1]), y:parseFloat(remoteData[offset + 2])};
this.renderExplosion(
parseFloat(remoteData[offset + 3]),
(remoteData[offset + 5] === "4"));
this.finished = (remoteData[offset + 5] === "1");
return offset + 6;
};
if(typeof(exports) !== 'undefined'){
exports.explosion = explosion;
} | ewoudj/game | static/laserwar/explosion.js | JavaScript | mit | 2,323 |
/**
* Module dependencies
*/
/**
* Sails.prototype.initialize()
*
* Start the Sails server
* NOTE: sails.load() should be run first.
*
* @api private
*/
module.exports = function initialize() {
var sails = this;
// Indicate that server is starting
sails.log.verbose('Starting app at ' + sails.config.appPath + '...');
process.on('exit', function() {
if (!sails._exiting) {
sails.lower();
}
});
// And fire the `ready` event
// This is listened to by attached servers, etc.
sails.emit('ready');
};
| Shyp/sails | lib/app/private/initialize.js | JavaScript | mit | 543 |
'use strict';
var link = 'http://127.0.0.1:49822/api/';
angular.module('myApp.viewProducts', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/viewProducts', {
templateUrl: 'partials/viewProducts/viewProducts.html',
controller: 'viewCategoryCtrl'
}).when('/viewProducts/:category', {
templateUrl: 'partials/viewProducts/viewProducts.html',
controller: 'viewCategoryCtrl'
});
}])
.filter('productsFilter', function() {
return function (items, params) {
var filteredBySize = filterBySize(items, params.size);//filter("material", params.material, items);
return filterByColor(filteredBySize, params.color);
//var material = filter("material", params.material, items);
//return filter("colors", params.color, material);
//return filterByColor(selectedMaterial, params.selectedColor);
}
})
.controller('viewCategoryCtrl', ['$http', '$route', function($http, $route) {
var view = this;
view.link = link;
view.products = [ ];
view.selectedMaterial = '*';
view.selectedColor = '*';
view.selectedSize = '*';
view.materials = [ ];
view.sizes = [ ];
view.categoryHasResults = true;
view.setMaterial = function(material) {
view.selectedMaterial = material;
console.log("New material: " + material);
};
view.setColor = function(color) {
view.selectedColor = color;
};
view.getColor = function() {
return view.selectedColor;
}
view.getMaterial = function() {
return view.selectedMaterial;
}
view.setSize = function(size) {
view.selectedSize = size;
};
view.getSize = function() {
return view.selectedSize;
}
var category = $route.current.params.category;
var categoryFinal = "";
if (category) {
category = category.toUpperCase();
console.log("has category");
if(category === "BACKPACK" || category === "HARDCASE"
|| category === "MESSENGER" || category === "SHOULDER"
|| category === "SLEEVE" || category === "TOTE"
|| category === "WHEELED")
categoryFinal = "bycategory/" + category;
}
else
console.log("hasn't category");
$http.get(link + 'products/' + categoryFinal).success(function(data) {
view.categoryHasResults = true;
view.products = data.products;
view.materials = getMaterials(data.products);
view.colors = getColors(data.products);
view.sizes = getSizes(data.products).sort();
console.log("...");
if (data.products.length === 0) {
view.categoryHasResults = false;
}
}
);
}]);
function showCategory(category) {
$('.portfolio-item').hide();
$(category).slideToggle();
}
/**
*
* @param field product field to filter
* @param filter value of the filter
* @param items items to filter
* @returns {Array}
*/
function filter(field, filter, items) {
var newItems = [];
for (var i = 0; i < items.length; i++) {
if (filter == '*') {
newItems.push(items[i]);
continue;
}
var value = items[i][field];
if (value.toUpperCase() == filter.toUpperCase())
newItems.push(items[i]);
};
return newItems;
}
function filterByColor(items, color) {
if (color === "*")
return items;
var newItems = [];
for(var i = 0; i < items.length; i++) {
var subproducts = items[i].subproducts;
for(var j = 0; j < subproducts.length; j++) {
if(subproducts[j].color.toUpperCase() === color.toUpperCase()) {
newItems.push(items[i]);
break;
}
}
}
return newItems;
}
function filterBySize(items, size) {
if (size === "*")
return items;
var newItems = [];
for(var i = 0; i < items.length; i++) {
var subproducts = items[i].subproducts;
for(var j = 0; j < subproducts.length; j++) {
if(subproducts[j].size === size) {
newItems.push(items[i]);
break;
}
}
}
return newItems;
}
function getMaterials(products) {
var materials = [];
for(var i in products) {
// console.log(products);
if (materials.indexOf(products[i].material) == -1)
materials.push(products[i].material);
}
return materials;
}
function getColors(items) {
var colors = [];
for(var i = 0; i < items.length; i++) {
var subproducts = items[i].subproducts;
for(var j = 0; j < subproducts.length; j++) {
if(colors.indexOf(subproducts[j].color) == -1) {
colors.push(subproducts[j].color);
}
}
}
return colors;
}
function getSizes(items) {
console.log(items);
var sizes = [];
for(var i = 0; i < items.length; i++) {
var subproducts = items[i].subproducts;
for(var j = 0; j < subproducts.length; j++) {
if(sizes.indexOf(subproducts[j].size) == -1) {
sizes.push(subproducts[j].size);
}
}
}
return sizes;
} | dvn123/SINF | app/partials/viewProducts/viewProducts.js | JavaScript | mit | 5,567 |
/*
* Validates Dutch phonenumbers and more.
* Copyright (C) Doeke Zanstra 2001-2009
* Distributed under the BSD License
* See http://www.xs4all.nl/~zanstra/dzLib/telNr.htm for more info.
*/
//--| v1.4
//--| Lijst van regionale kengetallen (nummers moeten 10 cijfers hebben)
TelNr.prototype.regio4=',0111,0113,0114,0115,0117,0118,0161,0162,0164,0165,0166,0167,0168,0172,0174,0180,0181,0182,0183,0184,0186,0187,0222,0223,0224,0226,0227,0228,0229,0251,0252,0255,0294,0297,0299,0313,0314,0315,0316,0317,0318,0320,0321,0341,0342,0343,0344,0345,0346,0347,0348,0411,0412,0413,0416,0418,0475,0478,0481,0485,0486,0487,0488,0492,0493,0495,0497,0499,0511,0512,0513,0514,0515,0516,0517,0518,0519,0521,0522,0523,0524,0525,0527,0528,0529,0541,0543,0544,0545,0546,0547,0548,0561,0562,0566,0570,0571,0572,0573,0575,0577,0578,0591,0592,0593,0594,0595,0596,0597,0598,0599,';
TelNr.prototype.regio3=',010,013,015,020,023,024,026,030,033,035,036,038,040,043,045,046,050,053,055,058,070,071,072,073,074,075,076,077,078,079,';
//--| Kengetallen, niet beschikbaar voor reservering
TelNr.prototype.magNiet4=',0110,0112,0116,0119,0160,0163,0169,0170,0171,0173,0175,0176,0177,0178,0179,0185,0188,0189,0220,0221,0225,0250,0253,0254,0256,0257,0258,0259,0290,0291,0292,0293,0295,0296,0298,0310,0311,0312,0319,0322,0323,0324,0325,0326,0327,0328,0329,0340,0349,0410,0414,0415,0417,0419,0470,0471,0472,0473,0474,0476,0477,0479,0480,0482,0483,0484,0489,0490,0491,0494,0496,0498,0510,0520,0526,0540,0542,0549,0560,0563,0564,0565,0567,0568,0569,0574,0576,0579,0590,06761,06762,06763,06764,06765,06766,06767,06768,06769,0801,0802,0803,0804,0805,0806,0807,0808,0809,0901,0902,0903,0904,0905,0907,0908,';
TelNr.prototype.magNiet3=',012,014,019,021,027,028,037,039,042,060,068,069,081,083,085,086,088,089,091,092,093,094,095,096,097,098,099,';
//--| 0800,0900,0906 en 0909 nummers kunnen kort (8 tekens) zijn, zoals
//--| vermeldt in onderstaande arrays. Anders zijn ze lang (11 tekens).
TelNr.prototype.infoNrKort=
{ '0800':['00','01','03','04','05','06','07','08','09',
'10','11','12','13','14','15','16','17','18','19',
'20','21',
'41','43','46','49',
'50','51',
'60','61',
'70','71',
'80','81',
'90','91']
, '0900':['00','01','02','03','04','05','06','07','08','09',
'13','14','15','17','18','19',
'80','81','83','84','86','88',
'92','93','95','96','97','98']
, '0906':['00','01','02','03','05','06','07','08','09',
'13','14','15','17','18','19',
'80','81','83','84','86','88',
'92','93','95','96','97','98']
, '0909':['00','01','02','03','05','06','07','08','09',
'13','14','15','17','18','19',
'80','81','83','84','86','88',
'92','93','95','96','97','98']
};
TelNr.prototype.landNr=31; //default landen nummer
TelNr.prototype.errors=
[ 'Nummer moet 10 cijfers hebben'
, 'Nummer moet 8 cijfers hebben'
, 'Nummer moet 11 cijfers hebben'
, 'Kengetal is niet beschikbaar voor toekenning of reservering'
, 'Het kengetal is niet herkend'
];
TelNr.prototype.toString=TelNr_toString;
function TelNr(strTelNr)
{
var intKengetalStart;
var intAbonneeNrStart;
var strKengetal, strSubKengetal;
//Zet landennummer
this.landNr=this.landNr;
//Converteer naar string en verwijder alle non-getallen
strTelNr=(''+strTelNr).replace(/[^0-9]/g,'');
if(/^06[1-5]/.test(strTelNr))
{
//--| mobiel nummer (in 065 zit ook nog een stukje semafonie)
//--| of internet (06760)
intKengetalStart=0;
intAbonneeNrStart=2;
this.validated=(strTelNr.length==10); //mobile nr should have 10 digits
if(!this.validated) this.error=this.errors[0];
this.type='mobiel';
}
else if(/^06760/.test(strTelNr))
{
//--| mobiel nummer (in 065 zit ook nog een stukje semafonie)
//--| of internet (06760)
intKengetalStart=0;
intAbonneeNrStart=5;
this.validated=(strTelNr.length==10); //mobile nr should have 10 digits
if(!this.validated) this.error=this.errors[0];
this.type='internet';
}
else if(/^08[47]/.test(strTelNr))
{
//--| Persoonlijke-assistentdiensten (bijv. fax bij KPN fax-in-email/XOIP)
intKengetalStart=0;
intAbonneeNrStart=3;
this.validated=(strTelNr.length==10); //mobile nr should have 10 digits
if(!this.validated) this.error=this.errors[0];
this.type='persoonlijke-assistentdiensten';
}
else if(this.infoNrKort[strTelNr.substr(0,4)])
{
//--| informatie nummer
intKengetalStart=0;
intAbonneeNrStart=4;
strKengetal=strTelNr.substr(0,4); //eerste 4 cijfers
strSubKengetal=strTelNr.substr(4,2); //volgende 2 cijfers
//controleer lengte
if(this.infoNrKort[strKengetal].exists(strSubKengetal))
{
this.validated=(strTelNr.length==8);
if(!this.validated) this.error=this.errors[1];
}
else
{
this.validated=(strTelNr.length==11);
if(!this.validated) this.error=this.errors[2];
}
this.type='informatie';
}
else if(this.regio3.indexOf(','+strTelNr.substr(0,3)+',')>=0 )
{
//--| regionaal nummer, met kort kengetal
intKengetalStart=0;
intAbonneeNrStart=3;
this.validated=(strTelNr.length==10);
if(!this.validated) this.error=this.errors[0];
this.type='regio';
}
else if(this.regio4.indexOf(','+strTelNr.substr(0,4)+',')>=0 )
{
//--| regionaal nummer, met kort kengetal
intKengetalStart=0;
intAbonneeNrStart=4;
this.validated=(strTelNr.length==10);
if(!this.validated) this.error=this.errors[0];
this.type='regio';
}
else if(this.magNiet3.indexOf(','+strTelNr.substr(0,3)+',')>=0
|| this.magNiet4.indexOf(','+strTelNr.substr(0,4)+',')>=0 )
{
intKengetalStart=0;
intAbonneeNrStart=0;
this.validated=false;
this.error=this.errors[3];
this.type=null;
}
else
{
//--| onbekend, neem aan dat kengetal 3 cijfers heeft
intKengetalStart=0;
intAbonneeNrStart=3;
this.validated=null;
this.error=this.errors[4];
this.type=null;
}
this.kengetal=strTelNr.substring(intKengetalStart,intAbonneeNrStart);
this.abonneeNr=strTelNr.substring(intAbonneeNrStart,strTelNr.length);
return this;
}
TelNr.translator =
[ {token:'INT', method:'"+"+this.landNr+"-(0)"+this.kengetal.substr(1)+"-"+this.abonneeNr'}
, {token:'KG', method:'this.kengetal'}
, {token:'kg', method:'this.kengetal.substr(1)'}
, {token:'KPN', method:'"("+this.kengetal+") "+this.abonneeNr.group(2,2,true,sep)'}
, {token:'kpn', method:'"("+this.kengetal+") "+this.abonneeNr'}
, {token:'NORM', method:'"("+this.kengetal+") "+this.abonneeNr.group(3,2,true,sep)'}
, {token:'NR2_', method:'this.abonneeNr.group(2,2,false,sep)'}
, {token:'NR_2', method:'this.abonneeNr.group(2,2,true,sep)'}
, {token:'NR3_', method:'this.abonneeNr.group(3,2,false,sep)'}
, {token:'NR_3', method:'this.abonneeNr.group(3,2,true,sep)'}
, {token:'NR', method:'this.abonneeNr'}
];
function TelNr_toString(format,sep)
//--#Converteert een telefoonnummer naar een string.
//--@format;type=string;optional;default='NORM'@Formaat van de string. Zie tabel.
//--@sep;type=string@Tussenvoegsel voor gegroepeerde nummers
/*$Tabel:Tokens in de formaterings string
KG :Kengetal (bijv: '050', '0515' of '06')
kg :Kengetal zonder nul (bijv: '50', '515' of '6')
NR :Abonneenummer (bijv: '23466808', '521276' of '3090127')
NR2_ :Abonneenummer
Groepjes van 2. Afwijkende groepjes achteraan (minimum lengte groepje is 2)
Bijv: '23 46 68 08', '52 12 76' of '30 90 127')
NR_2 :Abonneenummer
Groepjes van 2. Afwijkende groepjes vooraan (minimum lengte groepje is 2)
Bijv: '23 46 68 08', '52 12 76' of '309 01 27')
NR3_ :Abonneenummer
Groepjes van 3. Afwijkende groepjes achteraan (minimum lengte groepje is 2)
Bijv: '234 668 08', '521 276' of '309 01 27')
NR_3 :Abonneenummer
Groepjes van 3. Afwijkende groepjes vooraan (minimum lengte groepje is 2)
Bijv: '23 466 808', '521 276' of '30 90 127')
KPN :KPN formaat: '(KG) NR_2'
kpn :KPN formaat zonder groepering: '(KG) NR'
NORM :Hoe het volgens de auteur zou moeten: '(KG) NR_3'
KG-NR :Hoe de meeste mensen het spellen: 'KG-NR'
INT :Internationaal: '+31-(0)kg-NR'
*/
{
var sRes="";
var i=0;
var bFound;
if(typeof format=='undefined') format='NORM';
while(i<format.length)
{
for(var j=0; j<TelNr.translator.length; j++)
{
if(format.indexOf(TelNr.translator[j].token,i)==i)
{
sRes+=eval(TelNr.translator[j].method);
i+=TelNr.translator[j].token.length;
break;
}
}
if(j==TelNr.translator.length) //not found
{
sRes+=format.substr(i,1);
i++;
}
}
return sRes;
}
/*---Handy methods--*/
Array.prototype.top=function(n)
{
n=(n||0)+1;
return this[this.length-n]||null;
}
if(!Array.prototype.pop) Array.prototype.pop=function()
{
var r=this[this.length-1];
delete this[this.length-1];
this.length--;
return r;
}
Array.prototype.exists=Array_exists;
function Array_exists(value) {
for(var i=0; i<this.length; i++) {
if(this[i]==value) {
return true;
}
}
return false;
}
String.prototype.reverse=function() {
var s='';
for(var i=this.length-1; i>=0; i--)
{
s+=this.charAt(i);
}
return s;
}
String.prototype.group=function String_group(n1,n2,b,sep)
/*--#Formateer de string in groepjes van [n1] cijfers. Gebruik [n2] als minimale
grootte van een groepje. Als [b] true is, doe het afwijkende groepje vooraan,
anders achteraan. Gebruik [sep] als tussenvoegsel tussen de groepjes*/
//--@n1;type=integer;optional;default=3@Hoe groot een groepje cijfers moet zijn. n1>=1
//--@n2;type=integer;optional;default=2@Minimale lengte van een groepje cijfers. n2<=n1
//--@b;type=boolean;optional;default=false@Of het afwijkende groepje (indien deze voorkomt) vooraan moet staan.
//--@sep;type=string;optional;default=' '@De seperator.
{
var re=new RegExp('([0-9]{1,'+n1+'})','g');
var a, s;
var ret=[];
if(typeof n1=='undefined') n1=3;
if(typeof n2=='undefined') n2=2;
if(typeof b=='undefined') b=false;
if(typeof sep=='undefined') sep=' ';
if(b) s=this.reverse();
else s=this;
while(a=re.exec(s))
{
ret.push( a[1] );
}
if(ret.length>=2 && ret.top().length<n2)
{
//zijn er tenminste 2 groepjes en is de lengte van het laatste groepje te kort?
var k=ret.top(1), l=ret.top(); //één-na-laatste en laatste
if(parseInt((k.length+l.length)/2,10)>=n2)
{
//2 groepjes maken
ret[ret.length-1]=ret[ret.length-2].substr(n2)+ret[ret.length-1];
ret[ret.length-2]=ret[ret.length-2].substring(0,n2);
}
else
{
//laatste 2 groepjes samenvoegen
ret[ret.length-2]+=ret.pop();
}
}
if(b) return ret.join(sep).reverse();
else return ret.join(sep);
}
| kjepper/CallerPi | public/js/telnr.js | JavaScript | mit | 10,782 |
"use strict";
app.controller('specServerArchitectureController', ['$scope', '$rootScope', function ($scope, $rootScope) {
}]); | keithbox/AngularJS-CRUD-PHP | doc/v3/js/controller/spec01-sys-block-diagram.js | JavaScript | mit | 128 |
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
let Navbar = ({id, type, friendLists, demo}) => {
let title, parent = 0;
if(friendLists[id]) {
title = friendLists[id].title;
parent = friendLists[id].parent;
}
let parentList=[];
let currentParent = parent;
while(currentParent !== -1) {
if(currentParent === 0){
parentList.unshift(
<li key="all">
<Link to={demo ? '/demo/feed/' + type : '/feed/'+ type} className="list-header-extra" activeClassName="active">
{friendLists[currentParent].title}
</Link>
</li>
);
}
else{
parentList.unshift(
<li key={currentParent}>
<Link to={{ pathname: demo ? '/demo/feed/' + type : '/feed/'+ type, query: { listId: currentParent } }} className="list-header-extra" activeClassName="active">
{friendLists[currentParent].title}
</Link>
</li>
);
}
currentParent = friendLists[currentParent].parent;
}
return (
<nav>
<ul className="breadcrumb">
{
(type === 'include') ?
<span>分享範圍:</span> :
<span>排除對象:</span>
}
{parentList}
<li key="current">{title}</li>
</ul>
<button className="btn btn-default">
<Link to={demo ? '/demo/feed' : '/feed'}>
返回
</Link>
</button>
</nav>
)
};
Navbar.propTypes = {
id: PropTypes.number.isRequired,
type: PropTypes.string.isRequired,
friendLists: PropTypes.object.isRequired,
demo: PropTypes.bool.isRequired
};
const mapStateToProps = (state, ownProps) => {
return {
friendLists: state.entities.friendLists,
demo: state.demo
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
}
}
Navbar = connect(
mapStateToProps,
mapDispatchToProps
)(Navbar);
export default Navbar; | b00705008/TellYou | src/containers/Feed/Navbar.js | JavaScript | mit | 1,956 |
var path = require('path')
var webpack = require('webpack')
var CleanWebpackPlugin = require('clean-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var WorkboxPlugin = require('workbox-webpack-plugin')
// Phaser webpack config
var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/')
var phaser = path.join(phaserModule, 'build/custom/phaser-split.js')
var pixi = path.join(phaserModule, 'build/custom/pixi.js')
var p2 = path.join(phaserModule, 'build/custom/p2.js')
var definePlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false'))
})
module.exports = {
entry: {
app: [
'babel-polyfill',
path.resolve(__dirname, 'src/main.js')
],
vendor: ['pixi', 'p2', 'phaser', 'webfontloader']
},
output: {
path: path.resolve(__dirname, 'build'),
publicPath: './',
filename: 'js/bundle.js'
},
plugins: [
definePlugin,
new CleanWebpackPlugin(['build']),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.optimize.UglifyJsPlugin({
drop_console: true,
minimize: true,
output: {
comments: false
}
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor' /* chunkName= */ , filename: 'js/vendor.bundle.js' /* filename= */ }),
new HtmlWebpackPlugin({
filename: 'index.html', // path.resolve(__dirname, 'build', 'index.html'),
template: './src/index.html',
chunks: ['vendor', 'app'],
chunksSortMode: 'manual',
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
html5: true,
minifyCSS: true,
minifyJS: true,
minifyURLs: true,
removeComments: true,
removeEmptyAttributes: true
},
hash: true
}),
new CopyWebpackPlugin([
{ from: 'assets', to: 'assets' },
{ from: 'src/manifest.json', to: './manifest.json' }
]),
new WorkboxPlugin.GenerateSW({
clientsClaim: true,
skipWaiting: true
})
],
module: {
rules: [
{ test: /\.js$/, use: ['babel-loader'], include: path.join(__dirname, 'src') },
{ test: /pixi\.js/, use: ['expose-loader?PIXI'] },
{ test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] },
{ test: /p2\.js/, use: ['expose-loader?p2'] }
]
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
resolve: {
alias: {
'phaser': phaser,
'pixi': pixi,
'p2': p2
}
}
}
| lean/phaser-es6-webpack | webpack.production.config.js | JavaScript | mit | 2,563 |
module.exports = { tuple, fst, snd, swap }
// -- Construct a new tuple.
// tuple :: ...Any -> Array
function tuple(...any) {
return any
}
// -- Extract the first component of a pair.
// fst :: Array -> Any
function fst(pair) {
return pair[0]
}
// -- Extract the second component of a pair.
// snd :: Array -> Any
function snd(pair) {
return pair[1]
}
// -- Swap the components of a pair.
// swap :: Array -> Array
function swap(pair) {
return [pair[1], pair[0]]
}
| gummesson/tuples | index.js | JavaScript | mit | 476 |
var PouchDB = require('pouchdb'),
_ = require('underscore');
var Store = function(client) {
this.client = client;
this.db = new PouchDB('data_store', {
db : require('memdown')
});
this.container = {
cookie:""
};
};
Store.prototype.get = function get(_id) {
var client = this.client,
container = this.container;
return container[_id] || false;
};
Store.prototype.set = function set(_id, data) {
var client = this.client,
container = this.container;
container[_id] = container[_id] || null;
container[_id] = data;
client.emit('db:change:' + _id);
};
Store.prototype.updateAll = function set(data) {
var client = this.client,
container = this.container;
container = _.extend(container, data);
client.emit('db:change:all', container);
};
module.exports = Store;
| donaldej/adjs | lib/Store.js | JavaScript | mit | 800 |
export { default } from "@getflights/ember-mist-components/components/output-field-select/component";
| pjcarly/ember-mist-components | app/components/output-field-select/component.js | JavaScript | mit | 102 |
// spots
core.require('/connector/connector0.js','/line/spots.js',function (connectorP,linePP) {
let rs = connectorP.instantiate();
/* adjustable parameters */
rs.interval = 10;
rs['stroke-width'] = 4;
rs.stroke = 'black';
/* end adjustable parameters */
rs.numSpots = 0;
rs.initializePrototype = function () {
core.assignPrototype(this,'lineP',linePP);
}
rs.set('shaftProperties',core.lift(['numSpots','stroke','stroke-width','interval']));
ui.hide(rs,['end0','end1','shaft','shaftProperties','numSpots']);
return rs;
});
| chrisGoad/prototypejungle | connector/spots.js | JavaScript | mit | 534 |
angular.module("TTT")
.controller("emuController", function($location, $scope) {
var vm = this;
$(".textbox").text("Emus have overrun Australia destroying all crops. You are sent to 1932 where Major Merideth has second thoughts about facing the fierce emu mob once more.");
$(".bodyemu").css("background-image", "url(https://upload.wikimedia.org/wikipedia/commons/d/dc/Emus,_Wilsons_Promontory_National_Park.jpg)")
$(".bodyemu").css("background-size", "600px 600px");
// PUB SCENE //
vm.option1pub = false;
vm.option2pub = false;
$(".one").show();
$(".one").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: I don't even deserve to be called a Major!");
$(".two").show();
game.changeBackground(".bodyemu", "../images/MeredithatPub.png");
$scope.$apply();
})
$(".two").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: Do you mean because of the emus?");
$(".three").show();
$scope.$apply();
})
$(".three").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: Yes, the emus! Lost to a bunch of bloody birds.");
$(".four").show();
$scope.$apply();
})
$(".four").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: Was it really all that bad, shouldn’t you give it another go?");
$(".five").show();
$scope.$apply();
})
$(".five").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: If we had a military division with the bullet-carrying capacity of these birds it would face any army in the world...They can face machine guns with the invulnerability of tanks. They are like Zulus whom even dum-dum bullets could not stop.");
$(".six").show();
$scope.$apply();
})
$(".six").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: I won’t face those birds again!");
vm.option1pub = true;
vm.option2pub = true;
$scope.$apply();
})
$(".left-pub").on("click", function (){
$(".textbox").text("*You run out of the pub after Major Merideth, unfortunately there was a herd of sheep running through town at that moment. Caught in a fluffy doom, you were trampled to death by sheep.* GAME OVER!! Click the arrow to try again.");
vm.option1pub = false;
vm.option2pub = false;
$(".six").show();
game.changeBackground(".bodyemu", "../images/SheepTrample.png");
$scope.$apply();
})
$(".right-pub").on("click", function (){
$(".textbox").text("*You let him stumble off into the night, deciding to go to his base in the morning. You have a plan...*");
vm.option1pub = false;
vm.option2pub = false;
$(".seven").show();
game.changeBackground(".bodyemu", "../images/Base.png");
$scope.$apply();
})
// BASE SCENE //
vm.option1base = false;
vm.option2base = false;
$(".seven").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: You! The meddlesome person from the pub! Why don’t you leave me alone?");
$(".eight").show();
$scope.$apply();
})
$(".eight").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: There aren’t enough experienced machine gunners in Australia. You are needed to lead the campaign against the emus and protect the farmlands from destruction!");
$(".nine").show();
$scope.$apply();
})
$(".nine").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: I wasn’t successful before, and I thought I saw a strange interloper assisting the emus last time I was out there.");
$(".ten").show();
$scope.$apply();
})
$(".ten").on("click", function (){
$(this).hide();
$(".textbox").text("Time to unveil your plan. Do you entice him with food or tell your fake story of woe?");
vm.option1base = true;
vm.option2base = true;
$scope.$apply();
})
$(".left-base").on("click", function (){
$(".textbox").text("Marta: You must be hungry this early in the morning, have this delicious dish.");
vm.option1base = false;
vm.option2base = false;
$(".thirteen").show();
game.changeBackground(".bodyemu", "../images/MeredithFood.png");
$scope.$apply();
})
$(".right-base").on("click", function (){
$(".textbox").text("Marta: The Emus -- They ate our crops, trampled the other animals, broke down my home, and killed my family. It happened to me, it will happen to others. It’s up to you to once more raise arms against this menace and face your feathered foes! Their numbers are strong, but only you can guide us!");
vm.option1base = false;
vm.option2base = false;
$(".eleven").show();
$scope.$apply();
})
// The Woe Choice //
$(".eleven").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: The menace is even greater than I thought! We haven’t a chance!");
$(".twelve").show();
$scope.$apply();
})
$(".twelve").on("click", function (){
$(this).hide();
$(".textbox").text("*Unfortunately, Major Merideth’s phobia was exacerbated by your rousing speech. In his panic to escape he hopped in a vehicle and accidently backed over and trampled you. GAME OVER!! Click the arrow to try again.*");
$(".ten").show();
game.changeBackground(".bodyemu", "../images/JeepTrample.png");
$scope.$apply();
})
// The Food Choice //
$(".thirteen").on("click", function (){
$(this).hide();
$(".textbox").text("*You hand him a dish with some large drumsticks protruding from it*");
$(".fourteen").show();
$scope.$apply();
})
$(".fourteen").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: Wow, this is delicious. But why give this to me?");
$(".fifteen").show();
$scope.$apply();
})
$(".fifteen").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: Do you really like it? I was up most of the night preparing it for you.");
$(".sixteen").show();
$scope.$apply();
})
$(".fifteen").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: It’s -- It's... ");
$(".sixteen").show();
$scope.$apply();
})
$(".sixteen").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: It’s EMU! Think of the vast supply of this just waiting for us out there, just ripe for the plucking!");
$(".seventeen").show();
$scope.$apply();
})
$(".seventeen").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: But the dangers...");
$(".eighteen").show();
$scope.$apply();
})
$(".eighteen").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: Isn’t it worth this delicious dish?");
$(".nineteen").show();
$scope.$apply();
})
$(".nineteen").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: Let me round up the troops!");
$(".twenty").show();
$scope.$apply();
})
//EMU WAR SCENE //
vm.option1war = false;
vm.option2war = false;
$(".twenty").on("click", function (){
$(this).hide();
$(".textbox").text("*After gathering his platoon, you and his men head out into the field. After several days of travelling you find where the mob of emus are.*");
$(".twentyone").show();
game.changeBackground(".bodyemu", "../images/MeredithEmuField.png");
$scope.$apply();
})
$(".twentyone").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: All right men, I know you’re hungry after that search. I hunger too, hunger for vengeance and hunger for delicious emu meat!");
$(".twentytwo").show();
$scope.$apply();
})
$(".twentytwo").on("click", function (){
$(this).hide();
$(".textbox").text("Soldier: Sir! The emu mob is headed this way!");
$(".twentythree").show();
$scope.$apply();
})
$(".twentythree").on("click", function (){
$(this).hide();
$(".textbox").text("*Major Merideth falters and looks towards you, looking as if he wants input...*");
vm.option1war = true;
vm.option2war = true;
$scope.$apply();
})
$(".left-war").on("click", function (){
$(".textbox").text("Marta: We should use the element of surprise to our advantage, press the charge!");
vm.option1war = false;
vm.option2war = false;
$(".thirtyone").show();
$scope.$apply();
})
$(".right-war").on("click", function (){
$(".textbox").text("We should hide in the brush, surround the emus, and open fire all at once.");
vm.option1war = false;
vm.option2war = false;
$(".twentyfour").show();
$scope.$apply();
})
//Surprise//
$(".thirtyone").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: Of course, the dumb buzzards will never see it coming!");
$(".thirtytwo").show();
$scope.$apply();
})
$(".thirtytwo").on("click", function (){
$(this).hide();
$(".textbox").text("*All the soldiers rush out, guns blazing. They manage to fell a few emus, but most panicked and ran wild. Amidst the fighting, you and the soldiers are trampled by emu! GAME OVER!! Click the arrow to try again.*");
game.changeBackground(".bodyemu", "../images/EmuTrample.png");
$(".twentythree").show();
$scope.$apply();
})
//Ambush//
vm.option1end = false;
vm.option2end = false;
$(".twentyfour").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: Of course, the dumb buzzards will never see it coming!");
$(".twentyfive").show();
$scope.$apply();
})
$(".twentyfive").on("click", function (){
$(this).hide();
$(".textbox").text("*The volley was fierce with many emus falling. Wounded and beaten, the emus fled. The soldiers let out a hearty cry of victory.*");
$(".twentysix").show();
game.changeBackground(".bodyemu", "../images/DeadEmus.png");
$scope.$apply();
})
$(".twentysix").on("click", function (){
$(this).hide();
$(".textbox").text("Soldier: Sir, we’ve piled all the emus together and we have over 900!");
$(".twentyseven").show();
$scope.$apply();
})
$(".twentyseven").on("click", function (){
$(this).hide();
$(".textbox").text("Marta: It’s over 9000!!!!!!!");
$(".twentyeight").show();
$scope.$apply();
})
$(".twentyeight").on("click", function (){
$(this).hide();
$(".textbox").text("Soldier: um...no...more like 1000 I would say.");
$(".twentynine").show();
$scope.$apply();
})
$(".twentynine").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: 986 to be precise. But, this is a heartening start! Let us press the attack while we have them on the run!");
$(".thirty").show();
$scope.$apply();
})
$(".thirty").on("click", function (){
$(this).hide();
$(".textbox").text("*Should the troops pursue the wounded emus, finishing this once and for all or should you hold a party in celebration?*");
vm.option1end = true;
vm.option2end = true;
$scope.$apply();
})
$(".left-end").on("click", function (){
$(".textbox").text("Marta: Now is our chance, strike while it’s hot!");
vm.option1end = false;
vm.option2end = false;
$(".thirtyfour").show();
$scope.$apply();
})
$(".right-end").on("click", function (){
$(".textbox").text("Marta: These emus will never come back. Let's party like it's 1935!");
vm.option1end = false;
vm.option2end = false;
$(".thirtyseven").show();
$scope.$apply();
})
$(".thirtyseven").on("click", function (){
$(this).hide();
$(".textbox").text("*And so you do! Full of sardines and spam, you make your way back to the magic time bus. Where will you go next?*");
game.changeBackground(".bodyemu", "../images/EmuParty.png");
$(".thirtyeight").show();
$scope.$apply();
})
$(".thirtyeight").on("click", function (){
$location.path("/" + game.randomizer());
$scope.$apply();
})
$(".thirtyfour").on("click", function (){
$(this).hide();
$(".textbox").text("Meredith: After those fleeing emus!");
$(".thirtyfive").show();
$scope.$apply();
})
$(".thirtyfive").on("click", function (){
$(this).hide();
$(".textbox").text("*In the heat of the chase, you fail to notice the troop of kangaroos behind you. Amidst such chaos, the birds flee and you are trampled by fierce kicks. GAME OVER!!! Click the arrow to try again.*");
$(".thirty").show();
game.changeBackground(".bodyemu", "../images/RooTrample.png");
$scope.$apply();
})
});
| beck410/GJ_Timetravel | app/js/controllers/emu.controller.js | JavaScript | mit | 12,536 |
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
return queryInterface.addColumn('events', 'notes', Sequelize.TEXT);
},
down: function (queryInterface, Sequelize) {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.dropTable('users');
*/
return queryInterface.removeColumn('events', 'notes');
}
};
| lionelrudaz/api.wellnow.ch | migrations/20170406201552-addDescriptionToEvents.js | JavaScript | mit | 642 |
angular.module('app').factory('commentModel2_0', function($http, userModel)
{
var commentStatic = function(config)
{
this.id = null;
this.message = '';
this.author = new userModel;
this.subscribe = false;
this.notice = false;
this.parent = null;
this.children = [];
this.votePositive = 0;
this.voteNegative = 0;
this.date = '';
this.showForm = false;
this.level = 0;
this.entity_uri = '';
this.canVote = true;
this.configure(config);
};
var VOTE_TYPE_POSITIVE = 'positive';
var VOTE_TYPE_NEGATIVE = 'negative';
var comment = commentStatic.prototype;
comment.configure = function(config)
{
config = config || {};
this.id = config.id || this.id;
this.message = config.message || this.message;
if (config.author) {
this.author = new userModel(config.author);
}
this.entity_uri = config.entity_uri || this.entity_uri;
this.subscribe = config.subscribe || this.subscribe;
//this.notice = config.notice || this.notice;
this.parent = config.parent || this.parent;
if (config.children) {
config.children.forEach(function(childrenConfig){
var child = new commentStatic(childrenConfig);
this.children.push(child);
}, this);
}
this.votePositive = config.votePositive || this.votePositive;
this.voteNegative = config.voteNegative || this.voteNegative;
this.date = config.creation_date || this.date;
this.level = config.level || this.level;
this.canVote = config.canVote !== undefined ? config.canVote : this.canVote;
};
comment.isValid = function()
{
return this.message.length > 0;
};
comment.synchronize = function(url, callback)
{
var self = this;
var request = {
'author_uri': this.author.profile,
'parent': this.parent,
'entity_uri': this.entity_uri,
'message': this.message
};
$http.post(url, request)
.success(function(data){
if (data.model) {
self.configure(data.model);
if (typeof callback != 'undefined') {
callback(data.model);
}
}
})
.error(function(){
alert('Во время запроса произошла ошибка!');
});
};
comment.setParent = function(parent)
{
this.level = parent.level + 1;
this.parent = parent.id;
};
comment.isShowForm = function()
{
return this.showForm;
};
comment.toggleShowForm = function()
{
this.showForm = !this.showForm;
};
comment.voteURL = '';
comment.voting = function(url, vote)
{
var self = this;
var request = {
'user_uri': this.author.profile,
'vote': vote,
'comment_id': this.id
};
$http.post(url, request)
.success(function(data){
if (data.success !== true) {
self.showError();
return;
}
if (data.model) {
self.configure(data.model);
}
self.votePositive = data.votePositive || self.votePositive;
self.voteNegative = data.voteNegative || self.voteNegative;
self.canVote = false;
})
.error(function(){
self.showError();
});
}
comment.showError = function()
{
alert(_('Ошибка при отправке запроса. Попробуйте повторить.'));
}
comment.showErrorRequired = function()
{
alert(_('Введите обязательные поля'));
}
return commentStatic;
}); | Talaka-by/comments-client-module | assets/comments/model/comment.js | JavaScript | mit | 4,043 |
'use strict';
import webpack from 'webpack';
import Merge from 'webpack-merge';
import UglifyJsPlugin from 'uglifyjs-webpack-plugin';
import CommonConfig from './webpack.base.config';
export default Merge( CommonConfig, {
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin( {
minimize: false,
debug: false
} ),
new webpack.optimize.ModuleConcatenationPlugin(),
new UglifyJsPlugin()
]
} ); | putipong/meme-generator | webpack-config/webpack.prod.config.js | JavaScript | mit | 592 |
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
"use strict";
(function ()
{
this.PublishDuplicateRuleRequest = function (duplicateRuleId){
///<summary>
/// Contains the data that is needed to submit an asynchronous job to publish a duplicate rule.
///</summary>
///<param name="duplicateRuleId" type="String">
/// Sets the ID of the duplicate rule to be published. Required.
///</param>
if (!(this instanceof Sdk.PublishDuplicateRuleRequest)) {
return new Sdk.PublishDuplicateRuleRequest(duplicateRuleId);
}
Sdk.OrganizationRequest.call(this);
// Internal properties
var _duplicateRuleId = null;
// internal validation functions
function _setValidDuplicateRuleId(value) {
if (Sdk.Util.isGuid(value)) {
_duplicateRuleId = value;
}
else {
throw new Error("Sdk.PublishDuplicateRuleRequest DuplicateRuleId property is required and must be a String.")
}
}
//Set internal properties from constructor parameters
if (typeof duplicateRuleId != "undefined") {
_setValidDuplicateRuleId(duplicateRuleId);
}
function getRequestXml() {
return ["<d:request>",
"<a:Parameters>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>DuplicateRuleId</b:key>",
(_duplicateRuleId == null) ? "<b:value i:nil=\"true\" />" :
["<b:value i:type=\"e:guid\">", _duplicateRuleId, "</b:value>"].join(""),
"</a:KeyValuePairOfstringanyType>",
"</a:Parameters>",
"<a:RequestId i:nil=\"true\" />",
"<a:RequestName>PublishDuplicateRule</a:RequestName>",
"</d:request>"].join("");
}
this.setResponseType(Sdk.PublishDuplicateRuleResponse);
this.setRequestXml(getRequestXml());
// Public methods to set properties
this.setDuplicateRuleId = function (value) {
///<summary>
/// Sets the ID of the duplicate rule to be published. Required.
///</summary>
///<param name="value" type="String">
/// The ID of the duplicate rule to be published. Required.
///</param>
_setValidDuplicateRuleId(value);
this.setRequestXml(getRequestXml());
}
}
this.PublishDuplicateRuleRequest.__class = true;
this.PublishDuplicateRuleResponse = function (responseXml) {
///<summary>
/// Response to PublishDuplicateRuleRequest
///</summary>
if (!(this instanceof Sdk.PublishDuplicateRuleResponse)) {
return new Sdk.PublishDuplicateRuleResponse(responseXml);
}
Sdk.OrganizationResponse.call(this)
// Internal properties
var _jobId = null;
// Internal property setter functions
function _setJobId(xml) {
var valueNode = Sdk.Xml.selectSingleNode(xml, "//a:KeyValuePairOfstringanyType[b:key='JobId']/b:value");
if (!Sdk.Xml.isNodeNull(valueNode)) {
_jobId = Sdk.Xml.getNodeText(valueNode);
}
}
//Public Methods to retrieve properties
this.getJobId = function () {
///<summary>
/// Gets the ID of the asynchronous job for publishing a duplicate detection rule.
///</summary>
///<returns type="String">
/// The ID of the asynchronous job for publishing a duplicate detection rule.
///</returns>
return _jobId;
}
//Set property values from responseXml constructor parameter
_setJobId(responseXml);
}
this.PublishDuplicateRuleResponse.__class = true;
}).call(Sdk)
Sdk.PublishDuplicateRuleRequest.prototype = new Sdk.OrganizationRequest();
Sdk.PublishDuplicateRuleResponse.prototype = new Sdk.OrganizationResponse();
| daryllabar/XrmAutoNumberGenerator | WebResources/dlab_/scripts/messages/Sdk.PublishDuplicateRule.js | JavaScript | mit | 4,046 |
import defaultResolve from 'part:@sanity/base/document-actions'
import {TestConfirmDialogAction} from './actions/TestConfirmDialogAction'
import {TestErrorDialogAction} from './actions/TestErrorDialogAction'
import {TestLegacyDialogAction} from './actions/TestLegacyDialogAction'
import {TestModalDialogAction} from './actions/TestModalDialogAction'
import {TestPopoverDialogAction} from './actions/TestPopoverDialogAction'
import {TestSuccessDialogAction} from './actions/TestSuccessDialogAction'
function OnlyWhenPublishedAction() {
return {
label: `Document is published`,
}
}
export default function resolveDocumentActions(props) {
if (props.type === 'documentActionsTest') {
return [
TestConfirmDialogAction,
TestErrorDialogAction,
TestLegacyDialogAction,
TestModalDialogAction,
TestPopoverDialogAction,
TestSuccessDialogAction,
...defaultResolve(props),
]
}
return [...defaultResolve(props), props.published ? OnlyWhenPublishedAction : null].filter(
Boolean
)
}
| sanity-io/sanity | dev/test-studio/parts/resolveDocumentActions.js | JavaScript | mit | 1,041 |
// Generated on 2014-10-29 using generator-angular 0.8.0
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: {
// configurable paths
app: require('./bower.json').appPath || 'app',
dist: 'dist'
},
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['bowerInstall']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: true
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
base: [
'.tmp',
'<%= yeoman.app %>'
]
}
},
test: {
options: {
port: 9001,
base: [
'.tmp',
'test',
'<%= yeoman.app %>'
]
}
},
dist: {
options: {
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
],
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
bowerInstall: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: '<%= yeoman.app %>/'
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>']
}
},
// The following *-min tasks produce minified files in the dist folder
cssmin: {
options: {
root: '<%= yeoman.app %>'
}
},
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ngmin tries to make the code safe for minification automatically by
// using the Angular long form for dependency injection. It doesn't work on
// things like resolve or inject so those have to be done manually.
ngmin: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'fonts/*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= yeoman.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Test settings
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'bowerInstall',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'bowerInstall',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngmin',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'rev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
| circleback/test-ga-gtm | Gruntfile.js | JavaScript | mit | 9,032 |
var expect = require("chai").expect;
var splitter = require("../src/splitter.js");
var shell = require("shelljs");
var readPath = "tests/testdata.md",
pattern = "###",
cleanName = "###",
writePath = "tests/tmp/",
numberFiles = true;
describe("splitterWithCounter", function() {
it("should split markdown file into smaller files", function(done) {
shell.mkdir("-p", "tests/tmp");
splitter(readPath, pattern, cleanName, writePath, 10, numberFiles);
var filez = shell.ls("tests/tmp/*.md");
console.log(filez);
expect(filez).to.contain("tests/tmp/1-v0.0.1.md");
expect(filez).to.contain("tests/tmp/2-v0.0.2.md");
expect(filez).to.contain("tests/tmp/3-v0.0.3.md");
expect(filez).to.contain("tests/tmp/4-<empty-filename>.md");
shell.rm("-rf", "tests/tmp/");
done();
});
it("should throw error when given invalid file to read", function(done) {
readPath = "blahblahblah";
expect(
splitter.bind(splitter, readPath, pattern, cleanName, writePath)
).to.throw(Error);
done();
});
it("should exist", function(done) {
expect(splitter).to.exist;
done();
});
});
| accraze/split-md | tests/splitterWithCounter.test.js | JavaScript | mit | 1,140 |
const app = require("express")();
const static = require("express").static(__dirname + '/public');
const exphbs = require('express-handlebars');
const Handlebars = require('handlebars');
const handlebarsInstance = exphbs.create({
defaultLayout: 'main',
// Specify helpers which are only registered on this instance.
helpers: {
asJSON: (obj, spacing) => {
if (typeof spacing === "number")
return new Handlebars.SafeString(JSON.stringify(obj, null, spacing));
return new Handlebars.SafeString(JSON.stringify(obj));
}
},
partialsDir: [
'views/partials/'
]
});
const configRoutes = require("./routes");
const rewriteUnsupportedBrowserMethods = (req, res, next) => {
// If the user posts to the server with a property called _method, rewrite the request's method
// To be that method; so if they post _method=PUT you can now allow browsers to POST to a route that gets
// rewritten in this middleware to a PUT route
if (req.body && req.body._method) {
req.method = req.body._method;
delete req.body._method;
}
// let the next middleware run:
next();
};
// ---------- for debug only ----------
app.use(function(req, res, next) {
next();
})
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
secure: false // true for https
}
}));
app.use(require('connect-flash')());
app.use(require('cookie-parser')());
app.use("/public", static);
app.use(require("body-parser").json());
app.use(require("body-parser").urlencoded({
extended: true
}));
app.use(rewriteUnsupportedBrowserMethods);
app.engine('handlebars', handlebarsInstance.engine);
app.set('view engine', 'handlebars');
configRoutes(app);
app.listen(3000, () => {
console.log("We've now got a server!");
console.log("Your routes will be running on http://localhost:3000");
}); | Magicdalonglong/Stevensoverflow | app.js | JavaScript | mit | 1,996 |
var AnimationModule = {
name: "Timeline",
enabled: true,
render_helpers: true,
//settings_panel: [{name:"renderer", title:"Renderer", icon:null }],
_trajectories: [],
init: function()
{
//create the timeline
this.tab = InterfaceModule.lower_tabs_widget.addWidgetTab( Timeline );
this.timeline = this.tab.widget;
LEvent.bind( LS.GlobalScene, "afterRenderScene", this.renderView.bind(this));
LEvent.bind( LS.GlobalScene, "renderPicking", this.renderPicking.bind(this));
RenderModule.canvas_manager.addWidget( AnimationModule ); //capture update, render trajectories
},
createTimeline: function()
{
var timeline = this.timeline = new Timeline();
this.tab.add( this.timeline );
InterfaceModule.visorarea.addEventListener( "visibility_change", timeline_resize );
InterfaceModule.visorarea.addEventListener( "split_moved", timeline_resize );
window.addEventListener("resize", timeline_resize );
function timeline_resize(){
timeline.resize();
}
},
showTimeline: function( animation )
{
InterfaceModule.selectTab( RenderModule.name );
InterfaceModule.setLowerPanelVisibility( true );
if(animation)
this.timeline.setAnimation( animation );
},
attachKeyframesBehaviour: function( inspector )
{
var elements = inspector.root.querySelectorAll(".keyframe_icon");
for(var i = 0; i < elements.length; i++)
{
var element = elements[i];
element.draggable = true;
element.addEventListener("click", inner_click );
element.addEventListener("contextmenu", (function(e) {
if(e.button != 2) //right button
return false;
inner_rightclick(e);
e.preventDefault();
e.stopPropagation();
return false;
}).bind(this));
element.addEventListener("dragstart", inner_dragstart);
}
function inner_click(e)
{
AnimationModule.insertKeyframe( e.target, e.shiftKey );
e.preventDefault();
e.stopPropagation();
return true;
}
function inner_rightclick(e)
{
var menu = new LiteGUI.ContextMenu( ["Add UID track","Add name track","Show Info","Copy Query","Copy Unique Query"], { event: e, title:"Keyframe", callback: function(value) {
if(value == "Add UID track")
AnimationModule.insertKeyframe(e.target);
else if(value == "Add name track")
AnimationModule.insertKeyframe(e.target, true);
else if(value == "Copy Query")
AnimationModule.copyQueryToClipboard( e.target.dataset["propertyuid"], true );
else if(value == "Copy Unique Query")
AnimationModule.copyQueryToClipboard( e.target.dataset["propertyuid"] );
else
AnimationModule.showPropertyInfo( e.target.dataset["propertyuid"] );
}});
}
function inner_dragstart(e)
{
e.dataTransfer.setData("type", "property" );
e.dataTransfer.setData("uid", e.target.dataset["propertyuid"] );
var locator = e.target.dataset["propertyuid"];
//var info = LS.
if(e.shiftKey)
locator = LSQ.shortify( locator );
e.dataTransfer.setData("locator", locator );
}
},
copyQueryToClipboard: function( locator, shorten )
{
//shortify query
if(shorten)
locator = LSQ.shortify( locator );
LiteGUI.toClipboard( locator );
},
showPropertyInfo: function( property )
{
var info = LS.GlobalScene.getPropertyInfo( property );
if(!info)
return;
var that = this;
var dialog = new LiteGUI.Dialog("property_info",{ title:"Property Info", width: 400, draggable: true, closable: true });
var widgets = new LiteGUI.Inspector();
var locator_widget = widgets.addString("Locator", property, function(v){});
/*
locator_widget.style.cursor = "pointer";
locator_widget.setAttribute("draggable","true");
locator_widget.addEventListener("dragstart", function(event) {
event.dataTransfer.setData("locator", property );
event.dataTransfer.setData("type", "property");
if(info.node)
event.dataTransfer.setData("node_uid", info.node.uid);
//event.preventDefault();
});
*/
widgets.addString("Short Locator", LSQ.shortify( property ), function(v){});
widgets.widgets_per_row = 2;
widgets.addString("Parent", info.node ? info.node.name : "", { disabled: true } );
widgets.addString("Container", info.target ? LS.getObjectClassName( info.target ) : "", { disabled: true } );
widgets.addString("Property", info.name, { disabled: true } );
widgets.addString("Type", info.type, { disabled: true } );
widgets.widgets_per_row = 1;
if(info.type == "number")
widgets.addNumber("Value", info.value, inner_set );
else if(info.type == "boolean")
widgets.addCheckbox("Value", info.value, inner_set );
else if(info.type == "vec2")
widgets.addVector2("Value", info.value, inner_set );
else if(info.type == "vec3")
widgets.addVector3("Value", info.value, inner_set );
else if(info.type == "texture")
widgets.addTexture("Value", info.value, inner_set );
else if(info.type == "mesh")
widgets.addMesh("Value", info.value, inner_set );
else
widgets.addString("Value", info.value, inner_set );
widgets.addButtons(null,["Close"], function(v){
dialog.close();
return;
});
dialog.add( widgets );
dialog.adjustSize();
dialog.show();
function inner_set(v)
{
LS.GlobalScene.setPropertyValue( property, v );
LS.GlobalScene.refresh();
}
},
getKeyframeCode: function( target, property, options )
{
if(!target.getLocator)
return "";
var locator = target.getLocator();
if(!locator)
return "";
return "<span title='Create keyframe for "+property+"' class='keyframe_icon' data-propertyname='" + property + "' data-propertyuid='" + locator + "/" + property + "' ></span>";
},
insertKeyframe: function( button, relative )
{
this.timeline.onInsertKeyframeButton( button, relative );
this.tab.click();
},
renderView: function(e, camera)
{
if( !EditorView.render_helpers || !this.render_helpers || RenderModule.render_settings.in_player || !RenderModule.frame_updated )
return;
if(this.timeline.show_paths)
this.renderTrajectories(camera);
},
renderPicking: function(e, mouse_pos)
{
//cannot pick what is hidden
if(!EditorView.render_helpers || !this._trajectories.length )
return;
var temp = vec3.create();
var callback = this.onTrajectoryKeyframeClicked.bind(this);
for(var i = 0; i < this._trajectories.length; ++i)
{
var traj = this._trajectories[i];
var info = LS.GlobalScene.getPropertyInfoFromPath( traj.track._property_path );
if(!info)
continue;
var parent_matrix = null;
if( info.node && info.node.parentNode && info.node.parentNode.transform )
parent_matrix = info.node.parentNode.transform.getGlobalMatrixRef();
var points = traj.points;
var num = points.length;
for(var j = 0; j < num; ++j)
{
var pos = points[j];
if( parent_matrix )
pos = vec3.transformMat4( vec3.create(), pos, parent_matrix );
EditorView.addPickingPoint( pos, 10, { pos: pos, value: points[j], type: "keyframe", traj:i, instance: this, take: this.timeline.current_take, track: traj.index, num: j, callback: callback } );
}
}
},
renderTrajectories: function( camera )
{
LS.Renderer.resetGLState();
if(!this.timeline.current_take)
return;
var take = this.timeline.current_take;
if(take.tracks.length == 0)
return;
var selection = SelectionModule.getSelection();
if(!selection || selection.type != "keyframe")
selection = null;
this._trajectories.length = 0;
var white = [1,1,1,1];
var colorA = [0.5,0.6,0.5,1];
var colorB = [1.0,1.0,0.5,1];
for(var i = 0; i < take.tracks.length; ++i)
{
var track = take.tracks[i];
if(track.type != "position" || !track.enabled)
continue;
var num = track.getNumberOfKeyframes();
var start = -1;
var end = -1;
var points = [];
var colors = null;
if( selection && selection.track == i )
colors = [];
var info = LS.GlobalScene.getPropertyInfoFromPath( track._property_path );
if(!info) //unknown case but it happened sometimes
continue;
var parent_node = null;
if( info.node && info.node.parentNode && info.node.parentNode.transform )
{
parent_node = info.node.parentNode;
LS.Draw.push();
LS.Draw.setMatrix( parent_node.transform.getGlobalMatrixRef() );
}
for(var j = 0; j < num; ++j)
{
var keyframe = track.getKeyframe(j);
if(!keyframe)
continue;
if(j == 0)
start = keyframe[0];
else if(j == num - 1)
end = keyframe[0];
var pos = keyframe[1];
points.push(pos);
if(colors)
colors.push( j == selection.index ? colorB : colorA );
}
LS.Draw.setColor( colors ? white : colorA );
LS.Draw.setPointSize( 4 );
LS.Draw.renderPoints( points, colors );
this._trajectories.push( { index: i, points: points, track: track } );
if(track.interpolation == LS.Animation.NONE)
continue;
if(track.interpolation == LS.Animation.LINEAR)
{
if(points.length > 1)
LS.Draw.renderLines( points, null, true );
continue;
}
points = [];
var last = null;
for(var j = 0; j < num; ++j)
{
var keyframe = track.getKeyframe(j);
if(!keyframe)
continue;
if(last)
{
var start_t = last[0];
var end_t = keyframe[0];
var num_samples = Math.max(2, (end_t - start_t) * 10);
var offset = (end_t - start_t) / num_samples;
for(var k = 0; k <= num_samples; ++k)
{
var t = start_t + offset * k;
var sample = track.getSample(t, true, vec3.create());
if(!sample)
continue;
points.push(sample);
}
}
last = keyframe;
}
if(points.length > 1)
{
LS.Draw.setColor(colorA);
LS.Draw.renderLines( points, null, false );
}
if( parent_node )
LS.Draw.pop();
}
},
onTrajectoryKeyframeClicked: function(info, e)
{
this.timeline.selectKeyframe( info.track, info.num );
},
getTransformMatrix: function( element, mat, selection )
{
if(!this._trajectories.length)
return false;
var T = mat || mat4.create();
mat4.setTranslation( T, selection.pos );
return T;
},
applyTransformMatrix: function( matrix, center, property_name, selection )
{
if(!this._trajectories.length)
return false;
var track = this._trajectories[ selection.traj ];
if(!track)
return null;
var point = track.points[ selection.num ];
vec3.transformMat4( point, point, matrix );
if(selection.pos != selection.value) //update the visual point
vec3.transformMat4( selection.pos, selection.pos, matrix );
this.timeline.applyTracks();
return true;
},
update: function(dt)
{
if( this.timeline )
this.timeline.update(dt);
}
};
CORE.registerModule( AnimationModule ); | pjkui/webglstudio.js | editor/js/modules/animation.js | JavaScript | mit | 10,977 |
version https://git-lfs.github.com/spec/v1
oid sha256:bc552eab0d074f45c18272aa32b5ad192c1310f1ac2430a297a405a539bbf9b6
size 6366
| yogeshsaroya/new-cdnjs | ajax/libs/responsive-nav.js/1.0.31/responsive-nav.min.js | JavaScript | mit | 129 |
/**
* This directive displays a d3 node edge graph for a given UQ author
*/
'use strict';
angular.module('uql.orgs')
.controller('UqlOrgsStaffCollaborationCtrl', ['$scope', 'UQL_CONFIG_ORGS', function ($scope, UQL_CONFIG_ORGS) {
$scope.expectedViz = 'staff-collaboration';
$scope.filename = 'report-' + $scope.expectedViz + '.csv';
var defaultImage = UQL_CONFIG_ORGS.imagesBaseUrl + '/' + UQL_CONFIG_ORGS.viz['staff-collaboration'].defaultImage;
/**
* Take the data returned from our json call and format it
* suitably for output
*
* @param {Object[]} data
* @return {Array[]}
*/
$scope.formatData = function (data, width) {
if (!angular.isArray(data.nodes) || !angular.isArray(data.edges)) {
return false;
}
var nodes = data.nodes;
var nodeIndex = {};
// create a lookup table for the node index as this is
// how d3 maps edges
for (var i = 0, l = nodes.length; i < l; i++) {
nodes[i].full_name = makeName(nodes[i]);
if (nodes[i].uqr_id && (nodes[i].image_exists === 1)) {
nodes[i].image = UQL_CONFIG_ORGS.authorImageUrlBase + nodes[i].uqr_id + '.jpg';
} else {
nodes[i].image = defaultImage;
}
nodeIndex[nodes[i].username] = i;
}
var edges = [];
for (var j = 0, m = data.edges.length; j < m; j++) {
var row = data.edges[j];
edges.push({
'source': nodeIndex[row.author1],
'target': nodeIndex[row.author2],
'value': row.collaborations,
'x': width / m * j
});
}
return {
'nodes': nodes,
'edges': edges
};
};
/**
* Format the data suitable for a table
*
* @param {Object[]} data
* @return {Array[]}
*/
$scope.formatTableData = function (data) {
var returnVal = [];
var staff_lookup = {};
for (var i = 0, l = data.nodes.length; i < l; i++) {
var el = data.nodes[i];
staff_lookup[el.username] = el;
}
for (var j = 0, jl = data.edges.length; j < jl; j++) {
var row = data.edges[j];
var staff1 = staff_lookup[row.author1];
var staff2 = staff_lookup[row.author2];
returnVal.push([
makeName(staff1),
makeName(staff2),
parseInt(row.collaborations, 10)
]);
}
returnVal.sort(function (a, b) {
var sum = b[2] - a[2];
if (sum === 0) {
return (a[0] + a[1]).localeCompare(b[0] + b[1]);
}
return sum;
});
returnVal.unshift(
[
{type: 'string', name: 'Staff Member A'},
{type: 'string', name: 'Staff Member B'},
{type: 'number', name: 'Collaborative Publications'}
]
);
return returnVal;
};
/**
* Helper function to format an authors name
* @param author
*/
function makeName(author) {
return author.family_name + ', ' + author.given_name;
}
}]).controller('UqlOrgsStaffCollabModalInstanceCtrl', ['$scope', '$uibModalInstance', 'author', function ($scope, $uibModalInstance, author) {
$scope.author = author;
$scope.ok = function () {
$uibModalInstance.close();
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}])
.directive('uqlOrgsStaffCollaboration', ['$compile', '$uibModal', 'UQL_CONFIG_ORGS', function ($compile, $uibModal, UQL_CONFIG_ORGS) {
return {
restrict: 'E',
controller: 'UqlOrgsStaffCollaborationCtrl',
replace: true,
scope: {
viz: '=',
jsonData: '=data'
},
template: '<div></div>',
link: function postLink(scope, element, attrs) {
var force;
var width = attrs.width || 640;
var height = attrs.height || 480;
/**
* Display a popup showing info about the passed in author
*
* @param {Object} popup_user user object for the person clicked on we want to display a popup about
*/
scope.displayUserPopUp = function (popup_user) {
$uibModal.open({
templateUrl: UQL_CONFIG_ORGS.viewsBaseUrl + '/partials/author-popup.html',
controller: 'UqlOrgsStaffCollabModalInstanceCtrl',
windowClass: 'uql-authors-modal',
animation: false,
resolve: {
author: function () {
return popup_user;
}
}
});
};
/**
* Set up the containers and svg for graph
*
* @param height
* @param width
*/
function initGraph(height, width) {
d3.select('#chart_div > span').remove();
// create the svg canvas to display graph on
scope.group = d3.select('#chart_div').append('svg')
.attr('height', height)
.attr('width', width)
.attr('viewbox', '0 0 ' + width + ' ' + height)
.attr('preserveAspectRatio', 'xMidYMid')
.append('svg:g');
force = d3.layout.force()
.size([width, height])
.distance(120)
.charge(-200);
}
/**
* This is where the magic happens and the graph is displayed in d3
*
* @param {Object[]} data nodes and edges to display on the graph
*/
function showGraph(data) {
if (!angular.isArray(data.nodes) || !angular.isArray(data.edges)) {
return false;
}
var nodes = data.nodes;
var edges = data.edges;
// set up the d3 object
force.nodes(nodes)
.links(edges)
.start();
// style the lines
var links = scope.group.selectAll('.link')
.data(edges, function (d) {
return d.source.username + d.target.username;
});
var link = links.enter().append('line')
.attr('class', function (d) {
var classes = ['link'];
if (d.value > 20) {
classes.push('collabs-20');
} else if (d.value > 10) {
classes.push('collabs-10');
} else if (d.value > 5) {
classes.push('collabs-5');
} else if (d.value > 1) {
classes.push('collabs-1');
}
return classes.join(' ');
});
links.exit()
.transition()
.duration(1000)
.style('opacity', 0)
.remove();
// Add handler and animate nodes
var nodeset = scope.group.selectAll('.node')
.data(nodes, function (d) {
return d.username;
});
nodeset.exit()
.transition()
.duration(1000)
.style('opacity', 0)
.remove();
var node = nodeset.enter().append('g')
.attr('class', 'node')
.call(force.drag)
.on('dblclick', function (d) {
scope.displayUserPopUp(d);
});
// add some images, pretty the place up
node.append('image')
.attr('xlink:href', function (d) {
return d.image;
})
.attr('x', function (d) {
return -((d.image ? UQL_CONFIG_ORGS.viz['staff-collaboration'].authorImageSize : UQL_CONFIG_ORGS.viz['staff-collaboration'].defaultImageSize) / 2);
})
.attr('y', function (d) {
return -((d.image ? UQL_CONFIG_ORGS.viz['staff-collaboration'].authorImageSize : UQL_CONFIG_ORGS.viz['staff-collaboration'].defaultImageSize) / 2);
})
.attr('width', function (d) {
return d.image ? UQL_CONFIG_ORGS.viz['staff-collaboration'].authorImageSize : UQL_CONFIG_ORGS.viz['staff-collaboration'].defaultImageSize;
})
.attr('height', function (d) {
return d.image ? UQL_CONFIG_ORGS.viz['staff-collaboration'].authorImageSize : UQL_CONFIG_ORGS.viz['staff-collaboration'].defaultImageSize;
});
// give people names
node.append('text')
.attr('text-anchor', 'middle')
.attr('dy', function (d) {
return d.image ? UQL_CONFIG_ORGS.viz['staff-collaboration'].authorImageSize - 10 + 'px' : UQL_CONFIG_ORGS.viz['staff-collaboration'].defaultImageSize + 'px';
})
.text(function (d) {
return d.full_name;
});
// set layout on each tick of animation
force.on('tick', function () {
link.attr('x1', function (d) {
return d.source.x;
})
.attr('y1', function (d) {
return d.source.y;
})
.attr('x2', function (d) {
return d.target.x;
})
.attr('y2', function (d) {
return d.target.y;
});
node.attr('transform', function (d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
});
}
// go...
var htmlText = '<div id="chart_div"><span>Graph loading...</span></div>';
htmlText += '<uql-table filename="{{filename}}" data="tableData"></uql-table>';
element.html('<span>' + htmlText + '</span>');
$compile(element.contents())(scope);
initGraph(height, width);
scope.$watch('jsonData', function (jsonData) {
if ((scope.viz.name === scope.expectedViz) && angular.isObject(jsonData) && jsonData.nodes) {
var formattedData = scope.formatData(jsonData, width);
showGraph(formattedData);
scope.tableData = scope.formatTableData(jsonData);
}
});
}
};
}]);
| uqlibrary/uqlapp-frontend | frontend/app/scripts/modules/uql.orgs/directives/staffCollaborationDirective.js | JavaScript | mit | 9,913 |
'use strict';
var _ = require('lodash'),
Promise = require('bluebird'),
Umzug = require('umzug'),
db = require('../../models'),
umzug = require('./umzug'),
path = require('./path'),
Sequelize = db.Sequelize,
sequelize = db.sequelize;
function migrate() {
var migrator = new Umzug({
storage: umzug.getStorage(),
storageOptions: umzug.getStorageOptions({ sequelize: sequelize }),
logging: console.log,
migrations: {
params: [ sequelize.getQueryInterface(), Sequelize ],
path: path.getMigrationsPath(),
pattern: /\.js$/,
wrap: function (callback) {
if (callback.length === 3) {
return Promise.promisify(callback);
} else {
return callback;
}
}
}
});
return migrator.pending();
}
module.exports = _.assign({
setup: function (done) {
sequelize.authenticate()
.then(function () {
return migrate();
})
.then(function () {
return sequelize.sync();
})
.then(function () {
done();
})
.catch(done);
},
teardown: function (done) {
var queryInterface = sequelize.getQueryInterface();
Promise.all([
queryInterface.dropAllTables(),
queryInterface.dropAllEnums()
]).then(function () {
done();
}).catch(done);
}
}, db); | barmatz/node-app-testing-helpers-for-sequelize | test/helpers/sequelize.js | JavaScript | mit | 1,347 |
/*******************************************************************************
* Helper script for create_project.htm page.
* Copyright (c) 2013 Romain TOUZÉ
******************************************************************************/
var DATE_FORMAT="mm/dd/yy";
$(function (){
$('#id_start_date').datepicker({ dateFormat: DATE_FORMAT });
$('#id_end_date').datepicker({ dateFormat: DATE_FORMAT });
/* TODO form validation */
$('#submit_link').click(function () {
$('#creation_form').submit();
});
});
| rtouze/theRoofIsOnFire | theRoofIsOnFire/static/create_project.js | JavaScript | mit | 541 |
angular.module('App')
.config(['config', 'authProvider', function (config, authProvider) {
/**
* Config auth module
*/
authProvider.config(config.auth);
}]);
| meanstack-io/meanstack-cli | repository/auth/resources/assets/javascripts/angular/providers/auth.js | JavaScript | mit | 201 |
import React from 'react';
import addons from '@storybook/addons';
import AssetContainer from './addon/AssetContainer';
import {ADDON_ID, PANEL_ID} from './constants';
export default (options) => {
var { dataUrl } = options;
if (!dataUrl) {
console.log('The Brand.ai library viewer is not configured');
return;
}
addons.register(ADDON_ID, api => {
const channel = addons.getChannel();
addons.addPanel(PANEL_ID, {
title: 'Design Library',
render: () => <AssetContainer
channel={channel}
api={api}
dataUrl={dataUrl}
/>,
});
});
}
| brandai/brandai-storybook | src/manager.js | JavaScript | mit | 604 |
import Stream from './stream';
// Return a Stream that is currently live. If no such Stream exists,
// return the Stream with the closest start time that is in the future.
// Canceled streams are ignored
export default function find_next_stream (streams, since_week_start) {
streams = streams.filter(function (stream) {
return !stream.canceled;
});
var found;
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
if (since_week_start > stream.end_normalized) {
continue;
}
found = stream;
break;
}
if (!found) {
return streams[0].same_stream_next_week();
}
return found;
}
| XrXr/WhenIsKateLive | src/js/stream/find-next-stream.js | JavaScript | mit | 689 |
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define('User', {
name: DataTypes.STRING,
email: {type: DataTypes.STRING, unique: true},
uid: {type: DataTypes.STRING(64)},
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
birthday: DataTypes.DATE,
gender: DataTypes.STRING(8),
picture_small: DataTypes.STRING,
picture_large: DataTypes.STRING,
location_id: DataTypes.BIGINT.UNSIGNED,
location_name: DataTypes.STRING,
locale: DataTypes.STRING(12),
timezone: DataTypes.INTEGER,
remote_ip: DataTypes.STRING,
verified: DataTypes.BOOLEAN,
waiting_list: DataTypes.BOOLEAN
}, {
tableName: 'users',
createdAt : 'created_at',
updatedAt : 'updated_at',
timestamps : true,
underscored : true,
classMethods: {
associate: function (models) {
User.hasMany(models.Identity);
User.hasMany(models.Account);
}
}
});
return User;
};
| steemit-intl/steemit.com | db/models/user.js | JavaScript | mit | 1,106 |
import geometry from './geometry';
class torusGeometry extends geometry {
getIntro() {
return 'Creates a [THREE.TorusGeometry](https://threejs.org/docs/#api/geometries/TorusGeometry)';
}
getDescription() {
return '';
}
getAttributesText() {
return {
...super.getAttributesText(),
radius: '',
tube: '',
radialSegments: '',
tubularSegments: '',
arc: '',
};
}
}
module.exports = torusGeometry;
| toxicFork/react-three-renderer | docs/src/internalComponents/torusGeometry.js | JavaScript | mit | 460 |
/* globals module require */
"use strict";
const Router = require("express").Router;
module.exports = function(db) {
let router = new Router(),
controller = require("")
router.get("/", controller.all);
}; | kidroca/JavaScript-Applications | Workshop/02. Creating-SPA-apps/controllers/users.js | JavaScript | mit | 223 |
( function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
global.FormatData = module.require( "./format-data" );
module.exports = factory( global );
} else {
factory( global );
}
} )( this, function( global ) {
global.FormatData[ "it" ] = {
"MonthNames": [ "gennaio", "febbraio", "marzo", "aprile", "maggio",
"giugno", "luglio", "agosto", "settembre",
"ottobre", "novembre", "dicembre", "" ],
"MonthAbbreviations": [ "gen", "feb", "mar", "apr", "mag", "giu", "lug",
"ago", "set", "ott", "nov", "dic", "" ],
"DayNames": [ "domenica", "lunedì", "martedì", "mercoledì",
"giovedì", "venerdì", "sabato" ],
"DayAbbreviations": [ "dom", "lun", "mar", "mer", "gio", "ven", "sab" ],
"Eras": [ "BC", "dopo Cristo" ],
"NumberElements": [ ",", ".", ";", "%", "0", "#", "-", "E", "\u2030", "\u221e", "\ufffd" ],
"DateTimePatterns": [ "H.mm.ss z", "H.mm.ss z", "H.mm.ss", "H.mm",
"EEEE d MMMM yyyy", "d MMMM yyyy",
"d-MMM-yyyy", "dd/MM/yy", "{1} {0}" ],
"DateTimePatternChars": "GyMdkHmsSEDFwWahKzZ"
};
return global.FormatData;
} );
| yannickebongue/text-resources | src/format-data-it.js | JavaScript | mit | 1,262 |
import { test } from '../utils'
import { RuleTester } from 'eslint'
const ruleTester = new RuleTester()
, rule = require('rules/no-named-as-default')
ruleTester.run('no-named-as-default', rule, {
valid: [
test({ code: 'import "./malformed.js"' }),
test({code: 'import bar, { foo } from "./bar";'}),
test({code: 'import bar, { foo } from "./empty-folder";'}),
// es7
test({ code: 'export bar, { foo } from "./bar";'
, parser: 'babel-eslint' }),
test({ code: 'export bar from "./bar";'
, parser: 'babel-eslint' }),
],
invalid: [
test({
code: 'import foo from "./bar";',
errors: [ {
message: 'Using exported name \'foo\' as identifier for default export.'
, type: 'ImportDefaultSpecifier' } ] }),
test({
code: 'import foo, { foo as bar } from "./bar";',
errors: [ {
message: 'Using exported name \'foo\' as identifier for default export.'
, type: 'ImportDefaultSpecifier' } ] }),
// es7
test({
code: 'export foo from "./bar";',
parser: 'babel-eslint',
errors: [ {
message: 'Using exported name \'foo\' as identifier for default export.'
, type: 'ExportDefaultSpecifier' } ] }),
test({
code: 'export foo, { foo as bar } from "./bar";',
parser: 'babel-eslint',
errors: [ {
message: 'Using exported name \'foo\' as identifier for default export.'
, type: 'ExportDefaultSpecifier' } ] }),
test({
code: 'import foo from "./malformed.js"',
errors: [{
message: "Parse errors in imported module './malformed.js': 'return' outside of function (1:1)",
type: 'Literal',
}],
}),
],
})
| yp/eslint-plugin-import | tests/src/rules/no-named-as-default.js | JavaScript | mit | 1,707 |
/*global FM*/
/**
* An object type can be associated to a game object. Then all game objects of a
* certain type can be processed uniformally through the object type object.
* @class FM.ObjectType
* @param {string} pName The name of the object type.
* @constructor
* @author Simon Chauvin.
*/
FM.ObjectType = function (pName) {
"use strict";
/**
* Name of the type.
* @type string
* @private
*/
this.name = pName;
/**
* Specify if the game objects of the current type are alive.
* @type boolean
* @private
*/
this.alive = true;
/**
* Specify if the game objects of the current type are visible.
* @type boolean
* @private
*/
this.visible = true;
/**
* Specify the depth at which the game objects of the current type are drawn.
* @type int
* @private
*/
this.zIndex = 1;
/**
* Specify the different degrees of scrolling of game objects with this type.
* @type FM.Vector
* @private
*/
this.scrollFactor = new FM.Vector(1, 1);
/**
* Other types of game objects the current type has to collide with.
* @type Array
* @private
*/
this.collidesWith = [];
};
FM.ObjectType.prototype.constructor = FM.ObjectType;
/**
* Check if the game objects of the current type overlap with the game objects
* of the given type.
* @method FM.ObjectType#overlapsWithType
* @memberOf FM.ObjectType
* @param {FM.ObjectType} pType The type to test if it overlaps with the
* current one.
* @return {FM.Collision} Collision object if there is overlapping.
*/
FM.ObjectType.prototype.overlapsWithType = function (pType) {
"use strict";
var state = FM.Game.getCurrentState(),
quad = state.getQuad(),
gameObjects = state.members,
otherGameObjects,
i,
j,
hasType,
hasOtherType,
gameObject,
otherGameObject,
physic,
otherPhysic,
collision = null,
collisionTemp = null;
for (i = 0; i < gameObjects.length; i = i + 1) {
gameObject = gameObjects[i];
if (gameObject.isAlive()) {
physic = gameObject.components[FM.ComponentTypes.PHYSIC];
hasType = gameObject.hasType(this);
hasOtherType = gameObject.hasType(pType);
if (physic && (hasType || hasOtherType)) {
otherGameObjects = quad.retrieve(gameObject);
for (j = 0; j < otherGameObjects.length; j = j + 1) {
otherGameObject = otherGameObjects[j];
if (otherGameObject.isAlive()) {
otherPhysic = otherGameObject.components[FM.ComponentTypes.PHYSIC];
if (otherPhysic && ((hasType && otherGameObject.hasType(pType))
|| (hasOtherType && otherGameObject.hasType(this)))) {
collisionTemp = physic.overlapsWithObject(otherPhysic);
if (collisionTemp) {
collision = collisionTemp;
}
}
}
}
}
}
}
return collision;
};
/**
* Check if the game objects of the current type are overlapping with a
* specified game object.
* @method FM.ObjectType#overlapsWithObject
* @memberOf FM.ObjectType
* @param {FM.GameObject} pGameObject Game object to test with the game objects
* of the current type.
* @return {FM.Collision} Collision object if there is overlapping.
*/
FM.ObjectType.prototype.overlapsWithObject = function (pGameObject) {
"use strict";
var gameObjects = FM.Game.getCurrentState().getQuad().retrieve(pGameObject),
i,
otherGameObject,
physic = pGameObject.components[FM.ComponentTypes.PHYSIC],
otherPhysic,
collision = null,
collisionTemp = null;
if (physic && pGameObject.isAlive()) {
for (i = 0; i < gameObjects.length; i = i + 1) {
otherGameObject = gameObjects[i];
otherPhysic = otherGameObject.components[FM.ComponentTypes.PHYSIC];
if (otherGameObject.isAlive() && otherPhysic && otherGameObject.hasType(this)) {
collisionTemp = physic.overlapsWithObject(otherPhysic);
if (collisionTemp) {
collision = collisionTemp;
}
}
}
} else {
if (FM.Parameters.debug) {
if (!physic) {
console.log("WARNING: you need to provide a game object with a physic component for checking overlaps.");
}
}
}
return collision;
};
/**
* Ensure that the game objects of the current type collide with a specified one.
* @method FM.ObjectType#addTypeToCollideWith
* @memberOf FM.ObjectType
* @param {FM.ObjectType} pType The type to collide with to add to all game
* objects of this type.
*/
FM.ObjectType.prototype.addTypeToCollideWith = function (pType) {
"use strict";
this.collidesWith.push(pType);
var gameObjects = FM.Game.getCurrentState().members,
i,
gameObject,
physic;
for (i = 0; i < gameObjects.length; i = i + 1) {
gameObject = gameObjects[i];
physic = gameObject.components[FM.ComponentTypes.PHYSIC];
if (physic && gameObject.hasType(this)) {
physic.addTypeToCollideWith(pType);
}
}
};
/**
* Remove a type that was supposed to collide with all the game objects of this type.
* @method FM.ObjectType#removeTypeToCollideWith
* @memberOf FM.ObjectType
* @param {FM.ObjectType} pType The type to collide with to remove from all
* game objects of this type.
*/
FM.ObjectType.prototype.removeTypeToCollideWith = function (pType) {
"use strict";
this.collidesWith.splice(this.collidesWith.indexOf(pType), 1);
var gameObjects = FM.Game.getCurrentState().members,
i,
gameObject,
physic;
for (i = 0; i < gameObjects.length; i = i + 1) {
gameObject = gameObjects[i];
physic = gameObject.components[FM.ComponentTypes.PHYSIC];
if (physic && gameObject.hasType(this)) {
physic.removeTypeToCollideWith(pType);
}
}
};
/**
* Set the z-index of every game objects of the current type.
* @method FM.ObjectType#setZIndex
* @memberOf FM.ObjectType
* @param {int} pZIndex The z index at which all game objects of this type must
* be.
*/
FM.ObjectType.prototype.setZIndex = function (pZIndex) {
"use strict";
this.zIndex = pZIndex;
var gameObjects = FM.Game.getCurrentState().members,
i,
gameObject;
for (i = 0; i < gameObjects.length; i = i + 1) {
gameObject = gameObjects[i];
if (gameObject.hasType(this)) {
gameObject.zIndex = this.zIndex;
}
}
};
/**
* Set the scrollFactor of every game objects of the current type.
* @method FM.ObjectType#setScrollFactor
* @memberOf FM.ObjectType
* @param {FM.Vector} pScrollFactor The factor of scrolling to apply to all
* game objects of this type.
*/
FM.ObjectType.prototype.setScrollFactor = function (pScrollFactor) {
"use strict";
this.scrollFactor = pScrollFactor;
var gameObjects = FM.Game.getCurrentState().members,
i,
gameObject;
for (i = 0; i < gameObjects.length; i = i + 1) {
gameObject = gameObjects[i];
if (gameObject.hasType(this)) {
gameObject.scrollFactor = this.scrollFactor;
}
}
};
/**
* Kill all the game objects of this type.
* @method FM.ObjectType#kill
* @memberOf FM.ObjectType
*/
FM.ObjectType.prototype.kill = function () {
"use strict";
this.alive = false;
};
/**
* Hide all the game objects of this type.
* @method FM.ObjectType#hide
* @memberOf FM.ObjectType
*/
FM.ObjectType.prototype.hide = function () {
"use strict";
this.visible = false;
};
/**
* Revive all the game objects of this type.
* @method FM.ObjectType#revive
* @memberOf FM.ObjectType
*/
FM.ObjectType.prototype.revive = function () {
"use strict";
this.alive = true;
};
/**
* Show all the game objects of this type.
* @method FM.ObjectType#show
* @memberOf FM.ObjectType
*/
FM.ObjectType.prototype.show = function () {
"use strict";
this.visible = true;
};
/**
* Check if the game objects of this type are alive.
* @method FM.ObjectType#isAlive
* @memberOf FM.ObjectType
* @return {boolean} Whether all the game objects of this type are alive.
*/
FM.ObjectType.prototype.isAlive = function () {
"use strict";
return this.alive;
};
/**
* Check if the game object of this type are visible.
* @method FM.ObjectType#isVisible
* @memberOf FM.ObjectType
* @return {boolean} Whether all the game objects of this type are visible.
*/
FM.ObjectType.prototype.isVisible = function () {
"use strict";
return this.visible;
};
/**
* Retrieve the name of the type.
* @method FM.ObjectType#getName
* @memberOf FM.ObjectType
* @return {string} The name of the type.
*/
FM.ObjectType.prototype.getName = function () {
"use strict";
return this.name;
};
/**
* Destroy the type.
* @method FM.ObjectType#destroy
* @memberOf FM.ObjectType
*/
FM.ObjectType.prototype.destroy = function () {
"use strict";
this.name = null;
this.alive = null;
this.visible = null;
this.zIndex = null;
this.scrollFactor.destroy();
this.scrollFactor = null;
this.collidesWith = null;
};
| simonchauvin/FM.js-Engine | src/ObjectType.js | JavaScript | mit | 9,515 |
var Utils = function(){
this.generateCallBackForSQLiteQueryProcessing = function(emitter, arrayToStoreResults, eventToEmit, callback){
var processResults = function(err, results){
if(err) { throw err; }
var mySelf = this;
this.callback = callback;
this.resultArray = arrayToStoreResults;
results.forEach(function(row){
mySelf.resultArray.push(row);
});
this.eventVal = eventToEmit;
emitter.emit(this.eventVal);
if(this.callback){
this.callback();
}
};
return processResults;
};
this.generateFunctionToWaitOnEvent = function(emitter, eventList, eventCompleted, allDoneEvent){
var waiterFunction = function(){
console.log("Completed event is " + eventCompleted);
console.log("Event List is ");
console.log(eventList);
eventList[eventCompleted] = true;
for(var eventType in eventList){
if(!eventList[eventType]){
return;
}
}
console.log("Emitting all done event as " + allDoneEvent);
/* If I got here, all events have been completed */
emitter.emit(allDoneEvent);
};
return waiterFunction;
};
this.randomize = function(max){
var randomVal = Math.floor((Math.random()*100)%max);
return randomVal;
};
};
module.exports = Utils;
| AlLanMandragoran/BookWorm | Utils/Utils.js | JavaScript | mit | 1,252 |
"use strict";
function canMoveToSpace(gameState, spaceIndex) {
const isPlayerOne = gameState.isPlayerOne;
const boardSpace = gameState.board[spaceIndex];
if (boardSpace.isPlayerOne === isPlayerOne) {
return {isActivePlayer: true, isAvailable: true};
} else if (boardSpace.isPlayerOne === null) {
return {isActivePlayer: null, isAvailable: true};
} else if (boardSpace.isPlayerOne === !isPlayerOne) { // jshint ignore:line
return {isActivePlayer: false, isAvailable: boardSpace.numPieces === 1};
}
}
module.exports = canMoveToSpace; | KatherineThompson/acey-deucey-game-engine | lib/can-move-to-space.js | JavaScript | mit | 588 |
// Space Invaders with EaselJS by Gabor Pinter
// -------------------------------
// 0. Global variables
// I. Initialize document
// II. Set up "gameboard"
// III. Update screen (scenes)
// III. X.: Transparent things (available on all scenes)
// III. 0.: Main menu
// III. 1.: Animation
// III. 2.: Gameplay
// III. 3.: Game Over
// 0. Global variables
var framerate =60;
var stage, scene, score, lives, spaceship,
enemies, bullets, meteors, stars, explosions, gameStartDate;
var keys = {
cLeft: false,
cRight: false,
cUp: false,
cDown: false
}
var queue = new createjs.LoadQueue();
queue.on('progress', onProgress);
queue.on('complete', onComplete);
var progressText;
// I. Initailaze document & Preload
function init() {
//Defining stage
stage = new createjs.Stage("myCanvas");
progressText = new createjs.Text("0%", "24px Arial", "#fff");
progressText.x=stage.canvas.width/2;
progressText.y=stage.canvas.height/2;
stage.addChild(progressText);
stage.update();
//Preloader
loadManifest();
}
function loadManifest(){
queue.loadManifest([
{
id: 'spaceshipSprite',
src: 'spaceship.png'
},
{
id: 'alienSprite',
src: 'alien.png',
},
{
id: 'meteorSprite',
src: 'meteor.png'
}
])
}
function onProgress(e) {
var progress = Math.round(e.loaded*100);
console.log(progress);
progressText.text=progress+"%";
stage.update();
}
function onComplete(e) {
console.log("Everything loaded. Starting the game.");
//Set up game
gameSetup();
//Then set and launch a ticker
createjs.Ticker.setFPS(framerate);
createjs.Ticker.addEventListener("tick", updateFrame);
}
// II. Set up Game
function gameSetup() {
stage.removeAllChildren();
enemies = [];
bullets = [];
meteors = [];
explosions = [];
stars = [];
score = 0;
lives = 3;
keys.cLeft = false;
keys.cRight = false;
keys.cUp = false;
keys.cDown = false;
//Draw stars
startingStars=24;
for (var i=0; i<startingStars; i++){
//Create big and small stars
star = new createjs.Shape();
star.size=i%2+1; //can be 1 or 2
star.graphics.f("#eee").dc(0,0,star.size);
star.speed= 0.25* star.size; //can be 0.25 or 0.5
star.regX=star.size/2;
star.regY=star.size/2;
star.x=Math.floor(Math.random()*(stage.canvas.width-star.size)+star.size/2);
star.y=Math.floor(Math.random()*(stage.canvas.height-star.size)+star.size/2);
stage.addChild(star);
stars.push(star);
}
//Create spaceship
spaceship = new createjs.Bitmap(queue.getResult("spaceshipSprite"));
// spaceship= new createjs.Shape();
spaceship.size=50;
// spaceship.graphics.f("yellow").dr(0,0,spaceship.size, spaceship.size);
spaceship.speed=2;
spaceship.regX=spaceship.size/2;
spaceship.regY=spaceship.size/2;
spaceship.x=stage.canvas.width/2;
spaceship.y=stage.canvas.height+spaceship.size/2;
stage.addChild(spaceship);
scoreText = new createjs.Text("Score: "+score, "20px Arial", "#fff");
scoreText.baseline="alphabetic";
scoreText.textAlign="left";
scoreText.x=10;
scoreText.y=10;
livesText = new createjs.Text("Lives: "+lives, "20px Arial", "#fff");
livesText.baseline="alphabetic";
livesText.textAlign="right";
livesText.x=stage.canvas.width - 10;
livesText.y=10;
title = new createjs.Text("Space Invaders - Press space to start", "24px Arial", "#fff");
title.textAlign="center";
title.x=stage.canvas.width/2;
title.y=stage.canvas.height/2-30;
stage.addChild(title);
instructions = new createjs.Text("Use the arrow keys to move your spaceship. Press space to shoot. Don't let aliens reach the bottom of the screen. Avarage score of players: 800", "18px Arial", "#fff");
instructions.textAlign="center";
instructions.lineWidth=400;
instructions.x=stage.canvas.width/2;
instructions.y=stage.canvas.height/2+30;
stage.addChild(instructions);
scene=0;
}
// III. Update screen
function updateFrame() {
//X.Transparent elements
inSeconds(.5, spawnStar);
moveArray(stars);
fadeExplosions();
//Scenes
switch(scene) {
//0.Main menu
case 0:
mainMenu();
break;
//1.Animation
case 1:
revealSpaceship();
break;
//2.Gameplay
case 2:
inSeconds(2, spawnEnemy);
inSeconds(3, spawnMeteor);
moveArray(bullets);
moveArray(enemies);
moveArray(meteors);
rotateArray(meteors);
controlSpaceship();
checkHits();
break;
//3.Game Over
case 3:
gameOver();
moveArray(enemies);
moveArray(bullets);
moveArray(meteors);
rotateArray(meteors);
break;
}
stage.addChild(scoreText);
stage.addChild(livesText);
stage.update();
}
//X.Transparent functions
//Call a given function in every given seconds
function inSeconds(seconds, functionName) {
if (createjs.Ticker.getTicks()/framerate % seconds == 0) {
functionName();
}
}
//Calculate movement to adjust it to the framerate
function calcMovement(speed){
return speed / framerate * 60;
}
//Spawn an enemy
function spawnEnemy() {0
enemy=new createjs.Bitmap(queue.getResult("alienSprite"));
enemy.size=64;
enemy.speed=1 + ((Math.floor((createjs.Ticker.getTicks()-gameStartDate)/60))*0.01);
enemy.pointWorth=7;
enemy.regX=enemy.size/2;
enemy.regY=enemy.size/2;
enemy.y=-enemy.size/2;
enemy.x= Math.floor(Math.random()*(stage.canvas.width-enemy.size)+enemy.size/2);
stage.addChild(enemy);
enemies.push(enemy);
}
//Spawn a star (every 2nd is a big one)
function spawnStar() {
star = new createjs.Shape();
modStars=(stars.length%2); // can be 0 or 1
star.size=modStars+1; // can be 1 or 2
star.speed=.25*star.size; // can be 0.25 or 0.5
star.graphics.f('#eee').dc(0,0,star.size);
star.regX=star.size/2;
star.regY=star.size/2;
star.x=Math.floor(Math.random()*(stage.canvas.width-star.size)+star.size/2);
star.y=-star.size/2;
stage.addChild(star);
stars.push(star);
}
//Spawn a meteor
function spawnMeteor(){
meteor = new createjs.Bitmap(queue.getResult("meteorSprite"));
meteor.size=220;
meteor.speed=3;
meteor.hp=3+Math.floor(Math.random()*3);
meteor.pointWorth=1;
meteor.regX=meteor.size/2;
meteor.regY=meteor.size/2;
meteor.x=Math.floor(Math.random()*(stage.canvas.width-meteor.size)+meteor.size/2);
meteor.y=-meteor.size/2;
stage.addChild(meteor);
meteors.push(meteor);
}
//Move elements in array
function moveArray(Array){
for (var i=Array.length-1; i>=0; i--) {
//get independent from framerate
Array[i].y+=calcMovement(Array[i].speed);
if ((Array[i].y>stage.canvas.height+Array[i].size/2) ||
(Array[i].y<0-Array[i].size/2)) {
stage.removeChild(Array[i]);
Array.splice(i, 1);
if (Array==enemies){
lives--;
livesText.text="Lives: " + lives;
if (lives<=0 && scene==2) die();
}
}
}
}
//Rotate elements in array
function rotateArray(Array) {
for (var i=0; i<Array.length; i++) {
Array[i].rotation++;
}
}
//Explode animation
function explode(object) {
explosion = new createjs.Shape();
explosion.size=object.size/3;
explosion.graphics.f("#fff").dc(0,0,explosion.size,explosion.size);
explosion.alpha=.8;
explosion.regX=explosion.size/2;
explosion.regY=explosion.size/2;
explosion.x=object.x+object.size/4;
explosion.y=object.y+object.size/4;
explosions.push(explosion);
stage.addChild(explosion);
}
//Fade explosions
function fadeExplosions(){
for (var i = explosions.length-1; i>=0; i--) {
explosions[i].alpha-=.05;
explosions[i].scaleX+=.05;
explosions[i].scaleY+=.05;
if (explosions[i].alpha==0) {
stage.removeChild(explosions[i]);
explosions.splice(i, 1);
}
}
}
function takeDamage(x) {
lives--;
// blood = new createjs.Shape();
// blood.graphics.f("red").dr(0,0,stage.canvas.width, stage.canvas.height);
// blood.born=creatjs.Ticker.getTicks();
// blood.x=0;
// blood.y=0;
// blood.alpha=0.6;
// stage.addChild(blood);
livesText.text=("Lives: "+lives);
livesText.text=("Lives: "+lives);
}
//0.Menu functions
function mainMenu() {
window.onkeyup = function(e){
if (e.keyCode==32) {
gameStartDate=createjs.Ticker.getTicks();
stage.removeChild(title);
stage.removeChild(instructions);
stage.addChild(livesText);
stage.addChild(scoreText);
scene=1;
}
}
}
//1.Animation functions
function revealSpaceship() {
spaceship.y-=calcMovement(.5);
// spaceship.y -= .5;
if (spaceship.y<stage.canvas.height-stage.canvas.height/8) scene=2;
}
//2.Gameplay functions
function controlSpaceship() {
//key control
window.onkeydown = function(e){
if (e.keyCode==37) keys.cLeft=true;
if (e.keyCode==38) keys.cUp=true;
if (e.keyCode==39) keys.cRight=true;
if (e.keyCode==40) keys.cDown=true;
}
//binding keys
window.onkeyup = function(e) {
if (e.keyCode==37) keys.cLeft=false;
if (e.keyCode==38) keys.cUp=false;
if (e.keyCode==39) keys.cRight=false;
if (e.keyCode==40) keys.cDown=false;
if (e.keyCode==32) {
bullet = new createjs.Shape();
bullet.size=2;
bullet.graphics.f("#F4E3C2").dc(0,0,bullet.size);
bullet.regX=bullet.size/2;
bullet.regY=bullet.size/2;
bullet.x=spaceship.x;
bullet.y=spaceship.y-spaceship.size/2;
bullet.speed=-6;
stage.addChild(bullet);
bullets.push(bullet);
}
}
realSpeed=calcMovement(spaceship.speed);
//move spaceship
if ((keys.cLeft) && ((spaceship.x-=realSpeed)>0)) spaceship.x -= realSpeed;
if ((keys.cRight) && (spaceship.x+=realSpeed<=stage.canvas.width)) spaceship.x += realSpeed;
if ((keys.cUp) && (spaceship.y-=realSpeed>=0)) spaceship.y -= realSpeed;
if ((keys.cDown) && (spaceship.y+=realSpeed<=stage.canvas.height)) spaceship.y += realSpeed;
//Keep in stage on X axis
if (spaceship.x<spaceship.size/2) spaceship.x=spaceship.size/2;
if (spaceship.x>stage.canvas.width-spaceship.size/2) spaceship.x=stage.canvas.width-spaceship.size/2;
//Keep in stage on Y axis
if (spaceship.y<spaceship.size/2) spaceship.y=spaceship.size/2;
if (spaceship.y>stage.canvas.height-spaceship.size/2) spaceship.y=stage.canvas.height-spaceship.size/2;
}
function hitTest(elem1, elem2) {
return (elem1.x-elem1.size/2 < elem2.x-elem2.size/2 &&
elem1.x+elem1.size/2 > elem2.x-elem2.size/2 &&
elem1.y-elem1.size/2 < elem2.y-elem2.size/2 &&
elem1.y+elem1.size/2 > elem2.y-elem2.size/2);
}
function checkHits() {
//Enemies hit detection
for (var i=enemies.length-1; i>=0; i--){
//Enemies and spaceship
if (hitTest(enemies[i], spaceship)) {
explode(enemies[i]);
if (lives>1) {
stage.removeChild(enemies[i]);
enemies.splice(i,1);
takeDamage(1);
}
else die();
}
//Enemies and bullets
for (var b=bullets.length-1; b>=0; b--) {
if (hitTest(enemies[i], bullets[b])) {
explode(enemies[i]);
score+=enemies[i].pointWorth;
scoreText.text=("Score: "+score);
stage.removeChild(enemies[i]);
stage.removeChild(bullets[b]);
bullets.splice(b, 1);
enemies.splice(i, 1);
}
}
}
//Meteors hit detection
for (var i=meteors.length-1; i>=0; i--) {
//Meteors and spaceship
if (hitTest(meteors[i], spaceship)) {
explode(meteors[i]);
if (lives>1) {
stage.removeChild(meteors[i]);
meteors.splice(i,1);
lives--;
livesText.text=("Lives: "+lives);
}
else die();
}
//Meteors and bullets
for (var b=bullets.length-1; b>=0; b--) {
if (hitTest(meteors[i], bullets[b])) {
score+=meteors[i].pointWorth;
stage.removeChild(bullets[b]);
bullets.splice(b, 1);
meteors[i].hp--;
if (meteors[i].hp==0) {
score += (meteors[i].pointWorth*5);
explode(meteors[i]);
stage.removeChild(meteors[i]);
meteors.splice(i, 1);
}
scoreText.text=("Score: "+score);
}
}
}
}
function die(){
stage.removeChild(scoreText);
stage.removeChild(livesText);
gameOverText = new createjs.Text("You have died. Final score: "+score+". Press R to return to menu.", "24px Arial", "#fff");
gameOverText.textAlign="center";
gameOverText.lineWidth=350;
gameOverText.x=stage.canvas.width/2;
gameOverText.y=stage.canvas.height/2;
stage.addChild(gameOverText);
scene=3;
}
//3.GameOver functions
function gameOver() {
stage.removeChild(spaceship);
window.onkeyup=function(e){
if (e.keyCode==82) gameSetup();
}
} | gaboratorium/gaboratorium-notes | apps/space-invaders/js/js.js | JavaScript | mit | 12,734 |
/**
* Copyright 2015 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([ "./kendo.core" ], f);
})(function(){
(function(){
(function($, undefined) {
var kendo = window.kendo,
ui = kendo.ui,
keys = kendo.keys,
extend = $.extend,
each = $.each,
template = kendo.template,
Widget = ui.Widget,
excludedNodesRegExp = /^(ul|a|div)$/i,
NS = ".kendoPanelBar",
IMG = "img",
HREF = "href",
LAST = "k-last",
LINK = "k-link",
LINKSELECTOR = "." + LINK,
ERROR = "error",
ITEM = ".k-item",
GROUP = ".k-group",
VISIBLEGROUP = GROUP + ":visible",
IMAGE = "k-image",
FIRST = "k-first",
EXPAND = "expand",
SELECT = "select",
CONTENT = "k-content",
ACTIVATE = "activate",
COLLAPSE = "collapse",
MOUSEENTER = "mouseenter",
MOUSELEAVE = "mouseleave",
CONTENTLOAD = "contentLoad",
ACTIVECLASS = "k-state-active",
GROUPS = "> .k-panel",
CONTENTS = "> .k-content",
FOCUSEDCLASS = "k-state-focused",
DISABLEDCLASS = "k-state-disabled",
SELECTEDCLASS = "k-state-selected",
SELECTEDSELECTOR = "." + SELECTEDCLASS,
HIGHLIGHTCLASS = "k-state-highlight",
ACTIVEITEMSELECTOR = ITEM + ":not(.k-state-disabled)",
clickableItems = "> " + ACTIVEITEMSELECTOR + " > " + LINKSELECTOR + ", .k-panel > " + ACTIVEITEMSELECTOR + " > " + LINKSELECTOR,
disabledItems = ITEM + ".k-state-disabled > .k-link",
selectableItems = "> li > " + SELECTEDSELECTOR + ", .k-panel > li > " + SELECTEDSELECTOR,
defaultState = "k-state-default",
ARIA_DISABLED = "aria-disabled",
ARIA_EXPANDED = "aria-expanded",
ARIA_HIDDEN = "aria-hidden",
ARIA_SELECTED = "aria-selected",
VISIBLE = ":visible",
EMPTY = ":empty",
SINGLE = "single",
templates = {
content: template(
"<div role='region' class='k-content'#= contentAttributes(data) #>#= content(item) #</div>"
),
group: template(
"<ul role='group' aria-hidden='true' class='#= groupCssClass(group) #'#= groupAttributes(group) #>" +
"#= renderItems(data) #" +
"</ul>"
),
itemWrapper: template(
"<#= tag(item) # class='#= textClass(item, group) #' #= contentUrl(item) ##= textAttributes(item) #>" +
"#= image(item) ##= sprite(item) ##= text(item) #" +
"#= arrow(data) #" +
"</#= tag(item) #>"
),
item: template(
"<li role='menuitem' #=aria(item)#class='#= wrapperCssClass(group, item) #'>" +
"#= itemWrapper(data) #" +
"# if (item.items) { #" +
"#= subGroup({ items: item.items, panelBar: panelBar, group: { expanded: item.expanded } }) #" +
"# } else if (item.content || item.contentUrl) { #" +
"#= renderContent(data) #" +
"# } #" +
"</li>"
),
image: template("<img class='k-image' alt='' src='#= imageUrl #' />"),
arrow: template("<span class='#= arrowClass(item) #'></span>"),
sprite: template("<span class='k-sprite #= spriteCssClass #'></span>"),
empty: template("")
},
rendering = {
aria: function(item) {
var attr = "";
if (item.items || item.content || item.contentUrl) {
attr += ARIA_EXPANDED + "='" + (item.expanded ? "true" : "false") + "' ";
}
if (item.enabled === false) {
attr += ARIA_DISABLED + "='true'";
}
return attr;
},
wrapperCssClass: function (group, item) {
var result = "k-item",
index = item.index;
if (item.enabled === false) {
result += " " + DISABLEDCLASS;
} else if (item.expanded === true) {
result += " " + ACTIVECLASS;
} else {
result += " k-state-default";
}
if (index === 0) {
result += " k-first";
}
if (index == group.length-1) {
result += " k-last";
}
if (item.cssClass) {
result += " " + item.cssClass;
}
return result;
},
textClass: function(item, group) {
var result = LINK;
if (group.firstLevel) {
result += " k-header";
}
return result;
},
textAttributes: function(item) {
return item.url ? " href='" + item.url + "'" : "";
},
arrowClass: function(item) {
var result = "k-icon";
result += item.expanded ? " k-i-arrow-n k-panelbar-collapse" : " k-i-arrow-s k-panelbar-expand";
return result;
},
text: function(item) {
return item.encoded === false ? item.text : kendo.htmlEncode(item.text);
},
tag: function(item) {
return item.url || item.contentUrl ? "a" : "span";
},
groupAttributes: function(group) {
return group.expanded !== true ? " style='display:none'" : "";
},
groupCssClass: function() {
return "k-group k-panel";
},
contentAttributes: function(content) {
return content.item.expanded !== true ? " style='display:none'" : "";
},
content: function(item) {
return item.content ? item.content : item.contentUrl ? "" : " ";
},
contentUrl: function(item) {
return item.contentUrl ? 'href="' + item.contentUrl + '"' : "";
}
};
function updateArrow (items) {
items = $(items);
items.children(LINKSELECTOR).children(".k-icon").remove();
items
.filter(":has(.k-panel),:has(.k-content)")
.children(".k-link:not(:has([class*=k-i-arrow]))")
.each(function () {
var item = $(this),
parent = item.parent();
item.append("<span class='k-icon " + (parent.hasClass(ACTIVECLASS) ? "k-i-arrow-n k-panelbar-collapse" : "k-i-arrow-s k-panelbar-expand") + "'/>");
});
}
function updateFirstLast (items) {
items = $(items);
items.filter(".k-first:not(:first-child)").removeClass(FIRST);
items.filter(".k-last:not(:last-child)").removeClass(LAST);
items.filter(":first-child").addClass(FIRST);
items.filter(":last-child").addClass(LAST);
}
var PanelBar = Widget.extend({
init: function(element, options) {
var that = this,
content;
Widget.fn.init.call(that, element, options);
element = that.wrapper = that.element.addClass("k-widget k-reset k-header k-panelbar");
options = that.options;
if (element[0].id) {
that._itemId = element[0].id + "_pb_active";
}
that._tabindex();
that._initData(options);
that._updateClasses();
that._animations(options);
element
.on("click" + NS, clickableItems, function(e) {
if (that._click($(e.currentTarget))) {
e.preventDefault();
}
})
.on(MOUSEENTER + NS + " " + MOUSELEAVE + NS, clickableItems, that._toggleHover)
.on("click" + NS, disabledItems, false)
.on("keydown" + NS, $.proxy(that._keydown, that))
.on("focus" + NS, function() {
var item = that.select();
that._current(item[0] ? item : that._first());
})
.on("blur" + NS, function() {
that._current(null);
})
.attr("role", "menu");
content = element.find("li." + ACTIVECLASS + " > ." + CONTENT);
if (content[0]) {
that.expand(content.parent(), false);
}
that._angularCompile();
kendo.notify(that);
},
events: [
EXPAND,
COLLAPSE,
SELECT,
ACTIVATE,
ERROR,
CONTENTLOAD
],
options: {
name: "PanelBar",
animation: {
expand: {
effects: "expand:vertical",
duration: 200
},
collapse: { // if collapse animation effects are defined, they will be used instead of expand.reverse
duration: 200
}
},
expandMode: "multiple"
},
_angularCompile: function() {
var that = this;
that.angular("compile", function(){
return {
elements: that.element.children("li"),
data: [{ dataItem: that.options.$angular}]
};
});
},
_angularCleanup: function() {
var that = this;
that.angular("cleanup", function(){
return { elements: that.element.children("li") };
});
},
destroy: function() {
Widget.fn.destroy.call(this);
this.element.off(NS);
this._angularCleanup();
kendo.destroy(this.element);
},
_initData: function(options) {
var that = this;
if (options.dataSource) {
that.element.empty();
that.append(options.dataSource, that.element);
}
},
setOptions: function(options) {
var animation = this.options.animation;
this._animations(options);
options.animation = extend(true, animation, options.animation);
if ("dataSource" in options) {
this._initData(options);
}
Widget.fn.setOptions.call(this, options);
},
expand: function (element, useAnimation) {
var that = this,
animBackup = {};
if (that._animating && element.find("ul").is(":visible")) {
that.one("complete", function() {
setTimeout(function() {
that.expand(element);
});
});
return;
}
that._animating = true;
useAnimation = useAnimation !== false;
element = this.element.find(element);
element.each(function (index, item) {
item = $(item);
var groups = item.find(GROUPS).add(item.find(CONTENTS));
if (!item.hasClass(DISABLEDCLASS) && groups.length > 0) {
if (that.options.expandMode == SINGLE && that._collapseAllExpanded(item)) {
return that;
}
element.find("." + HIGHLIGHTCLASS).removeClass(HIGHLIGHTCLASS);
item.addClass(HIGHLIGHTCLASS);
if (!useAnimation) {
animBackup = that.options.animation;
that.options.animation = { expand: { effects: {} }, collapse: { hide: true, effects: {} } };
}
if (!that._triggerEvent(EXPAND, item)) {
that._toggleItem(item, false);
}
if (!useAnimation) {
that.options.animation = animBackup;
}
}
});
return that;
},
collapse: function (element, useAnimation) {
var that = this,
animBackup = {};
that._animating = true;
useAnimation = useAnimation !== false;
element = that.element.find(element);
element.each(function (index, item) {
item = $(item);
var groups = item.find(GROUPS).add(item.find(CONTENTS));
if (!item.hasClass(DISABLEDCLASS) && groups.is(VISIBLE)) {
item.removeClass(HIGHLIGHTCLASS);
if (!useAnimation) {
animBackup = that.options.animation;
that.options.animation = { expand: { effects: {} }, collapse: { hide: true, effects: {} } };
}
if (!that._triggerEvent(COLLAPSE, item)) {
that._toggleItem(item, true);
}
if (!useAnimation) {
that.options.animation = animBackup;
}
}
});
return that;
},
_toggleDisabled: function (element, enable) {
element = this.element.find(element);
element
.toggleClass(defaultState, enable)
.toggleClass(DISABLEDCLASS, !enable)
.attr(ARIA_DISABLED, !enable);
},
select: function (element) {
var that = this;
if (element === undefined) {
return that.element.find(selectableItems).parent();
}
element = that.element.find(element);
if (!element.length) {
this._updateSelected(element);
} else {
element
.each(function () {
var item = $(this),
link = item.children(LINKSELECTOR);
if (item.hasClass(DISABLEDCLASS)) {
return that;
}
if (!that._triggerEvent(SELECT, item)) {
that._updateSelected(link);
}
});
}
return that;
},
clearSelection: function() {
this.select($());
},
enable: function (element, state) {
this._toggleDisabled(element, state !== false);
return this;
},
disable: function (element) {
this._toggleDisabled(element, false);
return this;
},
append: function (item, referenceItem) {
referenceItem = this.element.find(referenceItem);
var inserted = this._insert(item, referenceItem, referenceItem.length ? referenceItem.find(GROUPS) : null);
each(inserted.items, function () {
inserted.group.append(this);
updateFirstLast(this);
});
updateArrow(referenceItem);
updateFirstLast(inserted.group.find(".k-first, .k-last"));
inserted.group.height("auto");
return this;
},
insertBefore: function (item, referenceItem) {
referenceItem = this.element.find(referenceItem);
var inserted = this._insert(item, referenceItem, referenceItem.parent());
each(inserted.items, function () {
referenceItem.before(this);
updateFirstLast(this);
});
updateFirstLast(referenceItem);
inserted.group.height("auto");
return this;
},
insertAfter: function (item, referenceItem) {
referenceItem = this.element.find(referenceItem);
var inserted = this._insert(item, referenceItem, referenceItem.parent());
each(inserted.items, function () {
referenceItem.after(this);
updateFirstLast(this);
});
updateFirstLast(referenceItem);
inserted.group.height("auto");
return this;
},
remove: function (element) {
element = this.element.find(element);
var that = this,
parent = element.parentsUntil(that.element, ITEM),
group = element.parent("ul");
element.remove();
if (group && !group.hasClass("k-panelbar") && !group.children(ITEM).length) {
group.remove();
}
if (parent.length) {
parent = parent.eq(0);
updateArrow(parent);
updateFirstLast(parent);
}
return that;
},
reload: function (element) {
var that = this;
element = that.element.find(element);
element.each(function () {
var item = $(this);
that._ajaxRequest(item, item.children("." + CONTENT), !item.is(VISIBLE));
});
},
_first: function() {
return this.element.children(ACTIVEITEMSELECTOR).first();
},
_last: function() {
var item = this.element.children(ACTIVEITEMSELECTOR).last(),
group = item.children(VISIBLEGROUP);
if (group[0]) {
return group.children(ACTIVEITEMSELECTOR).last();
}
return item;
},
_current: function(candidate) {
var that = this,
focused = that._focused,
id = that._itemId;
if (candidate === undefined) {
return focused;
}
that.element.removeAttr("aria-activedescendant");
if (focused && focused.length) {
if (focused[0].id === id) {
focused.removeAttr("id");
}
focused
.children(LINKSELECTOR)
.removeClass(FOCUSEDCLASS);
}
if ($(candidate).length) {
id = candidate[0].id || id;
candidate.attr("id", id)
.children(LINKSELECTOR)
.addClass(FOCUSEDCLASS);
that.element.attr("aria-activedescendant", id);
}
that._focused = candidate;
},
_keydown: function(e) {
var that = this,
key = e.keyCode,
current = that._current();
if (e.target != e.currentTarget) {
return;
}
if (key == keys.DOWN || key == keys.RIGHT) {
that._current(that._nextItem(current));
e.preventDefault();
} else if (key == keys.UP || key == keys.LEFT) {
that._current(that._prevItem(current));
e.preventDefault();
} else if (key == keys.ENTER || key == keys.SPACEBAR) {
that._click(current.children(LINKSELECTOR));
e.preventDefault();
} else if (key == keys.HOME) {
that._current(that._first());
e.preventDefault();
} else if (key == keys.END) {
that._current(that._last());
e.preventDefault();
}
},
_nextItem: function(item) {
if (!item) {
return this._first();
}
var group = item.children(VISIBLEGROUP),
next = item.nextAll(":visible").first();
if (group[0]) {
next = group.children("." + FIRST);
}
if (!next[0]) {
next = item.parent(VISIBLEGROUP).parent(ITEM).next();
}
if (!next[0]) {
next = this._first();
}
if (next.hasClass(DISABLEDCLASS)) {
next = this._nextItem(next);
}
return next;
},
_prevItem: function(item) {
if (!item) {
return this._last();
}
var prev = item.prevAll(":visible").first(),
result;
if (!prev[0]) {
prev = item.parent(VISIBLEGROUP).parent(ITEM);
if (!prev[0]) {
prev = this._last();
}
} else {
result = prev;
while (result[0]) {
result = result.children(VISIBLEGROUP).children("." + LAST);
if (result[0]) {
prev = result;
}
}
}
if (prev.hasClass(DISABLEDCLASS)) {
prev = this._prevItem(prev);
}
return prev;
},
_insert: function (item, referenceItem, parent) {
var that = this,
items,
plain = $.isPlainObject(item),
isReferenceItem = referenceItem && referenceItem[0],
groupData;
if (!isReferenceItem) {
parent = that.element;
}
groupData = {
firstLevel: parent.hasClass("k-panelbar"),
expanded: parent.parent().hasClass(ACTIVECLASS),
length: parent.children().length
};
if (isReferenceItem && !parent.length) {
parent = $(PanelBar.renderGroup({ group: groupData })).appendTo(referenceItem);
}
if (item instanceof kendo.Observable) {
item = item.toJSON();
}
if (plain || $.isArray(item)) { // is JSON
items = $.map(plain ? [ item ] : item, function (value, idx) {
if (typeof value === "string") {
return $(value);
} else {
return $(PanelBar.renderItem({
group: groupData,
item: extend(value, { index: idx })
}));
}
});
if (isReferenceItem) {
referenceItem.attr(ARIA_EXPANDED, false);
}
} else {
if (typeof item == "string" && item.charAt(0) != "<") {
items = that.element.find(item);
} else {
items = $(item);
}
that._updateItemsClasses(items);
}
return { items: items, group: parent };
},
_toggleHover: function(e) {
var target = $(e.currentTarget);
if (!target.parents("li." + DISABLEDCLASS).length) {
target.toggleClass("k-state-hover", e.type == MOUSEENTER);
}
},
_updateClasses: function() {
var that = this,
panels, items;
panels = that.element
.find("li > ul")
.not(function () { return $(this).parentsUntil(".k-panelbar", "div").length; })
.addClass("k-group k-panel")
.attr("role", "group");
panels.parent()
.attr(ARIA_EXPANDED, false)
.not("." + ACTIVECLASS)
.children("ul")
.attr(ARIA_HIDDEN, true)
.hide();
items = that.element.add(panels).children();
that._updateItemsClasses(items);
updateArrow(items);
updateFirstLast(items);
},
_updateItemsClasses: function(items) {
var length = items.length,
idx = 0;
for(; idx < length; idx++) {
this._updateItemClasses(items[idx], idx);
}
},
_updateItemClasses: function(item, index) {
var selected = this._selected,
contentUrls = this.options.contentUrls,
url = contentUrls && contentUrls[index],
root = this.element[0],
wrapElement, link;
item = $(item).addClass("k-item").attr("role", "menuitem");
if (kendo.support.browser.msie) { // IE10 doesn't apply list-style: none on invisible items otherwise.
item.css("list-style-position", "inside")
.css("list-style-position", "");
}
item
.children(IMG)
.addClass(IMAGE);
link = item
.children("a")
.addClass(LINK);
if (link[0]) {
link.attr("href", url); //url can be undefined
link.children(IMG)
.addClass(IMAGE);
}
item
.filter(":not([disabled]):not([class*=k-state])")
.addClass("k-state-default");
item
.filter("li[disabled]")
.addClass("k-state-disabled")
.attr(ARIA_DISABLED, true)
.removeAttr("disabled");
item
.children("div")
.addClass(CONTENT)
.attr("role", "region")
.attr(ARIA_HIDDEN, true)
.hide()
.parent()
.attr(ARIA_EXPANDED, false);
link = item.children(SELECTEDSELECTOR);
if (link[0]) {
if (selected) {
selected.removeAttr(ARIA_SELECTED)
.children(SELECTEDSELECTOR)
.removeClass(SELECTEDCLASS);
}
link.addClass(SELECTEDCLASS);
this._selected = item.attr(ARIA_SELECTED, true);
}
if (!item.children(LINKSELECTOR)[0]) {
wrapElement = "<span class='" + LINK + "'/>";
if (contentUrls && contentUrls[index] && item[0].parentNode == root) {
wrapElement = '<a class="k-link k-header" href="' + contentUrls[index] + '"/>';
}
item
.contents() // exclude groups, real links, templates and empty text nodes
.filter(function() { return (!this.nodeName.match(excludedNodesRegExp) && !(this.nodeType == 3 && !$.trim(this.nodeValue))); })
.wrapAll(wrapElement);
}
if (item.parent(".k-panelbar")[0]) {
item
.children(LINKSELECTOR)
.addClass("k-header");
}
},
_click: function (target) {
var that = this,
element = that.element,
prevent, contents, href, isAnchor;
if (target.parents("li." + DISABLEDCLASS).length) {
return;
}
if (target.closest(".k-widget")[0] != element[0]) {
return;
}
var link = target.closest(LINKSELECTOR),
item = link.closest(ITEM);
that._updateSelected(link);
contents = item.find(GROUPS).add(item.find(CONTENTS));
href = link.attr(HREF);
isAnchor = href && (href.charAt(href.length - 1) == "#" || href.indexOf("#" + that.element[0].id + "-") != -1);
prevent = !!(isAnchor || contents.length);
if (contents.data("animating")) {
return prevent;
}
if (that._triggerEvent(SELECT, item)) {
prevent = true;
}
if (prevent === false) {
return;
}
if (that.options.expandMode == SINGLE) {
if (that._collapseAllExpanded(item)) {
return prevent;
}
}
if (contents.length) {
var visibility = contents.is(VISIBLE);
if (!that._triggerEvent(!visibility ? EXPAND : COLLAPSE, item)) {
prevent = that._toggleItem(item, visibility);
}
}
return prevent;
},
_toggleItem: function (element, isVisible) {
var that = this,
childGroup = element.find(GROUPS),
link = element.find(LINKSELECTOR),
url = link.attr(HREF),
prevent, content;
if (childGroup.length) {
this._toggleGroup(childGroup, isVisible);
prevent = true;
} else {
content = element.children("." + CONTENT);
if (content.length) {
prevent = true;
if (!content.is(EMPTY) || url === undefined) {
that._toggleGroup(content, isVisible);
} else {
that._ajaxRequest(element, content, isVisible);
}
}
}
return prevent;
},
_toggleGroup: function (element, visibility) {
var that = this,
animationSettings = that.options.animation,
animation = animationSettings.expand,
collapse = extend({}, animationSettings.collapse),
hasCollapseAnimation = collapse && "effects" in collapse;
if (element.is(VISIBLE) != visibility) {
that._animating = false;
return;
}
element
.parent()
.attr(ARIA_EXPANDED, !visibility)
.attr(ARIA_HIDDEN, visibility)
.toggleClass(ACTIVECLASS, !visibility)
.find("> .k-link > .k-icon")
.toggleClass("k-i-arrow-n", !visibility)
.toggleClass("k-panelbar-collapse", !visibility)
.toggleClass("k-i-arrow-s", visibility)
.toggleClass("k-panelbar-expand", visibility);
if (visibility) {
animation = extend( hasCollapseAnimation ? collapse
: extend({ reverse: true }, animation), { hide: true });
animation.complete = function() {
that._animationCallback();
};
} else {
animation = extend( { complete: function (element) {
that._triggerEvent(ACTIVATE, element.closest(ITEM));
that._animationCallback();
} }, animation );
}
element
.kendoStop(true, true)
.kendoAnimate( animation );
},
_animationCallback: function() {
var that = this;
that.trigger("complete");
that._animating = false;
},
_collapseAllExpanded: function (item) {
var that = this, children, stopExpand = false;
var groups = item.find(GROUPS).add(item.find(CONTENTS));
if (groups.is(VISIBLE)) {
stopExpand = true;
}
if (!(groups.is(VISIBLE) || groups.length === 0)) {
children = item.siblings();
children.find(GROUPS).add(children.find(CONTENTS))
.filter(function () { return $(this).is(VISIBLE); })
.each(function (index, content) {
content = $(content);
stopExpand = that._triggerEvent(COLLAPSE, content.closest(ITEM));
if (!stopExpand) {
that._toggleGroup(content, true);
}
});
}
return stopExpand;
},
_ajaxRequest: function (element, contentElement, isVisible) {
var that = this,
statusIcon = element.find(".k-panelbar-collapse, .k-panelbar-expand"),
link = element.find(LINKSELECTOR),
loadingIconTimeout = setTimeout(function () {
statusIcon.addClass("k-loading");
}, 100),
data = {},
url = link.attr(HREF);
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "html",
data: data,
error: function (xhr, status) {
statusIcon.removeClass("k-loading");
if (that.trigger(ERROR, { xhr: xhr, status: status })) {
this.complete();
}
},
complete: function () {
clearTimeout(loadingIconTimeout);
statusIcon.removeClass("k-loading");
},
success: function (data) {
function getElements(){
return { elements: contentElement.get() };
}
try {
that.angular("cleanup", getElements);
contentElement.html(data);
that.angular("compile", getElements);
} catch (e) {
var console = window.console;
if (console && console.error) {
console.error(e.name + ": " + e.message + " in " + url);
}
this.error(this.xhr, "error");
}
that._toggleGroup(contentElement, isVisible);
that.trigger(CONTENTLOAD, { item: element[0], contentElement: contentElement[0] });
}
});
},
_triggerEvent: function (eventName, element) {
var that = this;
return that.trigger(eventName, { item: element[0] });
},
_updateSelected: function(link) {
var that = this,
element = that.element,
item = link.parent(ITEM),
selected = that._selected;
if (selected) {
selected.removeAttr(ARIA_SELECTED);
}
that._selected = item.attr(ARIA_SELECTED, true);
element.find(selectableItems).removeClass(SELECTEDCLASS);
element.find("> ." + HIGHLIGHTCLASS + ", .k-panel > ." + HIGHLIGHTCLASS).removeClass(HIGHLIGHTCLASS);
link.addClass(SELECTEDCLASS);
link.parentsUntil(element, ITEM).filter(":has(.k-header)").addClass(HIGHLIGHTCLASS);
that._current(item[0] ? item : null);
},
_animations: function(options) {
if (options && ("animation" in options) && !options.animation) {
options.animation = { expand: { effects: {} }, collapse: { hide: true, effects: {} } };
}
}
});
// client-side rendering
extend(PanelBar, {
renderItem: function (options) {
options = extend({ panelBar: {}, group: {} }, options);
var empty = templates.empty,
item = options.item;
return templates.item(extend(options, {
image: item.imageUrl ? templates.image : empty,
sprite: item.spriteCssClass ? templates.sprite : empty,
itemWrapper: templates.itemWrapper,
renderContent: PanelBar.renderContent,
arrow: item.items || item.content || item.contentUrl ? templates.arrow : empty,
subGroup: PanelBar.renderGroup
}, rendering));
},
renderGroup: function (options) {
return templates.group(extend({
renderItems: function(options) {
var html = "",
i = 0,
items = options.items,
len = items ? items.length : 0,
group = extend({ length: len }, options.group);
for (; i < len; i++) {
html += PanelBar.renderItem(extend(options, {
group: group,
item: extend({ index: i }, items[i])
}));
}
return html;
}
}, options, rendering));
},
renderContent: function (options) {
return templates.content(extend(options, rendering));
}
});
kendo.ui.plugin(PanelBar);
})(window.kendo.jQuery);
})();
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | assunluis80/Web-Starter-Template | assets/scripts/vendors/kendo_ui/kendo.panelbar.js | JavaScript | mit | 37,708 |
/*
DBObject bir tablo icin sql yazma surecini kisaltmayi amaclar.
Example usage
var dbo = new DBObject(tablename, database);
dbo.select(params, callbak)
dbo.get(id, callback)
dbo.insert(data, callback)
dbo.update(id, data, callback)
dbo.save(data, callback)
dbo.delete(id, callback)
*/
'use strict';
var util = require('util'),
_ = require('underscore'),
md5 = require('md5'),
moment = require('moment'),
debug = require('debug')('lib:dbobject');
class DBObject{
constructor (tablename, database, options){
this.options = _.extend({pick: [], omit: []}, options||{})
if(typeof this.options.pick === 'string') this.options.pick = this.options.pick.split(',')
if(typeof this.options.omit === 'string') this.options.omit = this.options.omit.split(',')
this.db = database
this.tablename = tablename
this.viewname = null
this.keyfields = null
this.fields = null
this.hiddenfields = []
//debug('DBObject options', this.options)
}
initialize(){
return Promise.all([this.db.getTableInfo(this.tablename), this.db.getTableInfo(this.tablename+'_view')]).then(function(result){
if(_.keys(result[1]).length) this.viewname = this.tablename+'_view';
this.fields = _.mapObject(result[1], function(f, name){ return f['readonly'] = true, f['hide'] = false, f; })
_.extend(this.fields, _.mapObject(result[0], function(f, name){ return f['readonly'] = false, f['hide'] = false, f; }) )
this.keyfields = _.pluck(_.select(this.fields, function(item){ return item.primary; }), 'name');
if(!this.options.pick.length) this.options.pick = _.keys(this.fields)
return this.fields;
}.bind(this))
}
hide(fields){
this.hiddenfields = fields.split(',');
}
encode(data, fields){
if(!fields)
fields = 'id,' + _.filter(this.fields, function(f){ return f.type == 'int'}).map(function(f){ return f.name}).join(',')
return this.db.encode(data, fields, this.tablename)
}
decode(data, fields){
if(!fields){
fields = _.filter(this.fields, function(f){ return f.type == 'int'}).map(function(f){ return f.name})
fields.indexOf('id') >= 0 || fields.unshift('id')
}
this.db.decode(data, fields, this.tablename)
}
where_object(key, param, field){
//debug('where_object', key, param, field)
// distribute param values
for(var i = 0; i < param[key].value.length; i++)
//param[key+'_'+i] = param[key].value[i]
param[key+'_'+i] = param[key+'_'+i] = this.formatter(param[key].value[i], field.type)
switch(param[key].op){
case 'between':
var w = []
param[key+'_0'] && w.push(util.format('T.%s >= :%s_0', key, key))
param[key+'_1'] && w.push(util.format('T.%s <= :%s_1', key, key))
return w.join(' and ')
break;
case 'in':
for(var i = 0; i < param[key].value.length; i++)
param[key+'_'+i] = param[key].value[i]
return util.format('T.%s in [%s]', key, _.map(_.range(0, param[key].value.length), function(val){ return ':'+key+'_'+val}).join(', '))
break;
case '>':
case '>=':
var sql = util.format('T.%s %s :%s', key, param[key].op, key)
return param[key] = param[key].value, sql
}
}
where_array(key, param, field){
param[key] = {op: param[key].length == 2 ? 'between' : 'in', value: param[key]}
return this.where_object(key, param, field)
}
formatter(value, type){
switch(type){
case 'date':
case 'datetime':
return value ? moment(value).format('YYYY-MM-DD') : value
break;
default:
return value
}
}
// ---==[ SELECT ]==---
selectSQL(param, options){
var db = this.db
//options = _.extend({fields: _.keys(this.fields)}, options);
options = _.defaults(options||{}, this.options)
var sql = {field: {}, table: {}, where: {}, limit: 100, offset: 0};
if(this.keyfields.join(',') != 'id')
sql['field']['id'] = util.format("concat_ws('-', %s)", _.map(this.keyfields, function(field){ return 't.'+field; }).join(', '));
_.each(_.difference(options.pick, options.omit), function(field){
sql['field'][field] = 't.'+field;
});
/*
_.each(_.difference(_.intersection(options.fields, _.keys(this.fields)), this.hiddenfields), function(field){
sql['field'][field] = 't.'+field;
});
*/
sql['table']['t'] = this.db.identify(this.viewname || this.tablename) + ' as t';
// gelen butun parametreler isleme girer, eger parametrelerde bir temizlik yapilacak ise api servislerinde yapilmali
_.each(param, function(val, key){
switch(key){
case 'que':
var ques = [];
_.each(this.fields, function(field, name){
if(field.type == 'varchar')
ques.push(util.format('t.%s %s :que', field.name, db.iLike));
})
sql.where['que'] = ques.join(' or ');
param.que = util.format('%%%s%%', val.trim());
break;
default:
var field = this.fields[key];
if(!field) break;
if(Array.isArray(val))
sql.where[key] = this.where_array(key, param, field)
else if(typeof val === 'object' && val !== null)
sql.where[key] = this.where_object(key, param, field)
else if(val === null)
sql.where[key] = util.format('t.%s is null', key);
else
switch(field.type){
case 'varchar':
case 'text':
sql.where[key] = util.format('t.%s %s :%s', key, db.iLike, key);
param[key] = util.format('%%%s%%', val)
break;
case 'int':
sql.where[key] = util.format('t.%s = :%s', key, key);
param[key] = this.formatter(val, field.type)
break;
case 'date':
case 'datetime':
sql.where[key] = util.format('t.%s = :%s', key, key);
param[key] = this.formatter(val, field.type)
break;
default:
debug('uncougtch data type:', field.name, field.type)
sql.where[key] = util.format('t.%s = :%s', key, key);
}
break;
}
}, this)
// apply options
_.each(options, function(val, key){
switch (key) {
case 'order':
sql['order'] = [];
_.each(val.split(','), function(f){
sql.order.push( (f.indexOf('.')>-1?'':'t.') + f.trim());
});
break;
case 'limit':
sql['limit'] = val;
break;
case 'offset':
sql['offset'] = val;
break;
}
});
debug('SelectSQL', sql, param)
return {sql: sql, param: param}
}
select(param, options){
return this
.initialize()
.then(this.selectSQL.bind(this, param, options))
.then(function(result){
return this.db.query(result.sql, result.param)
}.bind(this))
}
search(param, options){
return this.select(param, options)
}
// ---==[ GET ]==---
getSQL(id){
var sql = {field: {}, table: {}, where: {}};
if(this.keyfields.join(',') != 'id')
sql['field']['id'] = util.format("concat_ws('-', %s)", _.map(this.keyfields, function(field){ return 't.'+field; }).join(', '));
_.each(_.difference(_.keys(this.fields), this.hiddenfields), function(field){
sql['field'][field] = 't.'+field;
});
sql['table']['t'] = this.db.identify(this.viewname || this.tablename) + ' as t';
var param = _.object(this.keyfields, String(id).split('-'));
sql['where'] = _.map(this.keyfields, function(name){ return 't.'+name+' = :'+name});
return {sql: sql, param: param}
}
get(id){
var db = this.db;
return this.initialize()
.then(this.getSQL.bind(this, id))
.then(function(result){ return db.query(result.sql, result.param) })
.then(function(data){ return data[0] || null })
}
// ---==[ INSERT ]==---
insertSQL(values){
var db = this.db,
fields = _.intersection(
_.keys(values),
_.keys(_.pick(this.fields, function(f, name){ return !(f.autoincrement || f.readonly)}))
);
var param = _.mapObject(_.pick(values, fields), function(val){ return val === '' ? null : val});
var sql = util.format(
'INSERT INTO %s (%s) values(%s)',
db.identify(this.tablename),
_.map(fields, function(key){ return db.identify(key)}).join(', '),
_.map(fields, function(key){
var field = this.fields[key]
switch(field.type){
case 'timestamp':
if(param[key] == 'current_timestamp')
return 'current_timestamp'
else
return ':'+key
break;
default:
return ':'+key
}
}.bind(this)).join(', ')
)
if(db.Provider == 'PgSQL'){
sql += ' RETURNING ' + _.map(this.keyfields, function(key){ return db.identify(key)}).join(', ')
}
return {sql: sql, param: param}
}
insert(values){
var db = this.db
if(Array.isArray(values)){
var promises = values.map( this.insert.bind(this) )
return Promise.all(promises)
}
return this.initialize()
.then(this.insertSQL.bind(this, values))
.then(function(result){ return db.exec(result.sql, result.param) })
.then(function(res){
if(this.db.Provider == 'PgSQL'){
var id = _.values(res.result[0]).join('-');
} else {
var id = res.insertId ? res.insertId : _.values(_.pick(values, this.keyfields)).join('-')
}
return this.get(id)
}.bind(this))
}
// ---==[ UPDATE ]==---
updateSQL(id, values){
var db = this.db;
// requested fields
var fields = _.intersection(
_.keys(values),
_.keys(_.pick(this.fields, function(f, name){ return !(f.autoincrement || f.readonly)}))
);
// update params
var param = _.mapObject(_.pick(values, fields), function(val){ return val === '' ? null : val});
_.extend(param, _.object(_.map(this.keyfields, function(key){return 'key_'+key}), String(id).split('-')))
// build update sql
var sql = util.format(
'update %s set %s',
db.identify(this.tablename),
_.map(fields, function(key){
var field = this.fields[key]
switch(field.type){
case 'timestamp':
if(param[key] == 'current_timestamp')
return util.format('%s = %s', db.identify(key), 'current_timestamp')
else
return util.format('%s = :%s', db.identify(key), key)
break;
default:
//debug(field.type)
return util.format('%s = :%s', db.identify(key), key)
}
}.bind(this)).join(', ')
)
// add where clause
sql += util.format(' where %s', _.map(this.keyfields, function(key){ return util.format('%s = :key_%s', db.identify(key), key)}).join(' and '));
//debug(['UPDATE', sql, param])
return {sql: sql, param: param}
}
update(id, values){
var db = this.db
return this
.initialize()
.then(this.updateSQL.bind(this, id, values))
.then(function(result){ return db.exec(result.sql, result.param) })
.then(function(result){
return this.get(id)
}.bind(this))
}
// ---==[ DELETE ]==---
delete(id){
var db = this.db
return this.initialize()
.then(function(){
var param = _.object(this.keyfields, String(id).split('-')),
sql = util.format('delete from %s WHERE %s ',
db.identify(this.tablename),
_.map(_.keys(param), function(key){ return util.format('%s = :%s', db.identify(key), key)}).join(' and ')
)
return this.db.exec(sql, param).then(function(res){ return res.affectedRows ? true : false })
}.bind(this))
}
// ---==[ SAVE ]==---
save(data){
if(Array.isArray(data)){
var promises = data.map(function(item){ return this.save(item) }.bind(this))
return Promise.all(promises)
}
return new Promise(function(resolve, reject){
this.initialize()
.then(function(){
// find record id
return _.values(_.pick(data, this.keyfields)).join('-')
}.bind(this))
.then(this.get.bind(this))
.then(function(rec){
var id = _.values(_.pick(data, this.keyfields)).join('-')
return rec ? this.update(id, data) : this.insert(data)
}.bind(this))
.then(resolve)
.catch(reject)
}.bind(this))
}
};
module.exports = DBObject;
| cavitkeskin/CodeTest | lib/DBObject.js | JavaScript | mit | 11,639 |
export { default } from 'ember-ui-kit/components/ui-table'; | ming-codes/ember-ui-kit | app/components/ui-table.js | JavaScript | mit | 59 |
function Timer() {
this.startTime = null
this.endTime = null
this.executionTime = null
}
Timer.prototype = {
end: function()
{
this.endTime = new Date().getTime()
},
getExcutionTime: function()
{
return (this.endTime - this.startTime)/1000
},
getExcutionTimeFormatted: function()
{
return this.getExcutionTime() + " s"
},
isStarted: function()
{
return this.startTime !== null
},
reset: function()
{
this.startTime = null
this.endTime = null
this.executionTime = null
},
start: function()
{
this.startTime = new Date().getTime()
}
}
module.exports = Timer
| g4code/gdeployer | lib/gdeployer/timer.js | JavaScript | mit | 739 |
// require-Spec.js
describe("\'require\'", function(){
var new_module = {
name: "new_module",
exports: {
testApi: "testApi",
foo: (function() {})
},
option: {}
};
beforeEach(function (){
define(new_module.name, function(exports) {
for( api in new_module.exports ) {
exports[api] = new_module.exports[api];
}
});
});
afterEach(function() {
debug.reset();
})
it("should return null if module name does not exist", function() {
var module = require('doesnot_exist_module');
expect(module).toBe(null);
});
describe("should return ", function() {
it("module object", function() {
var required_module = require(new_module.name);
expect(required_module).toBeDefined();
var required_module_again = require(new_module.name);
expect(required_module).toBe(required_module_again);
});
it("correct module api", function() {
var defined_module = require(new_module.name);
for( var api in new_module.exports ) {
expect(defined_module[api]).toBeDefined();
expect(defined_module[api]).toBe(new_module.exports[api]);
}
});
});
}); | rihdus/modCraft | spec/3-require-Spec.js | JavaScript | mit | 1,124 |
'use strict';
describe('Chart.helpers.core', function() {
var helpers = Chart.helpers;
describe('noop', function() {
it('should be callable', function() {
expect(helpers.noop).toBeDefined();
expect(typeof helpers.noop).toBe('function');
expect(typeof helpers.noop.call).toBe('function');
});
it('should returns "undefined"', function() {
expect(helpers.noop(42)).not.toBeDefined();
expect(helpers.noop.call(this, 42)).not.toBeDefined();
});
});
describe('isArray', function() {
it('should return true if value is an array', function() {
expect(helpers.isArray([])).toBeTruthy();
expect(helpers.isArray([42])).toBeTruthy();
expect(helpers.isArray(new Array())).toBeTruthy();
expect(helpers.isArray(Array.prototype)).toBeTruthy();
expect(helpers.isArray(new Int8Array(2))).toBeTruthy();
expect(helpers.isArray(new Uint8Array())).toBeTruthy();
expect(helpers.isArray(new Uint8ClampedArray([128, 244]))).toBeTruthy();
expect(helpers.isArray(new Int16Array())).toBeTruthy();
expect(helpers.isArray(new Uint16Array())).toBeTruthy();
expect(helpers.isArray(new Int32Array())).toBeTruthy();
expect(helpers.isArray(new Uint32Array())).toBeTruthy();
expect(helpers.isArray(new Float32Array([1.2]))).toBeTruthy();
expect(helpers.isArray(new Float64Array([]))).toBeTruthy();
});
it('should return false if value is not an array', function() {
expect(helpers.isArray()).toBeFalsy();
expect(helpers.isArray({})).toBeFalsy();
expect(helpers.isArray(undefined)).toBeFalsy();
expect(helpers.isArray(null)).toBeFalsy();
expect(helpers.isArray(true)).toBeFalsy();
expect(helpers.isArray(false)).toBeFalsy();
expect(helpers.isArray(42)).toBeFalsy();
expect(helpers.isArray('Array')).toBeFalsy();
expect(helpers.isArray({__proto__: Array.prototype})).toBeFalsy();
});
});
describe('isObject', function() {
it('should return true if value is an object', function() {
expect(helpers.isObject({})).toBeTruthy();
expect(helpers.isObject({a: 42})).toBeTruthy();
expect(helpers.isObject(new Object())).toBeTruthy();
});
it('should return false if value is not an object', function() {
expect(helpers.isObject()).toBeFalsy();
expect(helpers.isObject(undefined)).toBeFalsy();
expect(helpers.isObject(null)).toBeFalsy();
expect(helpers.isObject(true)).toBeFalsy();
expect(helpers.isObject(false)).toBeFalsy();
expect(helpers.isObject(42)).toBeFalsy();
expect(helpers.isObject('Object')).toBeFalsy();
expect(helpers.isObject([])).toBeFalsy();
expect(helpers.isObject([42])).toBeFalsy();
expect(helpers.isObject(new Array())).toBeFalsy();
expect(helpers.isObject(new Date())).toBeFalsy();
});
});
describe('isFinite', function() {
it('should return true if value is a finite number', function() {
expect(helpers.isFinite(0)).toBeTruthy();
// eslint-disable-next-line no-new-wrappers
expect(helpers.isFinite(new Number(10))).toBeTruthy();
});
it('should return false if the value is infinite', function() {
expect(helpers.isFinite(Number.POSITIVE_INFINITY)).toBeFalsy();
expect(helpers.isFinite(Number.NEGATIVE_INFINITY)).toBeFalsy();
});
it('should return false if the value is not a number', function() {
expect(helpers.isFinite('a')).toBeFalsy();
expect(helpers.isFinite({})).toBeFalsy();
});
});
describe('isNullOrUndef', function() {
it('should return true if value is null/undefined', function() {
expect(helpers.isNullOrUndef(null)).toBeTruthy();
expect(helpers.isNullOrUndef(undefined)).toBeTruthy();
});
it('should return false if value is not null/undefined', function() {
expect(helpers.isNullOrUndef(true)).toBeFalsy();
expect(helpers.isNullOrUndef(false)).toBeFalsy();
expect(helpers.isNullOrUndef('')).toBeFalsy();
expect(helpers.isNullOrUndef('String')).toBeFalsy();
expect(helpers.isNullOrUndef(0)).toBeFalsy();
expect(helpers.isNullOrUndef([])).toBeFalsy();
expect(helpers.isNullOrUndef({})).toBeFalsy();
expect(helpers.isNullOrUndef([42])).toBeFalsy();
expect(helpers.isNullOrUndef(new Date())).toBeFalsy();
});
});
describe('valueOrDefault', function() {
it('should return value if defined', function() {
var object = {};
var array = [];
expect(helpers.valueOrDefault(null, 42)).toBe(null);
expect(helpers.valueOrDefault(false, 42)).toBe(false);
expect(helpers.valueOrDefault(object, 42)).toBe(object);
expect(helpers.valueOrDefault(array, 42)).toBe(array);
expect(helpers.valueOrDefault('', 42)).toBe('');
expect(helpers.valueOrDefault(0, 42)).toBe(0);
});
it('should return default if undefined', function() {
expect(helpers.valueOrDefault(undefined, 42)).toBe(42);
expect(helpers.valueOrDefault({}.foo, 42)).toBe(42);
});
});
describe('callback', function() {
it('should return undefined if fn is not a function', function() {
expect(helpers.callback()).not.toBeDefined();
expect(helpers.callback(null)).not.toBeDefined();
expect(helpers.callback(42)).not.toBeDefined();
expect(helpers.callback([])).not.toBeDefined();
expect(helpers.callback({})).not.toBeDefined();
});
it('should call fn with the given args', function() {
var spy = jasmine.createSpy('spy');
helpers.callback(spy);
helpers.callback(spy, []);
helpers.callback(spy, ['foo']);
helpers.callback(spy, [42, 'bar']);
expect(spy.calls.argsFor(0)).toEqual([]);
expect(spy.calls.argsFor(1)).toEqual([]);
expect(spy.calls.argsFor(2)).toEqual(['foo']);
expect(spy.calls.argsFor(3)).toEqual([42, 'bar']);
});
it('should call fn with the given scope', function() {
var spy = jasmine.createSpy('spy');
var scope = {};
helpers.callback(spy);
helpers.callback(spy, [], null);
helpers.callback(spy, [], undefined);
helpers.callback(spy, [], scope);
expect(spy.calls.all()[0].object).toBe(window);
expect(spy.calls.all()[1].object).toBe(window);
expect(spy.calls.all()[2].object).toBe(window);
expect(spy.calls.all()[3].object).toBe(scope);
});
it('should return the value returned by fn', function() {
expect(helpers.callback(helpers.noop, [41])).toBe(undefined);
expect(helpers.callback(function(i) {
return i + 1;
}, [41])).toBe(42);
});
});
describe('each', function() {
it('should iterate over an array forward if reverse === false', function() {
var scope = {};
var scopes = [];
var items = [];
var keys = [];
helpers.each(['foo', 'bar', 42], function(item, key) {
scopes.push(this);
items.push(item);
keys.push(key);
}, scope);
expect(scopes).toEqual([scope, scope, scope]);
expect(items).toEqual(['foo', 'bar', 42]);
expect(keys).toEqual([0, 1, 2]);
});
it('should iterate over an array backward if reverse === true', function() {
var scope = {};
var scopes = [];
var items = [];
var keys = [];
helpers.each(['foo', 'bar', 42], function(item, key) {
scopes.push(this);
items.push(item);
keys.push(key);
}, scope, true);
expect(scopes).toEqual([scope, scope, scope]);
expect(items).toEqual([42, 'bar', 'foo']);
expect(keys).toEqual([2, 1, 0]);
});
it('should iterate over object properties', function() {
var scope = {};
var scopes = [];
var items = [];
helpers.each({a: 'foo', b: 'bar', c: 42}, function(item, key) {
scopes.push(this);
items[key] = item;
}, scope);
expect(scopes).toEqual([scope, scope, scope]);
expect(items).toEqual(jasmine.objectContaining({a: 'foo', b: 'bar', c: 42}));
});
it('should not throw when called with a non iterable object', function() {
expect(function() {
helpers.each(undefined);
}).not.toThrow();
expect(function() {
helpers.each(null);
}).not.toThrow();
expect(function() {
helpers.each(42);
}).not.toThrow();
});
});
describe('_elementsEqual', function() {
it('should return true if arrays are the same', function() {
expect(helpers._elementsEqual(
[{datasetIndex: 0, index: 1}, {datasetIndex: 0, index: 2}],
[{datasetIndex: 0, index: 1}, {datasetIndex: 0, index: 2}])).toBeTruthy();
});
it('should return false if arrays are not the same', function() {
expect(helpers._elementsEqual([], [{datasetIndex: 0, index: 1}])).toBeFalsy();
expect(helpers._elementsEqual([{datasetIndex: 0, index: 2}], [{datasetIndex: 0, index: 1}])).toBeFalsy();
});
});
describe('clone', function() {
it('should clone primitive values', function() {
expect(helpers.clone()).toBe(undefined);
expect(helpers.clone(null)).toBe(null);
expect(helpers.clone(true)).toBe(true);
expect(helpers.clone(42)).toBe(42);
expect(helpers.clone('foo')).toBe('foo');
});
it('should perform a deep copy of arrays', function() {
var o0 = {a: 42};
var o1 = {s: 's'};
var a0 = ['bar'];
var a1 = [a0, o0, 2];
var f0 = function() {};
var input = [a1, o1, f0, 42, 'foo'];
var output = helpers.clone(input);
expect(output).toEqual(input);
expect(output).not.toBe(input);
expect(output[0]).not.toBe(a1);
expect(output[0][0]).not.toBe(a0);
expect(output[1]).not.toBe(o1);
});
it('should perform a deep copy of objects', function() {
var a0 = ['bar'];
var a1 = [1, 2, 3];
var o0 = {a: a1, i: 42};
var f0 = function() {};
var input = {o: o0, a: a0, f: f0, s: 'foo', i: 42};
var output = helpers.clone(input);
expect(output).toEqual(input);
expect(output).not.toBe(input);
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
expect(output.a).not.toBe(a0);
});
});
describe('merge', function() {
it('should not allow prototype pollution', function() {
var test = helpers.merge({}, JSON.parse('{"__proto__":{"polluted": true}}'));
expect(test.prototype).toBeUndefined();
expect(Object.prototype.polluted).toBeUndefined();
});
it('should update target and return it', function() {
var target = {a: 1};
var result = helpers.merge(target, {a: 2, b: 'foo'});
expect(target).toEqual({a: 2, b: 'foo'});
expect(target).toBe(result);
});
it('should return target if not an object', function() {
expect(helpers.merge(undefined, {a: 42})).toEqual(undefined);
expect(helpers.merge(null, {a: 42})).toEqual(null);
expect(helpers.merge('foo', {a: 42})).toEqual('foo');
expect(helpers.merge(['foo', 'bar'], {a: 42})).toEqual(['foo', 'bar']);
});
it('should ignore sources which are not objects', function() {
expect(helpers.merge({a: 42})).toEqual({a: 42});
expect(helpers.merge({a: 42}, null)).toEqual({a: 42});
expect(helpers.merge({a: 42}, 42)).toEqual({a: 42});
});
it('should recursively overwrite target with source properties', function() {
expect(helpers.merge({a: {b: 1}}, {a: {c: 2}})).toEqual({a: {b: 1, c: 2}});
expect(helpers.merge({a: {b: 1}}, {a: {b: 2}})).toEqual({a: {b: 2}});
expect(helpers.merge({a: [1, 2]}, {a: [3, 4]})).toEqual({a: [3, 4]});
expect(helpers.merge({a: 42}, {a: {b: 0}})).toEqual({a: {b: 0}});
expect(helpers.merge({a: 42}, {a: null})).toEqual({a: null});
expect(helpers.merge({a: 42}, {a: undefined})).toEqual({a: undefined});
});
it('should merge multiple sources in the correct order', function() {
var t0 = {a: {b: 1, c: [1, 2]}};
var s0 = {a: {d: 3}, e: {f: 4}};
var s1 = {a: {b: 5}};
var s2 = {a: {c: [6, 7]}, e: 'foo'};
expect(helpers.merge(t0, [s0, s1, s2])).toEqual({a: {b: 5, c: [6, 7], d: 3}, e: 'foo'});
});
it('should deep copy merged values from sources', function() {
var a0 = ['foo'];
var a1 = [1, 2, 3];
var o0 = {a: a1, i: 42};
var output = helpers.merge({}, {a: a0, o: o0});
expect(output).toEqual({a: a0, o: o0});
expect(output.a).not.toBe(a0);
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
});
});
describe('mergeIf', function() {
it('should not allow prototype pollution', function() {
var test = helpers.mergeIf({}, JSON.parse('{"__proto__":{"polluted": true}}'));
expect(test.prototype).toBeUndefined();
expect(Object.prototype.polluted).toBeUndefined();
});
it('should update target and return it', function() {
var target = {a: 1};
var result = helpers.mergeIf(target, {a: 2, b: 'foo'});
expect(target).toEqual({a: 1, b: 'foo'});
expect(target).toBe(result);
});
it('should return target if not an object', function() {
expect(helpers.mergeIf(undefined, {a: 42})).toEqual(undefined);
expect(helpers.mergeIf(null, {a: 42})).toEqual(null);
expect(helpers.mergeIf('foo', {a: 42})).toEqual('foo');
expect(helpers.mergeIf(['foo', 'bar'], {a: 42})).toEqual(['foo', 'bar']);
});
it('should ignore sources which are not objects', function() {
expect(helpers.mergeIf({a: 42})).toEqual({a: 42});
expect(helpers.mergeIf({a: 42}, null)).toEqual({a: 42});
expect(helpers.mergeIf({a: 42}, 42)).toEqual({a: 42});
});
it('should recursively copy source properties in target only if they do not exist in target', function() {
expect(helpers.mergeIf({a: {b: 1}}, {a: {c: 2}})).toEqual({a: {b: 1, c: 2}});
expect(helpers.mergeIf({a: {b: 1}}, {a: {b: 2}})).toEqual({a: {b: 1}});
expect(helpers.mergeIf({a: [1, 2]}, {a: [3, 4]})).toEqual({a: [1, 2]});
expect(helpers.mergeIf({a: 0}, {a: {b: 2}})).toEqual({a: 0});
expect(helpers.mergeIf({a: null}, {a: 42})).toEqual({a: null});
expect(helpers.mergeIf({a: undefined}, {a: 42})).toEqual({a: undefined});
});
it('should merge multiple sources in the correct order', function() {
var t0 = {a: {b: 1, c: [1, 2]}};
var s0 = {a: {d: 3}, e: {f: 4}};
var s1 = {a: {b: 5}};
var s2 = {a: {c: [6, 7]}, e: 'foo'};
expect(helpers.mergeIf(t0, [s0, s1, s2])).toEqual({a: {b: 1, c: [1, 2], d: 3}, e: {f: 4}});
});
it('should deep copy merged values from sources', function() {
var a0 = ['foo'];
var a1 = [1, 2, 3];
var o0 = {a: a1, i: 42};
var output = helpers.mergeIf({}, {a: a0, o: o0});
expect(output).toEqual({a: a0, o: o0});
expect(output.a).not.toBe(a0);
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
});
});
describe('resolveObjectKey', function() {
it('should resolve empty key to root object', function() {
const obj = {test: true};
expect(helpers.resolveObjectKey(obj, '')).toEqual(obj);
});
it('should resolve one level', function() {
const obj = {
bool: true,
str: 'test',
int: 42,
obj: {name: 'object'}
};
expect(helpers.resolveObjectKey(obj, 'bool')).toEqual(true);
expect(helpers.resolveObjectKey(obj, 'str')).toEqual('test');
expect(helpers.resolveObjectKey(obj, 'int')).toEqual(42);
expect(helpers.resolveObjectKey(obj, 'obj')).toEqual(obj.obj);
});
it('should resolve multiple levels', function() {
const obj = {
child: {
level: 1,
child: {
level: 2,
child: {
level: 3
}
}
}
};
expect(helpers.resolveObjectKey(obj, 'child.level')).toEqual(1);
expect(helpers.resolveObjectKey(obj, 'child.child.level')).toEqual(2);
expect(helpers.resolveObjectKey(obj, 'child.child.child.level')).toEqual(3);
});
it('should resolve circular reference', function() {
const root = {};
const child = {root};
child.child = child;
root.child = child;
expect(helpers.resolveObjectKey(root, 'child')).toEqual(child);
expect(helpers.resolveObjectKey(root, 'child.child.child.child.child.child')).toEqual(child);
expect(helpers.resolveObjectKey(root, 'child.child.root')).toEqual(root);
});
it('should break at empty key', function() {
const obj = {
child: {
level: 1,
child: {
level: 2,
child: {
level: 3
}
}
}
};
expect(helpers.resolveObjectKey(obj, 'child..level')).toEqual(obj.child);
expect(helpers.resolveObjectKey(obj, 'child.child.level...')).toEqual(2);
expect(helpers.resolveObjectKey(obj, '.')).toEqual(obj);
expect(helpers.resolveObjectKey(obj, '..')).toEqual(obj);
});
it('should resolve undefined', function() {
const obj = {
child: {
level: 1,
child: {
level: 2,
child: {
level: 3
}
}
}
};
expect(helpers.resolveObjectKey(obj, 'level')).toEqual(undefined);
expect(helpers.resolveObjectKey(obj, 'child.level.a')).toEqual(undefined);
});
it('should throw on invalid input', function() {
expect(() => helpers.resolveObjectKey(undefined, undefined)).toThrow();
expect(() => helpers.resolveObjectKey({}, null)).toThrow();
expect(() => helpers.resolveObjectKey({}, false)).toThrow();
expect(() => helpers.resolveObjectKey({}, true)).toThrow();
expect(() => helpers.resolveObjectKey({}, 1)).toThrow();
});
});
});
| nnnick/Chart.js | test/specs/helpers.core.tests.js | JavaScript | mit | 17,897 |
define(function(require) {
var string = require('base/string');
describe('string', function() {
describe('trim(str)', function (){
it('should trim leading or trailing whitespace', function () {
expect(string.trim(' foo bar ')).toBe('foo bar');
expect(string.trim('\n\n\nfoo bar\n\r\n\n')).toBe('foo bar');
});
});
describe('trimLeft(str)', function () {
it('should trim leading whitespace', function() {
expect(string.trimLeft(' foo bar ')).toBe('foo bar ');
});
});
describe('trimRight(str)', function () {
it('should trim trailing whitespace', function() {
expect(string.trimRight(' foo bar ')).toBe(' foo bar');
});
});
});
}); | bizdevfe/dragonfly | test/spec/base/string.js | JavaScript | mit | 838 |
/**
*
* @param options
* @returns {*}
*/
jDoc.engines.RTF.prototype._controlWordsParsers.rin = function (options) {
var parseParams = options.parseParams,
parseResult = options.parseResult,
propertyName,
param = options.param;
if (parseParams.currentTextElementParent) {
if (parseParams.currentTextElementParent.css.direction === "rtl") {
propertyName = "paddingLeft";
} else {
propertyName = "paddingRight";
}
parseParams.currentTextElementParent.dimensionCSSRules[propertyName] = {
value: param / 20,
units: "pt"
};
}
return {
parseParams: parseParams,
parseResult: parseResult
};
}; | bardt/jDoc | src/engines/RTF/reader/private/_controlWordsParsers/format/rin.js | JavaScript | mit | 740 |
describe('serverValidationManager tests', function () {
var serverValidationManager;
beforeEach(module('umbraco.services'));
beforeEach(inject(function ($injector) {
serverValidationManager = $injector.get('serverValidationManager');
}));
describe('managing field validation errors', function () {
it('can add and retrieve field validation errors', function () {
//arrange
serverValidationManager.addFieldError("Name", "Required");
//act
var err = serverValidationManager.getFieldError("Name");
//assert
expect(err).not.toBeUndefined();
expect(err.propertyAlias).toBeNull();
expect(err.fieldName).toEqual("Name");
expect(err.errorMsg).toEqual("Required");
});
it('will return null for a non-existing field error', function () {
//arrange
serverValidationManager.addFieldError("Name", "Required");
//act
var err = serverValidationManager.getFieldError("DoesntExist");
//assert
expect(err).toBeUndefined();
});
it('detects if a field error exists', function () {
//arrange
serverValidationManager.addFieldError("Name", "Required");
//act
var err1 = serverValidationManager.hasFieldError("Name");
var err2 = serverValidationManager.hasFieldError("DoesntExist");
//assert
expect(err1).toBe(true);
expect(err2).toBe(false);
});
});
describe('managing property validation errors', function () {
it('can retrieve property validation errors for a sub field', function () {
//arrange
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
serverValidationManager.addPropertyError("myProperty", null, "value2", "Another value 2");
//act
var err1 = serverValidationManager.getPropertyError("myProperty", null, "value1");
var err2 = serverValidationManager.getPropertyError("myProperty", null, "value2");
//assert
expect(err1).not.toBeUndefined();
expect(err1.propertyAlias).toEqual("myProperty");
expect(err1.fieldName).toEqual("value1");
expect(err1.errorMsg).toEqual("Some value 1");
expect(err2).not.toBeUndefined();
expect(err2.propertyAlias).toEqual("myProperty");
expect(err2.fieldName).toEqual("value2");
expect(err2.errorMsg).toEqual("Another value 2");
});
it('can add a property errors with multiple sub fields and it the first will be retreived with only the property alias', function () {
//arrange
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
serverValidationManager.addPropertyError("myProperty", null, "value2", "Another value 2");
//act
var err = serverValidationManager.getPropertyError("myProperty");
//assert
expect(err).not.toBeUndefined();
expect(err.propertyAlias).toEqual("myProperty");
expect(err.fieldName).toEqual("value1");
expect(err.errorMsg).toEqual("Some value 1");
});
it('will return null for a non-existing property error', function () {
//arrage
serverValidationManager.addPropertyError("myProperty", null, "value", "Required");
//act
var err = serverValidationManager.getPropertyError("DoesntExist", null, "value");
//assert
expect(err).toBeUndefined();
});
it('detects if a property error exists', function () {
//arrange
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
serverValidationManager.addPropertyError("myProperty", null, "value2", "Another value 2");
//act
var err1 = serverValidationManager.hasPropertyError("myProperty");
var err2 = serverValidationManager.hasPropertyError("myProperty", null, "value1");
var err3 = serverValidationManager.hasPropertyError("myProperty", null, "value2");
var err4 = serverValidationManager.hasPropertyError("notFound");
var err5 = serverValidationManager.hasPropertyError("myProperty", null, "notFound");
//assert
expect(err1).toBe(true);
expect(err2).toBe(true);
expect(err3).toBe(true);
expect(err4).toBe(false);
expect(err5).toBe(false);
});
it('can remove a property error with a sub field specified', function () {
//arrage
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
serverValidationManager.addPropertyError("myProperty", null, "value2", "Another value 2");
//act
serverValidationManager.removePropertyError("myProperty", null, "value1");
//assert
expect(serverValidationManager.hasPropertyError("myProperty", null, "value1")).toBe(false);
expect(serverValidationManager.hasPropertyError("myProperty", null, "value2")).toBe(true);
});
it('can remove a property error and all sub field errors by specifying only the property', function () {
//arrage
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
serverValidationManager.addPropertyError("myProperty", null, "value2", "Another value 2");
//act
serverValidationManager.removePropertyError("myProperty");
//assert
expect(serverValidationManager.hasPropertyError("myProperty", null, "value1")).toBe(false);
expect(serverValidationManager.hasPropertyError("myProperty", null, "value2")).toBe(false);
});
});
describe('validation error subscriptions', function() {
it('can subscribe to a field error', function() {
var args;
//arrange
serverValidationManager.subscribe(null, null, "Name", function (isValid, propertyErrors, allErrors) {
args = {
isValid: isValid,
propertyErrors: propertyErrors,
allErrors: allErrors
};
});
//act
serverValidationManager.addFieldError("Name", "Required");
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
//assert
expect(args).not.toBeUndefined();
expect(args.isValid).toBe(false);
expect(args.propertyErrors.length).toEqual(1);
expect(args.propertyErrors[0].errorMsg).toEqual("Required");
expect(args.allErrors.length).toEqual(2);
});
it('can get the field subscription callbacks', function () {
//arrange
var cb1 = function() {
};
var cb2 = function () {
};
serverValidationManager.subscribe(null, null, "Name", cb1);
serverValidationManager.subscribe(null, null, "Title", cb2);
//act
serverValidationManager.addFieldError("Name", "Required");
serverValidationManager.addFieldError("Title", "Invalid");
//assert
var nameCb = serverValidationManager.getFieldCallbacks("Name");
expect(nameCb).not.toBeUndefined();
expect(nameCb.length).toEqual(1);
expect(nameCb[0].propertyAlias).toBeNull();
expect(nameCb[0].fieldName).toEqual("Name");
expect(nameCb[0].callback).toEqual(cb1);
var titleCb = serverValidationManager.getFieldCallbacks("Title");
expect(titleCb).not.toBeUndefined();
expect(titleCb.length).toEqual(1);
expect(titleCb[0].propertyAlias).toBeNull();
expect(titleCb[0].fieldName).toEqual("Title");
expect(titleCb[0].callback).toEqual(cb2);
});
it('can subscribe to a property error for both a property and its sub field', function () {
var args1;
var args2;
var numCalled = 0;
//arrange
serverValidationManager.subscribe("myProperty", null, "value1", function (isValid, propertyErrors, allErrors) {
args1 = {
isValid: isValid,
propertyErrors: propertyErrors,
allErrors: allErrors
};
});
serverValidationManager.subscribe("myProperty", null, "", function (isValid, propertyErrors, allErrors) {
numCalled++;
args2 = {
isValid: isValid,
propertyErrors: propertyErrors,
allErrors: allErrors
};
});
//act
serverValidationManager.addPropertyError("myProperty", null, "value1", "Some value 1");
serverValidationManager.addPropertyError("myProperty", null, "value2", "Some value 2");
serverValidationManager.addPropertyError("myProperty", null, "", "Some value 3");
//assert
expect(args1).not.toBeUndefined();
expect(args1.isValid).toBe(false);
//this is only one because this subscription is targetting only a sub field
expect(args1.propertyErrors.length).toEqual(1);
expect(args1.propertyErrors[0].errorMsg).toEqual("Some value 1");
//NOTE: though you might think this should be 3, it's actually correct at 2 since the last error that doesn't have a sub field
// specified doesn't actually get added because it already detects that a property error exists for the alias.
expect(args1.allErrors.length).toEqual(2);
expect(args2).not.toBeUndefined();
expect(args2.isValid).toBe(false);
//This is 2 because we are looking for all property errors including sub fields
expect(args2.propertyErrors.length).toEqual(2);
expect(args2.propertyErrors[0].errorMsg).toEqual("Some value 1");
expect(args2.propertyErrors[1].errorMsg).toEqual("Some value 2");
expect(args2.allErrors.length).toEqual(2);
//Even though only 2 errors are added, the callback is called 3 times because any call to addPropertyError will invoke the callback
// if the property has errors existing.
expect(numCalled).toEqual(3);
});
//TODO: Finish testing the rest!
});
});
| lars-erik/Umbraco-CMS | src/Umbraco.Web.UI.Client/test/unit/common/services/server-validation-manager.spec.js | JavaScript | mit | 11,076 |
import {SubmissionError} from 'redux-form'
import axios from 'axios'
import alert, {confirmation} from '../../../../components/utils/alerts'
import {smallBox, bigBox, SmartMessageBox} from "../../../../components/utils/actions/MessageActions";
import Msg from '../../../../components/i18n/Msg'
import {isYesClicked, isNoClicked, instanceAxios} from '../../../../components/utils/functions'
import LanguageStore from '../../../../components/i18n/LanguageStore'
import Loader, {Visibility as LoaderVisibility} from '../../../../components/Loader/Loader';
//http://thecodebarbarian.com/unhandled-promise-rejections-in-node.js.html
function submit(values){
//console.log(values);
return instanceAxios.get('/api/teachers/' + values.teacherId + '/' + values.email + '/')
.then(res=>{
//throw {email: 'That email is already taken'}
if(res.data.Email===''){
if(values.teacherId>0){
update(values);
}
else{
insert(values);
}
}
else{
throw new SubmissionError({
email: 'email is already taken',
_error: 'You cannot proceed further!'
})
}
})
}
function insert(values){
LoaderVisibility(true);
console.log(values);
instanceAxios.post('/api/teachers', values)
.then(function (response) {
LoaderVisibility(false);
alert('s', 'Teacher details have been saved.');
$('#teacherPopup').modal('hide');
})
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
//console.log(error.response.data);
//console.log(error.response.status);
//console.log(error.response.headers);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
//throw new SubmissionError({ _error: "That's weird. "});
//reject('error error error');
return Promise.resolve(true).then(() => {
throw new SubmissionError({ email: 'User does not exist', _error: 'Login failed!' });
});
// return new SubmissionError({
// email: 'email is already taken',
// _error: 'You cannot proceed further!'
// });
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
//console.log(error.config);
//alert('f', '');
LoaderVisibility(false);
});
}
function update(values){
//console.log('in update');
//console.log(values);
LoaderVisibility(true);
instanceAxios.put('/api/teachers', values)
.then(function (response) {
alert('s','Teacher details have been updated.');
$('#teacherPopup').modal('hide');
LoaderVisibility(false);
})
.catch(function (error) {
console.log(error);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
});
}
export function remove(id, delCell){
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function(ButtonPressed){
deleteRecord(ButtonPressed, id, delCell);
});
}
function deleteRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
LoaderVisibility(true);
console.log('teacher dele conf yes by func');
// console.log(id);
$.ajax({
url : '/api/RemoveTeacher/' + id,
type: "POST",
//data : formData,
success: function(data, textStatus, jqXHR)
{
console.log('success...');
alert('s','Teacher details have been deleted.');
var table = $('#teachersGrid').DataTable();
table
.row( delCell.parents('tr') )
.remove()
.draw();
LoaderVisibility(false);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('error = ', jqXHR, textStatus, errorThrown);
alert('f','');
LoaderVisibility(false);
}
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
export function submitQualification(values, teacherId){
values = Object.assign({}, values, {teacherId});
LoaderVisibility(true);
instanceAxios.post('/api/TeacherQualifications', values)
.then(function (response) {
alert('s', 'Qualification details have been saved.');
$('#teacherQualificationsGrid').DataTable().ajax.reload();
$('#tabList').trigger('click');
LoaderVisibility(false);
})
.catch(function (error) {
console.log(error);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
throw new SubmissionError({
_error: 'Something went wrong, please contact system administrator!'
});
});
}
export function submitExperience(values, teacherId){
values = Object.assign({}, values, {teacherId});
LoaderVisibility(true);
instanceAxios.post('/api/TeacherExperiences', values)
.then(function (response) {
alert('s', 'Experience details have been saved.');
$('#teacherExperiencesGrid').DataTable().ajax.reload();
$('#tabListExp').trigger('click');
LoaderVisibility(false);
})
.catch(function (error) {
console.log(error);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
throw new SubmissionError({
_error: 'Something went wrong, please contact system administrator!'
});
});
}
export function submitTeacherSubject(values1, teacherId){
let values = Object.assign({}, {teacherId}, {subjectId: values1.subjectId.join()});
LoaderVisibility(true);
console.log('teacher class submit ', values);
//instanceAxios.post('/api/TeachersSubjects', values)
instanceAxios.post('/api/TeachersSubjects/'+teacherId+'/'+values.subjectId)
.then(function (response) {
alert('s', 'data has been saved successfully');
$('#teacherSubjectsGrid').DataTable().ajax.reload();
$('#tabListSubject').trigger('click');
LoaderVisibility(false);
})
.catch(function (error) {
console.log(error);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
// return Promise.resolve(true).then(() => {
// throw new SubmissionError({ subjectId: 'error error error', _error: 'Something went wrong, please contact system administrator!' });
// });
new Promise((_, reject) => reject(new Error('woops'))).
// Prints "caught woops"
then(null, error => { console.log('caught', error.message); });
});
}
export function submitTeacherClass(values1, teacherId){
let values = Object.assign({}, {teacherId}, {classId: values1.classId.join()});
LoaderVisibility(true);
//console.log('teacher class submit ', values);
instanceAxios.post('/api/TeachersClasses/'+teacherId+'/'+values.classId)
.then(function (response) {
alert('s', 'data has been saved successfully');
$('#TeacherClassesGrid').DataTable().ajax.reload();
$('#tabListClass').trigger('click');
LoaderVisibility(false);
})
.catch(function (error) {
console.log(error);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
throw new SubmissionError({
_error: 'Something went wrong, please contact system administrator!'
});
});
}
export function removeQualification(id, delCell){
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function(ButtonPressed){
deleteQualificationRecord(ButtonPressed, id, delCell);
});
}
function deleteQualificationRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
LoaderVisibility(true);
console.log('del quali yes');
console.log(Date());
//axios.delete('/api/TeacherQualifications/' + id)
instanceAxios.post('/api/RemoveTeacherQualification/' + id)
.then(function (response) {
alert('s','Qualification details have been deleted.');
var table = $('#teacherQualificationsGrid').DataTable();
table
.row( delCell.parents('tr') )
.remove()
.draw();
//console.log('after row del ..')
console.log(Date());
LoaderVisibility(false);
})
.catch(function (error) {
alert('f','');
LoaderVisibility(false);
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
export function removeExperience(id, delCell){
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function(ButtonPressed){
deleteExperienceRecord(ButtonPressed, id, delCell);
});
}
function deleteExperienceRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
console.log('del expe yes');
console.log(Date());
LoaderVisibility(true);
//axios.delete('/api/TeacherExperiences/' + id)
instanceAxios.post('/api/RemoveTeacherExperience/' + id)
.then(function (response) {
alert('s','Experience details have been deleted.');
var table = $('#teacherExperiencesGrid').DataTable();
table
.row( delCell.parents('tr') )
.remove()
.draw();
console.log(Date());
LoaderVisibility(false);
})
.catch(function (error) {
alert('f','');
LoaderVisibility(false);
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
export function removeTeacherSubject(id, delCell){
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function(ButtonPressed){
deleteTeacherSubjectRecord(ButtonPressed, id, delCell);
});
}
function deleteTeacherSubjectRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
LoaderVisibility(true);
console.log('RemoveTeacherSubject ', id);
instanceAxios.post('/api/RemoveTeacherSubject/' + id)
.then(function (response) {
alert('s','data has been deleted successfully');
var table = $('#teacherSubjectsGrid').DataTable();
table
.row( delCell.parents('tr') )
.remove()
.draw();
LoaderVisibility(false);
})
.catch(function (error) {
alert('f','');
console.log(error);
LoaderVisibility(false);
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
export function removeTeacherClass(id, delCell){
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function(ButtonPressed){
deleteTeacherClassRecord(ButtonPressed, id, delCell);
});
}
function deleteTeacherClassRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
LoaderVisibility(true);
instanceAxios.post('/api/RemoveTeacherClass/' + id)
.then(function (response) {
alert('s','data has been deleted successfully');
var table = $('#TeacherClassesGrid').DataTable();
table
.row( delCell.parents('tr') )
.remove()
.draw();
console.log(Date());
LoaderVisibility(false);
})
.catch(function (error) {
alert('f','');
LoaderVisibility(false);
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
export default submit | zraees/sms-project | client/src/app/routes/settings/containers/Teachers/submit.js | JavaScript | mit | 13,765 |
//http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl
import {
shader,
parseParamNumber,
toFloatString
} from '../util'
/*
* @param {Number} amount 0..1 , (real value 0..360)
*/
export default function hue (amount = 1) {
const C = toFloatString( parseParamNumber(amount))
return shader(`
vec3 hsv = rgb2hsv(pixelColor.rgb);
hsv.x += ${C};
outColor = vec4(hsv2rgb(hsv).rgb, pixelColor.a);
`);
} | easylogic/codemirror-colorpicker | src/util/gl/filter/pixel/hue.js | JavaScript | mit | 456 |
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.WebRTC = f()}})(function(){var define,module,exports;return (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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.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){
// Require packages.
var util = require('util');
var webrtcSupport = require('webrtcsupport');
var PeerConnection = require('rtcpeerconnection');
var WildEmitter = require('wildemitter');
var FileTransfer = require('filetransfer');
/**
* Contact peer prototype.
*
* Contact peer container, this holds information to one contact peer.
*
* @param {Object} contactPeerOptions A collection of options.
*
* @example
* options = {
* signalling: Signalling,
* uniqueID: "uniqueID",
* applicationID: "applicationID",
* isData: false,
* receiveOfferMedia: {
* offerToReceiveAudio: 1,
* offerToReceiveVideo: 1
* }
* }
*/
function ContactPeer(contactPeerOptions) {
// local.
var self = this;
// Call emitter constructor.
WildEmitter.call(this);
this.closed = false;
var myParent = contactPeerOptions.parent;
this.parent = myParent;
// The signalling transport provider.
var mySignalling = contactPeerOptions.signalling;
this.signalling = mySignalling;
// Assign this contact details.
this.uniqueID = contactPeerOptions.uniqueID;
this.applicationID = contactPeerOptions.applicationID;
this.contactDetails = '';
// Get the parent logger.
this.logger = myParent.logger;
// Store all channels.
var receiveDataChannel = null;
var sendDataChannel = null;
var receiveBuffer = [];
var receivedSize = 0;
var sentSize = 0;
this.isData = contactPeerOptions.isData;
this.fileName = "";
this.fileSize = 0;
this.fileType = "";
this.fileLastModified = 0;
this.fileToSend = null;
this.receiveMedia = contactPeerOptions.receiveOfferMedia || myParent.config.receiveOfferMedia;
this.remoteStream = null;
this.remoteStreamVideoElement = null;
// MediaRecorder
this.mediaRecorder = null;
try {
// Create a new peer connection to the STUN and TURN servers
// with the ICE configuration.
var myPeerConnection = new RTCPeerConnection(
myParent.config.peerConnectionConfiguration);
//var myPeerConnection = new PeerConnection(
// myParent.config.peerConnectionConfiguration, myParent.config.peerConnectionConstraints);
// Assign to local.
this.peerConnection = myPeerConnection;
}
catch (e) {
// Log the error.
this.logger.error("Error connecting to RTCPeerConnection: " + e);
}
// If created.
if (this.peerConnection) {
// Send any ice candidates to the other peers.
this.peerConnection.onicecandidate = function (evt) {
var config = {
data: evt,
signalling: mySignalling
};
// Send ICE candiate.
self.onIceCandidateHandler(config);
};
// ICE connection state change.
this.peerConnection.oniceconnectionstatechange = function (evt) {
myParent.emit('peerContactEventICEStateChange', "Peer ICE connection state changed.", self, evt);
};
// When a stream has been removed.
this.peerConnection.onremovestream = function (evt) {
myParent.emit('peerContactEventRemoveStream', "Peer connection stream removed.", self, evt);
};
/*
try {
// Browsers other than FireFox may have a problem
// with this event.
// Once remote stream arrives, show it in the remote video element.
// onremovestream is deprecated.
this.peerConnection.removeTrack = function (evt) {
myParent.emit('peerContactEventRemoveStream', "Peer connection stream removed.", self, evt);
};
}
catch (e) { }
*/
// Once remote stream arrives, show it in the remote video element.
// onaddstream is deprecated.
this.peerConnection.onaddstream = function (evt) {
self.remoteStream = evt.stream;
myParent.emit('peerContactEventAddStream', "Peer connection stream added.", self, evt);
};
/*
try {
// Browsers other than FireFox may have a problem
// with this event.
// Once remote stream arrives, show it in the remote video element.
// onaddstream is deprecated.
this.peerConnection.ontrack = function (evt) {
self.remoteStream = evt.stream;
myParent.emit('peerContactEventAddTrack', "Peer connection stream added.", self, evt);
};
}
catch (e) { }
*/
// Data channel handler.
this.peerConnection.ondatachannel = function (evt) {
// Clear the buffer.
receiveBuffer = [];
receivedSize = 0;
// Assign the receive channel.
receiveDataChannel = evt.channel;
receiveDataChannel.binaryType = "arraybuffer";
// On data channel receive message callback.
receiveDataChannel.onmessage = function (event) {
receiveBuffer.push(event.data);
receivedSize += event.data.byteLength;
myParent.emit('peerContactEventDataChannelReceivedSize', "Peer connection data channel received size.", self, receivedSize);
// We are assuming that our signaling protocol told
// about the expected file size (and name, hash, etc).
if (receivedSize >= self.fileSize) {
myParent.emit('peerContactEventDataChannelReceiveComplete', "Peer connection data channel received complete.", self, receiveBuffer);
receiveBuffer = [];
receiveDataChannel.close();
receiveDataChannel = null;
}
};
// Data channel open.
receiveDataChannel.onopen = function() {
// If data channel is active.
if (receiveDataChannel) {
// Receive channel state.
var readyState = receiveDataChannel.readyState;
myParent.emit('peerContactEventDataChannelOpen', "Peer connection data channel open.", self, readyState);
}
};
// Data channel close.
receiveDataChannel.onclose = function() {
// If data channel is active.
if (receiveDataChannel) {
// Receive channel state.
var readyState = receiveDataChannel.readyState;
myParent.emit('peerContactEventDataChannelClose', "Peer connection data channel close.", self, readyState);
}
};
// Data channel error.
receiveDataChannel.onerror = function (error) {
myParent.emit('peerContactEventDataChannelError', "Peer connection data channel error.", self, error);
};
};
try {
// Create a data channel from the peer connection.
this.sendDataChannel = this.peerConnection.createDataChannel("sendReceiveDataChannel_" + this.uniqueID + "_" + this.applicationID);
this.sendDataChannel.binaryType = "arraybuffer";
// On open
this.sendDataChannel.onopen = function () {
// Get the file.
var file = self.fileToSend;
// If file is size zero.
if (!file || file.size === 0) {
return;
}
// Set send size.
sentSize = 0;
// If data channel is active.
if (self.sendDataChannel) {
// Send channel state.
var readyState = self.sendDataChannel.readyState;
myParent.emit('peerContactEventDataChannelOpen', "Peer connection data channel open.", self, readyState);
// Sent the file data in chunks
var chunkSize = 8096;
var sliceFile = function(offset) {
// Create a file reader.
var reader = new window.FileReader();
// When the file is opened.
reader.onload = (function() {
return function(e) {
// Send the file through the data channel.
self.sendDataChannel.send(e.target.result);
// Create timeout.
if (file.size > offset + e.target.result.byteLength) {
window.setTimeout(sliceFile, 0, offset + chunkSize);
}
// Set the current sent size.
sentSize = offset + e.target.result.byteLength;
myParent.emit('peerContactEventDataChannelSentSize', "Peer connection data channel sent size.", self, sentSize);
// If all the data has been sent.
if (sentSize >= file.size) {
// Close the data channel.
myParent.emit('peerContactEventDataChannelSentComplete', "Peer connection data channel sent complete.", self, null);
}
};
})(file);
// Read the file array into the buffer.
var slice = file.slice(offset, offset + chunkSize);
reader.readAsArrayBuffer(slice);
};
// Sent the file with no offset.
sliceFile(0);
}
};
// On close
this.sendDataChannel.onclose = function () {
// If data channel is active.
if (self.sendDataChannel) {
// Sen channel state.
var readyState = self.sendDataChannel.readyState;
myParent.emit('peerContactEventDataChannelClose', "Peer connection data channel close.", self, readyState);
}
};
// On error
this.sendDataChannel.onerror = function (error) {
myParent.emit('peerContactEventDataChannelError', "Peer connection data channel error.", self, error);
};
// On message.
this.sendDataChannel.onmessage = function (event) { };
}
catch (e)
{
// Edge does not support
// createDataChannel on the
// RTCPeerConnection object.
// Log the error.
this.logger.error("Error creating data channel on RTCPeerConnection: " + e);
}
}
}
/**
* Send a message to this contact.
*
* @param {string} message The message to send to the contact.
*/
ContactPeer.prototype.sendMessage = function (message) {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
// Send the message through the signalling provider.
this.signalling.sendMessage(contactUniqueID, contactApplicationID, message);
};
/**
* Send the state to this contact.
*
* @param {string} state The state to send to the contact.
*/
ContactPeer.prototype.sendState = function (state) {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
// Send the state through the signalling provider.
this.signalling.sendClientState(contactUniqueID, contactApplicationID, state);
};
/**
* Send the details to this contact.
*
* @param {string} details The details to send to the contact.
*/
ContactPeer.prototype.sendDetails = function (details) {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
// Send the details through the signalling provider.
this.signalling.sendClientDetails(contactUniqueID, contactApplicationID, details);
};
/**
* Send do not want to answer to this contact.
*/
ContactPeer.prototype.noAnswer = function () {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
// Send the message through the signalling provider.
this.signalling.noAnswer(contactUniqueID, contactApplicationID);
};
/**
* Send a request asking if this contact is available.
*/
ContactPeer.prototype.isAvailable = function () {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
// Send the message through the signalling provider.
this.signalling.contactAvailable(contactUniqueID, contactApplicationID)
};
/**
* Send end call to this contact.
*/
ContactPeer.prototype.sendEndCall = function () {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
// Send the message through the signalling provider.
this.signalling.sendEndCallToContact(contactUniqueID, contactApplicationID)
};
/**
* Set the contact information.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
*/
ContactPeer.prototype.setContactInfo = function (uniqueID, applicationID) {
this.uniqueID = uniqueID;
this.applicationID= applicationID;
};
/**
* Get the contact unique id.
*
* @return {string} Returns the contact unique id.
*/
ContactPeer.prototype.getUniqueID = function () {
// Get this contact details.
var contactUniqueID = this.uniqueID;
return contactUniqueID;
};
/**
* Get the contact application id.
*
* @return {string} Returns the contact application id.
*/
ContactPeer.prototype.getApplicationID = function () {
// Get this contact details.
var contactApplicationID = this.applicationID;
return contactApplicationID;
};
/**
* Set the contact details.
*
* @param {string} details The contact details.
*/
ContactPeer.prototype.setContactDetails = function (details) {
this.contactDetails = details;
};
/**
* Get the contact details.
*
* @return {string} Returns the contact details.
*/
ContactPeer.prototype.getContactDetails = function () {
// Get this contact details.
var contactDetails = this.contactDetails;
return contactDetails;
};
/**
* Set the remote stream to the video element.
*
* @param {object} videoElement The remote video element.
* @param {MediaStream} stream The remote video stream.
*
* @return {boolean} True if the stream has been added; else false.
*/
ContactPeer.prototype.setRemoteStreamToVideoElement = function (videoElement, stream) {
// If stream exists.
if (this.remoteStream) {
// Assign the video element.
this.remoteStreamVideoElement = videoElement;
this.remoteStreamVideoElement.srcObject = this.remoteStream;
return true;
}
else if (stream) {
// Assign the video element.
this.remoteStream = stream;
this.remoteStreamVideoElement = videoElement;
this.remoteStreamVideoElement.srcObject = stream;
return true;
}
return false;
};
/**
* Set the remote video element.
*
* @param {object} videoElement The remote video element.
*/
ContactPeer.prototype.setRemoteVideoElement = function (videoElement) {
// Assign the video element.
this.remoteStreamVideoElement = videoElement;
};
/**
* Get the contact media stream.
*
* @return {MediaStream} Returns the contact media stream.
*/
ContactPeer.prototype.getStream = function () {
// Get this contact stream.
var stream = this.remoteStream;
return stream;
};
/**
* Set the file transfer information.
*
* @param {string} name The file name to send.
* @param {number} size The file size.
* @param {string} type The file type.
* @param {number} lastModified The file last modified date.
*/
ContactPeer.prototype.setFileInfo = function (name, size, type, lastModified) {
this.fileName = name;
this.fileSize = size;
this.fileType = type;
this.fileLastModified = lastModified;
};
/**
* Close the contact peer connection.
*/
ContactPeer.prototype.close = function () {
if (this.closed) return;
this.closed = true;
try {
// Remove the stream.
this.closeStream();
this.closeReceiveDataChannel();
this.closeSendDataChannel();
}
catch (e) {
// Log the error.
this.logger.error("Error closing streams: " + e);
}
this.remoteStream = null;
this.remoteStreamVideoElement = null;
try {
// Close peer connection.
this.peerConnection.close();
this.peerConnection = null;
}
catch (e) {
// Log the error.
this.logger.error("Error closing RTCPeerConnection: " + e);
}
try {
// Stop recording.
this.stopRecording();
}
catch (e) {
// Log the error.
this.logger.error("Error stopping recording: " + e);
}
// Call the peer stream removed event handler.
this.parent.emit('peerContactEventClose', "Peer connection has been closed.", this, null);
try {
// Get the index of the current peer.
var peerIndex = this.parent.contactPeers.indexOf(this);
if (peerIndex > -1) {
this.parent.contactPeers.splice(peerIndex, 1);
}
}
catch (e) {}
};
/**
* Close the contact receive data channel.
*/
ContactPeer.prototype.closeReceiveDataChannel = function () {
// If data channel exists.
if (this.receiveDataChannel) {
this.receiveDataChannel.close();
this.receiveDataChannel = null;
}
};
/**
* Close the contact send data channel.
*/
ContactPeer.prototype.closeSendDataChannel = function () {
// If data channel exists.
if (this.sendDataChannel) {
this.sendDataChannel.close();
this.sendDataChannel = null;
}
};
/**
* Add the local media stream to the contact.
*
* @param {MediaStream} stream Local media stream.
*/
ContactPeer.prototype.addStream = function (stream) {
// If stream exists.
if (stream) {
try {
// If peer.
if (this.peerConnection) {
// Add the local stream to the peer connection.
this.peerConnection.addStream(stream);
}
}
catch (e) {
// Log the error.
this.logger.error("Error adding stream to RTCPeerConnection: " + e);
}
}
};
/**
* Add the local media stream to the contact.
*
* @param {MediaStream} stream Local media stream.
*/
ContactPeer.prototype.addStreamTracks = function (stream) {
// If stream exists.
if (stream) {
try {
// If peer.
if (this.peerConnection) {
stream.getTracks().forEach(function(track) {
this.peerConnection.addTrack(track, stream);
});
}
}
catch (e) {
// Log the error.
this.logger.error("Error adding stream tracks to RTCPeerConnection: " + e);
}
}
};
/**
* Remove the local media stream to the contact.
*
* @param {MediaStream} stream Local media stream.
*/
ContactPeer.prototype.removeStreamTracks = function (stream) {
// If stream exists.
if (stream) {
try {
// If peer.
if (this.peerConnection) {
stream.getTracks().forEach(function(track) {
this.peerConnection.removeTrack(track, stream);
});
}
}
catch (e) {
// Log the error.
this.logger.error("Error removing stream tracks to RTCPeerConnection: " + e);
}
}
};
/**
* Set the contact session description.
*
* @param {RTCSessionDescription} sdp Session description.
*/
ContactPeer.prototype.setRemoteDescription = function (sdp) {
// If peer.
if (this.peerConnection) {
// Set the contact session description.
this.peerConnection.setRemoteDescription(new RTCSessionDescription(sdp));
}
};
/**
* Add the ICE candidate.
*
* @param {RTCIceCandidateInit} candidate Add candidate.
*/
ContactPeer.prototype.addIceCandidate = function (candidate) {
// If peer.
if (this.peerConnection) {
// Add the ICE candidate.
this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
}
};
/**
* On ICE candidate.
*
* @param {candidate} evt Add candidate.
*/
ContactPeer.prototype.onIceCandidateHandler = function (evt) {
// Get this contact details.
var contactUniqueID = this.uniqueID;
var contactApplicationID = this.applicationID;
var isDataChannel = this.isData;
// Send the message through the signalling provider.
evt.signalling.iceCandidate(contactUniqueID, contactApplicationID, evt.data.candidate, isDataChannel)
};
/**
* Mute the audio and video tracks in the media stream.
*
* @param {boolean} mute True to mute; else false.
*/
ContactPeer.prototype.muteAudioVideo = function (mute) {
// If peer.
if (this.peerConnection) {
// If a sender exists.
if (this.peerConnection.getSenders) {
// For each sender track.
this.peerConnection.getSenders().forEach(function (sender) {
if (sender.track) {
// Disable-enable the sender track.
sender.track.enabled = !mute;
}
});
}
else {
// For each local stream.
this.peerConnection.getLocalStreams().forEach(function (stream) {
// For each audio stream.
stream.getAudioTracks().forEach(function (track) {
// Disable-enable the local track.
track.enabled = !mute;
});
// For each video stream.
stream.getVideoTracks().forEach(function (track) {
// Disable-enable the local track.
track.enabled = !mute;
});
});
}
}
};
/**
* Close the contact media stream.
*/
ContactPeer.prototype.closeStream = function () {
// If peer.
if (this.peerConnection) {
if (this.remoteStream) {
// Stop all tracks.
this.remoteStream.getTracks().forEach (
function (track) {
track.stop();
}
);
// If video element.
if (this.remoteStreamVideoElement) {
this.remoteStreamVideoElement.srcObject = null;
}
}
}
};
/**
* Start recording remote stream.
*
* @param {string} [recordingOptions] The recording options.
* @param {number} timeInterval The time interval (milliseconds).
*/
ContactPeer.prototype.startRecording = function (recordingOptions, timeInterval) {
// If stream exists.
if (this.remoteStream) {
// Get this local stream.
var stream = this.remoteStream;
// Recording mime type.
var options = {mimeType: 'video/webm'};
try {
// Create media recorder.
this.mediaRecorder = new MediaRecorder(stream, recordingOptions);
}
catch (e) {
// Log the error.
this.logger.error("Error creating MediaRecorder: " + e);
}
// If media recorder created.
if (this.mediaRecorder) {
// On stop recording.
this.mediaRecorder.onstop = function (evt) {
this.parent.emit('peerContactRecordingStopped', "Peer has stopped recording.", this, evt);
};
// Recorded data is available.
this.mediaRecorder.ondataavailable = function (event) {
// If data exists.
if (event.data && event.data.size > 0) {
// Send the chunck on data.
this.parent.emit('peerContactRecordingData', "Peer has recording data.", this, event.data);
}
};
// Collect 10ms of data.
this.mediaRecorder.start(timeInterval);
}
}
};
/**
* Stop recording remote stream.
*/
ContactPeer.prototype.stopRecording = function () {
// If media recorder created.
if (this.mediaRecorder) {
this.mediaRecorder.stop();
this.mediaRecorder = null;
}
};
/**
* Pause recording local stream.
*/
ContactPeer.prototype.pauseRecording = function () {
// If media recorder created.
if (this.mediaRecorder) {
this.mediaRecorder.pause();
}
};
/**
* Resume recording local stream.
*/
ContactPeer.prototype.resumeRecording = function () {
// If media recorder created.
if (this.mediaRecorder) {
this.mediaRecorder.resume();
}
};
/**
* Create the offer and send the call request.
*/
ContactPeer.prototype.sendOfferRequest = function () {
// Create local refs.
var localUniqueID = this.uniqueID;
var localApplicationID = this.applicationID;
var localPC = this.peerConnection;
var localSig = this.signalling;
var localLogger = this.logger;
var localMedaia = this.receiveMedia;
var localParent = this.parent;
// If peer.
if (this.peerConnection) {
// Create a call offer.
this.peerConnection.createOffer(
function (offer) {
// Create a new RTC session.
var request = new RTCSessionDescription(offer);
// Set the local call offer session description.
localPC.setLocalDescription(new RTCSessionDescription(request),
function () {
// Set the request.
localSig.sendOffer(localUniqueID, localApplicationID, request);
},
function (error) {
localLogger.error(error);
}
);
},
function (error) {
// Session error.
localParent.emit('peerContactEventSessionError', "Failed to create session description.", self, error);
},
localMedaia
);
}
};
/**
* Create the answer and send the call response.
*/
ContactPeer.prototype.sendAnswerResponse = function () {
// Create local refs.
var localUniqueID = this.uniqueID;
var localApplicationID = this.applicationID;
var localPC = this.peerConnection;
var localSig = this.signalling;
var localLogger = this.logger;
var localParent = this.parent;
// If peer.
if (this.peerConnection) {
this.peerConnection.createAnswer(
function (answer) {
// Create a new RTC session.
var response = new RTCSessionDescription(answer);
// Set the local call answer session description.
localPC.setLocalDescription(response,
function () {
// Set the response.
localSig.sendAnswer(localUniqueID, localApplicationID, response);
},
function (error) {
localLogger.error(error);
}
);
},
function (error) {
// Session error.
localParent.emit('peerContactEventSessionError', "Failed to create session description.", self, error);
}
);
}
};
/**
* Create the file transfer offer and send the call request.
*
* @param {File} file The file to send.
*/
ContactPeer.prototype.sendFileTransferOfferRequest = function (file) {
// Create local refs.
var localUniqueID = this.uniqueID;
var localApplicationID = this.applicationID;
var localPC = this.peerConnection;
var localSig = this.signalling;
var localLogger = this.logger;
var localParent = this.parent;
// If sent data channel exists.
if (this.sendDataChannel) {
// Set the file send.
this.fileToSend = file;
}
// If peer.
if (this.peerConnection) {
// Create a call offer.
this.peerConnection.createOffer(
function (offer) {
// Create a new RTC session.
var request = new RTCSessionDescription(offer);
// Set the local call offer session description.
localPC.setLocalDescription(new RTCSessionDescription(request),
function () {
// Set the request.
localSig.sendFileTransferOffer(localUniqueID, localApplicationID, request, file.name, file.size, file.type, file.lastModified);
},
function (error) {
localLogger.error(error);
}
);
},
function (error) {
// Session error.
localParent.emit('peerContactEventSessionError', "Failed to create session description.", self, error);
}
);
}
};
/**
* Create the file transfer answer and send the call response.
*/
ContactPeer.prototype.sendFileTransferAnswerResponse = function () {
// Create local refs.
var localUniqueID = this.uniqueID;
var localApplicationID = this.applicationID;
var localPC = this.peerConnection;
var localSig = this.signalling;
var localLogger = this.logger;
var localParent = this.parent;
// If peer.
if (this.peerConnection) {
this.peerConnection.createAnswer(
function (answer) {
// Create a new RTC session.
var response = new RTCSessionDescription(answer);
// Set the local call answer session description.
localPC.setLocalDescription(response,
function () {
// Set the response.
localSig.sendFileTransferAnswer(localUniqueID, localApplicationID, response);
},
function (error) {
localLogger.error(error);
}
);
},
function (error) {
// Session error.
localParent.emit('peerContactEventSessionError', "Failed to create session description.", self, error);
}
);
}
};
/**
* Create the join conference offer and send the call request.
*/
ContactPeer.prototype.sendJoinConferenceOfferRequest = function () {
// Create local refs.
var localUniqueID = this.uniqueID;
var localApplicationID = this.applicationID;
var localPC = this.peerConnection;
var localSig = this.signalling;
var localLogger = this.logger;
var localMedaia = this.receiveMedia;
var localParent = this.parent;
// If peer.
if (this.peerConnection) {
// Create a call offer.
this.peerConnection.createOffer(
function (offer) {
// Create a new RTC session.
var request = new RTCSessionDescription(offer);
// Set the local call offer session description.
localPC.setLocalDescription(new RTCSessionDescription(request),
function () {
// Set the request.
localSig.sendJoinConferenceOffer(localUniqueID, localApplicationID, request);
},
function (error) {
localLogger.error(error);
}
);
},
function (error) {
// Session error.
localParent.emit('peerContactEventSessionError', "Failed to create session description.", self, error);
},
localMedaia
);
}
};
/**
* Create the join conference answer and send the call response.
*/
ContactPeer.prototype.sendJoinConferenceAnswerResponse = function () {
// Create local refs.
var localUniqueID = this.uniqueID;
var localApplicationID = this.applicationID;
var localPC = this.peerConnection;
var localSig = this.signalling;
var localLogger = this.logger;
var localParent = this.parent;
// If peer.
if (this.peerConnection) {
this.peerConnection.createAnswer(
function (answer) {
// Create a new RTC session.
var response = new RTCSessionDescription(answer);
// Set the local call answer session description.
localPC.setLocalDescription(response,
function () {
// Set the response.
localSig.sendJoinConferenceAnswer(localUniqueID, localApplicationID, response);
},
function (error) {
localLogger.error(error);
}
);
},
function (error) {
// Session error.
localParent.emit('peerContactEventSessionError', "Failed to create session description.", self, error);
}
);
}
};
// Export the prototype.
module.exports = ContactPeer;
},{"filetransfer":5,"rtcpeerconnection":12,"util":20,"webrtcsupport":21,"wildemitter":22}],2:[function(require,module,exports){
// Require packages.
var util = require('util');
var WildEmitter = require('wildemitter');
/**
* Signalling prototype.
*
* Signalling class used to signal other contacted
* clients, this signalling class uses WebSockets
* for the signalling transport.
*
* @param {Object} signalOptions A collection of options.
*
* @example
* options = {
* signallingURL: "wss://127.0.0.1:443"
* }
*/
function Signalling(signalOptions) {
// local.
var self = this;
this.closed = false;
var myParent = signalOptions.parent;
var item;
// Set options.
var options = signalOptions || {};
// Call emitter constructor.
WildEmitter.call(this);
// Get the parent logger.
this.logger = myParent.logger;
// Configuration.
var config = this.config = {
signallingURL: "wss://127.0.0.1:443"
};
// Set options, override existing.
for (item in options) {
if (options.hasOwnProperty(item)) {
this.config[item] = options[item];
}
}
try {
// Create a new WebSocket client for signalling.
this.webSocket = new WebSocket(config.signallingURL);
}
catch (e) {
this.logger.error("Error connecting to WebSocket: " + e);
}
// If created.
if (this.webSocket) {
// Open new connection handler.
this.webSocket.onopen = function (openEvent) {
// Send open connection alert.
myParent.emit('signallingEventOpen', "Signalling has opened.", this, openEvent);
};
// Error handler.
this.webSocket.onerror = function (errorEvent) {
// Send error connection alert.
myParent.emit('signallingEventError', "Signalling has encountered and unknown error.", this, errorEvent);
};
// Connection closed handler.
this.webSocket.onclose = function (closeEvent) {
// Send close connection alert.
myParent.emit('signallingEventClose', "Signalling has closed.", this, closeEvent);
};
// Incomming messsage handler.
this.webSocket.onmessage = function (messageEvent) {
var signal = null;
// Get the signl from the WebSocket.
signal = JSON.parse(messageEvent.data);
// If a valid response.
if (signal.response) {
// If error.
if (signal.error) {
// Get the error message.
myParent.emit('signallingEventErrorDetails', "Signalling has encountered an error.", this, signal.error);
}
else if (signal.applications) {
myParent.emit('signallingEventApplications', "Signalling has applications", this, signal.applications);
}
else if (signal.uniques) {
myParent.emit('signallingEventUniques', "Signalling has uniques", this, signal.uniques);
}
else if (signal.groups) {
myParent.emit('signallingEventGroups', "Signalling has groups", this, signal.groups);
}
else {
// If settings have been applied.
if (signal.settings && signal.settings === true) {
// The client settings.
myParent.emit('signallingEventSettings', "Signalling settings have been applied.", this, signal.settings);
}
else if (signal.contactAvailable) {
// Get the contact details.
var uniqueID = signal.contactUniqueID;
var applicationID = signal.contactApplicationID;
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
contactAvailable: signal.contactAvailable
};
// Send signal.
myParent.emit('signallingEventAvailable', "Signalling contact available.", this, details);
}
else if (signal.contactMessage) {
// A message from a contact.
// Get the contact details.
var uniqueID = signal.contactUniqueID;
var applicationID = signal.contactApplicationID;
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
contactMessage: signal.contactMessage
};
// Send message.
myParent.emit('signallingEventMessage', "Signalling contact message.", this, details);
}
else if (signal.clientState) {
// A message from a contact.
// Get the contact details.
var uniqueID = signal.contactUniqueID;
var applicationID = signal.contactApplicationID;
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
contactState: signal.state
};
// Send message.
myParent.emit('signallingEventState', "Signalling contact state.", this, details);
}
else if (signal.clientDetails) {
// A message from a contact.
// Get the contact details.
var uniqueID = signal.contactUniqueID;
var applicationID = signal.contactApplicationID;
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
clientDetails: signal.details
};
// Send message.
myParent.emit('signallingEventDetails', "Signalling contact details.", this, details);
}
else {
// If the client is available
if (signal.available && signal.available === true) {
// Get the contact details.
var uniqueID = signal.contactUniqueID;
var applicationID = signal.contactApplicationID;
var isDataChannel = false;
// If this is a file transfer or data channel.
if (signal.fileTransferOffer || signal.fileTransferAnswer || signal.isData) {
var isDataChannel = true;
}
// A SDP signal has been received.
if (signal.sdp) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
sdp: signal.sdp,
isData: isDataChannel
};
// Send SDP data.
myParent.emit('signallingEventSDP', "Signalling an SDP signal has been received.", this, details);
}
// Add the peer ICE candidate.
if (signal.candidate) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
candidate: signal.candidate,
type: signal.type,
isData: isDataChannel
};
// Send candidate data.
myParent.emit('signallingEventCandidate', "Signalling a candidate signal has been received.", this, details);
}
// If a call request offer was sent.
if (signal.callOffer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
};
// Send offer data.
myParent.emit('signallingEventOffer', "Signalling an offer signal has been received.", this, details);
}
// If the call response answer was sent.
if (signal.callAnswer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
};
// Send answer data.
myParent.emit('signallingEventAnswer', "Signalling an answer signal has been received.", this, details);
}
// If a join conference request offer was sent.
if (signal.joinConferenceOffer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
conference: signal.conferenceCall
};
// Send offer data.
myParent.emit('signallingEventJoinConferenceOffer', "Signalling a join conference offer signal has been received.", this, details);
}
// If the join conference response answer was sent.
if (signal.joinConferenceAnswer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
conference: signal.conferenceCall
};
// Send answer data.
myParent.emit('signallingEventJoinConferenceAnswer', "Signalling a join conference answer signal has been received.", this, details);
}
// If a file transfer request offer was sent.
if (signal.fileTransferOffer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
name: signal.name,
size: signal.size,
type: signal.type,
lastModified: signal.lastModified,
fileTransfer: signal.fileTransferOffer
};
// Send file transfer offer data.
myParent.emit('signallingEventFileOffer', "Signalling a file transfer offer signal has been received.", this, details);
}
// If file transfer response answer was sent.
if (signal.fileTransferAnswer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
fileTransfer: signal.fileTransferAnswer
};
// Send file answer data.
myParent.emit('signallingEventFileAnswer', "Signalling a file answer signal has been received.", this, details);
}
// The client did not accept the call request.
if (signal.noanswer) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
noanswer: signal.noanswer
};
// Send file answer data.
myParent.emit('signallingEventNoAnswer', "Signalling the peer contact did not answer.", this, details);
}
// The remote client closed, ended the call.
if (signal.endCallRemote) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
endCallRemote: signal.endCallRemote
};
// Send file answer data.
myParent.emit('signallingEventEndCall', "Signalling the peer contact ended the call.", this, details);
}
// If contact typing a message.
if (signal.contactTypingMessage) {
// Details.
var details = {
contactUniqueID: uniqueID,
contactApplicationID: applicationID,
contactTypingMessage: signal.contactTypingMessage,
typing: signal.typing
};
// If typing.
if (signal.typing && signal.typing === true) {
// The client is typing a message.
myParent.emit('signallingEventTypingMessage', "Signalling the contact is typing a message.", this, details);
}
else {
// The client has stopped typing.
myParent.emit('signallingEventTypingMessage', "Signalling the contact has stopped typing.", this, details);
}
}
else {
// Details.
var details = {
contactAvailable: signal.available
};
// The client is available.
myParent.emit('signallingEventSelfAvailable', "Signalling the contact is available.", this, details);
}
}
else {
// Details.
var details = {
contactAvailable: signal.available
};
// The client is not available.
myParent.emit('signallingEventSelfAvailable', "Signalling the contact is not available.", this, details);
}
}
}
}
else {
// Unknown error from the WebSocket.
myParent.emit('signallingEventErrorDetails', "Signalling has encountered an unknown error.", this, null);
}
};
};
}
/**
* Change this client details.
*
* @param {string} uniqueID The client unique id.
* @param {string} applicationID The client application id.
* @param {boolean} available True if this client is avaliable for contact; else false.
* @param {boolean} broadcast True if this client allows the unique id to be broadcast; else false.
* @param {boolean} broadcastAppID True if this client allows the application id to be broadcast; else false.
* @param {string} accessToken The access token.
*/
Signalling.prototype.changeClientSettings = function (uniqueID, applicationID, available, broadcast, broadcastAppID, accessToken) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"uniqueID": uniqueID,
"applicationID": applicationID,
"available": available,
"broadcast": broadcast,
"broadcastAppID": broadcastAppID,
"accessToken": accessToken
})
);
};
/**
* Send the current state of the client to the contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {string} state The client state.
*/
Signalling.prototype.sendClientState = function (contactUniqueID, contactApplicationID, state) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"clientState": true,
"state": state
})
);
};
/**
* Send the current details of the client to the contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {string} details The client details.
*/
Signalling.prototype.sendClientDetails = function (contactUniqueID, contactApplicationID, details) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"clientDetails": true,
"details": details
})
);
};
/**
* Send a message to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {string} message The message to send.
*/
Signalling.prototype.sendMessage = function (contactUniqueID, contactApplicationID, message) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"contactMessage": message
})
);
};
/**
* Send ICE candidate details to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {string} candidate The candidate details.
* @param {boolean} isData Is the candidate a data channel.
*/
Signalling.prototype.iceCandidate = function (contactUniqueID, contactApplicationID, candidate, isData) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"candidate": candidate,
"type": "candidate",
"isData": isData
})
);
};
/**
* Send do not want to answer to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
Signalling.prototype.noAnswer = function (contactUniqueID, contactApplicationID) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"noanswer": true
})
);
};
/**
* Send end of call to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
Signalling.prototype.sendEndCallToContact = function (contactUniqueID, contactApplicationID) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"endCallRemote": true
})
);
};
/**
* Send a request asking if the contact is available.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
Signalling.prototype.contactAvailable = function (contactUniqueID, contactApplicationID) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"contactAvailable": true
})
);
};
/**
* Send the offer to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {RTCSessionDescription} sdpOfferRequest The SDP offer.
*/
Signalling.prototype.sendOffer = function (contactUniqueID, contactApplicationID, sdpOfferRequest) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"callOffer": true,
"sdp": sdpOfferRequest
})
);
};
/**
* Send the answer to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {RTCSessionDescription} sdpAnswerResponse The SDP answer.
*/
Signalling.prototype.sendAnswer = function (contactUniqueID, contactApplicationID, sdpAnswerResponse) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"callAnswer": true,
"sdp": sdpAnswerResponse
})
);
};
/**
* Send to the contact a message indicating that this client is joining the conference.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {RTCSessionDescription} sdpOfferRequest The SDP offer.
*/
Signalling.prototype.sendJoinConferenceOffer = function (contactUniqueID, contactApplicationID, sdpOfferRequest) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"joinConferenceOffer": true,
"conferenceCall": true,
"sdp": sdpOfferRequest
})
);
};
/**
* Send to the contact a message indicating that this client has joined the conference.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {RTCSessionDescription} sdpAnswerResponse The SDP answer.
*/
Signalling.prototype.sendJoinConferenceAnswer = function (contactUniqueID, contactApplicationID, sdpAnswerResponse) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"joinConferenceAnswer": true,
"conferenceCall": true,
"sdp": sdpAnswerResponse
})
);
};
/**
* Send a message to the contact that this contact has started typing.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
Signalling.prototype.startedTypingMessage = function (contactUniqueID, contactApplicationID) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"contactTypingMessage": true,
"typing" : true
})
);
};
/**
* Send a message to the contact that this contact has stopped typing.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
Signalling.prototype.stoppedTypingMessage = function (contactUniqueID, contactApplicationID) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"contactTypingMessage": true,
"typing" : false
})
);
};
/**
* Send the file transfer offer to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {RTCSessionDescription} sdpOfferRequest The SDP offer.
* @param {string} fileName The file name to send.
* @param {number} fileSize The file size.
* @param {string} fileType The file type.
* @param {number} fileLastModified The file last modified date.
*/
Signalling.prototype.sendFileTransferOffer = function (contactUniqueID, contactApplicationID, sdpOfferRequest, fileName, fileSize, fileType, fileLastModified) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"fileTransferOffer": true,
"name": fileName,
"size": fileSize,
"type": fileType,
"lastModified": fileLastModified,
"sdp": sdpOfferRequest
})
);
};
/**
* Send the file transfer answer to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
* @param {RTCSessionDescription} sdpAnswerResponse The SDP answer.
*/
Signalling.prototype.sendFileTransferAnswer = function (contactUniqueID, contactApplicationID, sdpAnswerResponse) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"fileTransferAnswer": true,
"sdp": sdpAnswerResponse
})
);
};
/**
* Send do not want the file transfer answer to this contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
Signalling.prototype.noFileTransferAnswer = function (contactUniqueID, contactApplicationID) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send(
JSON.stringify(
{
"contactUniqueID": contactUniqueID,
"contactApplicationID": contactApplicationID,
"noanswer": true
})
);
};
/**
* Sent a request to get the list of uniques.
*/
Signalling.prototype.contactUniqueIDList = function () {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send("uniqueids");
}
/**
* Sent a request to get the list of applications.
*/
Signalling.prototype.contactApplicationIDList = function () {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send("applicationids");
}
/**
* Sent a request to get the list of groups.
*/
Signalling.prototype.contactGroupList = function () {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
// Send to the signalling provider.
this.webSocket.send("uniqueapplication");
}
/**
* Close the current signalling connection.
*/
Signalling.prototype.close = function () {
if (this.closed) return;
this.closed = true;
// Close the WebSocket connection.
if (this.webSocket) {
// If the socket is not open.
if (this.webSocket.readyState !== this.webSocket.OPEN) return;
try {
// Close.
this.webSocket.close();
this.webSocket = null;
}
catch (e) {
// Log the error.
this.logger.error("Error closing signalling: " + e);
}
}
};
// Export the prototype.
module.exports = Signalling;
},{"util":20,"wildemitter":22}],3:[function(require,module,exports){
// Require packages.
var util = require('util');
var WildEmitter = require('wildemitter');
var webrtcSupport = require('webrtcsupport');
var mockconsole = require('mockconsole');
var localMedia = require('localmedia');
var ContactPeer = require('./contactpeer');
var Signalling = require('./signalling');
/**
* WebRTC adapter prototype.
*
* WebRTC adapter controls the interaction between the
* signalling provider and the contact peers
* implementation.
*
* @param {Object} webRtcOptions A collection of options.
*
* @example
* options = {
* debug: true,
* uniqueID: "uniqueID",
* applicationID: "applicationID",
* signallingURL: "wss://127.0.0.1:443",
* peerConnectionConfiguration: {
* iceServers: [
* {
* "urls": "stun:stun.l.google.com:19302"
* },
* {
* "urls": "turn:127.0.0.1:19305?transport=udp",
* "username": "username",
* "credential": "password"
* },
* {
* "urls": "turn:127.0.0.1:19305?transport=tcp",
* "username": "username",
* "credential": "password"
* }
* ]
* },
* peerConnectionConstraints: {
* optional: []
* },
* receiveOfferMedia: {
* offerToReceiveAudio: 1,
* offerToReceiveVideo: 1
* }
* }
*/
function WebRtcAdapter(webRtcOptions) {
// local.
var self = this;
this.closed = false;
var item;
// Call emitter constructor.
WildEmitter.call(this);
// Set the webRTC options.
var options = webRtcOptions || {};
// Assign this contact details.
this.uniqueID = webRtcOptions.uniqueID;
this.applicationID = webRtcOptions.applicationID;
// Store all contact peers.
this.contactPeers = [];
// The local stream.
this.localStream = null;
this.localStreamVideoElement = null;
// MediaRecorder
this.mediaRecorder = null;
// Configuration.
var config = this.config = {
debug: false,
// Peer connection configuration.
peerConnectionConfiguration: {
iceServers: [
{
"urls": "stun:stun.l.google.com:19302"
}
]
},
// Peer connection constraints.
peerConnectionConstraints: {
optional: []
},
// Receive offer media config.
receiveOfferMedia: {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
},
// Signalling URL.
signallingURL: "wss://127.0.0.1:443"
};
// Log nothing by default, following "the rule of silence":
// http://www.linfo.org/rule_of_silence.html
this.logger = function () {
// Assume that if you're in debug mode and you didn't
// pass in a logger, you actually want to log as much as
// possible.
if (webRtcOptions.debug) {
return webRtcOptions.logger || console;
}
else {
// Use your logger which should have its own logic
// for output. Return the no-op.
return webRtcOptions.logger || mockconsole;
}
}();
// Set options, override existing.
for (item in options) {
if (options.hasOwnProperty(item)) {
this.config[item] = options[item];
}
}
// Check for support
if (!webrtcSupport.support) {
this.logger.error("Your browser does not support WebRTC");
}
// Call localMedia constructor, setup
// to override members.
localMedia.call(this, this.config);
// Signalling configuration.
var configSignalling = {
signallingURL: config.signallingURL,
parent: self
};
// Create the websocket signalling provider.
this.signalling = new Signalling(configSignalling);
// Override on speaking method in local media.
this.on('speaking', function () {
if (!self.hardMuted) {
}
});
// Override on stoppedSpeaking method in local media.
this.on('stoppedSpeaking', function () {
if (!self.hardMuted) {
}
});
// Override on volumeChange method in local media.
this.on('volumeChange', function (volume, treshold) {
if (!self.hardMuted) {
}
});
// log events in debug mode
if (this.config.debug) {
// Capture all events.
this.on('*', function (event, val1, val2, val3) {
var logger;
// if you didn't pass in a logger and you explicitly turning on debug
// we're just going to assume you're wanting log output with console
if (self.config.logger === mockconsole) {
logger = console;
}
else {
logger = self.logger;
}
// Log the event.
logger.log('event:', event, val1, val2);
});
}
}
// Inherit local media members.
util.inherits(WebRtcAdapter, localMedia);
/**
* Change client settings.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} available True if this client is avaliable for contact; else false.
* @param {boolean} broadcast True if this client allows the unique id to be broadcast; else false.
* @param {boolean} broadcastAppID True if this client allows the application id to be broadcast; else false.
* @param {string} accessToken The access token.
*/
WebRtcAdapter.prototype.changeClientSettings = function (uniqueID, applicationID, available, broadcast, broadcastAppID, accessToken) {
// Assign this client details.
this.uniqueID = uniqueID;
this.applicationID = applicationID;
// Change client settings
this.signalling.changeClientSettings(uniqueID, applicationID, available, broadcast, broadcastAppID, accessToken);
};
/**
* Get the client unique id.
*
* @return {string} Returns the client unique id.
*/
WebRtcAdapter.prototype.getUniqueID = function () {
// Get this contact details.
var contactUniqueID = this.uniqueID;
return contactUniqueID;
};
/**
* Get the client application id.
*
* @return {string} Returns the client application id.
*/
WebRtcAdapter.prototype.getApplicationID = function () {
// Get this contact details.
var contactApplicationID = this.applicationID;
return contactApplicationID;
};
/**
* Send started typing to contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
*/
WebRtcAdapter.prototype.startedTypingMessage = function (uniqueID, applicationID) {
// Send the message to the peer.
this.signalling.startedTypingMessage(uniqueID, applicationID);
};
/**
* Send stopped typing to contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
*/
WebRtcAdapter.prototype.stoppedTypingMessage = function (uniqueID, applicationID) {
// Send the message to the peer.
this.signalling.stoppedTypingMessage(uniqueID, applicationID);
};
/**
* Get the contact unique list.
*/
WebRtcAdapter.prototype.contactUniqueIDList = function () {
this.signalling.contactUniqueIDList();
}
/**
* Get the contact application list.
*/
WebRtcAdapter.prototype.contactApplicationIDList = function () {
this.signalling.contactApplicationIDList();
}
/**
* Get the contact group list.
*/
WebRtcAdapter.prototype.contactGroupList = function () {
this.signalling.contactGroupList();
}
/**
* Create a new contact.
*
* @param {Object} opts A collection of options.
*
* @example
* options = {
* uniqueID: "uniqueID",
* applicationID: "applicationID",
* isData: false,
* receiveOfferMedia: {
* offerToReceiveAudio: 1,
* offerToReceiveVideo: 1
* }
* }
*
* @return {ContactPeer} Returns the contact.
*/
WebRtcAdapter.prototype.createContactPeer = function (opts) {
var peer;
opts.parent = this;
opts.signalling = this.signalling;
// Create a contact peer.
peer = new ContactPeer(opts);
// Add the contact peer to the collection
// of contact peers.
this.contactPeers.push(peer);
// Return the current contact peer.
return peer;
};
/**
* Remove all contacts.
*/
WebRtcAdapter.prototype.removeContactPeers = function () {
// Get all peers.
this.getContactPeers().forEach(function (peer) {
// Close the connection.
peer.close();
});
};
/**
* Remove the contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} isData True if contact is only data channel; else false.
*/
WebRtcAdapter.prototype.removeContactPeer = function (uniqueID, applicationID, isData) {
// Get all peers.
this.getContactPeers().forEach(function (peer) {
if (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData) {
// Close the connection.
peer.close();
}
});
};
/**
* Get all contacts.
*
* @return {Array} Returns the contact list.
*/
WebRtcAdapter.prototype.getContactPeers = function () {
return this.contactPeers.filter(function (peer) {
// Return the peers.
return true;
});
};
/**
* Get the contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} isData True if contact is only data channel; else false.
*
* @return {ContactPeer} Returns the contact.
*/
WebRtcAdapter.prototype.getContactPeer = function (uniqueID, applicationID, isData) {
return this.contactPeers.filter(function (peer) {
// Return the contact.
return (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData);
});
};
/**
* Is the contact in the contact list.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
*
* @return {ContactPeer} Returns the contact; else null.
*/
WebRtcAdapter.prototype.isContactPeer = function (uniqueID, applicationID) {
return this.contactPeers.filter(function (peer) {
// Return the contact.
return (peer.uniqueID === uniqueID && peer.applicationID === applicationID);
});
};
/**
* Send the client state to all contacts.
*
* @param {string} state The state to sent.
*/
WebRtcAdapter.prototype.sendStateToAllContacts = function (state) {
this.contactPeers.forEach(function (peer) {
// Send the state to the peer.
peer.sendState(state);
});
};
/**
* Send a message to all contacts.
*
* @param {string} message The message to sent.
*/
WebRtcAdapter.prototype.sendMessageToAllContacts = function (message) {
this.contactPeers.forEach(function (peer) {
// Send the message to the peer.
peer.sendMessage(message);
});
};
/**
* Send a message to the contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {string} message The message to sent.
* @param {boolean} isData True if contact is only data channel; else false.
*/
WebRtcAdapter.prototype.sendMessageToContact = function (uniqueID, applicationID, message, isData) {
this.contactPeers.forEach(function (peer) {
if (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData) {
// Send the message to the peer.
peer.sendMessage(message);
}
});
};
/**
* Send a details to all contacts.
*
* @param {string} details The details to sent.
*/
WebRtcAdapter.prototype.sendDetailsToAllContacts = function (details) {
this.contactPeers.forEach(function (peer) {
// Send the details to the peer.
peer.sendDetails(details);
});
};
/**
* Send a details to the contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {string} details The details to sent.
* @param {boolean} isData True if contact is only data channel; else false.
*/
WebRtcAdapter.prototype.sendDetailsToContact = function (uniqueID, applicationID, details, isData) {
this.contactPeers.forEach(function (peer) {
if (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData) {
// Send the details to the peer.
peer.sendDetails(details);
}
});
};
/**
* Send end of call to all contacts.
*/
WebRtcAdapter.prototype.sendEndCallToAllContacts = function () {
this.contactPeers.forEach(function (peer) {
// Send the message to the peer.
peer.sendEndCall();
});
};
/**
* Send end of call to the contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} isData True if contact is only data channel; else false.
*/
WebRtcAdapter.prototype.sendEndCallToContact = function (uniqueID, applicationID, isData) {
this.contactPeers.forEach(function (peer) {
if (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData) {
// Send the message to the peer.
peer.sendEndCall();
}
});
};
/**
* Set the file transfer information for the contact.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} isData True if contact is only data channel; else false.
* @param {string} fileName The file name to send.
* @param {number} fileSize The file size.
* @param {string} fileType The file type.
* @param {number} fileLastModified The file last modified date.
*/
WebRtcAdapter.prototype.setContactFileInfo = function (uniqueID, applicationID, isData, fileName, fileSize, fileType, fileLastModified) {
this.contactPeers.forEach(function (peer) {
if (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData) {
// Send the message to the peer.
peer.setFileInfo(fileName, fileSize, fileType, fileLastModified);
}
});
};
/**
* Send is contact avaliable request.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} isData True if contact is only data channel; else false.
*/
WebRtcAdapter.prototype.isContactAvailable = function (uniqueID, applicationID, isData) {
this.contactPeers.forEach(function (peer) {
if (peer.uniqueID === uniqueID && peer.applicationID === applicationID && peer.isData === isData) {
// Send the message to the peer.
peer.isAvailable();
}
});
};
/**
* Close this adapter.
*/
WebRtcAdapter.prototype.close = function () {
if (this.closed) return;
this.closed = true;
try {
// Close the local stream.
this.closeStream();
this.localStream = null;
this.localStreamVideoElement = null;
}
catch (e) {
// Log the error.
this.logger.error("Error closing stream: " + e);
}
try {
// Close the singalling
this.signalling.close();
this.signalling = null;
}
catch (e) {
// Log the error.
this.logger.error("Error closing signalling: " + e);
}
try {
// Stop recording.
this.stopRecording();
}
catch (e) {
// Log the error.
this.logger.error("Error stopping recording: " + e);
}
// Close all contacts
this.removeContactPeers();
};
/**
* Mute the audio and video tracks for the local stream.
*
* @param {boolean} mute True to mute; else false.
*/
WebRtcAdapter.prototype.muteAudioVideo = function (mute) {
// For each contact.
this.contactPeers.forEach(function (peer) {
// Mute the local stream.
peer.muteAudioVideo(mute);
});
};
/**
* Close the local stream.
*/
WebRtcAdapter.prototype.closeStream = function () {
// If local stream.
if (self.localStream) {
// Stop all tracks.
self.localStream.getTracks().forEach (
function (track) {
track.stop();
}
);
// If video element.
if (self.localStreamVideoElement) {
self.localStreamVideoElement.srcObject = null;
}
}
};
/**
* Create the local audio and video stream.
*
* @param {boolean} audio True to enable audio in local stream; else false.
* @param {boolean} video True to enable video in local stream; else false.
*/
WebRtcAdapter.prototype.createStream = function (audio, video) {
// Create local refs.
var localLogger = this.logger;
// Get the local stream.
navigator.mediaDevices.getUserMedia({ "audio": audio, "video": video }).then(
function (stream) {
// Init the local video stream.
self.localStream = stream;
self.localStreamVideoElement.srcObject = self.localStream;
}).catch(
function (error) {
localLogger.error(error);
});
}
/**
* Create a local capture media, screen or application window (Note only for Firefox).
*
* @param {string} captureMediaSource The capture media source ('screen' or 'window').
*/
WebRtcAdapter.prototype.createStreamCapture = function (captureMediaSource) {
// Create local refs.
var localLogger = this.logger;
// Capture constraints
var constraints = {
video: {
mediaSource: captureMediaSource,
width: {max: '1920'},
height: {max: '1080'},
frameRate: {max: '10'}
}
};
// Get the local stream.
navigator.mediaDevices.getUserMedia(constraints).then(
function (stream) {
// Init the local video stream.
self.localStream = stream;
self.localStreamVideoElement.srcObject = self.localStream;
}).catch(
function (error) {
localLogger.error(error);
});
}
/**
* Create the local media stream.
*
* @param {string} constraints The media constraints.
* @link https://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints
* @example
* qvga = video: {width: {exact: 320}, height: {exact: 240}}
* vga = video: {width: {exact: 640}, height: {exact: 480}}
* hd = video: {width: {exact: 1280}, height: {exact: 720}}
* fullHd =video: {width: {exact: 1920}, height: {exact: 1080}}
* fourK = video: {width: {exact: 4096}, height: {exact: 2160}}
*
* audio: {deviceId: audioSource ? {exact: audioSource} : undefined}
* video: {deviceId: videoSource ? {exact: videoSource} : undefined}
*/
WebRtcAdapter.prototype.createStreamEx = function (constraints) {
// Create local refs.
var localLogger = this.logger;
// Get the local stream.
navigator.mediaDevices.getUserMedia(constraints).then(
function (stream) {
// Init the local video stream.
self.localStream = stream;
self.localStreamVideoElement.srcObject = self.localStream;
}).catch(
function (error) {
localLogger.error(error);
});
}
/**
* Get all audio input devices.
*
* @param {object} callback The callback function.
*/
WebRtcAdapter.prototype.getAudioInputDevices = function (callback) {
// Create local refs.
var localLogger = this.logger;
var devices = [];
// Get the local devices.
navigator.mediaDevices.enumerateDevices().then(
function (deviceInfos) {
// For each device.
for (var i = 0; i !== deviceInfos.length; ++i) {
// Current device.
var deviceInfo = deviceInfos[i];
// If audio input.
if (deviceInfo.kind === 'audioinput') {
devices.push(deviceInfo);
}
}
// Send callback.
callback(devices);
}).catch(
function (error) {
localLogger.error(error);
});
}
/**
* Get all audio output devices.
*
* @param {object} callback The callback function.
*/
WebRtcAdapter.prototype.getAudioOutputDevices = function (callback) {
// Create local refs.
var localLogger = this.logger;
var devices = [];
// Get the local devices.
navigator.mediaDevices.enumerateDevices().then(
function (deviceInfos) {
// For each device.
for (var i = 0; i !== deviceInfos.length; ++i) {
// Current device.
var deviceInfo = deviceInfos[i];
// If audio output.
if (deviceInfo.kind === 'audiooutput') {
devices.push(deviceInfo);
}
}
// Send callback.
callback(devices);
}).catch(
function (error) {
localLogger.error(error);
});
}
/**
* Get all video input devices.
*
* @param {object} callback The callback function.
*/
WebRtcAdapter.prototype.getVideoInputDevices = function (callback) {
// Create local refs.
var localLogger = this.logger;
var devices = [];
// Get the local devices.
navigator.mediaDevices.enumerateDevices().then(
function (deviceInfos) {
// For each device.
for (var i = 0; i !== deviceInfos.length; ++i) {
// Current device.
var deviceInfo = deviceInfos[i];
// If video input.
if (deviceInfo.kind === 'videoinput') {
devices.push(deviceInfo);
}
}
// Send callback.
callback(devices);
}).catch(
function (error) {
localLogger.error(error);
});
}
/**
* Set the local stream to the video element.
*
* @param {object} videoElement The local video element.
*
* @return {boolean} True if the stream has been added; else false.
*/
WebRtcAdapter.prototype.setLocalStreamToVideoElement = function (videoElement) {
// If stream exists.
if (this.localStream) {
// Assign the video element.
self.localStreamVideoElement = videoElement;
self.localStreamVideoElement.srcObject = self.localStream;
return true;
}
else {
return false;
}
};
/**
* Set the local video element.
*
* @param {object} videoElement The local video element.
*/
WebRtcAdapter.prototype.setLocalVideoElement = function (videoElement) {
// Assign the video element.
self.localStreamVideoElement = videoElement;
};
/**
* Get the local stream.
*
* @return {MediaStream} Returns the local stream.
*/
WebRtcAdapter.prototype.getStream = function () {
// Get this local stream.
var stream = self.localStream;
return stream;
};
/**
* Start recording local stream.
*
* @param {string} [recordingOptions] The recording options.
* @param {number} timeInterval The time interval (milliseconds).
*/
WebRtcAdapter.prototype.startRecording = function (recordingOptions, timeInterval) {
// If stream exists.
if (self.localStream) {
// Get this local stream.
var stream = self.localStream;
try {
// Create media recorder.
this.mediaRecorder = new MediaRecorder(stream, recordingOptions);
}
catch (e) {
// Log the error.
this.logger.error("Error creating MediaRecorder: " + e);
}
// If media recorder created.
if (this.mediaRecorder) {
// Create local refs.
var localSelf = this;
// On stop recording.
this.mediaRecorder.onstop = function (evt) {
localSelf.emit('adapterRecordingStopped', "Adapter has stopped recording.", localSelf, evt);
};
// Recorded data is available.
this.mediaRecorder.ondataavailable = function (event) {
// If data exists.
if (event.data && event.data.size > 0) {
// Send the chunck on data.
localSelf.emit('adapterRecordingData', "Adapter has recording data.", localSelf, event.data);
}
};
// Collect 10ms of data.
this.mediaRecorder.start(timeInterval);
}
}
};
/**
* Stop recording local stream.
*/
WebRtcAdapter.prototype.stopRecording = function () {
// If media recorder created.
if (this.mediaRecorder) {
this.mediaRecorder.stop();
this.mediaRecorder = null;
}
};
/**
* Pause recording local stream.
*/
WebRtcAdapter.prototype.pauseRecording = function () {
// If media recorder created.
if (this.mediaRecorder) {
this.mediaRecorder.pause();
}
};
/**
* Resume recording local stream.
*/
WebRtcAdapter.prototype.resumeRecording = function () {
// If media recorder created.
if (this.mediaRecorder) {
this.mediaRecorder.resume();
}
};
// Export the prototype.
module.exports = WebRtcAdapter;
},{"./contactpeer":1,"./signalling":2,"localmedia":8,"mockconsole":10,"util":20,"webrtcsupport":21,"wildemitter":22}],4:[function(require,module,exports){
// Require packages.
var util = require('util');
var WildEmitter = require('wildemitter');
var webrtcSupport = require('webrtcsupport');
var mockconsole = require('mockconsole');
var localMedia = require('localmedia');
var WebRtcAdapter = require('./webrtcadapter');
/**
* WebRTC prototype.
*
* WebRTC controls the interaction between the
* adapter and user configuration.
*
* @param {Object} webRtcOptions A collection of options.
*
* @example
* options = {
* debug: true,
* signallingURL: "wss://127.0.0.1:443",
* peerConnectionConfiguration: {
* iceServers: [
* {
* "urls": "stun:stun.l.google.com:19302"
* },
* {
* "urls": "turn:127.0.0.1:19305?transport=udp",
* "username": "username",
* "credential": "password"
* },
* {
* "urls": "turn:127.0.0.1:19305?transport=tcp",
* "username": "username",
* "credential": "password"
* }
* ]
* },
* peerConnectionConstraints: {
* optional: []
* },
* receiveOfferMedia: {
* offerToReceiveAudio: 1,
* offerToReceiveVideo: 1
* }
* }
*/
function WebRTC(webRtcOptions) {
// local.
var self = this;
this.closed = false;
var item;
var options = webRtcOptions || {};
var config = this.config = {
debug: false,
// Receive offer media config.
receiveOfferMedia: {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
},
// Local video settings.
localVideo: {
autoplay: true,
mirror: true,
muted: true
}
};
// Log nothing by default, following "the rule of silence":
// http://www.linfo.org/rule_of_silence.html
this.logger = function () {
// Assume that if you're in debug mode and you didn't
// pass in a logger, you actually want to log as much as
// possible.
if (webRtcOptions.debug) {
return webRtcOptions.logger || console;
}
else {
// Use your logger which should have its own logic
// for output. Return the no-op.
return webRtcOptions.logger || mockconsole;
}
}();
var myLogger = this.logger;
// set our config from options
for (item in options) {
if (options.hasOwnProperty(item)) {
this.config[item] = options[item];
}
}
// attach detected support for convenience
this.capabilities = webrtcSupport;
// Call WildEmitter constructor.
WildEmitter.call(this);
// instantiate our main WebRTC helper
// using same logger from logic here
webRtcOptions.logger = myLogger;
webRtcOptions.debug = false;
// Create the webrtc adapter.
this.webrtcadapter = new WebRtcAdapter(webRtcOptions);
// Proxy events from WebRtcAdapter
this.webrtcadapter.on('*', function () {
self.emit.apply(self, arguments);
});
// log all events in debug mode
if (config.debug) {
this.on('*', this.logger.log.bind(this.logger, 'WebRTC event:'));
}
// Signalling event.
this.webrtcadapter.on('signallingEventOpen', function (text, signalling, arg) {
var argum = {
open: true,
text: text
};
self.emit('connectionOpen', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventError', function (text, signalling, arg) {
var argum = {
error: true,
data: arg.data,
text: text
};
self.emit('connectionError', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventClose', function (text, signalling, arg) {
var argum = {
close: true,
text: text
};
self.emit('connectionClose', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventErrorDetails', function (text, signalling, arg) {
var argum = {
error: arg,
text: text
};
self.emit('signalError', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventApplications', function (text, signalling, arg) {
var argum = {
list: arg,
text: text
};
self.emit('signalApplications', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventUniques', function (text, signalling, arg) {
var argum = {
list: arg,
text: text
};
self.emit('signalUniques', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventGroups', function (text, signalling, arg) {
var argum = {
list: arg,
text: text
};
self.emit('signalGroups', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventSettings', function (text, signalling, arg) {
var argum = {
setting: arg,
text: text
};
self.emit('signalSettings', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventAvailable', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
available: arg.contactAvailable,
text: text
};
// Emit the message.
self.emit('signalAvailable', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventSelfAvailable', function (text, signalling, arg) {
var argum = {
available: arg.contactAvailable,
text: text
};
// Emit the message.
self.emit('signalSelfAvailable', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventMessage', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
message: arg.contactMessage,
text: text
};
// Emit the message.
self.emit('signalMessage', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventState', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
state: arg.contactState,
text: text
};
// Emit the message.
self.emit('signalState', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventDetails', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
contact.setContactDetails(arg.clientDetails);
var argum = {
contact: contact,
details: arg.clientDetails,
text: text
};
// Emit the message.
self.emit('signalDetails', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventJoinConferenceOffer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
conference: arg.conference,
text: text
};
// Emit the message.
self.emit('signalJoinConferenceOffer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventJoinConferenceAnswer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
conference: arg.conference,
text: text
};
// Emit the message.
self.emit('signalJoinConferenceAnswer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventSDP', function (text, signalling, arg) {
// Get the contact.
var contact = null;
// If file transfer or data channel.
if (arg.isData) {
// Get data contact.
contact = self.createContactData(arg.contactUniqueID, arg.contactApplicationID);
}
else {
contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
}
// Set the remote description.
contact.setRemoteDescription(arg.sdp)
});
// Signalling event.
this.webrtcadapter.on('signallingEventCandidate', function (text, signalling, arg) {
// Get the contact.
var contact = null;
// If file transfer or data channel.
if (arg.isData) {
// Get data contact.
contact = self.createContactData(arg.contactUniqueID, arg.contactApplicationID);
}
else {
contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
}
// Set the ICE candidate.
contact.addIceCandidate(arg.candidate)
});
// Signalling event.
this.webrtcadapter.on('signallingEventOffer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
text: text
};
// Emit the message.
self.emit('signalOffer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventAnswer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
text: text
};
// Emit the message.
self.emit('signalAnswer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventFileOffer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContactData(arg.contactUniqueID, arg.contactApplicationID);
contact.setFileInfo(arg.name, arg.size, arg.type, arg.lastModified);
var argum = {
contact: contact,
name: arg.name,
size: arg.size,
text: text
};
// Emit the message.
self.emit('signalFileOffer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventFileAnswer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContactData(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
text: text
};
// Emit the message.
self.emit('signalFileAnswer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventNoAnswer', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
text: text
};
// Emit the message.
self.emit('signalNoAnswer', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventEndCall', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
text: text
};
// Emit the message.
self.emit('signalEndCall', argum);
});
// Signalling event.
this.webrtcadapter.on('signallingEventTypingMessage', function (text, signalling, arg) {
// Get the contact.
var contact = self.createContact(arg.contactUniqueID, arg.contactApplicationID);
var argum = {
contact: contact,
typing: arg.typing,
text: text
};
// Emit the message.
self.emit('signalTyping', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventICEStateChange', function (text, contact, arg) {
var argum = {
contact: contact,
state: arg,
text: text
};
// Emit the message.
self.emit('contactICEStateChange', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventRemoveStream', function (text, contact, arg) {
var argum = {
contact: contact,
remove: arg,
text: text
};
// Emit the message.
self.emit('contactRemoveStream', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventAddStream', function (text, contact, arg) {
var argum = {
contact: contact,
add: arg,
text: text
};
// Emit the message.
self.emit('contactAddStream', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventAddTrack', function (text, contact, arg) {
var argum = {
contact: contact,
add: arg,
text: text
};
// Emit the message.
self.emit('contactAddStream', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelReceivedSize', function (text, contact, arg) {
var argum = {
contact: contact,
size: arg,
text: text
};
// Emit the message.
self.emit('contactReceiveSize', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelReceiveComplete', function (text, contact, arg) {
var argum = {
contact: contact,
buffer: arg,
text: text
};
// Emit the message.
self.emit('contactReceiveComplete', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelOpen', function (text, contact, arg) {
var argum = {
contact: contact,
open: arg,
text: text
};
// Emit the message.
self.emit('contactReceiveOpen', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelClose', function (text, contact, arg) {
var argum = {
contact: contact,
close: arg,
text: text
};
// Emit the message.
self.emit('contactReceiveClose', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelError', function (text, contact, arg) {
var argum = {
contact: contact,
error: arg,
text: text
};
// Emit the message.
self.emit('contactReceiveError', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelSentSize', function (text, contact, arg) {
var argum = {
contact: contact,
size: arg,
text: text
};
// Emit the message.
self.emit('contactSentSize', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventDataChannelSentComplete', function (text, contact, arg) {
var argum = {
contact: contact,
buffer: arg,
text: text
};
// Emit the message.
self.emit('contactSentComplete', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventClose', function (text, contact, arg) {
var argum = {
contact: contact,
close: arg,
text: text
};
// Emit the message.
self.emit('contactClose', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactEventSessionError', function (text, contact, arg) {
var argum = {
contact: contact,
session: arg,
text: text
};
// Emit the message.
self.emit('contactSessionError', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactRecordingData', function (text, contact, arg) {
var argum = {
contact: contact,
data: arg,
text: text
};
// Emit the message.
self.emit('peerRecordingData', argum);
});
// Contact event.
this.webrtcadapter.on('peerContactRecordingStopped', function (text, contact, arg) {
var argum = {
contact: contact,
evt: arg,
text: text
};
// Emit the message.
self.emit('peerRecordingStopped', argum);
});
// Adapter event.
this.on('adapterRecordingData', function (text, adapter, arg) {
var argum = {
data: arg,
text: text
};
// Emit the message.
self.emit('recordingData', argum);
});
// Adapter event.
this.on('adapterRecordingStopped', function (text, adapter, arg) {
var argum = {
evt: arg,
text: text
};
// Emit the message.
self.emit('recordingStopped', argum);
});
}
/**
* WebRTC prototype constructor.
*/
WebRTC.prototype = Object.create(WildEmitter.prototype, {
constructor: {
value: WebRTC
}
});
/**
* Create a new contact if it does not exist, else return existing contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*
* @return {ContactPeer} Returns the contact.
*/
WebRTC.prototype.createContact = function (contactUniqueID, contactApplicationID) {
// Get the contact.
var contact = this.webrtcadapter.getContactPeer(contactUniqueID, contactApplicationID, false);
if (contact[0]) {
// Return the contact.
return contact[0];
}
else {
// Options.
var options = {
uniqueID: contactUniqueID,
applicationID: contactApplicationID,
isData: false
};
// Create a new contact.
contact = this.webrtcadapter.createContactPeer(options);
return contact;
}
};
/**
* Create a new data contact if it does not exist, else return existing contact.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*
* @return {ContactPeer} Returns the contact.
*/
WebRTC.prototype.createContactData = function (contactUniqueID, contactApplicationID) {
// Get the contact.
var contact = this.webrtcadapter.getContactPeer(contactUniqueID, contactApplicationID, true);
if (contact[0]) {
// Return the contact.
return contact[0];
}
else {
// Options.
var options = {
uniqueID: contactUniqueID,
applicationID: contactApplicationID,
isData: true
};
// Create a new contact.
contact = this.webrtcadapter.createContactPeer(options);
return contact;
}
};
/**
* Remove the contact if it exists.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
WebRTC.prototype.removeContact = function (contactUniqueID, contactApplicationID) {
// Get the contact.
var contact = this.webrtcadapter.getContactPeer(contactUniqueID, contactApplicationID, false);
if (contact[0]) {
// Remove contact.
this.webrtcadapter.removeContactPeer(contactUniqueID, contactApplicationID, false);
}
};
/**
* Remove the data contact if it exists.
*
* @param {string} contactUniqueID The contact unique id.
* @param {string} contactApplicationID The contact application id.
*/
WebRTC.prototype.removeContactData = function (contactUniqueID, contactApplicationID) {
// Get the contact.
var contact = this.webrtcadapter.getContactPeer(contactUniqueID, contactApplicationID, true);
if (contact[0]) {
// Remove contact.
this.webrtcadapter.removeContactPeer(contactUniqueID, contactApplicationID, true);
}
};
/**
* Is the contact in the contact list.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
*
* @return {boolean} True if the contact is in the list; else false.
*/
WebRTC.prototype.isContactPeer = function (contactUniqueID, contactApplicationID) {
// Get the contact.
var contact = this.webrtcadapter.isContactPeer(contactUniqueID, contactApplicationID);
if (contact[0]) {
// Found one.
return true;
}
else {
return false;
}
};
/**
* Close the webRTC interface.
*/
WebRTC.prototype.close = function () {
if (this.closed) return;
this.closed = true;
try {
// Close the interface.
this.webrtcadapter.close();
}
catch (e) {
// Log the error.
this.logger.error("Error closing the WebRTC interface: " + e);
}
};
/**
* Change client settings.
*
* @param {string} uniqueID The contact unique id.
* @param {string} applicationID The contact application id.
* @param {boolean} available True if this client is avaliable for contact; else false.
* @param {boolean} broadcast True if this client allows the unique id to be broadcast; else false.
* @param {boolean} broadcastAppID True if this client allows the application id to be broadcast; else false.
* @param {string} accessToken The access token.
*/
WebRTC.prototype.changeClientSettings = function (uniqueID, applicationID, available, broadcast, broadcastAppID, accessToken) {
// Change client settings
this.webrtcadapter.changeClientSettings(uniqueID, applicationID, available, broadcast, broadcastAppID, accessToken);
};
/**
* Create the local audio and video stream.
*
* @param {boolean} audio True to enable audio in local stream; else false.
* @param {boolean} video True to enable video in local stream; else false.
*/
WebRTC.prototype.createStream = function (audio, video) {
// Create stream.
this.webrtcadapter.createStream(audio, video);
}
/**
* Create the local media stream.
*
* @param {string} audioSource The audio source.
* @param {string} videoSource The video source.
*/
WebRTC.prototype.createStreamSource = function (audioSource, videoSource) {
// Create the constraint.
var constraints = {
audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
// Create stream.
this.webrtcadapter.createStreamEx(constraints);
}
/**
* Create a local capture media, screen or application window (Note only for Firefox).
*
* @param {string} captureMediaSource The capture media source ('screen' or 'window').
*/
WebRTC.prototype.createStreamCapture = function (captureMediaSource) {
// Create stream.
this.webrtcadapter.createStreamCapture(captureMediaSource);
}
/**
* Create the local media stream.
*
* @param {string} constraints The media constraints.
* @link https://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints
* @example
* qvga = video: {width: {exact: 320}, height: {exact: 240}}
* vga = video: {width: {exact: 640}, height: {exact: 480}}
* hd = video: {width: {exact: 1280}, height: {exact: 720}}
* fullHd =video: {width: {exact: 1920}, height: {exact: 1080}}
* fourK = video: {width: {exact: 4096}, height: {exact: 2160}}
*
* audio: {deviceId: audioSource ? {exact: audioSource} : undefined}
* video: {deviceId: videoSource ? {exact: videoSource} : undefined}
*/
WebRTC.prototype.createStreamEx = function (constraints) {
// Create stream.
this.webrtcadapter.createStreamEx(constraints);
}
/**
* Set the local video element.
*
* @param {object} videoElement The local video element.
*/
WebRTC.prototype.setLocalVideoElement = function (videoElement) {
// Assign the video element.
this.webrtcadapter.setLocalVideoElement(videoElement);
};
/**
* Get all audio input sources.
*
* @param {object} callback The callback function.
*/
WebRTC.prototype.getAudioInputSources = function (callback) {
// Get all devices
var deviceIndex = 1;
var sources = [];
// Get the device list.
this.webrtcadapter.getAudioInputDevices(function(devices) {
// For each device.
devices.forEach(function (device) {
var info = {
deviceID: device.deviceId,
deviceText: device.label || 'microphone ' + deviceIndex
};
// Add to source.
sources.push(info);
deviceIndex++;
});
// Send callback.
callback(sources);
});
}
/**
* Get all audio output sources.
*
* @param {object} callback The callback function.
*/
WebRTC.prototype.getAudioOutputSources = function (callback) {
// Get all devices
var deviceIndex = 1;
var sources = [];
// Get the device list.
this.webrtcadapter.getAudioOutputDevices(function(devices) {
// For each device.
devices.forEach(function (device) {
var info = {
deviceID: device.deviceId,
deviceText: device.label || 'speaker ' + deviceIndex
};
// Add to source.
sources.push(info);
deviceIndex++;
});
// Send callback.
callback(sources);
});
}
/**
* Get all video input sources.
*
* @param {object} callback The callback function.
*/
WebRTC.prototype.getVideoInputSources = function (callback) {
// Get all devices
var deviceIndex = 1;
var sources = [];
// Get the device list.
this.webrtcadapter.getVideoInputDevices(function(devices) {
// For each device.
devices.forEach(function (device) {
var info = {
deviceID: device.deviceId,
deviceText: device.label || 'camera ' + deviceIndex
};
// Add to source.
sources.push(info);
deviceIndex++;
});
// Send callback.
callback(sources);
});
}
/**
* Attach audio output device to video element using device/sink ID.
*
* @param {object} videoElement The video element.
* @param {string} deviceID The source device id.
*/
WebRTC.prototype.attachSinkIdVideoElement = function (videoElement, deviceID) {
// If no sink id applied.
if (typeof videoElement.sinkId !== 'undefined') {
// Set the device ID.
videoElement.setSinkId(deviceID)
.then(function() {
// Success.
})
.catch(function(e) {
// Log the error.
this.logger.error("Error assigning device ID: " + e);
});
}
else {
this.logger.error("Browser does not support output device selection.");
}
};
/**
* Close the local stream.
*/
WebRTC.prototype.closeStream = function () {
// Close stream.
this.webrtcadapter.closeStream();
};
// Export the prototype.
module.exports = WebRTC;
},{"./webrtcadapter":3,"localmedia":8,"mockconsole":10,"util":20,"webrtcsupport":21,"wildemitter":22}],5:[function(require,module,exports){
var WildEmitter = require('wildemitter');
var util = require('util');
function Sender(opts) {
WildEmitter.call(this);
var options = opts || {};
this.config = {
chunksize: 16384,
pacing: 0
};
// set our config from options
var item;
for (item in options) {
this.config[item] = options[item];
}
this.file = null;
this.channel = null;
}
util.inherits(Sender, WildEmitter);
Sender.prototype.send = function (file, channel) {
var self = this;
this.file = file;
this.channel = channel;
var usePoll = typeof channel.bufferedAmountLowThreshold !== 'number';
var offset = 0;
var sliceFile = function() {
var reader = new window.FileReader();
reader.onload = (function() {
return function(e) {
self.channel.send(e.target.result);
self.emit('progress', offset, file.size, e.target.result);
if (file.size > offset + e.target.result.byteLength) {
if (usePoll) {
window.setTimeout(sliceFile, self.config.pacing);
} else if (channel.bufferedAmount <= channel.bufferedAmountLowThreshold) {
window.setTimeout(sliceFile, 0);
} else {
// wait for bufferedAmountLow to fire
}
} else {
self.emit('progress', file.size, file.size, null);
self.emit('sentFile');
}
offset = offset + self.config.chunksize;
};
})(file);
var slice = file.slice(offset, offset + self.config.chunksize);
reader.readAsArrayBuffer(slice);
};
if (!usePoll) {
channel.bufferedAmountLowThreshold = 8 * this.config.chunksize;
channel.addEventListener('bufferedamountlow', sliceFile);
}
window.setTimeout(sliceFile, 0);
};
function Receiver() {
WildEmitter.call(this);
this.receiveBuffer = [];
this.received = 0;
this.metadata = {};
this.channel = null;
}
util.inherits(Receiver, WildEmitter);
Receiver.prototype.receive = function (metadata, channel) {
var self = this;
if (metadata) {
this.metadata = metadata;
}
this.channel = channel;
// chrome only supports arraybuffers and those make it easier to calc the hash
channel.binaryType = 'arraybuffer';
this.channel.onmessage = function (event) {
var len = event.data.byteLength;
self.received += len;
self.receiveBuffer.push(event.data);
self.emit('progress', self.received, self.metadata.size, event.data);
if (self.received === self.metadata.size) {
self.emit('receivedFile', new window.Blob(self.receiveBuffer), self.metadata);
self.receiveBuffer = []; // discard receivebuffer
} else if (self.received > self.metadata.size) {
// FIXME
console.error('received more than expected, discarding...');
self.receiveBuffer = []; // just discard...
}
};
};
module.exports = {};
module.exports.support = typeof window !== 'undefined' && window && window.File && window.FileReader && window.Blob;
module.exports.Sender = Sender;
module.exports.Receiver = Receiver;
},{"util":20,"wildemitter":22}],6:[function(require,module,exports){
// cache for constraints and callback
var cache = {};
module.exports = function (constraints, cb) {
var hasConstraints = arguments.length === 2;
var callback = hasConstraints ? cb : constraints;
var error;
if (typeof window === 'undefined' || window.location.protocol === 'http:') {
error = new Error('NavigatorUserMediaError');
error.name = 'HTTPS_REQUIRED';
return callback(error);
}
if (window.navigator.userAgent.match('Chrome')) {
var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
var maxver = 33;
var isCef = !window.chrome.webstore;
// "known" crash in chrome 34 and 35 on linux
if (window.navigator.userAgent.match('Linux')) maxver = 35;
// check that the extension is installed by looking for a
// sessionStorage variable that contains the extension id
// this has to be set after installation unless the contest
// script does that
if (sessionStorage.getScreenMediaJSExtensionId) {
chrome.runtime.sendMessage(sessionStorage.getScreenMediaJSExtensionId,
{type:'getScreen', id: 1}, null,
function (data) {
if (!data || data.sourceId === '') { // user canceled
var error = new Error('NavigatorUserMediaError');
error.name = 'NotAllowedError';
callback(error);
} else {
constraints = (hasConstraints && constraints) || {audio: false, video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 3
}
}};
constraints.video.mandatory.chromeMediaSourceId = data.sourceId;
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
}
}
);
} else if (window.cefGetScreenMedia) {
//window.cefGetScreenMedia is experimental - may be removed without notice
window.cefGetScreenMedia(function(sourceId) {
if (!sourceId) {
var error = new Error('cefGetScreenMediaError');
error.name = 'CEF_GETSCREENMEDIA_CANCELED';
callback(error);
} else {
constraints = (hasConstraints && constraints) || {audio: false, video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 3
},
optional: [
{googLeakyBucket: true},
{googTemporalLayeredScreencast: true}
]
}};
constraints.video.mandatory.chromeMediaSourceId = sourceId;
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
}
});
} else if (isCef || (chromever >= 26 && chromever <= maxver)) {
// chrome 26 - chrome 33 way to do it -- requires bad chrome://flags
// note: this is basically in maintenance mode and will go away soon
constraints = (hasConstraints && constraints) || {
video: {
mandatory: {
googLeakyBucket: true,
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 3,
chromeMediaSource: 'screen'
}
}
};
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
} else {
// chrome 34+ way requiring an extension
var pending = window.setTimeout(function () {
error = new Error('NavigatorUserMediaError');
error.name = 'EXTENSION_UNAVAILABLE';
return callback(error);
}, 1000);
cache[pending] = [callback, hasConstraints ? constraints : null];
window.postMessage({ type: 'getScreen', id: pending }, '*');
}
} else if (window.navigator.userAgent.match('Firefox')) {
var ffver = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
if (ffver >= 33) {
constraints = (hasConstraints && constraints) || {
video: {
mozMediaSource: 'window',
mediaSource: 'window'
}
};
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
var lastTime = stream.currentTime;
var polly = window.setInterval(function () {
if (!stream) window.clearInterval(polly);
if (stream.currentTime == lastTime) {
window.clearInterval(polly);
if (stream.onended) {
stream.onended();
}
}
lastTime = stream.currentTime;
}, 500);
}).catch(function (err) {
callback(err);
});
} else {
error = new Error('NavigatorUserMediaError');
error.name = 'EXTENSION_UNAVAILABLE'; // does not make much sense but...
}
}
};
typeof window !== 'undefined' && window.addEventListener('message', function (event) {
if (event.origin != window.location.origin) {
return;
}
if (event.data.type == 'gotScreen' && cache[event.data.id]) {
var data = cache[event.data.id];
var constraints = data[1];
var callback = data[0];
delete cache[event.data.id];
if (event.data.sourceId === '') { // user canceled
var error = new Error('NavigatorUserMediaError');
error.name = 'NotAllowedError';
callback(error);
} else {
constraints = constraints || {audio: false, video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 3
},
optional: [
{googLeakyBucket: true},
{googTemporalLayeredScreencast: true}
]
}};
constraints.video.mandatory.chromeMediaSourceId = event.data.sourceId;
window.navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
callback(null, stream);
}).catch(function (err) {
callback(err);
});
}
} else if (event.data.type == 'getScreenPending') {
window.clearTimeout(event.data.id);
}
});
},{}],7:[function(require,module,exports){
var WildEmitter = require('wildemitter');
function getMaxVolume (analyser, fftBins) {
var maxVolume = -Infinity;
analyser.getFloatFrequencyData(fftBins);
for(var i=4, ii=fftBins.length; i < ii; i++) {
if (fftBins[i] > maxVolume && fftBins[i] < 0) {
maxVolume = fftBins[i];
}
};
return maxVolume;
}
var audioContextType;
if (typeof window !== 'undefined') {
audioContextType = window.AudioContext || window.webkitAudioContext;
}
// use a single audio context due to hardware limits
var audioContext = null;
module.exports = function(stream, options) {
var harker = new WildEmitter();
// make it not break in non-supported browsers
if (!audioContextType) return harker;
//Config
var options = options || {},
smoothing = (options.smoothing || 0.1),
interval = (options.interval || 50),
threshold = options.threshold,
play = options.play,
history = options.history || 10,
running = true;
//Setup Audio Context
if (!audioContext) {
audioContext = new audioContextType();
}
var sourceNode, fftBins, analyser;
analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
analyser.smoothingTimeConstant = smoothing;
fftBins = new Float32Array(analyser.frequencyBinCount);
if (stream.jquery) stream = stream[0];
if (stream instanceof HTMLAudioElement || stream instanceof HTMLVideoElement) {
//Audio Tag
sourceNode = audioContext.createMediaElementSource(stream);
if (typeof play === 'undefined') play = true;
threshold = threshold || -50;
} else {
//WebRTC Stream
sourceNode = audioContext.createMediaStreamSource(stream);
threshold = threshold || -50;
}
sourceNode.connect(analyser);
if (play) analyser.connect(audioContext.destination);
harker.speaking = false;
harker.setThreshold = function(t) {
threshold = t;
};
harker.setInterval = function(i) {
interval = i;
};
harker.stop = function() {
running = false;
harker.emit('volume_change', -100, threshold);
if (harker.speaking) {
harker.speaking = false;
harker.emit('stopped_speaking');
}
analyser.disconnect();
sourceNode.disconnect();
};
harker.speakingHistory = [];
for (var i = 0; i < history; i++) {
harker.speakingHistory.push(0);
}
// Poll the analyser node to determine if speaking
// and emit events if changed
var looper = function() {
setTimeout(function() {
//check if stop has been called
if(!running) {
return;
}
var currentVolume = getMaxVolume(analyser, fftBins);
harker.emit('volume_change', currentVolume, threshold);
var history = 0;
if (currentVolume > threshold && !harker.speaking) {
// trigger quickly, short history
for (var i = harker.speakingHistory.length - 3; i < harker.speakingHistory.length; i++) {
history += harker.speakingHistory[i];
}
if (history >= 2) {
harker.speaking = true;
harker.emit('speaking');
}
} else if (currentVolume < threshold && harker.speaking) {
for (var i = 0; i < harker.speakingHistory.length; i++) {
history += harker.speakingHistory[i];
}
if (history == 0) {
harker.speaking = false;
harker.emit('stopped_speaking');
}
}
harker.speakingHistory.shift();
harker.speakingHistory.push(0 + (currentVolume > threshold));
looper();
}, interval);
};
looper();
return harker;
}
},{"wildemitter":22}],8:[function(require,module,exports){
var util = require('util');
var hark = require('hark');
var getScreenMedia = require('getscreenmedia');
var WildEmitter = require('wildemitter');
var mockconsole = require('mockconsole');
function isAllTracksEnded(stream) {
var isAllTracksEnded = true;
stream.getTracks().forEach(function (t) {
isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded;
});
return isAllTracksEnded;
}
function shouldWorkAroundFirefoxStopStream() {
if (typeof window === 'undefined') {
return false;
}
if (!window.navigator.mozGetUserMedia) {
return false;
}
var match = window.navigator.userAgent.match(/Firefox\/(\d+)\./);
var version = match && match.length >= 1 && parseInt(match[1], 10);
return version < 50;
}
function LocalMedia(opts) {
WildEmitter.call(this);
var config = this.config = {
detectSpeakingEvents: false,
audioFallback: false,
media: {
audio: true,
video: true
},
harkOptions: null,
logger: mockconsole
};
var item;
for (item in opts) {
if (opts.hasOwnProperty(item)) {
this.config[item] = opts[item];
}
}
this.logger = config.logger;
this._log = this.logger.log.bind(this.logger, 'LocalMedia:');
this._logerror = this.logger.error.bind(this.logger, 'LocalMedia:');
this.localStreams = [];
this.localScreens = [];
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
this._logerror('Your browser does not support local media capture.');
}
this._audioMonitors = [];
this.on('localStreamStopped', this._stopAudioMonitor.bind(this));
this.on('localScreenStopped', this._stopAudioMonitor.bind(this));
}
util.inherits(LocalMedia, WildEmitter);
LocalMedia.prototype.start = function (mediaConstraints, cb) {
var self = this;
var constraints = mediaConstraints || this.config.media;
this.emit('localStreamRequested', constraints);
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
if (constraints.audio && self.config.detectSpeakingEvents) {
self._setupAudioMonitor(stream, self.config.harkOptions);
}
self.localStreams.push(stream);
stream.getTracks().forEach(function (track) {
track.addEventListener('ended', function () {
if (isAllTracksEnded(stream)) {
self._removeStream(stream);
}
});
});
self.emit('localStream', stream);
if (cb) {
return cb(null, stream);
}
}).catch(function (err) {
// Fallback for users without a camera
if (self.config.audioFallback && err.name === 'NotFoundError' && constraints.video !== false) {
constraints.video = false;
self.start(constraints, cb);
return;
}
self.emit('localStreamRequestFailed', constraints);
if (cb) {
return cb(err, null);
}
});
};
LocalMedia.prototype.stop = function (stream) {
this.stopStream(stream);
this.stopScreenShare(stream);
};
LocalMedia.prototype.stopStream = function (stream) {
var self = this;
if (stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
stream.getTracks().forEach(function (track) { track.stop(); });
//Half-working fix for Firefox, see: https://bugzilla.mozilla.org/show_bug.cgi?id=1208373
if (shouldWorkAroundFirefoxStopStream()) {
this._removeStream(stream);
}
}
} else {
this.localStreams.forEach(function (stream) {
stream.getTracks().forEach(function (track) { track.stop(); });
//Half-working fix for Firefox, see: https://bugzilla.mozilla.org/show_bug.cgi?id=1208373
if (shouldWorkAroundFirefoxStopStream()) {
self._removeStream(stream);
}
});
}
};
LocalMedia.prototype.startScreenShare = function (constraints, cb) {
var self = this;
this.emit('localScreenRequested');
if (typeof constraints === 'function' && !cb) {
cb = constraints;
constraints = null;
}
getScreenMedia(constraints, function (err, stream) {
if (!err) {
self.localScreens.push(stream);
stream.getTracks().forEach(function (track) {
track.addEventListener('ended', function () {
var isAllTracksEnded = true;
stream.getTracks().forEach(function (t) {
isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded;
});
if (isAllTracksEnded) {
self._removeStream(stream);
}
});
});
self.emit('localScreen', stream);
} else {
self.emit('localScreenRequestFailed');
}
// enable the callback
if (cb) {
return cb(err, stream);
}
});
};
LocalMedia.prototype.stopScreenShare = function (stream) {
var self = this;
if (stream) {
var idx = this.localScreens.indexOf(stream);
if (idx > -1) {
stream.getTracks().forEach(function (track) { track.stop(); });
//Half-working fix for Firefox, see: https://bugzilla.mozilla.org/show_bug.cgi?id=1208373
if (shouldWorkAroundFirefoxStopStream()) {
this._removeStream(stream);
}
}
} else {
this.localScreens.forEach(function (stream) {
stream.getTracks().forEach(function (track) { track.stop(); });
//Half-working fix for Firefox, see: https://bugzilla.mozilla.org/show_bug.cgi?id=1208373
if (shouldWorkAroundFirefoxStopStream()) {
self._removeStream(stream);
}
});
}
};
// Audio controls
LocalMedia.prototype.mute = function () {
this._audioEnabled(false);
this.emit('audioOff');
};
LocalMedia.prototype.unmute = function () {
this._audioEnabled(true);
this.emit('audioOn');
};
// Video controls
LocalMedia.prototype.pauseVideo = function () {
this._videoEnabled(false);
this.emit('videoOff');
};
LocalMedia.prototype.resumeVideo = function () {
this._videoEnabled(true);
this.emit('videoOn');
};
// Combined controls
LocalMedia.prototype.pause = function () {
this.mute();
this.pauseVideo();
};
LocalMedia.prototype.resume = function () {
this.unmute();
this.resumeVideo();
};
// Internal methods for enabling/disabling audio/video
LocalMedia.prototype._audioEnabled = function (bool) {
this.localStreams.forEach(function (stream) {
stream.getAudioTracks().forEach(function (track) {
track.enabled = !!bool;
});
});
};
LocalMedia.prototype._videoEnabled = function (bool) {
this.localStreams.forEach(function (stream) {
stream.getVideoTracks().forEach(function (track) {
track.enabled = !!bool;
});
});
};
// check if all audio streams are enabled
LocalMedia.prototype.isAudioEnabled = function () {
var enabled = true;
this.localStreams.forEach(function (stream) {
stream.getAudioTracks().forEach(function (track) {
enabled = enabled && track.enabled;
});
});
return enabled;
};
// check if all video streams are enabled
LocalMedia.prototype.isVideoEnabled = function () {
var enabled = true;
this.localStreams.forEach(function (stream) {
stream.getVideoTracks().forEach(function (track) {
enabled = enabled && track.enabled;
});
});
return enabled;
};
LocalMedia.prototype._removeStream = function (stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
this.localStreams.splice(idx, 1);
this.emit('localStreamStopped', stream);
} else {
idx = this.localScreens.indexOf(stream);
if (idx > -1) {
this.localScreens.splice(idx, 1);
this.emit('localScreenStopped', stream);
}
}
};
LocalMedia.prototype._setupAudioMonitor = function (stream, harkOptions) {
this._log('Setup audio');
var audio = hark(stream, harkOptions);
var self = this;
var timeout;
audio.on('speaking', function () {
self.emit('speaking');
});
audio.on('stopped_speaking', function () {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
self.emit('stoppedSpeaking');
}, 1000);
});
audio.on('volume_change', function (volume, threshold) {
self.emit('volumeChange', volume, threshold);
});
this._audioMonitors.push({audio: audio, stream: stream});
};
LocalMedia.prototype._stopAudioMonitor = function (stream) {
var idx = -1;
this._audioMonitors.forEach(function (monitors, i) {
if (monitors.stream === stream) {
idx = i;
}
});
if (idx > -1) {
this._audioMonitors[idx].audio.stop();
this._audioMonitors.splice(idx, 1);
}
};
module.exports = LocalMedia;
},{"getscreenmedia":6,"hark":7,"mockconsole":10,"util":20,"wildemitter":22}],9:[function(require,module,exports){
(function (global){
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array ? array.length : 0;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array ? array.length : 0;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeKeys = overArg(Object.keys, Object);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
return this.has(key) && delete this.__data__[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
return getMapData(this, key)['delete'](key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
getMapData(this, key).set(key, value);
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
this.__data__ = new ListCache(entries);
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
return this.__data__['delete'](key);
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var cache = this.__data__;
if (cache instanceof ListCache) {
var pairs = cache.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
return this;
}
cache = this.__data__ = new MapCache(pairs);
}
cache.set(key, value);
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
// Safari 9 makes `arguments.length` enumerable in strict mode.
var result = (isArray(value) || isArguments(value))
? baseTimes(value.length, String)
: [];
var length = result.length,
skipIndexes = !!length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (key == 'length' || isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
object[key] = value;
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {boolean} [isFull] Specify a clone including symbols.
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
var result;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
if (isHostObject(value)) {
return object ? value : {};
}
result = initCloneObject(isFunc ? {} : value);
if (!isDeep) {
return copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (!isArr) {
var props = isFull ? getAllKeys(value) : keys(value);
}
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
function baseCreate(proto) {
return isObject(proto) ? objectCreate(proto) : {};
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
return objectToString.call(value);
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var result = new buffer.constructor(buffer.length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
assignValue(object, key, newValue === undefined ? source[key] : newValue);
}
return object;
}
/**
* Copies own symbol properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* Creates an array of the own enumerable symbol properties of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge < 14, and promises in Node.js.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = objectToString.call(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : undefined;
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, true, true);
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = cloneDeep;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],10:[function(require,module,exports){
var methods = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(",");
var l = methods.length;
var fn = function () {};
var mockconsole = {};
while (l--) {
mockconsole[methods[l]] = fn;
}
module.exports = mockconsole;
},{}],11:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],12:[function(require,module,exports){
var util = require('util');
var SJJ = require('sdp-jingle-json');
var WildEmitter = require('wildemitter');
var cloneDeep = require('lodash.clonedeep');
function PeerConnection(config, constraints) {
var self = this;
var item;
WildEmitter.call(this);
config = config || {};
config.iceServers = config.iceServers || [];
// make sure this only gets enabled in Google Chrome
// EXPERIMENTAL FLAG, might get removed without notice
this.enableChromeNativeSimulcast = false;
if (constraints && constraints.optional && window.chrome &&
navigator.appVersion.match(/Chromium\//) === null) {
constraints.optional.forEach(function (constraint) {
if (constraint.enableChromeNativeSimulcast) {
self.enableChromeNativeSimulcast = true;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
this.enableMultiStreamHacks = false;
if (constraints && constraints.optional && window.chrome) {
constraints.optional.forEach(function (constraint) {
if (constraint.enableMultiStreamHacks) {
self.enableMultiStreamHacks = true;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
this.restrictBandwidth = 0;
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetRestrictBandwidth) {
self.restrictBandwidth = constraint.andyetRestrictBandwidth;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
// bundle up ice candidates, only works for jingle mode
// number > 0 is the delay to wait for additional candidates
// ~20ms seems good
this.batchIceCandidates = 0;
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetBatchIce) {
self.batchIceCandidates = constraint.andyetBatchIce;
}
});
}
this.batchedIceCandidates = [];
// EXPERIMENTAL FLAG, might get removed without notice
// this attemps to strip out candidates with an already known foundation
// and type -- i.e. those which are gathered via the same TURN server
// but different transports (TURN udp, tcp and tls respectively)
if (constraints && constraints.optional && window.chrome) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetFasterICE) {
self.eliminateDuplicateCandidates = constraint.andyetFasterICE;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
// when using a server such as the jitsi videobridge we don't need to signal
// our candidates
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetDontSignalCandidates) {
self.dontSignalCandidates = constraint.andyetDontSignalCandidates;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
this.assumeSetLocalSuccess = false;
if (constraints && constraints.optional) {
constraints.optional.forEach(function (constraint) {
if (constraint.andyetAssumeSetLocalSuccess) {
self.assumeSetLocalSuccess = constraint.andyetAssumeSetLocalSuccess;
}
});
}
// EXPERIMENTAL FLAG, might get removed without notice
// working around https://bugzilla.mozilla.org/show_bug.cgi?id=1087551
// pass in a timeout for this
if (window.navigator.mozGetUserMedia) {
if (constraints && constraints.optional) {
this.wtFirefox = 0;
constraints.optional.forEach(function (constraint) {
if (constraint.andyetFirefoxMakesMeSad) {
self.wtFirefox = constraint.andyetFirefoxMakesMeSad;
if (self.wtFirefox > 0) {
self.firefoxcandidatebuffer = [];
}
}
});
}
}
this.pc = new RTCPeerConnection(config, constraints);
if (typeof this.pc.getLocalStreams === 'function') {
this.getLocalStreams = this.pc.getLocalStreams.bind(this.pc);
} else {
this.getLocalStreams = function () {
return [];
};
}
if (typeof this.pc.getSenders === 'function') {
this.getSenders = this.pc.getSenders.bind(this.pc);
} else {
this.getSenders = function () {
return [];
};
}
if (typeof this.pc.getRemoteStreams === 'function') {
this.getRemoteStreams = this.pc.getRemoteStreams.bind(this.pc);
} else {
this.getRemoteStreams = function () {
return [];
};
}
if (typeof this.pc.getReceivers === 'function') {
this.getReceivers = this.pc.getReceivers.bind(this.pc);
} else {
this.getReceivers = function () {
return [];
};
}
this.addStream = this.pc.addStream.bind(this.pc);
this.removeStream = function (stream) {
if (typeof self.pc.removeStream === 'function') {
self.pc.removeStream.apply(self.pc, arguments);
} else if (typeof self.pc.removeTrack === 'function') {
stream.getTracks().forEach(function (track) {
self.pc.removeTrack(track);
});
}
};
if (typeof this.pc.removeTrack === 'function') {
this.removeTrack = this.pc.removeTrack.bind(this.pc);
}
// proxy some events directly
this.pc.onremovestream = this.emit.bind(this, 'removeStream');
this.pc.onremovetrack = this.emit.bind(this, 'removeTrack');
this.pc.onaddstream = this.emit.bind(this, 'addStream');
this.pc.onnegotiationneeded = this.emit.bind(this, 'negotiationNeeded');
this.pc.oniceconnectionstatechange = this.emit.bind(this, 'iceConnectionStateChange');
this.pc.onsignalingstatechange = this.emit.bind(this, 'signalingStateChange');
// handle ice candidate and data channel events
this.pc.onicecandidate = this._onIce.bind(this);
this.pc.ondatachannel = this._onDataChannel.bind(this);
this.localDescription = {
contents: []
};
this.remoteDescription = {
contents: []
};
this.config = {
debug: false,
sid: '',
isInitiator: true,
sdpSessionID: Date.now(),
useJingle: false
};
this.iceCredentials = {
local: {},
remote: {}
};
// apply our config
for (item in config) {
this.config[item] = config[item];
}
if (this.config.debug) {
this.on('*', function () {
var logger = config.logger || console;
logger.log('PeerConnection event:', arguments);
});
}
this.hadLocalStunCandidate = false;
this.hadRemoteStunCandidate = false;
this.hadLocalRelayCandidate = false;
this.hadRemoteRelayCandidate = false;
this.hadLocalIPv6Candidate = false;
this.hadRemoteIPv6Candidate = false;
// keeping references for all our data channels
// so they dont get garbage collected
// can be removed once the following bugs have been fixed
// https://crbug.com/405545
// https://bugzilla.mozilla.org/show_bug.cgi?id=964092
// to be filed for opera
this._remoteDataChannels = [];
this._localDataChannels = [];
this._candidateBuffer = [];
}
util.inherits(PeerConnection, WildEmitter);
Object.defineProperty(PeerConnection.prototype, 'signalingState', {
get: function () {
return this.pc.signalingState;
}
});
Object.defineProperty(PeerConnection.prototype, 'iceConnectionState', {
get: function () {
return this.pc.iceConnectionState;
}
});
PeerConnection.prototype._role = function () {
return this.isInitiator ? 'initiator' : 'responder';
};
// Add a stream to the peer connection object
PeerConnection.prototype.addStream = function (stream) {
this.localStream = stream;
this.pc.addStream(stream);
};
// helper function to check if a remote candidate is a stun/relay
// candidate or an ipv6 candidate
PeerConnection.prototype._checkLocalCandidate = function (candidate) {
var cand = SJJ.toCandidateJSON(candidate);
if (cand.type == 'srflx') {
this.hadLocalStunCandidate = true;
} else if (cand.type == 'relay') {
this.hadLocalRelayCandidate = true;
}
if (cand.ip.indexOf(':') != -1) {
this.hadLocalIPv6Candidate = true;
}
};
// helper function to check if a remote candidate is a stun/relay
// candidate or an ipv6 candidate
PeerConnection.prototype._checkRemoteCandidate = function (candidate) {
var cand = SJJ.toCandidateJSON(candidate);
if (cand.type == 'srflx') {
this.hadRemoteStunCandidate = true;
} else if (cand.type == 'relay') {
this.hadRemoteRelayCandidate = true;
}
if (cand.ip.indexOf(':') != -1) {
this.hadRemoteIPv6Candidate = true;
}
};
// Init and add ice candidate object with correct constructor
PeerConnection.prototype.processIce = function (update, cb) {
cb = cb || function () {};
var self = this;
// ignore any added ice candidates to avoid errors. why does the
// spec not do this?
if (this.pc.signalingState === 'closed') return cb();
if (update.contents || (update.jingle && update.jingle.contents)) {
var contentNames = this.remoteDescription.contents.map(function (c) { return c.name; });
var contents = update.contents || update.jingle.contents;
contents.forEach(function (content) {
var transport = content.transport || {};
var candidates = transport.candidates || [];
var mline = contentNames.indexOf(content.name);
var mid = content.name;
var remoteContent = self.remoteDescription.contents.find(function (c) {
return c.name === content.name;
});
// process candidates as a callback, in case we need to
// update ufrag and pwd with offer/answer
var processCandidates = function () {
candidates.forEach(
function (candidate) {
var iceCandidate = SJJ.toCandidateSDP(candidate);
self.pc.addIceCandidate(
new RTCIceCandidate({
candidate: iceCandidate,
sdpMLineIndex: mline,
sdpMid: mid
}), function () {
// well, this success callback is pretty meaningless
},
function (err) {
self.emit('error', err);
}
);
self._checkRemoteCandidate(iceCandidate);
});
cb();
};
if (self.iceCredentials.remote[content.name] && transport.ufrag &&
self.iceCredentials.remote[content.name].ufrag !== transport.ufrag) {
if (remoteContent) {
remoteContent.transport.ufrag = transport.ufrag;
remoteContent.transport.pwd = transport.pwd;
var offer = {
type: 'offer',
jingle: self.remoteDescription
};
offer.sdp = SJJ.toSessionSDP(offer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'incoming'
});
self.pc.setRemoteDescription(new RTCSessionDescription(offer),
function () {
processCandidates();
},
function (err) {
self.emit('error', err);
}
);
} else {
self.emit('error', 'ice restart failed to find matching content');
}
} else {
processCandidates();
}
});
} else {
// working around https://code.google.com/p/webrtc/issues/detail?id=3669
if (update.candidate && update.candidate.candidate.indexOf('a=') !== 0) {
update.candidate.candidate = 'a=' + update.candidate.candidate;
}
if (this.wtFirefox && this.firefoxcandidatebuffer !== null) {
// we cant add this yet due to https://bugzilla.mozilla.org/show_bug.cgi?id=1087551
if (this.pc.localDescription && this.pc.localDescription.type === 'offer') {
this.firefoxcandidatebuffer.push(update.candidate);
return cb();
}
}
self.pc.addIceCandidate(
new RTCIceCandidate(update.candidate),
function () { },
function (err) {
self.emit('error', err);
}
);
self._checkRemoteCandidate(update.candidate.candidate);
cb();
}
};
// Generate and emit an offer with the given constraints
PeerConnection.prototype.offer = function (constraints, cb) {
var self = this;
var hasConstraints = arguments.length === 2;
var mediaConstraints = hasConstraints && constraints ? constraints : {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
};
cb = hasConstraints ? cb : constraints;
cb = cb || function () {};
if (this.pc.signalingState === 'closed') return cb('Already closed');
// Actually generate the offer
this.pc.createOffer(
function (offer) {
// does not work for jingle, but jingle.js doesn't need
// this hack...
var expandedOffer = {
type: 'offer',
sdp: offer.sdp
};
if (self.assumeSetLocalSuccess) {
self.emit('offer', expandedOffer);
cb(null, expandedOffer);
}
self._candidateBuffer = [];
self.pc.setLocalDescription(offer,
function () {
var jingle;
if (self.config.useJingle) {
jingle = SJJ.toSessionJSON(offer.sdp, {
role: self._role(),
direction: 'outgoing'
});
jingle.sid = self.config.sid;
self.localDescription = jingle;
// Save ICE credentials
jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.local[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
expandedOffer.jingle = jingle;
}
expandedOffer.sdp.split('\r\n').forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkLocalCandidate(line);
}
});
if (!self.assumeSetLocalSuccess) {
self.emit('offer', expandedOffer);
cb(null, expandedOffer);
}
},
function (err) {
self.emit('error', err);
cb(err);
}
);
},
function (err) {
self.emit('error', err);
cb(err);
},
mediaConstraints
);
};
// Process an incoming offer so that ICE may proceed before deciding
// to answer the request.
PeerConnection.prototype.handleOffer = function (offer, cb) {
cb = cb || function () {};
var self = this;
offer.type = 'offer';
if (offer.jingle) {
if (this.enableChromeNativeSimulcast) {
offer.jingle.contents.forEach(function (content) {
if (content.name === 'video') {
content.application.googConferenceFlag = true;
}
});
}
if (this.enableMultiStreamHacks) {
// add a mixed video stream as first stream
offer.jingle.contents.forEach(function (content) {
if (content.name === 'video') {
var sources = content.application.sources || [];
if (sources.length === 0 || sources[0].ssrc !== "3735928559") {
sources.unshift({
ssrc: "3735928559", // 0xdeadbeef
parameters: [
{
key: "cname",
value: "deadbeef"
},
{
key: "msid",
value: "mixyourfecintothis please"
}
]
});
content.application.sources = sources;
}
}
});
}
if (self.restrictBandwidth > 0) {
if (offer.jingle.contents.length >= 2 && offer.jingle.contents[1].name === 'video') {
var content = offer.jingle.contents[1];
var hasBw = content.application && content.application.bandwidth && content.application.bandwidth.bandwidth;
if (!hasBw) {
offer.jingle.contents[1].application.bandwidth = { type: 'AS', bandwidth: self.restrictBandwidth.toString() };
offer.sdp = SJJ.toSessionSDP(offer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'outgoing'
});
}
}
}
// Save ICE credentials
offer.jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.remote[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
offer.sdp = SJJ.toSessionSDP(offer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'incoming'
});
self.remoteDescription = offer.jingle;
}
offer.sdp.split('\r\n').forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkRemoteCandidate(line);
}
});
self.pc.setRemoteDescription(new RTCSessionDescription(offer),
function () {
cb();
},
cb
);
};
// Answer an offer with audio only
PeerConnection.prototype.answerAudioOnly = function (cb) {
var mediaConstraints = {
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: false
}
};
this._answer(mediaConstraints, cb);
};
// Answer an offer without offering to recieve
PeerConnection.prototype.answerBroadcastOnly = function (cb) {
var mediaConstraints = {
mandatory: {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
}
};
this._answer(mediaConstraints, cb);
};
// Answer an offer with given constraints default is audio/video
PeerConnection.prototype.answer = function (constraints, cb) {
var hasConstraints = arguments.length === 2;
var callback = hasConstraints ? cb : constraints;
var mediaConstraints = hasConstraints && constraints ? constraints : {
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
}
};
this._answer(mediaConstraints, callback);
};
// Process an answer
PeerConnection.prototype.handleAnswer = function (answer, cb) {
cb = cb || function () {};
var self = this;
if (answer.jingle) {
answer.sdp = SJJ.toSessionSDP(answer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'incoming'
});
self.remoteDescription = answer.jingle;
// Save ICE credentials
answer.jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.remote[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
}
answer.sdp.split('\r\n').forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkRemoteCandidate(line);
}
});
self.pc.setRemoteDescription(
new RTCSessionDescription(answer),
function () {
if (self.wtFirefox) {
window.setTimeout(function () {
self.firefoxcandidatebuffer.forEach(function (candidate) {
// add candidates later
self.pc.addIceCandidate(
new RTCIceCandidate(candidate),
function () { },
function (err) {
self.emit('error', err);
}
);
self._checkRemoteCandidate(candidate.candidate);
});
self.firefoxcandidatebuffer = null;
}, self.wtFirefox);
}
cb(null);
},
cb
);
};
// Close the peer connection
PeerConnection.prototype.close = function () {
this.pc.close();
this._localDataChannels = [];
this._remoteDataChannels = [];
this.emit('close');
};
// Internal code sharing for various types of answer methods
PeerConnection.prototype._answer = function (constraints, cb) {
cb = cb || function () {};
var self = this;
if (!this.pc.remoteDescription) {
// the old API is used, call handleOffer
throw new Error('remoteDescription not set');
}
if (this.pc.signalingState === 'closed') return cb('Already closed');
self.pc.createAnswer(
function (answer) {
var sim = [];
if (self.enableChromeNativeSimulcast) {
// native simulcast part 1: add another SSRC
answer.jingle = SJJ.toSessionJSON(answer.sdp, {
role: self._role(),
direction: 'outgoing'
});
if (answer.jingle.contents.length >= 2 && answer.jingle.contents[1].name === 'video') {
var groups = answer.jingle.contents[1].application.sourceGroups || [];
var hasSim = false;
groups.forEach(function (group) {
if (group.semantics == 'SIM') hasSim = true;
});
if (!hasSim &&
answer.jingle.contents[1].application.sources.length) {
var newssrc = JSON.parse(JSON.stringify(answer.jingle.contents[1].application.sources[0]));
newssrc.ssrc = '' + Math.floor(Math.random() * 0xffffffff); // FIXME: look for conflicts
answer.jingle.contents[1].application.sources.push(newssrc);
sim.push(answer.jingle.contents[1].application.sources[0].ssrc);
sim.push(newssrc.ssrc);
groups.push({
semantics: 'SIM',
sources: sim
});
// also create an RTX one for the SIM one
var rtxssrc = JSON.parse(JSON.stringify(newssrc));
rtxssrc.ssrc = '' + Math.floor(Math.random() * 0xffffffff); // FIXME: look for conflicts
answer.jingle.contents[1].application.sources.push(rtxssrc);
groups.push({
semantics: 'FID',
sources: [newssrc.ssrc, rtxssrc.ssrc]
});
answer.jingle.contents[1].application.sourceGroups = groups;
answer.sdp = SJJ.toSessionSDP(answer.jingle, {
sid: self.config.sdpSessionID,
role: self._role(),
direction: 'outgoing'
});
}
}
}
var expandedAnswer = {
type: 'answer',
sdp: answer.sdp
};
if (self.assumeSetLocalSuccess) {
// not safe to do when doing simulcast mangling
var copy = cloneDeep(expandedAnswer);
self.emit('answer', copy);
cb(null, copy);
}
self._candidateBuffer = [];
self.pc.setLocalDescription(answer,
function () {
if (self.config.useJingle) {
var jingle = SJJ.toSessionJSON(answer.sdp, {
role: self._role(),
direction: 'outgoing'
});
jingle.sid = self.config.sid;
self.localDescription = jingle;
expandedAnswer.jingle = jingle;
}
if (self.enableChromeNativeSimulcast) {
// native simulcast part 2:
// signal multiple tracks to the receiver
// for anything in the SIM group
if (!expandedAnswer.jingle) {
expandedAnswer.jingle = SJJ.toSessionJSON(answer.sdp, {
role: self._role(),
direction: 'outgoing'
});
}
expandedAnswer.jingle.contents[1].application.sources.forEach(function (source, idx) {
// the floor idx/2 is a hack that relies on a particular order
// of groups, alternating between sim and rtx
source.parameters = source.parameters.map(function (parameter) {
if (parameter.key === 'msid') {
parameter.value += '-' + Math.floor(idx / 2);
}
return parameter;
});
});
expandedAnswer.sdp = SJJ.toSessionSDP(expandedAnswer.jingle, {
sid: self.sdpSessionID,
role: self._role(),
direction: 'outgoing'
});
}
expandedAnswer.sdp.split('\r\n').forEach(function (line) {
if (line.indexOf('a=candidate:') === 0) {
self._checkLocalCandidate(line);
}
});
if (!self.assumeSetLocalSuccess) {
var copy = cloneDeep(expandedAnswer);
self.emit('answer', copy);
cb(null, copy);
}
},
function (err) {
self.emit('error', err);
cb(err);
}
);
},
function (err) {
self.emit('error', err);
cb(err);
},
constraints
);
};
// Internal method for emitting ice candidates on our peer object
PeerConnection.prototype._onIce = function (event) {
var self = this;
if (event.candidate) {
if (this.dontSignalCandidates) return;
var ice = event.candidate;
var expandedCandidate = {
candidate: {
candidate: ice.candidate,
sdpMid: ice.sdpMid,
sdpMLineIndex: ice.sdpMLineIndex
}
};
this._checkLocalCandidate(ice.candidate);
var cand = SJJ.toCandidateJSON(ice.candidate);
var already;
var idx;
if (this.eliminateDuplicateCandidates && cand.type === 'relay') {
// drop candidates with same foundation, component
// take local type pref into account so we don't ignore udp
// ones when we know about a TCP one. unlikely but...
already = this._candidateBuffer.filter(
function (c) {
return c.type === 'relay';
}).map(function (c) {
return c.foundation + ':' + c.component;
}
);
idx = already.indexOf(cand.foundation + ':' + cand.component);
// remember: local type pref of udp is 0, tcp 1, tls 2
if (idx > -1 && ((cand.priority >> 24) >= (already[idx].priority >> 24))) {
// drop it, same foundation with higher (worse) type pref
return;
}
}
if (this.config.bundlePolicy === 'max-bundle') {
// drop candidates which are duplicate for audio/video/data
// duplicate means same host/port but different sdpMid
already = this._candidateBuffer.filter(
function (c) {
return cand.type === c.type;
}).map(function (cand) {
return cand.address + ':' + cand.port;
}
);
idx = already.indexOf(cand.address + ':' + cand.port);
if (idx > -1) return;
}
// also drop rtcp candidates since we know the peer supports RTCP-MUX
// this is a workaround until browsers implement this natively
if (this.config.rtcpMuxPolicy === 'require' && cand.component === '2') {
return;
}
this._candidateBuffer.push(cand);
if (self.config.useJingle) {
if (!ice.sdpMid) { // firefox doesn't set this
if (self.pc.remoteDescription && self.pc.remoteDescription.type === 'offer') {
// preserve name from remote
ice.sdpMid = self.remoteDescription.contents[ice.sdpMLineIndex].name;
} else {
ice.sdpMid = self.localDescription.contents[ice.sdpMLineIndex].name;
}
}
if (!self.iceCredentials.local[ice.sdpMid]) {
var jingle = SJJ.toSessionJSON(self.pc.localDescription.sdp, {
role: self._role(),
direction: 'outgoing'
});
jingle.contents.forEach(function (content) {
var transport = content.transport || {};
if (transport.ufrag) {
self.iceCredentials.local[content.name] = {
ufrag: transport.ufrag,
pwd: transport.pwd
};
}
});
}
expandedCandidate.jingle = {
contents: [{
name: ice.sdpMid,
creator: self._role(),
transport: {
transportType: 'iceUdp',
ufrag: self.iceCredentials.local[ice.sdpMid].ufrag,
pwd: self.iceCredentials.local[ice.sdpMid].pwd,
candidates: [
cand
]
}
}]
};
if (self.batchIceCandidates > 0) {
if (self.batchedIceCandidates.length === 0) {
window.setTimeout(function () {
var contents = {};
self.batchedIceCandidates.forEach(function (content) {
content = content.contents[0];
if (!contents[content.name]) contents[content.name] = content;
contents[content.name].transport.candidates.push(content.transport.candidates[0]);
});
var newCand = {
jingle: {
contents: []
}
};
Object.keys(contents).forEach(function (name) {
newCand.jingle.contents.push(contents[name]);
});
self.batchedIceCandidates = [];
self.emit('ice', newCand);
}, self.batchIceCandidates);
}
self.batchedIceCandidates.push(expandedCandidate.jingle);
return;
}
}
this.emit('ice', expandedCandidate);
} else {
this.emit('endOfCandidates');
}
};
// Internal method for processing a new data channel being added by the
// other peer.
PeerConnection.prototype._onDataChannel = function (event) {
// make sure we keep a reference so this doesn't get garbage collected
var channel = event.channel;
this._remoteDataChannels.push(channel);
this.emit('addChannel', channel);
};
// Create a data channel spec reference:
// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelInit
PeerConnection.prototype.createDataChannel = function (name, opts) {
var channel = this.pc.createDataChannel(name, opts);
// make sure we keep a reference so this doesn't get garbage collected
this._localDataChannels.push(channel);
return channel;
};
PeerConnection.prototype.getStats = function () {
if (typeof arguments[0] === 'function') {
var cb = arguments[0];
this.pc.getStats().then(function (res) {
cb(null, res);
}, function (err) {
cb(err);
});
} else {
return this.pc.getStats.apply(this.pc, arguments);
}
};
module.exports = PeerConnection;
},{"lodash.clonedeep":9,"sdp-jingle-json":13,"util":20,"wildemitter":22}],13:[function(require,module,exports){
var toSDP = require('./lib/tosdp');
var toJSON = require('./lib/tojson');
// Converstion from JSON to SDP
exports.toIncomingSDPOffer = function (session) {
return toSDP.toSessionSDP(session, {
role: 'responder',
direction: 'incoming'
});
};
exports.toOutgoingSDPOffer = function (session) {
return toSDP.toSessionSDP(session, {
role: 'initiator',
direction: 'outgoing'
});
};
exports.toIncomingSDPAnswer = function (session) {
return toSDP.toSessionSDP(session, {
role: 'initiator',
direction: 'incoming'
});
};
exports.toOutgoingSDPAnswer = function (session) {
return toSDP.toSessionSDP(session, {
role: 'responder',
direction: 'outgoing'
});
};
exports.toIncomingMediaSDPOffer = function (media) {
return toSDP.toMediaSDP(media, {
role: 'responder',
direction: 'incoming'
});
};
exports.toOutgoingMediaSDPOffer = function (media) {
return toSDP.toMediaSDP(media, {
role: 'initiator',
direction: 'outgoing'
});
};
exports.toIncomingMediaSDPAnswer = function (media) {
return toSDP.toMediaSDP(media, {
role: 'initiator',
direction: 'incoming'
});
};
exports.toOutgoingMediaSDPAnswer = function (media) {
return toSDP.toMediaSDP(media, {
role: 'responder',
direction: 'outgoing'
});
};
exports.toCandidateSDP = toSDP.toCandidateSDP;
exports.toMediaSDP = toSDP.toMediaSDP;
exports.toSessionSDP = toSDP.toSessionSDP;
// Conversion from SDP to JSON
exports.toIncomingJSONOffer = function (sdp, creators) {
return toJSON.toSessionJSON(sdp, {
role: 'responder',
direction: 'incoming',
creators: creators
});
};
exports.toOutgoingJSONOffer = function (sdp, creators) {
return toJSON.toSessionJSON(sdp, {
role: 'initiator',
direction: 'outgoing',
creators: creators
});
};
exports.toIncomingJSONAnswer = function (sdp, creators) {
return toJSON.toSessionJSON(sdp, {
role: 'initiator',
direction: 'incoming',
creators: creators
});
};
exports.toOutgoingJSONAnswer = function (sdp, creators) {
return toJSON.toSessionJSON(sdp, {
role: 'responder',
direction: 'outgoing',
creators: creators
});
};
exports.toIncomingMediaJSONOffer = function (sdp, creator) {
return toJSON.toMediaJSON(sdp, {
role: 'responder',
direction: 'incoming',
creator: creator
});
};
exports.toOutgoingMediaJSONOffer = function (sdp, creator) {
return toJSON.toMediaJSON(sdp, {
role: 'initiator',
direction: 'outgoing',
creator: creator
});
};
exports.toIncomingMediaJSONAnswer = function (sdp, creator) {
return toJSON.toMediaJSON(sdp, {
role: 'initiator',
direction: 'incoming',
creator: creator
});
};
exports.toOutgoingMediaJSONAnswer = function (sdp, creator) {
return toJSON.toMediaJSON(sdp, {
role: 'responder',
direction: 'outgoing',
creator: creator
});
};
exports.toCandidateJSON = toJSON.toCandidateJSON;
exports.toMediaJSON = toJSON.toMediaJSON;
exports.toSessionJSON = toJSON.toSessionJSON;
},{"./lib/tojson":16,"./lib/tosdp":17}],14:[function(require,module,exports){
exports.lines = function (sdp) {
return sdp.split('\r\n').filter(function (line) {
return line.length > 0;
});
};
exports.findLine = function (prefix, mediaLines, sessionLines) {
var prefixLength = prefix.length;
for (var i = 0; i < mediaLines.length; i++) {
if (mediaLines[i].substr(0, prefixLength) === prefix) {
return mediaLines[i];
}
}
// Continue searching in parent session section
if (!sessionLines) {
return false;
}
for (var j = 0; j < sessionLines.length; j++) {
if (sessionLines[j].substr(0, prefixLength) === prefix) {
return sessionLines[j];
}
}
return false;
};
exports.findLines = function (prefix, mediaLines, sessionLines) {
var results = [];
var prefixLength = prefix.length;
for (var i = 0; i < mediaLines.length; i++) {
if (mediaLines[i].substr(0, prefixLength) === prefix) {
results.push(mediaLines[i]);
}
}
if (results.length || !sessionLines) {
return results;
}
for (var j = 0; j < sessionLines.length; j++) {
if (sessionLines[j].substr(0, prefixLength) === prefix) {
results.push(sessionLines[j]);
}
}
return results;
};
exports.mline = function (line) {
var parts = line.substr(2).split(' ');
var parsed = {
media: parts[0],
port: parts[1],
proto: parts[2],
formats: []
};
for (var i = 3; i < parts.length; i++) {
if (parts[i]) {
parsed.formats.push(parts[i]);
}
}
return parsed;
};
exports.rtpmap = function (line) {
var parts = line.substr(9).split(' ');
var parsed = {
id: parts.shift()
};
parts = parts[0].split('/');
parsed.name = parts[0];
parsed.clockrate = parts[1];
parsed.channels = parts.length == 3 ? parts[2] : '1';
return parsed;
};
exports.sctpmap = function (line) {
// based on -05 draft
var parts = line.substr(10).split(' ');
var parsed = {
number: parts.shift(),
protocol: parts.shift(),
streams: parts.shift()
};
return parsed;
};
exports.fmtp = function (line) {
var kv, key, value;
var parts = line.substr(line.indexOf(' ') + 1).split(';');
var parsed = [];
for (var i = 0; i < parts.length; i++) {
kv = parts[i].split('=');
key = kv[0].trim();
value = kv[1];
if (key && value) {
parsed.push({key: key, value: value});
} else if (key) {
parsed.push({key: '', value: key});
}
}
return parsed;
};
exports.crypto = function (line) {
var parts = line.substr(9).split(' ');
var parsed = {
tag: parts[0],
cipherSuite: parts[1],
keyParams: parts[2],
sessionParams: parts.slice(3).join(' ')
};
return parsed;
};
exports.fingerprint = function (line) {
var parts = line.substr(14).split(' ');
return {
hash: parts[0],
value: parts[1]
};
};
exports.extmap = function (line) {
var parts = line.substr(9).split(' ');
var parsed = {};
var idpart = parts.shift();
var sp = idpart.indexOf('/');
if (sp >= 0) {
parsed.id = idpart.substr(0, sp);
parsed.senders = idpart.substr(sp + 1);
} else {
parsed.id = idpart;
parsed.senders = 'sendrecv';
}
parsed.uri = parts.shift() || '';
return parsed;
};
exports.rtcpfb = function (line) {
var parts = line.substr(10).split(' ');
var parsed = {};
parsed.id = parts.shift();
parsed.type = parts.shift();
if (parsed.type === 'trr-int') {
parsed.value = parts.shift();
} else {
parsed.subtype = parts.shift() || '';
}
parsed.parameters = parts;
return parsed;
};
exports.candidate = function (line) {
var parts;
if (line.indexOf('a=candidate:') === 0) {
parts = line.substring(12).split(' ');
} else { // no a=candidate
parts = line.substring(10).split(' ');
}
var candidate = {
foundation: parts[0],
component: parts[1],
protocol: parts[2].toLowerCase(),
priority: parts[3],
ip: parts[4],
port: parts[5],
// skip parts[6] == 'typ'
type: parts[7],
generation: '0'
};
for (var i = 8; i < parts.length; i += 2) {
if (parts[i] === 'raddr') {
candidate.relAddr = parts[i + 1];
} else if (parts[i] === 'rport') {
candidate.relPort = parts[i + 1];
} else if (parts[i] === 'generation') {
candidate.generation = parts[i + 1];
} else if (parts[i] === 'tcptype') {
candidate.tcpType = parts[i + 1];
}
}
candidate.network = '1';
return candidate;
};
exports.sourceGroups = function (lines) {
var parsed = [];
for (var i = 0; i < lines.length; i++) {
var parts = lines[i].substr(13).split(' ');
parsed.push({
semantics: parts.shift(),
sources: parts
});
}
return parsed;
};
exports.sources = function (lines) {
// http://tools.ietf.org/html/rfc5576
var parsed = [];
var sources = {};
for (var i = 0; i < lines.length; i++) {
var parts = lines[i].substr(7).split(' ');
var ssrc = parts.shift();
if (!sources[ssrc]) {
var source = {
ssrc: ssrc,
parameters: []
};
parsed.push(source);
// Keep an index
sources[ssrc] = source;
}
parts = parts.join(' ').split(':');
var attribute = parts.shift();
var value = parts.join(':') || null;
sources[ssrc].parameters.push({
key: attribute,
value: value
});
}
return parsed;
};
exports.groups = function (lines) {
// http://tools.ietf.org/html/rfc5888
var parsed = [];
var parts;
for (var i = 0; i < lines.length; i++) {
parts = lines[i].substr(8).split(' ');
parsed.push({
semantics: parts.shift(),
contents: parts
});
}
return parsed;
};
exports.bandwidth = function (line) {
var parts = line.substr(2).split(':');
var parsed = {};
parsed.type = parts.shift();
parsed.bandwidth = parts.shift();
return parsed;
};
exports.msid = function (line) {
var data = line.substr(7);
var parts = data.split(' ');
return {
msid: data,
mslabel: parts[0],
label: parts[1]
};
};
},{}],15:[function(require,module,exports){
module.exports = {
initiator: {
incoming: {
initiator: 'recvonly',
responder: 'sendonly',
both: 'sendrecv',
none: 'inactive',
recvonly: 'initiator',
sendonly: 'responder',
sendrecv: 'both',
inactive: 'none'
},
outgoing: {
initiator: 'sendonly',
responder: 'recvonly',
both: 'sendrecv',
none: 'inactive',
recvonly: 'responder',
sendonly: 'initiator',
sendrecv: 'both',
inactive: 'none'
}
},
responder: {
incoming: {
initiator: 'sendonly',
responder: 'recvonly',
both: 'sendrecv',
none: 'inactive',
recvonly: 'responder',
sendonly: 'initiator',
sendrecv: 'both',
inactive: 'none'
},
outgoing: {
initiator: 'recvonly',
responder: 'sendonly',
both: 'sendrecv',
none: 'inactive',
recvonly: 'initiator',
sendonly: 'responder',
sendrecv: 'both',
inactive: 'none'
}
}
};
},{}],16:[function(require,module,exports){
var SENDERS = require('./senders');
var parsers = require('./parsers');
var idCounter = Math.random();
exports._setIdCounter = function (counter) {
idCounter = counter;
};
exports.toSessionJSON = function (sdp, opts) {
var i;
var creators = opts.creators || [];
var role = opts.role || 'initiator';
var direction = opts.direction || 'outgoing';
// Divide the SDP into session and media sections.
var media = sdp.split(/\r?\nm=/);
for (i = 1; i < media.length; i++) {
media[i] = 'm=' + media[i];
if (i !== media.length - 1) {
media[i] += '\r\n';
}
}
var session = media.shift() + '\r\n';
var sessionLines = parsers.lines(session);
var parsed = {};
var contents = [];
for (i = 0; i < media.length; i++) {
contents.push(exports.toMediaJSON(media[i], session, {
role: role,
direction: direction,
creator: creators[i] || 'initiator'
}));
}
parsed.contents = contents;
var groupLines = parsers.findLines('a=group:', sessionLines);
if (groupLines.length) {
parsed.groups = parsers.groups(groupLines);
}
return parsed;
};
exports.toMediaJSON = function (media, session, opts) {
var creator = opts.creator || 'initiator';
var role = opts.role || 'initiator';
var direction = opts.direction || 'outgoing';
var lines = parsers.lines(media);
var sessionLines = parsers.lines(session);
var mline = parsers.mline(lines[0]);
var content = {
creator: creator,
name: mline.media,
application: {
applicationType: 'rtp',
media: mline.media,
payloads: [],
encryption: [],
feedback: [],
headerExtensions: []
},
transport: {
transportType: 'iceUdp',
candidates: [],
fingerprints: []
}
};
if (mline.media == 'application') {
// FIXME: the description is most likely to be independent
// of the SDP and should be processed by other parts of the library
content.application = {
applicationType: 'datachannel'
};
content.transport.sctp = [];
}
var desc = content.application;
var trans = content.transport;
// If we have a mid, use that for the content name instead.
var mid = parsers.findLine('a=mid:', lines);
if (mid) {
content.name = mid.substr(6);
}
if (parsers.findLine('a=sendrecv', lines, sessionLines)) {
content.senders = 'both';
} else if (parsers.findLine('a=sendonly', lines, sessionLines)) {
content.senders = SENDERS[role][direction].sendonly;
} else if (parsers.findLine('a=recvonly', lines, sessionLines)) {
content.senders = SENDERS[role][direction].recvonly;
} else if (parsers.findLine('a=inactive', lines, sessionLines)) {
content.senders = 'none';
}
if (desc.applicationType == 'rtp') {
var bandwidth = parsers.findLine('b=', lines);
if (bandwidth) {
desc.bandwidth = parsers.bandwidth(bandwidth);
}
var ssrc = parsers.findLine('a=ssrc:', lines);
if (ssrc) {
desc.ssrc = ssrc.substr(7).split(' ')[0];
}
var rtpmapLines = parsers.findLines('a=rtpmap:', lines);
rtpmapLines.forEach(function (line) {
var payload = parsers.rtpmap(line);
payload.parameters = [];
payload.feedback = [];
var fmtpLines = parsers.findLines('a=fmtp:' + payload.id, lines);
// There should only be one fmtp line per payload
fmtpLines.forEach(function (line) {
payload.parameters = parsers.fmtp(line);
});
var fbLines = parsers.findLines('a=rtcp-fb:' + payload.id, lines);
fbLines.forEach(function (line) {
payload.feedback.push(parsers.rtcpfb(line));
});
desc.payloads.push(payload);
});
var cryptoLines = parsers.findLines('a=crypto:', lines, sessionLines);
cryptoLines.forEach(function (line) {
desc.encryption.push(parsers.crypto(line));
});
if (parsers.findLine('a=rtcp-mux', lines)) {
desc.mux = true;
}
var fbLines = parsers.findLines('a=rtcp-fb:*', lines);
fbLines.forEach(function (line) {
desc.feedback.push(parsers.rtcpfb(line));
});
var extLines = parsers.findLines('a=extmap:', lines);
extLines.forEach(function (line) {
var ext = parsers.extmap(line);
ext.senders = SENDERS[role][direction][ext.senders];
desc.headerExtensions.push(ext);
});
var ssrcGroupLines = parsers.findLines('a=ssrc-group:', lines);
desc.sourceGroups = parsers.sourceGroups(ssrcGroupLines || []);
var ssrcLines = parsers.findLines('a=ssrc:', lines);
var sources = desc.sources = parsers.sources(ssrcLines || []);
var msidLine = parsers.findLine('a=msid:', lines);
if (msidLine) {
var msid = parsers.msid(msidLine);
['msid', 'mslabel', 'label'].forEach(function (key) {
for (var i = 0; i < sources.length; i++) {
var found = false;
for (var j = 0; j < sources[i].parameters.length; j++) {
if (sources[i].parameters[j].key === key) {
found = true;
}
}
if (!found) {
sources[i].parameters.push({ key: key, value: msid[key] });
}
}
});
}
if (parsers.findLine('a=x-google-flag:conference', lines, sessionLines)) {
desc.googConferenceFlag = true;
}
}
// transport specific attributes
var fingerprintLines = parsers.findLines('a=fingerprint:', lines, sessionLines);
var setup = parsers.findLine('a=setup:', lines, sessionLines);
fingerprintLines.forEach(function (line) {
var fp = parsers.fingerprint(line);
if (setup) {
fp.setup = setup.substr(8);
}
trans.fingerprints.push(fp);
});
var ufragLine = parsers.findLine('a=ice-ufrag:', lines, sessionLines);
var pwdLine = parsers.findLine('a=ice-pwd:', lines, sessionLines);
if (ufragLine && pwdLine) {
trans.ufrag = ufragLine.substr(12);
trans.pwd = pwdLine.substr(10);
trans.candidates = [];
var candidateLines = parsers.findLines('a=candidate:', lines, sessionLines);
candidateLines.forEach(function (line) {
trans.candidates.push(exports.toCandidateJSON(line));
});
}
if (desc.applicationType == 'datachannel') {
var sctpmapLines = parsers.findLines('a=sctpmap:', lines);
sctpmapLines.forEach(function (line) {
var sctp = parsers.sctpmap(line);
trans.sctp.push(sctp);
});
}
return content;
};
exports.toCandidateJSON = function (line) {
var candidate = parsers.candidate(line.split(/\r?\n/)[0]);
candidate.id = (idCounter++).toString(36).substr(0, 12);
return candidate;
};
},{"./parsers":14,"./senders":15}],17:[function(require,module,exports){
var SENDERS = require('./senders');
exports.toSessionSDP = function (session, opts) {
var role = opts.role || 'initiator';
var direction = opts.direction || 'outgoing';
var sid = opts.sid || session.sid || Date.now();
var time = opts.time || Date.now();
var sdp = [
'v=0',
'o=- ' + sid + ' ' + time + ' IN IP4 0.0.0.0',
's=-',
't=0 0'
];
var contents = session.contents || [];
var hasSources = false;
contents.forEach(function (content) {
if (content.application.sources &&
content.application.sources.length) {
hasSources = true;
}
});
if (hasSources) {
sdp.push('a=msid-semantic: WMS *');
}
var groups = session.groups || [];
groups.forEach(function (group) {
sdp.push('a=group:' + group.semantics + ' ' + group.contents.join(' '));
});
contents.forEach(function (content) {
sdp.push(exports.toMediaSDP(content, opts));
});
return sdp.join('\r\n') + '\r\n';
};
exports.toMediaSDP = function (content, opts) {
var sdp = [];
var role = opts.role || 'initiator';
var direction = opts.direction || 'outgoing';
var desc = content.application;
var transport = content.transport;
var payloads = desc.payloads || [];
var fingerprints = (transport && transport.fingerprints) || [];
var mline = [];
if (desc.applicationType == 'datachannel') {
mline.push('application');
mline.push('1');
mline.push('DTLS/SCTP');
if (transport.sctp) {
transport.sctp.forEach(function (map) {
mline.push(map.number);
});
}
} else {
mline.push(desc.media);
mline.push('1');
if (fingerprints.length > 0) {
mline.push('UDP/TLS/RTP/SAVPF');
} else if (desc.encryption && desc.encryption.length > 0) {
mline.push('RTP/SAVPF');
} else {
mline.push('RTP/AVPF');
}
payloads.forEach(function (payload) {
mline.push(payload.id);
});
}
sdp.push('m=' + mline.join(' '));
sdp.push('c=IN IP4 0.0.0.0');
if (desc.bandwidth && desc.bandwidth.type && desc.bandwidth.bandwidth) {
sdp.push('b=' + desc.bandwidth.type + ':' + desc.bandwidth.bandwidth);
}
if (desc.applicationType == 'rtp') {
sdp.push('a=rtcp:1 IN IP4 0.0.0.0');
}
if (transport) {
if (transport.ufrag) {
sdp.push('a=ice-ufrag:' + transport.ufrag);
}
if (transport.pwd) {
sdp.push('a=ice-pwd:' + transport.pwd);
}
var pushedSetup = false;
fingerprints.forEach(function (fingerprint) {
sdp.push('a=fingerprint:' + fingerprint.hash + ' ' + fingerprint.value);
if (fingerprint.setup && !pushedSetup) {
sdp.push('a=setup:' + fingerprint.setup);
}
});
if (transport.sctp) {
transport.sctp.forEach(function (map) {
sdp.push('a=sctpmap:' + map.number + ' ' + map.protocol + ' ' + map.streams);
});
}
}
if (desc.applicationType == 'rtp') {
sdp.push('a=' + (SENDERS[role][direction][content.senders] || 'sendrecv'));
}
sdp.push('a=mid:' + content.name);
if (desc.sources && desc.sources.length) {
(desc.sources[0].parameters || []).forEach(function (param) {
if (param.key === 'msid') {
sdp.push('a=msid:' + param.value);
}
});
}
if (desc.mux) {
sdp.push('a=rtcp-mux');
}
var encryption = desc.encryption || [];
encryption.forEach(function (crypto) {
sdp.push('a=crypto:' + crypto.tag + ' ' + crypto.cipherSuite + ' ' + crypto.keyParams + (crypto.sessionParams ? ' ' + crypto.sessionParams : ''));
});
if (desc.googConferenceFlag) {
sdp.push('a=x-google-flag:conference');
}
payloads.forEach(function (payload) {
var rtpmap = 'a=rtpmap:' + payload.id + ' ' + payload.name + '/' + payload.clockrate;
if (payload.channels && payload.channels != '1') {
rtpmap += '/' + payload.channels;
}
sdp.push(rtpmap);
if (payload.parameters && payload.parameters.length) {
var fmtp = ['a=fmtp:' + payload.id];
var parameters = [];
payload.parameters.forEach(function (param) {
parameters.push((param.key ? param.key + '=' : '') + param.value);
});
fmtp.push(parameters.join(';'));
sdp.push(fmtp.join(' '));
}
if (payload.feedback) {
payload.feedback.forEach(function (fb) {
if (fb.type === 'trr-int') {
sdp.push('a=rtcp-fb:' + payload.id + ' trr-int ' + (fb.value ? fb.value : '0'));
} else {
sdp.push('a=rtcp-fb:' + payload.id + ' ' + fb.type + (fb.subtype ? ' ' + fb.subtype : ''));
}
});
}
});
if (desc.feedback) {
desc.feedback.forEach(function (fb) {
if (fb.type === 'trr-int') {
sdp.push('a=rtcp-fb:* trr-int ' + (fb.value ? fb.value : '0'));
} else {
sdp.push('a=rtcp-fb:* ' + fb.type + (fb.subtype ? ' ' + fb.subtype : ''));
}
});
}
var hdrExts = desc.headerExtensions || [];
hdrExts.forEach(function (hdr) {
sdp.push('a=extmap:' + hdr.id + (hdr.senders ? '/' + SENDERS[role][direction][hdr.senders] : '') + ' ' + hdr.uri);
});
var ssrcGroups = desc.sourceGroups || [];
ssrcGroups.forEach(function (ssrcGroup) {
sdp.push('a=ssrc-group:' + ssrcGroup.semantics + ' ' + ssrcGroup.sources.join(' '));
});
var ssrcs = desc.sources || [];
ssrcs.forEach(function (ssrc) {
for (var i = 0; i < ssrc.parameters.length; i++) {
var param = ssrc.parameters[i];
sdp.push('a=ssrc:' + (ssrc.ssrc || desc.ssrc) + ' ' + param.key + (param.value ? (':' + param.value) : ''));
}
});
var candidates = transport.candidates || [];
candidates.forEach(function (candidate) {
sdp.push(exports.toCandidateSDP(candidate));
});
return sdp.join('\r\n');
};
exports.toCandidateSDP = function (candidate) {
var sdp = [];
sdp.push(candidate.foundation);
sdp.push(candidate.component);
sdp.push(candidate.protocol.toUpperCase());
sdp.push(candidate.priority);
sdp.push(candidate.ip);
sdp.push(candidate.port);
var type = candidate.type;
sdp.push('typ');
sdp.push(type);
if (type === 'srflx' || type === 'prflx' || type === 'relay') {
if (candidate.relAddr && candidate.relPort) {
sdp.push('raddr');
sdp.push(candidate.relAddr);
sdp.push('rport');
sdp.push(candidate.relPort);
}
}
if (candidate.tcpType && candidate.protocol.toUpperCase() == 'TCP') {
sdp.push('tcptype');
sdp.push(candidate.tcpType);
}
sdp.push('generation');
sdp.push(candidate.generation || '0');
// FIXME: apparently this is wrong per spec
// but then, we need this when actually putting this into
// SDP so it's going to stay.
// decision needs to be revisited when browsers dont
// accept this any longer
return 'a=candidate:' + sdp.join(' ');
};
},{"./senders":15}],18:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],19:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],20:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":19,"_process":11,"inherits":18}],21:[function(require,module,exports){
// created by @HenrikJoreteg
var prefix;
var version;
if (window.mozRTCPeerConnection || navigator.mozGetUserMedia) {
prefix = 'moz';
version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
} else if (window.webkitRTCPeerConnection || navigator.webkitGetUserMedia) {
prefix = 'webkit';
version = navigator.userAgent.match(/Chrom(e|ium)/) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
}
var PC = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
var MediaStream = window.webkitMediaStream || window.MediaStream;
var screenSharing = window.location.protocol === 'https:' &&
((prefix === 'webkit' && version >= 26) ||
(prefix === 'moz' && version >= 33))
var AudioContext = window.AudioContext || window.webkitAudioContext;
var videoEl = document.createElement('video');
var supportVp8 = videoEl && videoEl.canPlayType && videoEl.canPlayType('video/webm; codecs="vp8", vorbis') === "probably";
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia;
// export support flags and constructors.prototype && PC
module.exports = {
prefix: prefix,
browserVersion: version,
support: !!PC && !!getUserMedia,
// new support style
supportRTCPeerConnection: !!PC,
supportVp8: supportVp8,
supportGetUserMedia: !!getUserMedia,
supportDataChannel: !!(PC && PC.prototype && PC.prototype.createDataChannel),
supportWebAudio: !!(AudioContext && AudioContext.prototype.createMediaStreamSource),
supportMediaStream: !!(MediaStream && MediaStream.prototype.removeTrack),
supportScreenSharing: !!screenSharing,
// constructors
AudioContext: AudioContext,
PeerConnection: PC,
SessionDescription: SessionDescription,
IceCandidate: IceCandidate,
MediaStream: MediaStream,
getUserMedia: getUserMedia
};
},{}],22:[function(require,module,exports){
/*
WildEmitter.js is a slim little event emitter by @henrikjoreteg largely based
on @visionmedia's Emitter from UI Kit.
Why? I wanted it standalone.
I also wanted support for wildcard emitters like this:
emitter.on('*', function (eventName, other, event, payloads) {
});
emitter.on('somenamespace*', function (eventName, payloads) {
});
Please note that callbacks triggered by wildcard registered events also get
the event name as the first argument.
*/
module.exports = WildEmitter;
function WildEmitter() { }
WildEmitter.mixin = function (constructor) {
var prototype = constructor.prototype || constructor;
prototype.isWildEmitter= true;
// Listen on the given `event` with `fn`. Store a group name if present.
prototype.on = function (event, groupName, fn) {
this.callbacks = this.callbacks || {};
var hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
func._groupName = group;
(this.callbacks[event] = this.callbacks[event] || []).push(func);
return this;
};
// Adds an `event` listener that will be invoked a single
// time then automatically removed.
prototype.once = function (event, groupName, fn) {
var self = this,
hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
function on() {
self.off(event, on);
func.apply(this, arguments);
}
this.on(event, group, on);
return this;
};
// Unbinds an entire group
prototype.releaseGroup = function (groupName) {
this.callbacks = this.callbacks || {};
var item, i, len, handlers;
for (item in this.callbacks) {
handlers = this.callbacks[item];
for (i = 0, len = handlers.length; i < len; i++) {
if (handlers[i]._groupName === groupName) {
//console.log('removing');
// remove it and shorten the array we're looping through
handlers.splice(i, 1);
i--;
len--;
}
}
}
return this;
};
// Remove the given callback for `event` or all
// registered callbacks.
prototype.off = function (event, fn) {
this.callbacks = this.callbacks || {};
var callbacks = this.callbacks[event],
i;
if (!callbacks) return this;
// remove all handlers
if (arguments.length === 1) {
delete this.callbacks[event];
return this;
}
// remove specific handler
i = callbacks.indexOf(fn);
callbacks.splice(i, 1);
if (callbacks.length === 0) {
delete this.callbacks[event];
}
return this;
};
/// Emit `event` with the given args.
// also calls any `*` handlers
prototype.emit = function (event) {
this.callbacks = this.callbacks || {};
var args = [].slice.call(arguments, 1),
callbacks = this.callbacks[event],
specialCallbacks = this.getWildcardCallbacks(event),
i,
len,
item,
listeners;
if (callbacks) {
listeners = callbacks.slice();
for (i = 0, len = listeners.length; i < len; ++i) {
if (!listeners[i]) {
break;
}
listeners[i].apply(this, args);
}
}
if (specialCallbacks) {
len = specialCallbacks.length;
listeners = specialCallbacks.slice();
for (i = 0, len = listeners.length; i < len; ++i) {
if (!listeners[i]) {
break;
}
listeners[i].apply(this, [event].concat(args));
}
}
return this;
};
// Helper for for finding special wildcard event handlers that match the event
prototype.getWildcardCallbacks = function (eventName) {
this.callbacks = this.callbacks || {};
var item,
split,
result = [];
for (item in this.callbacks) {
split = item.split('*');
if (item === '*' || (split.length === 2 && eventName.slice(0, split[0].length) === split[0])) {
result = result.concat(this.callbacks[item]);
}
}
return result;
};
};
WildEmitter.mixin(WildEmitter);
},{}]},{},[4])(4)
}); | drazenzadravec/projects | WebRTC/electron/lib/webrtc.bundle.js | JavaScript | mit | 285,832 |
// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
config = {
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: process.env.HEROKU_URL,
mail: {
transport: 'SMTP',
options: {
service: 'Mailgun',
auth: {
user: process.env.MAILGUN_SMTP_LOGIN,
pass: process.env.MAILGUN_SMTP_PASSWORD
}
}
},
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '0.0.0.0',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.PORT
}
},
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
// Change this to your Ghost blogs published URL.
url: 'http://localhost:2368',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
// Export config
module.exports = config;
| ftasse/writer-blog | config.js | JavaScript | mit | 3,966 |
jQuery.extend(DateInput.DEFAULT_OPTS, {
month_names: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
short_month_names: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
short_day_names: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"]
}); | jonleighton/date_input | translations/jquery.date_input.uk_UA.js | JavaScript | mit | 497 |
const PouchDB = require('pouchdb');
const Product = require('./models/product.js');
const User = require('./models/user.js');
const Faker = require('faker');
const Constants = require('./constants.js');
// let database = new PouchDB('market');
module.exports = class Database {
constructor() {
this.database = new PouchDB('market');
}
/**
* Fill the database with some mock data
*/
fillDatabaseWithMockData(howManyProduct) {
this.hasDatabase();
var i = 0;
for(i; i < howManyProduct; i++) {
let fakeUser = Faker.helpers.userCard();
fakeUser.avatar = Faker.internet.avatar(50, 50);
delete fakeUser.website;
delete fakeUser.company;
let randomPic = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
this.add(
Constants.typeProduct,
new Product(
this.generateUniqueID(Constants.typeProduct),
Faker.commerce.product(),
Faker.lorem.sentence(20),
Faker.commerce.price(),
Faker.commerce.color(),
Faker.commerce.department(),
Faker.commerce.productMaterial(),
Faker.image.food(200, 100) + '/' + randomPic,
Faker.image.food(800, 400) + '/' + randomPic
)
);
this.add(
Constants.typeUser,
new User(
this.generateUniqueID(Constants.typeUser),
fakeUser.username,
fakeUser.name,
fakeUser.email,
fakeUser.address,
fakeUser.phone,
fakeUser.avatar
)
);
}
}
/**
* Generate unique ID
*/
generateUniqueID(type) {
return type + '/' + Math.random().toString(36).substr(2, 9);
}
/**
* Delete database
* Call this function is you want to reset all data
*/
deleteMockData() {
return this.database.destroy().then((response) => {
if (response.ok) {
this.database = null;
console.log('*************************************');
console.log('* Database successfully destroyed ! *');
console.log('*************************************');
return Promise.resolve(response);
}
}).catch((error) => {
console.log('********************************************************');
console.log('* Error happened, the database couln\'t be destroyed ! *');
console.log('********************************************************');
});
}
/**
* Add product into database
* @param {string} type Type of doc products/users
* @param {object} obj Object to add
*/
add(type, obj) {
this.hasDatabase();
return this.database.put(obj).then((result) => {
if (result.ok) {
console.log( type + ' successfully added ! With ID : ' + result.id);
return Promise.resolve(result);
}
}).catch((error) => {
console.log('Error happened, the ' + type + ' couln\'t be added !', error);
return Promise.reject({
success: false,
message: 'Error happened, the ' + type + ' couln\'t be added !',
error: error
});
});
}
/**
* Update product into database
* @param {string} type Type of doc product or user
* @param {object} object Contain the new value of the product/user
*/
update(type, obj) {
this.hasDatabase();
let insert = {};
if (type === Constants.typeUser) {
insert = {
_id: obj._id,
_rev: obj._rev,
username: obj.username,
name: obj.name,
email: obj.email,
address: obj.address,
phone: obj.phone,
avatar: obj.avatar
};
}
if (type === Constants.typeProduct) {
insert = {
_id: obj._id,
_rev: obj._rev,
title: obj.title,
description: obj.description,
price: obj.price,
color: obj.color,
department: obj.department,
material: obj.material,
thumb: obj.thumb,
image: obj.image
};
}
return this.database.put(insert).then((result) => {
if (result.ok) {
console.log(type + ' successfully updated !', result);
return Promise.resolve(result);
}
}).catch((error) => {
console.log('Error happened, ' + type + ' couln\'t be updated !', error);
return Promise.reject({
success: false,
message: 'Error happened, ' + type + ' couln\'t be updated !',
error: error
});
});
}
/**
* Delete a product into the database
* @param {string} type Type of doc products/users
* @param {string} id Doc ID
*/
delete(type, id) {
this.hasDatabase();
return this.database.get(id).then((doc) => {
return this.database.remove(doc);
}).then((result) => {
if (result.ok) {
console.log(type + ' successfully deleted !', result);
return Promise.resolve(result);
}
}).catch((error) => {
console.log('Error happened, ' + type + ' couln\'t be deleted !', error);
return Promise.reject({
success: false,
message: 'Error happened, ' + type + ' couln\'t be deleted !',
error: error
});
});
}
/**
* Fetch a product from the database
* @param {string} type Type of doc products/users
* @param {string} id Doc ID
*/
get(type, id) {
this.hasDatabase();
return this.database.get(id).then((doc) => {
if (doc) {
console.log(type + ' successfully fetched !', doc);
return Promise.resolve(doc);
}
}).catch((error) => {
console.log('Error happened, ' + type + ' couln\'t be fetched !', error);
return Promise.reject({
success: false,
message: 'Error happened, ' + type + ' couln\'t be fetched !',
error: error
});
});
}
/**
* Fetch all doc from the database by type
*/
getAll(type) {
this.hasDatabase();
return this.database.allDocs({
include_docs: true,
startkey: type,
endkey: type + '\uffff'
}).then((result) => {
console.log(type + ' successfully fetched !', result);
let data = [];
for (var i in result.rows) {
data.push(result.rows[i].doc);
}
return new Promise((resolve, reject) => {
resolve(data);
});
}).catch((error) => {
console.log('Error happened, ' + type + ' couln\'t be fetched !', error);
return Promise.reject(error);
});
}
/**
* Check if the database is created
*/
hasDatabase() {
if (this.database === null) {
this.database = new PouchDB('market');
}
}
} | MISTERSOFT/nodejs-mock-webservice | database.js | JavaScript | mit | 7,747 |
"use strict";
module.exports = function (config) {
var isCI = process.env['CI'];
var baseConfig = {
frameworks: ['mocha', 'chai-sinon', 'sinon', 'chai'],
files: [
'tests/**/*.js'
],
preprocessors: {
'tests/**/*.js': ['webpack', 'sourcemap']
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
}]
}
},
webpackMiddleware: {
noInfo: true
},
reporters: [
'dots'
],
// web server port
port: 8081,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers.
browsers: [
'Firefox',
'Chrome'
],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 120000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
};
if (isCI) {
// Open Sauce config.
baseConfig.sauceLabs = {
testName: 'snabbdom-virtualize unit tests',
recordScreenshots: false
};
baseConfig.customLaunchers = {
'SL_Chrome': {
base: 'SauceLabs',
platform: 'OS X 10.11',
browserName: 'chrome'
},
'SL_Firefox': {
base: 'SauceLabs',
platform: 'OS X 10.11',
browserName: 'firefox'
},
'SL_Edge': {
base: 'SauceLabs',
platform: 'Windows 10',
browserName: 'microsoftedge'
},
'SL_IE_9': {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9.0',
platform: 'Windows 7'
},
'SL_Safari_9': {
base: 'SauceLabs',
browserName: 'safari',
version: '9.0',
platform: 'OS X 10.11'
}
};
baseConfig.reporters.push('saucelabs');
baseConfig.browsers = Object.keys(baseConfig.customLaunchers);
}
config.set(baseConfig);
}
| appcues/snabbdom-virtualize | test/karma.conf.js | JavaScript | mit | 2,796 |
// Add filters here | MetropolitanTransportationCommission/vpp-webapp | client/public/utils/filters/filters.js | JavaScript | mit | 19 |
var interfaceCSF_1_1Zpt_1_1IAddOnAssemblyFinder =
[
[ "GetAssemblyPath", "interfaceCSF_1_1Zpt_1_1IAddOnAssemblyFinder.html#ade92d81f988cfec8473c8cebd8a24d2f", null ]
]; | csf-dev/ZPT-Sharp | docs/_legacy/v1.x/api/interfaceCSF_1_1Zpt_1_1IAddOnAssemblyFinder.js | JavaScript | mit | 172 |
module.exports = {
CITY_ID: 'tainan.gov.tw',
API_HOST: 'http://open1999.tainan.gov.tw:82'
}
| wonderchang/tainan-open-1999 | src/config.js | JavaScript | mit | 96 |
export default class Intern {
constructor() {
this.voiceModule = window.speechSynthesis;
this.inOffice = Boolean(this.voiceModule);
this.degrees = [];
if (this.inOffice) {
this.educate();
this.voiceModule.onvoiceschanged = this.educate;
}
}
say(message) {
if (!this.inOffice || this.degrees.length === 0) {
return false;
}
let preferredDegree = this.degrees.find((degree) =>
degree.lang === 'ja-JP'
);
if (!preferredDegree) {
preferredDegree = this.degrees[0];
}
// Interrupt the intern, as they are too good at queueing messages
if (this.voiceModule.speaking) {
this.voiceModule.cancel();
}
const script = new SpeechSynthesisUtterance(message);
script.voice = preferredDegree;
this.voiceModule.speak(script);
return true;
}
educate = () => {
this.degrees = this.voiceModule.getVoices();
}
}
| team-thyme/soundboard-front-end | frontend/src/helpers/Intern.js | JavaScript | mit | 1,048 |
const DPR = window.devicePixelRatio || 1;
export default {
gameBgColor: '#282c34',
localStorageName: 'minesweeper',
// 默认游戏面板属性
tileWidth: 64,
tileHeight: 64,
boardWidth: 9,
boardHeight: 9,
mineTotal: 10,
// 计时器与地雷计数器图标尺寸与颜色
timerIconSize: Math.min(48 * DPR, 128),
mineIconSize: Math.min(48 * DPR, 128),
timerIconColor: '#0e89b6',
mineIconColor: '#0e89b6',
iconMargin: Math.min(16 * DPR, 40),
// 默认文本样式
defaultTextStyle: {
font: 'normal 32px PingFang SC,Helvetica Neue,Helvetica,Microsoft Yahei,Arial,Hiragino Sans GB,sans-serif',
fontSize: Math.min(32 * DPR, 80),
fill: '#ffffff',
boundsAlignV: 'middle',
}
}
| flyerq/minesweeper | src/config.js | JavaScript | mit | 723 |
// Separate Numbers with Commas in JavaScript **Pairing Challenge**
// I worked on this challenge with: Luis Ybarra
// Pseudocode
// INPUT: Integer - Number
// OUTPUT: String representation of the Integer INPUT with commas added
// STEPS:
// 1. Convert Integer to String
// 2. Reverse the String
// 3. Add a comma after every set of three digits
// 4. Reverse the String
// 5. Return the String.
// Initial Solution
function separate_initial(num) {
var result = (""+num).split("");
result.reverse();
for(var i = 1; i <= result.length; i++) {
if (i % 4 == 0)
result.splice(i-1, 0, ",");
}
result.reverse();
console.log(result.join(""))
};
separate_initial(1234567);
// Refactored Solution
function separate_comma(num){
var x = num.toLocaleString();
console.log(x)
}
separate_comma(23423423452)
// var example
// Your Own Tests (OPTIONAL)
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(separate_comma(23423423452) === 23,423,423,452),
"Error",
"1. "
)
assert(
(separate_initial(123456) === 123,456), "Error", "2."
)
// Reflection
/*
What was it like to approach the problem from the perspective of JavaScript? Did you approach the problem differently
The concept was the same but we had to get used to diffrent syntax
What did you learn about iterating over arrays in JavaScript?
I consolidated a bit more my knowledge of the for loop.
What was different about solving this problem in JavaScript?
Apart from the syntax it was pretty mucht the same concept
What built-in methods did you find to incorporate in your refactored solution?
we found toLocaleString which add commas to numbers.
*/
| Norberto94/phase-0 | week-7/nums_commas.js | JavaScript | mit | 1,809 |
/** @format */
import { Platform } from 'react-native'
import { Client, Configuration, StandardDelivery } from 'bugsnag-react-native'
const config = new Configuration('my API key!')
var endpoint = Platform.OS === 'ios' ? 'http://localhost:9339' : 'http://10.0.2.2:9339'
config.delivery = new StandardDelivery(endpoint, endpoint)
config.autoCaptureSessions = false
const bugsnag = new Client(config)
export default bugsnag;
import {AppRegistry} from 'react-native'
import App from './App'
import {name as appName} from './app.json'
AppRegistry.registerComponent(appName, () => App)
| bugsnag/bugsnag-react-native | features/fixtures/sampler/index.js | JavaScript | mit | 585 |
import { CommandMessage } from "discord.js-commando";
import isNumber from "lodash/isNumber";
import moment from "moment";
import { autobind } from "core-decorators";
import t from "text-table";
import WebcordCommand from "lib/WebcordCommand";
import TwitchApiClient from "services/twitch/api";
import { Channel, Stream } from "models/";
import logger from "config/logger";
import { ServiceTypes } from "utils/constants";
const VALID_CATEGORIES = [
"streams",
"channels",
"stream",
"channel",
];
@autobind
export default class TwitchFindCommand extends WebcordCommand {
constructor(client, group) {
super(client, {
name: "twitch-find",
aliases: ["find", "search"],
group,
memberName: "twitch-find",
description: "Search for things on Twitch, such as streams, channels, games etc.",
guildOnly: false,
argsType: "multiple",
throttling: {
usages: 3,
duration: 30,
},
examples: [
"find streams Grand Theft Auto V",
"find channels SirPinkleton",
"find stream SirPinkleton00",
"find channel 9072112",
],
}, {
method: "find",
});
}
/** @type {TwitchApiClient} */
get api() {
return this.client.apiClients.get("twitch");
}
async run(msg, [ category, ...rest ]) {
this.debug(".run called; category %s, rest %o", category, rest);
if(!VALID_CATEGORIES.includes(category))
return msg.inform(`Invalid command usage; the pattern is {command} {category} {search term}. Valid categories are ${VALID_CATEGORIES.join(", ")}`);
if(rest.length === 0)
return msg.reply(`Can't look for Twitch streams without a search term`);
msg.channel.startTyping();
const searchTerm = rest.join(" ");
switch(category) {
case "streams":
await this.findStreams(msg, searchTerm); break;
case "channels":
await this.findChannels(msg, searchTerm); break;
case "channel":
case "stream":
await this.findSingle(msg, searchTerm); break;
}
msg.channel.stopTyping();
this.debug("done");
}
async runExternal(msg, { searchTerm }) {
if(!searchTerm)
return super.reject(`Can't look for Twitch streams without a search term`);
const { _total, channels } = await this.api.searchChannels(searchTerm);
return super.resolve({
_total,
channels,
});
}
/**
* @param {CommandMessage} msg
* @param {String} searchTerm
*/
async findStreams(msg, searchTerm) {
this.debug(".findStreams called with searchTerm %s", searchTerm);
try {
let { _total, streams } = await this.api.searchStreams(searchTerm, { limit: 10 });
if(streams.length === 0)
return msg.info("No results");
msg.info(this.listStreams(streams, searchTerm, _total, 10), { duration: 40000 });
} catch(e) {
logger.error(e);
return msg.reply(`Stream search failed`);
}
}
/**
* @param {CommandMessage} msg
* @param {String} searchTerm
*/
async findChannels(msg, searchTerm) {
this.debug(".findChannels called with searchTerm %s", searchTerm);
try {
let { _total, channels } = await this.api.searchChannels(searchTerm, { limit: 10 });
if(channels.length === 0)
return msg.info("No results", { duration: 7500 });
msg.info(this.listChannels(channels, searchTerm, _total, 10), { duration: 40000 });
} catch(e) {
logger.error(e);
return msg.warn(`Stream search failed`);
}
}
/**
* @param {CommandMessage} msg
* @param {String} args
*/
async findSingle(msg, args) {
this.debug(".findSingle called with args %s", args);
const searchTerm = args.split(" ")[0];
const stream = await this.api.getStream(searchTerm);
if(stream)
msg.channel.send(stream.statusSummary, { embed: stream.statusEmbed });
else
msg.warn(`Couldn't find a stream with the search term ${searchTerm}`, { duration: 5000 });
}
listChannels = (channels, searchTerm, found, limit) => {
const summary = channels.map(stream => {
const {
displayName,
url,
} = stream;
return [displayName, `<${url}>`];
});
const table = t(summary, { align: ["l", "r"] });
if(channels.length === 1)
return `Found 1 channel with the search term ${searchTerm}:\n${table}`;
if(channels.length === limit)
return `Found ${found} channels with the search term ${searchTerm}, showing top ${channels.length} results:\n${table}`;
return `Found ${channels.length} channels with the search term ${searchTerm}:\n${table}`;
}
listStreams = (streams, searchTerm, found, limit) => {
const summary = streams.map(stream => {
const {
channel: {
displayName,
url,
},
id,
createdAt,
game,
lastStream,
} = stream;
return [displayName, game, `<${url}>`, `Uptime ${moment(createdAt).fromNow(true)}`];
});
const table = t(summary, { align: ["l", "c", "r", "r"] });
if(streams.length === 1)
return `Found 1 stream with the search term ${searchTerm}:\n${table}`;
if(streams.length === limit)
return `Found ${found} streams with the search term ${searchTerm}, showing top ${streams.length} results:\n${table}`;
return `Found ${streams.length} streams with the search term ${searchTerm}:\n${table}`;
}
}
| kettui/webcord-bot | src/services/twitch/commands/twitch-find.js | JavaScript | mit | 6,110 |
$(document).ready(function() {
/* Get a grid from the URL if it exists */
/*
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
userColors = getParameterByName('colors');
*/
var boxNo = 0;
/* Generate the grid for colors! */
function generateGrid(height,width){
var toAppend = "";
for(var i=0; i<height; i++ ){
toAppend = toAppend + "<div class='row box-row'>";
for(var j=0; j<width; j++ ){
toAppend = toAppend + "<div class='box box-r" + i + "-c" + j + " hidden-sm col-lg-2 col-2'></div>";
}
toAppend = toAppend + "</div><!-- .box-row -->";
}
return toAppend;
}
$('.boxes-row .boxes').append(generateGrid(2,6));
$('.player .boxes').append(generateGrid(6,6));
/* Set the height to match the width */
function setHeight(selector){
var width = $(selector).width();
$(selector).css({'height':width+'px'});
}
function setPadHeight(selector){
var width = $(selector).width();
width = width + 15;
$(selector).css({'height':width+'px'});
}
/* setHeight('.boxes'); */
setPadHeight('.box');
setPadHeight('.player .boxes');
$(window).resize(function(){
setHeight('.bc-iframe');
/* setHeight('.boxes'); */
setPadHeight('.box');
setPadHeight('.player .boxes');
});
/* Insert the bandcamp widget so that we can control the callback */
function callIframe() {
var bcPlayer="<iframe id='bcPlayer' class='bc-iframe' style='border: 0; width: 100%;' src='' seamless> <a href='http://d8ts.bandcamp.com/album/da-tes'>DA/TES by Splotch & Emoticon Dream</a></iframe>";
var srcUrl="http://bandcamp.com/EmbeddedPlayer/album=185332851/size=large/bgcol=ffffff/linkcol=0687f5/transparent=true/";
$('.bc-col').prepend(bcPlayer);
$('iframe#bcPlayer').attr('src', srcUrl);
$('iframe#bcPlayer').load(function() {
setHeight('.bc-iframe');
});
}
callIframe();
/* COLOR THE GRID! */
var play_settings = {
rainbow_mode: 1,
grid_size: 0
};
if (play_settings.rainbow_mode) {
rainbow_mode();
}
function rainbow_mode() {
$('.box').on('mouseenter', function(){
var d = new Date();
var s = d.getSeconds();
var c = s*6; //0-60 seconds --> 0-360 color range
var decColor = c + ", 80%, 40%";
var newColor = "hsl(" + decColor.toString(16) + ")";
/* var newColor = Color(jQuery.Color(oldColor)).toRgbaString(); */
$(this).data("color",c);
$(this).css("background", newColor);
//$(this).animate({background: + newColor }, 100, function(){
/* $(this).animate({backgroundColor: "#eee" }); */
//}); console.log('got here: ' + newColor );
});
}
$('.release-date a, .header').click(function(){
relaseDateLink = $('.release-date a');
if (relaseDateLink.css('font-size') == '120px')
{
$(relaseDateLink).animate({fontSize: "20px"},300);
}
else if (relaseDateLink.css('font-size') == '20px'){
$(relaseDateLink).animate({fontSize: "120px"},300);
}
$('.header-hide').slideToggle(function(){
});
});
$('.box').click(function(){
if ($(this).css('background-color') != '#ccc')
{
$(this).css('background-color','#ccc');
}
});
$('.dates a').popover({trigger:'hover'});
/* Touch screen support */
/*
$('.box-row .box').live("touchstart",function(e){
var $link_id = $(this).attr('id');
if ($(this).parent().data('clicked') == $link_id) {
// element has been tapped (hovered), reset 'clicked' data flag on parent element and return true (activating the link)
$(this).parent().data('clicked', null);
return true;
} else {
$(this).trigger("mouseenter").siblings().trigger("mouseout"); //triggers the hover state on the tapped link (because preventDefault(); breaks this) and untriggers the hover state for all other links in the container.
// element has not been tapped (hovered) yet, set 'clicked' data flag on parent element to id of clicked link, and prevent click
e.preventDefault(); // return false; on the end of this else statement would do the same
$(this).parent().data('clicked', $link_id); //set this link's ID as the last tapped link ('clicked')
}
});
*/
});
| mpgarate/emoticondream.com | DA/TES/js/playergrid.js | JavaScript | mit | 4,332 |
define(
"famous-ui/ColorPicker/ColorButton",
[
"require",
"exports",
"module",
"famous/EventHandler",
"famous/CanvasSurface"
],
function (t, i, e)
{
function s(t, i) {
this.size = t, this.canvasSize = [2 * this.size[0], 2 * this.size[1]], o.call(this, {
size: this.size,
canvasSize: this.canvasSize
}), this.color = i, this.colorSurface(this.color.getHex())
}
t("famous/EventHandler");
var o = t("famous/CanvasSurface");
s.prototype = Object.create(o.prototype), s.prototype.colorSurface = function (t) {
var i = this.getContext("2d");
i.clearRect(0, 0, this.canvasSize[0], this.canvasSize[1]), i.fillStyle = t, i.fillRect(0, 0, this.canvasSize[0], this.canvasSize[1])
}, e.exports = s
}
); | tcha-tcho/famous_basic | js/famous/famous-ui/Colorpicker/ColorButton.js | JavaScript | mit | 916 |
var searchData=
[
['paset',['PASET',['../lcdvars_8h.html#ae23dd30399e167b6335fbd6cb6eba496',1,'lcdvars.h']]],
['pc',['PC',['../struct_t_i_m_e_r___type.html#aae64a9b4b2b024def414615068715511',1,'TIMER_Type']]],
['pclk',['PCLK',['../lpc2106_8h.html#a4e4204874a63b2a01811ee2819285f58',1,'lpc2106.h']]],
['pconp',['PCONP',['../group___l_p_c2106___peripheral_instances.html#gaca7c245b2477a5abdec386b73bda1d15',1,'lpc2106.h']]],
['pconp_5fbase',['PCONP_BASE',['../group___l_p_c2106___peripheral_memory_locations.html#gadb2a0990660f1a5c69885dbc2b4deb07',1,'lpc2106.h']]],
['pin',['PIN',['../struct_g_p_i_o___type.html#a37562d25ab6f3eeb822d20ad58c9c4e7',1,'GPIO_Type::PIN()'],['../ncled_8c.html#aeabac9491522ec7f68102bfeab33d5c1',1,'pin(): ncled.c']]],
['pins',['pins',['../spi_8c.html#abb759ff71dfcc81df33a41fc285ccef1',1,'spi.c']]],
['pinsel',['PINSEL',['../group___l_p_c2106___peripheral_instances.html#gadcf85a8a6da60e211f5dd37abc27b999',1,'lpc2106.h']]],
['pinsel_5fbase',['PINSEL_BASE',['../group___l_p_c2106___peripheral_memory_locations.html#ga3dc1ab7e0fa0ae9bbe08e6d50d34ee85',1,'lpc2106.h']]],
['pos',['POS',['../lcd_8c.html#a9b784f55e6174a327c8121784e2cfb1d',1,'lcd.c']]],
['pr',['PR',['../struct_t_i_m_e_r___type.html#acadb541051be34a08dffcab67ec23555',1,'TIMER_Type']]],
['prclk',['PRCLK',['../timer_8c.html#a34bc98f63f2ad3cf205d3bc259f4c15c',1,'timer.c']]],
['prefrac',['PREFRAC',['../struct_r_t_c_prescaler___type.html#a40b89a9e531d5e0e6e480c99d5f64059',1,'RTCPrescaler_Type']]],
['preint',['PREINT',['../struct_r_t_c_prescaler___type.html#a6c4fc20113ba06a27d94efbc9b824bf9',1,'RTCPrescaler_Type']]],
['pstate',['pstate',['../projeto_2main_8c.html#ae2c5c6e43322ef8562c59e746ccf7aa0',1,'main.c']]],
['ptlin',['PTLIN',['../lcdvars_8h.html#a66c7b621961829dd9b90709fbc3b8b80',1,'lcdvars.h']]],
['ptlout',['PTLOUT',['../lcdvars_8h.html#a589c01ff36bc4c7462f75e5dc8d1fbb0',1,'lcdvars.h']]],
['pwrctr',['PWRCTR',['../lcdvars_8h.html#af70321a672c44691614e8442e5dc528d',1,'lcdvars.h']]]
];
| edukng623/NoughtsNCrosses | docs/doxygen/html/search/all_f.js | JavaScript | mit | 2,028 |
/* eslint-disable import/no-extraneous-dependencies,import/no-unresolved */
import React, { useState } from 'react';
import { Form } from 'react-bootstrap';
import { Typeahead } from 'react-bootstrap-typeahead';
import options from '../data';
/* example-start */
const BasicExample = () => {
const [singleSelections, setSingleSelections] = useState([]);
const [multiSelections, setMultiSelections] = useState([]);
return (
<>
<Form.Group>
<Form.Label>Single Selection</Form.Label>
<Typeahead
id="basic-typeahead-single"
labelKey="name"
onChange={setSingleSelections}
options={options}
placeholder="Choose a state..."
selected={singleSelections}
/>
</Form.Group>
<Form.Group style={{ marginTop: '20px' }}>
<Form.Label>Multiple Selections</Form.Label>
<Typeahead
id="basic-typeahead-multiple"
labelKey="name"
multiple
onChange={setMultiSelections}
options={options}
placeholder="Choose several states..."
selected={multiSelections}
/>
</Form.Group>
</>
);
};
/* example-end */
export default BasicExample;
| ericgio/react-bootstrap-typeahead | example/src/examples/BasicExample.js | JavaScript | mit | 1,227 |
$(document).ready(function(){
$("body").prepend(Fairywren.makeNavbar());
Fairywren.swarm.alert = $("#swarm").find("#alert");
jQuery.get('api/swarm').
done(
function(data)
{
if(! Fairywren.isError(data))
{
Fairywren.swarm.data = data;
Fairywren.swarm();
}
}
).fail(Fairywren.handleServerFailure(Fairywren.swarm.alert) );
});
Fairywren.swarm = function()
{
var out = $("#swarm");
for(username in Fairywren.swarm.data)
{
var div = $("<div />");
var a = $("<span />");
a.text(username);
var user = Fairywren.swarm.data[username]
//a.attr('href' ,'user.html#' + user.href );
div.append($("<h4 />").append(a));
var table = $("<table />");
table.addClass('table');
var thead = $("<thead />");
var tr = $("<tr />");
tr.append($("<th />").text('IP'));
tr.append($("<th />").text('Port'));
tr.append($("<th />").text('Last Seen'));
tr.append($("<th />").text('First Seen'));
thead.append(tr);
table.append(thead);
var tbody = $("<tbody />");
for(var i = 0; i != user.length; ++i)
{
var tr = $("<tr />");
var peer = user[i];
tr.append($("<td />").text(peer.ip));
tr.append($("<td />").text(peer.port));
tr.append($("<td />").text(Fairywren.trimIsoFormatDate(peer.lastSeen)));
tr.append($("<td />").text(Fairywren.trimIsoFormatDate(peer.firstSeen)));
tbody.append(tr);
}
table.append(tbody);
div.append(table);
out.append(div);
}
};
| hydrogen18/fairywren | html/js/swarm.js | JavaScript | mit | 1,464 |
{
"Button": {
"Save": "enregistrer",
"Cancel": "annuler",
"MoreOptions": "plus d'options",
"SaveAndKeepOpen": "enregistrer et rester ici"
},
"Status": {
"Published": "publié",
"Unpublished": "en attente/brouillon"
},
"SaveMode": {
"show": "afficher cet élément",
"hide": "masquer cet élément",
"branch": "masquer les changements en tant que brouillon"
},
"Message": {
"Saving": "En cours d'enregistrement...",
"Saved": "Enregistré",
"ErrorWhileSaving": "Une erreur s'est produite lors de l'enregistrement.",
"WillPublish": "publié dès l'enregistrement",
"WontPublish": "ne sera pas publié immédiatement",
"PleaseCreateDefLang": "Veuillez modifier ceci dans la langue par défaut d'abord.",
"ExitOk": "Voulez-vous vraiment quitter ?",
"Deleting": "suppression...",
"Error": "erreur",
"CantSaveProcessing": "Impossible de sauvegarder car quelque chose d'autre est en cours de traitement",
"CantSaveInvalid": "Formulaire invalide, ne peut pas être enregistrer, erreur sur : <ul>{0}</ul>"
},
"Errors": {
"UnclearError": "Quelque chose s'est mal passé - tout ou en partie. Désolé :(",
"InnerControlMustOverride": "Un controle interne doit supplanter cette fontion.",
"UnsavedChanges": "Il y a des données non enregistrées.",
"DefLangNotFound": "Pas trouvé de langue par défaut, mais plusieurs - mise à jour impossible",
"AdamUploadError": "Le téléchargement a échoué. La cause la plus probable est que le fichier que vous essayez de télécharger est supérieur à la taille de téléchargement maximale."
},
"General": {},
"EditEntity": {
"DefaultTitle": "Mise à jour d'item",
"SlotUsedtrue": "Cet item est en mode modif. Click here to lock / remove it and revert to default.",
"SlotUsedfalse": "Cet item est verrouillé et restera vide ou par défault. Les valeurs sont montrées à titre indicatif. Cliquer ici pour déverrouiller si nécessaire."
},
"FieldType": {
"Entity": {
"Choose": "-- Choix de l'item à ajouter --",
"New": "-- Nouveau --",
"EntityNotFound": "(item non trouvé)",
"DragMove": "ré-ordonner la liste à la souris",
"Edit": "mettre à jour cet item",
"Remove": "supprimer de la liste"
}
},
"LangMenu": {
"UseDefault": "auto (par défaut)",
"In": "dans {{langues}}",
"EditableIn": "editable dans {{langues}}",
"AlsoUsedIn": ", aussi utilisé dans {{more}}",
"NotImplemented": "Action par encore implémentée.",
"CopyNotPossible": "Copie impossible: la rubrique est désactivée.",
"Unlink": "traduire (délier)",
"LinkDefault": "liée par défaut",
"GoogleTranslate": "traduction automatique (Google)",
"Copy": "copier de",
"Use": "utiliser de",
"Share": "partager de",
"AllFields": "tous les champs"
},
"LangWrapper": {
"CreateValueInDefFirst": "Renseigner la rubrique '{{fieldname}}' dans la langue par défaut, avant de la traduire."
},
"CalendarPopup": {
"ClearButton": "Nettoyer",
"CloseButton": "Fait",
"CurrentButton": "Aujourd'hui"
},
"Dialog1": {},
"dialog2": {},
"Extension.TinyMce": {
"Link.AdamFile": "Lien via ADAM-fichier (recommandé)",
"Link.AdamFile.Tooltip": "Lien utilisant ADAM - déposez simplement les fichiers à l'aide du gestionnaire automatique des actifs numériques",
"Image.AdamImage": "Insérer l'image via ADAM (recommandé)",
"Image.AdamImage.Tooltip": "Image via ADAM : déposez simplement des fichiers à l'aide du gestionnaire automatique d'actifs numériques",
"Link.DnnFile": "Lien via DNN-fichiers",
"Link.DnnFile.Tooltip": "Lier un fichier via DNN (tous les fichiers, lent)",
"Image.DnnImage": "Insérer une image via DNN (lent)",
"Image.DnnImage.Tooltip": "Image via le gestionnaire de fichiers DNN (tous les fichiers, lent)",
"Link.Page": "Lien vers une autre page",
"Link.Page.Tooltip": "Lien vers une page du site actuel",
"Link.Anchor.Tooltip": "Ancre pour lier à l'utilisation .../page#nomdelancre",
"SwitchMode.Pro": "Passer en mode avancé",
"SwitchMode.Standard": "Passer en mode standard",
"H1": "H1",
"H2": "H2",
"H3": "H3",
"Remove": "Supprimer",
"ContentBlock.Add": "Ajouter une application ou un content-type"
}
} | 2sic/2sxc-eav-languages | dist/i18n/edit-fr.js | JavaScript | mit | 4,184 |
// Syöte ----------------------------------------------------------------------
function Nappain() {
this.painetut = {};
this.VASEN = 37;
this.YLOS = 38;
this.OIKEA = 39;
this.ALAS = 40;
}
Nappain.prototype.painettu = function(koodi) {
return this.painetut[koodi];
};
Nappain.prototype.painettaessa = function(tapahtuma) {
this.painetut[tapahtuma.keyCode] = true;
};
Nappain.prototype.irrottaessa = function(tapahtuma) {
delete this.painetut[tapahtuma.keyCode];
};
function assosioiNappain(nappain) {
window.addEventListener('keyup', function(event) { nappain.irrottaessa(event); }, false);
window.addEventListener('keydown', function(event) { nappain.painettaessa(event); }, false);
}
| luutifa/jstetris | deadcode.js | JavaScript | mit | 736 |
'use strict';
class Attachment {
constructor(properties) {
properties = properties || {};
this.timestamp = properties.timestamp || Date.now();
this.name = properties.name;
this.base64 = properties.base64;
this.url = properties.url;
this.headers = properties.headers;
this.file = properties.file;
this.isRedirect = properties.isRedirect || false;
}
/**
* Check is attachment is an image
*
* @returns {Boolean} Is image
*/
isImage() {
if(this.headers) {
return this.headers.indexOf('image/') > -1;
}
if(this.url) {
return this.url.match(/\.(png|jpg|bmp|gif)/) != null;
}
return false;
}
/**
* Gets the timestamp
*
* @returns {Date} Timestamp
*/
getTimestamp() {
if(!this.timestamp) { return null; }
let date;
if(!isNaN(this.timestamp)) {
date = new Date(parseInt(this.timestamp));
} else {
date = new Date(this.timestamp);
}
if(!date || isNaN(date.getTime())) { return null; }
return date;
}
/**
* Gets the name
*
* @returns {String} Name
*/
getName() {
return this.name;
}
/**
* Gets the URL
*
* @returns {String} URL
*/
getURL() {
return this.url;
}
/**
* Gets the base64 string
*
* @returns {String} Base64
*/
getBase64() {
return this.base64;
}
}
module.exports = Attachment;
| Putaitu/samoosa | src/client/js/models/Attachment.js | JavaScript | mit | 1,611 |
'use strict'
var shimmer = require('../shimmer')
var logger = require('../logger').child({component: 'pg'})
var parseSql = require('../db/parse-sql')
var POSTGRES = require('../metrics/names').POSTGRES
var util = require('util')
// Adds a segment
// The `config` argument is either a statement string template or a pg statement
// config object with a `text` property holding the statement string template.
function initializeSegment(tracer, segment, client, config) {
var statement
if (config && (typeof config === 'string' || config instanceof String)) {
statement = config
} else if (config && config.text) {
statement = config.text
} else {
// Won't be matched by parser, but should be handled properly
statement = 'Other'
}
var ps = parseSql(POSTGRES.PREFIX, statement)
var model = ps.model
var operation = ps.operation
segment.name = POSTGRES.STATEMENT + (model || 'other') + '/' + operation
segment.captureDBInstanceAttributes(client.host, client.port, client.database)
logger.trace(
'capturing postgresql query. model: %s, operation: %s',
model,
operation
)
tracer.getTransaction().addRecorder(ps.recordMetrics.bind(ps, segment))
}
module.exports = function initialize(agent, pgsql) {
if (!pgsql) return
var tracer = agent.tracer
// allows for native wrapping to not happen if not necessary
// when env var is true
if (process.env.NODE_PG_FORCE_NATIVE) {
return instrumentPGNative('pg', pgsql)
}
// The pg module defines "native" getter which sets up the native client lazily
// (only when called). We replace the getter, so that we can instrument the native
// client. The original getter replaces itself with the instance of the native
// client, so only instrument if the getter exists (otherwise assume already
// instrumented).
var origGetter = pgsql.__lookupGetter__('native')
if (origGetter) {
delete pgsql.native
pgsql.__defineGetter__('native', function getNative() {
var temp = origGetter()
instrumentPGNative('pg.native', temp)
return temp
})
}
// wrapping for native
function instrumentPGNative(eng, pg) {
shimmer.wrapMethod(pg, 'pg', 'Client', wrapClient)
shimmer.wrapMethod(pg.pools, 'pg.pools', 'Client', wrapClient)
shimmer.wrapMethod(pg, 'pg', 'Pool', wrapPool)
function newApply(Cls) {
return new (Cls.bind.apply(Cls, arguments))()
}
function wrapPool(Pool) {
if (shimmer.isWrapped(Pool)) {
return Pool
}
util.inherits(WrappedPool, Pool)
WrappedPool.__NR_original = Pool
return WrappedPool
/* eslint-disable no-unused-vars */
function WrappedPool(options, Client) {
/* eslint-enable no-unused-vars */
if (!(this instanceof WrappedPool)) {
return newApply(WrappedPool, arguments)
}
Pool.apply(this, arguments)
this.Client = wrapClient(this.Client)
}
}
function wrapClient(Client) {
if (shimmer.isWrapped(Client)) {
return Client
}
util.inherits(WrappedClient, Client)
Object.keys(Client).forEach(function forEachClientKey(k) {
WrappedClient[k] = Client[k]
})
WrappedClient.__NR_original = Client
return WrappedClient
// -------------------------------------------------------------------- //
/* eslint-disable no-unused-vars */
function WrappedClient(options) {
/* eslint-enable no-unused-vars */
// NOTE: This is an instance of PG's `Client` class, _not_ its
// `Connection` class. This is an important distinction as the
// latter does not have the host/port/database meta data.
// Apply the constructor. JavaScript really needs a better way to do this.
// This logic is the same as `newApply`, however for some reason `newApply`
// does not work on Node v0.8 or v0.10. For `WrappedPool` this doesn't
// matter since the versions of PG it is in don't support those ancient
// versions of Node either, but here we must do it ourselves.
var args = tracer.slice(arguments)
args.unshift(Client) // `unshift` === `push_front`
var client = new (Client.bind.apply(Client, args))()
// Wrap the methods we care about.
shimmer.wrapMethod(client, 'Client', 'connect', wrapConnect)
shimmer.wrapMethod(client, 'Client', 'query', wrapNativeQuery)
return client
}
function wrapConnect(connect) {
return function wrappedConnect(callback) {
if (typeof callback === 'function') {
callback = tracer.bindFunction(callback)
}
return connect.call(this, callback)
}
}
function wrapNativeQuery(original) {
return tracer.wrapFunction(
POSTGRES.STATEMENT + 'Unknown',
null,
original,
nativeQueryWrapper,
nativeResponseWrapper
)
}
function nativeQueryWrapper(segment, args, bindCallback) {
initializeSegment(tracer, segment, this, args[0])
var pos = args.length - 1
var last = args[pos]
// Proxy callback in case they start new segments
args[pos] = bindCallback(last)
return args
}
function nativeResponseWrapper(segment, result, bindCallback) {
// Wrap end and error events too, in case they start new segments
// within them. Use end and error events to end segments.
result.on('error', end)
result.on('end', end)
function end() {
segment.touch()
logger.trace(
'postgres command trace segment ended by event for transaction %s.',
segment.transaction.id
)
}
// TODO: Maybe .on and .addListener shouldn't be different
// Proxy events too, in case they start new segments within handlers
shimmer.wrapMethod(result, 'query.on', 'on', function queryOnWrapper(on) {
return function queryOnWrapped() {
if (arguments[1]) {
if (arguments[0] !== 'row') {
arguments[1] = bindCallback(arguments[1])
} else {
arguments[1] = tracer.bindFunction(arguments[1], segment, true)
}
}
return on.apply(this, arguments)
}
})
shimmer.wrapMethod(
result,
'query.addListener',
'addListener',
queryAddListenerWrapper
)
function queryAddListenerWrapper(addL) {
return function queryAddListenerWrapped() {
if (arguments[1]) {
if (arguments[0] !== 'row') {
arguments[1] = bindCallback(arguments[1])
} else {
arguments[1] = tracer.bindFunction(arguments[1], segment, true)
}
}
addL.apply(this, arguments)
}
}
return result
}
}
}
// wrapping for JS
shimmer.wrapMethod(
pgsql && pgsql.Client && pgsql.Client.prototype,
'pg.Client.prototype',
'query',
wrapQuery
)
function wrapQuery(original) {
return tracer.wrapFunction(
POSTGRES.STATEMENT + 'Unknown',
null,
original,
queryWrapper,
responseWrapper
)
}
function queryWrapper(segment, args, bindCallback) {
var position = args.length - 1
var last = args[position]
initializeSegment(tracer, segment, this, args[0])
// Proxy callbacks in case they start new segments
if (typeof last === 'function') {
args[position] = bindCallback(last, true, true)
} else if (Array.isArray(last) && typeof last[last.length - 1] === 'function') {
var callback = last[last.length - 1]
last[last.length - 1] = bindCallback(callback)
}
return args
}
function responseWrapper(segment, query, bindCallback) {
// Use end and error events to end segments
query.on('error', end)
query.on('end', end)
function end() {
segment.end()
logger.trace(
'postgres command trace segment ended by event for transaction %s.',
segment.transaction.id
)
}
// Proxy events too, in case they start new segments within handlers
shimmer.wrapMethod(query, 'query.on', 'on', function queryOnWrapper(on) {
return function queryOnWrapped() {
if (arguments[1]) {
if (arguments[0] !== 'row') {
arguments[1] = bindCallback(arguments[1])
} else {
arguments[1] = tracer.bindFunction(arguments[1], segment, true)
}
}
return on.apply(this, arguments)
}
})
shimmer.wrapMethod(query, 'query.addListener', 'addListener', addListenerWrapper)
function addListenerWrapper(addL) {
return function wrappedAddListener() {
if (arguments[1]) {
if (arguments[0] !== 'row') {
arguments[1] = bindCallback(arguments[1])
} else {
arguments[1] = tracer.bindFunction(arguments[1], segment, true)
}
}
addL.apply(this, arguments)
}
}
return query
}
}
| dnosk/Firesong | node_modules/newrelic/lib/instrumentation/pg.js | JavaScript | mit | 9,216 |
'use strict';
// Make sure lines are splited correctly
// http://stackoverflow.com/questions/1155678/javascript-string-newline-character
const NEW_LINE = /\r\n|\n|\r/,
path = require('path'),
fs = require('fs'),
Q = require('q'),
cwd = process.cwd();
/**
* Take ical string data and convert to JSON
*
* @param {string} source
* @returns {Object}
**/
function convert(source) {
let currentKey = '',
currentValue = '',
objectNames = [],
output = {},
parentObj = {},
lines0 = source.split(NEW_LINE),
splitAt;
let currentObj = output;
let parents = [];
//merge multi-line items
const lines = lines0.reduce((acc, curr, i) => {
if (curr[0] === ' ') {
const prev = acc.pop();
const new_elem = prev.concat(curr.substr(1));
acc.push(new_elem);
} else {
acc.push(curr);
}
return acc;
}, []);
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
//some lines are a continuation of the previous one & start with a ' ;'
if (line.substr(0, 2) === ' ;') {
const nextLine = lines.splice(i+1, 1);
line += nextLine;
}
if (line.charAt(0) === ' ') {
currentObj[currentKey] += line.substr(1);
} else {
splitAt = line.indexOf(':');
if (splitAt < 0) {
continue;
}
//key:value
currentKey = line.substr(0, splitAt);
currentValue = line.substr(splitAt + 1);
switch (currentKey) {
case 'BEGIN':
parents.push(parentObj);
parentObj = currentObj;
if (parentObj[currentValue] == null) {
parentObj[currentValue] = [];
}
// Create a new object, store the reference for future uses
currentObj = {};
parentObj[currentValue].push(currentObj);
break;
case 'END':
currentObj = parentObj;
parentObj = parents.pop();
break;
default:
if(currentObj[currentKey]) {
if(!Array.isArray(currentObj[currentKey])) {
currentObj[currentKey] = [currentObj[currentKey]];
}
currentObj[currentKey].push(currentValue);
} else {
currentObj[currentKey] = currentValue;
}
}
}
}
return output;
};
/**
* Take JSON, revert back to ical
* @param {Object} object
* @return {String}
**/
function revert(object) {
let lines = [];
for (let key in object) {
let value = object[key];
if (Array.isArray(value)) {
value.forEach((item) => {
lines.push(`BEGIN:${key}`);
lines.push(revert(item));
lines.push(`END:${key}`);
});
} else {
let fullLine = `${key}:${value}`;
do {
// According to ical spec, lines of text should be no longer
// than 75 octets
lines.push(fullLine.substr(0, 75));
fullLine = ' ' + fullLine.substr(75);
} while (fullLine.length > 1);
}
}
return lines.join('\n');
}
/**
* Pass in options to parse and generate JSON files
* @param {Object} options
* @return {Promise}
**/
function run(options) {
let files, filePromises = [];
files = options.args || [];
for (let i = 0; i < files.length; i++) {
let file = files[i];
let filePath = path.resolve(cwd, file);
if (!fs.existsSync(filePath)) {
continue;
}
let stat = fs.statSync(filePath);
let ext = path.extname(filePath);
let isConvert = !options.revert && ext === '.ics'
let isRevert = options.revert && ext === '.json'
if (!stat.isFile() || (!isConvert && !isRevert)) {
continue;
}
filePromises.push(Q.nfcall(fs.readFile, filePath)
.then((buffer) => {
let output;
let data = buffer.toString();
if (isConvert) {
output = convert(data);
output = JSON.stringify(output, null, ' ');
} else if (isRevert) {
output = revert(data);
}
let basename = path.basename(filePath, ext);
let dirname = path.dirname(filePath);
let compiledExt = isConvert ? '.json' : '.ics';
let writePath = path.join(dirname, basename) + compiledExt;
return Q.nfcall(fs.writeFile, writePath, output);
})
.fail((error) => {
throw new Error(error);
}));
}
return Q.all(filePromises);
}
module.exports = {
run: run,
revert: revert,
convert: convert,
}
| machinshin/ical2json | index.js | JavaScript | mit | 4,447 |
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true
},
proxy: {
'/proxy/*': {
target: 'http://dev.buzzfeed.com',
secure: false,
},
},
}).listen(3000, 'dev.buzzfeed.com', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at dev.buzzfeed.com:3000');
});
| harrygreen/parlay | server.js | JavaScript | mit | 545 |
/* globals require, module */
/**
* Module dependencies.
*/
var pathtoRegexp = require('path-to-regexp');
/**
* Module exports.
*/
module.exports = page;
/**
* To work properly with the URL
* history.location generated polyfill in https://github.com/devote/HTML5-History-API
*/
var location = window.history.location || window.location;
/**
* Perform initial dispatch.
*/
var dispatch = true;
/**
* Base path.
*/
var base = '';
/**
* Running flag.
*/
var running;
/**
* HashBang option
*/
var hashbang = false;
/**
* Register `path` with callback `fn()`,
* or route `path`, or `page.start()`.
*
* page(fn);
* page('*', fn);
* page('/user/:id', load, user);
* page('/user/' + user.id, { some: 'thing' });
* page('/user/' + user.id);
* page();
*
* @param {String|Function} path
* @param {Function} fn...
* @api public
*/
function page(path, fn) {
// <callback>
if ('function' === typeof path) {
return page('*', path);
}
// route <path> to <callback ...>
if ('function' === typeof fn) {
var route = new Route(path);
for (var i = 1; i < arguments.length; ++i) {
page.callbacks.push(route.middleware(arguments[i]));
}
// show <path> with [state]
} else if ('string' == typeof path) {
'string' === typeof fn
? page.redirect(path, fn)
: page.show(path, fn);
// start [options]
} else {
page.start(path);
}
}
/**
* Callback functions.
*/
page.callbacks = [];
/**
* Get or set basepath to `path`.
*
* @param {String} path
* @api public
*/
page.base = function(path){
if (0 === arguments.length) return base;
base = path;
};
/**
* Bind with the given `options`.
*
* Options:
*
* - `click` bind to click events [true]
* - `popstate` bind to popstate [true]
* - `dispatch` perform initial dispatch [true]
*
* @param {Object} options
* @api public
*/
page.start = function(options){
options = options || {};
if (running) return;
running = true;
if (false === options.dispatch) dispatch = false;
if (false !== options.popstate) window.addEventListener('popstate', onpopstate, false);
if (false !== options.click) window.addEventListener('click', onclick, false);
if (true === options.hashbang) hashbang = true;
if (!dispatch) return;
var url = (hashbang && ~location.hash.indexOf('#!'))
? location.hash.substr(2) + location.search
: location.pathname + location.search + location.hash;
page.replace(url, null, true, dispatch);
};
/**
* Unbind click and popstate event handlers.
*
* @api public
*/
page.stop = function(){
if (!running) return;
running = false;
window.removeEventListener('click', onclick, false);
window.removeEventListener('popstate', onpopstate, false);
};
/**
* Show `path` with optional `state` object.
*
* @param {String} path
* @param {Object} state
* @param {Boolean} dispatch
* @return {Context}
* @api public
*/
page.show = function(path, state, dispatch){
var ctx = new Context(path, state);
if (false !== dispatch) page.dispatch(ctx);
if (false !== ctx.handled) ctx.pushState();
return ctx;
};
/**
* Show `path` with optional `state` object.
*
* @param {String} from
* @param {String} to
* @api public
*/
page.redirect = function(from, to) {
page(from, function (e) {
setTimeout(function() {
page.replace(to);
});
});
};
/**
* Replace `path` with optional `state` object.
*
* @param {String} path
* @param {Object} state
* @return {Context}
* @api public
*/
page.replace = function(path, state, init, dispatch){
var ctx = new Context(path, state);
ctx.init = init;
ctx.save(); // save before dispatching, which may redirect
if (false !== dispatch) page.dispatch(ctx);
return ctx;
};
/**
* Dispatch the given `ctx`.
*
* @param {Object} ctx
* @api private
*/
page.dispatch = function(ctx){
var i = 0;
function next() {
var fn = page.callbacks[i++];
if (!fn) return unhandled(ctx);
fn(ctx, next);
}
next();
};
/**
* Unhandled `ctx`. When it's not the initial
* popstate then redirect. If you wish to handle
* 404s on your own use `page('*', callback)`.
*
* @param {Context} ctx
* @api private
*/
function unhandled(ctx) {
if (ctx.handled) return;
var current;
if (hashbang) {
current = base + location.hash.replace('#!','');
} else {
current = location.pathname + location.search;
}
if (current === ctx.canonicalPath) return;
page.stop();
ctx.handled = false;
location.href = ctx.canonicalPath;
}
/**
* Initialize a new "request" `Context`
* with the given `path` and optional initial `state`.
*
* @param {String} path
* @param {Object} state
* @api public
*/
function Context(path, state) {
if ('/' === path[0] && 0 !== path.indexOf(base)) path = base + path;
var i = path.indexOf('?');
this.canonicalPath = path;
this.path = path.replace(base, '') || '/';
this.title = document.title;
this.state = state || {};
this.state.path = path;
this.querystring = ~i
? path.slice(i + 1)
: '';
this.pathname = ~i
? path.slice(0, i)
: path;
this.params = [];
// fragment
this.hash = '';
if (!~this.path.indexOf('#')) return;
var parts = this.path.split('#');
this.path = parts[0];
this.hash = parts[1] || '';
this.querystring = this.querystring.split('#')[0];
}
/**
* Expose `Context`.
*/
page.Context = Context;
/**
* Push state.
*
* @api private
*/
Context.prototype.pushState = function(){
history.pushState(this.state
, this.title
, hashbang && this.path !== '/'
? '#!' + this.path
: this.canonicalPath);
};
/**
* Save the context state.
*
* @api public
*/
Context.prototype.save = function(){
history.replaceState(this.state
, this.title
, hashbang && this.path !== '/'
? '#!' + this.path
: this.canonicalPath);
};
/**
* Initialize `Route` with the given HTTP `path`,
* and an array of `callbacks` and `options`.
*
* Options:
*
* - `sensitive` enable case-sensitive routes
* - `strict` enable strict matching for trailing slashes
*
* @param {String} path
* @param {Object} options.
* @api private
*/
function Route(path, options) {
options = options || {};
this.path = (path === '*') ? '(.*)' : path;
this.method = 'GET';
this.regexp = pathtoRegexp(this.path,
this.keys = [],
options.sensitive,
options.strict);
}
/**
* Expose `Route`.
*/
page.Route = Route;
/**
* Return route middleware with
* the given callback `fn()`.
*
* @param {Function} fn
* @return {Function}
* @api public
*/
Route.prototype.middleware = function(fn){
var self = this;
return function(ctx, next){
if (self.match(ctx.path, ctx.params)) return fn(ctx, next);
next();
};
};
/**
* Check if this route matches `path`, if so
* populate `params`.
*
* @param {String} path
* @param {Array} params
* @return {Boolean}
* @api private
*/
Route.prototype.match = function(path, params){
var keys = this.keys,
qsIndex = path.indexOf('?'),
pathname = ~qsIndex
? path.slice(0, qsIndex)
: path,
m = this.regexp.exec(decodeURIComponent(pathname));
if (!m) return false;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = 'string' === typeof m[i]
? decodeURIComponent(m[i])
: m[i];
if (key) {
params[key.name] = undefined !== params[key.name]
? params[key.name]
: val;
} else {
params.push(val);
}
}
return true;
};
/**
* Handle "populate" events.
*/
function onpopstate(e) {
if (e.state) {
var path = e.state.path;
page.replace(path, e.state);
}
}
/**
* Handle "click" events.
*/
function onclick(e) {
if (1 != which(e)) return;
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
if (e.defaultPrevented) return;
// ensure link
var el = e.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (!el || 'A' != el.nodeName) return;
// ensure non-hash for the same path
var link = el.getAttribute('href');
if (el.pathname === location.pathname && (el.hash || '#' === link)) return;
// Check for mailto: in the href
if (link && link.indexOf("mailto:") > -1) return;
// check target
if (el.target) return;
// x-origin
if (!sameOrigin(el.href)) return;
// rebuild path
var path = el.pathname + el.search + (el.hash || '');
// same page
var orig = path;
path = path.replace(base, '');
if (base && orig === path) return;
e.preventDefault();
page.show(orig);
}
/**
* Event button.
*/
function which(e) {
e = e || window.event;
return null === e.which
? e.button
: e.which;
}
/**
* Check if `href` is the same origin.
*/
function sameOrigin(href) {
var origin = location.protocol + '//' + location.hostname;
if (location.port) origin += ':' + location.port;
return (href && (0 === href.indexOf(origin)));
}
page.sameOrigin = sameOrigin;
| AndryGP/loopback-polymer-test | client/bower_components/page/index.js | JavaScript | mit | 9,743 |
$(document).ready(function () {
//NOTE: Ajax command MUST start with the Ajax provider key. (Plugin Ref)
$('#syspay_cmdSave').unbind("click");
$('#syspay_cmdSave').click(function () {
$('.processing').show();
$('.actionbuttonwrapper').hide();
nbxget('nbrightsystempay_savesettings', '.syspaydata', '.syspayreturnmsg');
});
$('.selectlang').unbind("click");
$(".selectlang").click(function () {
$('.editlanguage').hide();
$('.actionbuttonwrapper').hide();
$('.processing').show();
$("#nextlang").val($(this).attr("editlang"));
nbxget('nbrightsystempay_selectlang', '.syspaydata', '.syspaydata');
});
$(document).on("nbxgetcompleted", NBS_SysPay_nbxgetCompleted); // assign a completed event for the ajax calls
// function to do actions after an ajax call has been made.
function NBS_SysPay_nbxgetCompleted(e) {
$('.processing').hide();
$('.actionbuttonwrapper').show();
$('.editlanguage').show();
if (e.cmd == 'nbrightsyspayajax_selectlang') {
}
};
});
| leedavi/NBrightSystemPay | Themes/config/js/systempay.js | JavaScript | mit | 1,142 |
version https://git-lfs.github.com/spec/v1
oid sha256:13b184013af00192afea923539131e9804f0068ce382bae3dd94bd73e4a7bb08
size 7017
| yogeshsaroya/new-cdnjs | ajax/libs/foundation/5.3.0/js/foundation/foundation.reveal.min.js | JavaScript | mit | 129 |
YUI.add("extension-view-parent", function(Y) {
"use strict";
var ViewParent = function() {},
classRegex = /\s+/;
ViewParent.ATTRS = {
children : {
value : false
}
};
ViewParent.prototype = {
initializer : function() {
this._viewParentHandles = [
//Make sure new child views bubble
this.on("childrenChange", this._childrenChange, this),
//Stick children into rendered DOM after the parent has rendered itself
Y.Do.after(this.renderChildren, this, "render", this)
];
//catch initial values of views ATTR
this._childrenChange({
newVal : this.get("children")
});
},
//destroy child views & clean up all handles
destructor : function() {
Y.Object.each(this.get("children"), function(view) {
view.destroy();
});
new Y.EventTarget(this._viewParentHandles).detach();
this._viewParentHandles = null;
},
renderChild : function(name, view) {
var parent = this.get("container"),
slot = parent.one("[data-child=\"" + name + "\"]"),
el, classes, css;
if(!slot) {
return;
}
view.render();
el = view.get("container");
classes = el.get("className");
// Ensure we don't double up on any classes
css = [ "child", name, view.name ].concat(slot.get("className").split(classRegex));
css = Y.Array.dedupe(css).filter(function(str) {
return str.length || classes.indexOf(str) === -1;
});
if(css.length) {
el.addClass(css.join(" "));
}
slot.replace(el);
},
//render all the child views & inject them into the placeholders
renderChildren : function() {
var children = this.get("children"),
name;
if(!children) {
return;
}
this.get("container").addClass("parent");
for(name in children) {
this.renderChild(name, children[name]);
}
},
//make sure custom events from child views bubble to parent view
_childrenChange : function(e) {
var self = this,
id = Y.stamp(this);
Y.Object.each(e.newVal, function(view) {
if(id in view) {
return;
}
view[id] = true;
view.set("parent", self);
view.addTarget(self);
});
}
};
Y.namespace("Extensions").ViewParent = ViewParent;
}, "@VERSION@", {
requires : [
"view",
"event-custom"
]
});
| tivac/yui-viewparent | extension-view-parent.js | JavaScript | mit | 3,125 |
"use strict";
define([
'marionette',
"ldsh!../../templates/list/EmptyIssuesView.html"
], function(Marionette, template) {
/**
* Renders only if issues collection is empty
*/
return Marionette.ItemView.extend({
template: template
});
}); | AlexTiTanium/GithubUI | app/modules/issues/view/list/EmptyIssuesView.js | JavaScript | mit | 276 |
var gulp = require("gulp");
var connect = require("gulp-connect");
var less = require("gulp-less");
var browserSync = require('browser-sync');
var notify = require("gulp-notify");
var plumber = require("gulp-plumber");
gulp.task("move", function () {
return gulp.src(
['./bower_components/bootstrap/dist/js/**/*bootstrap*js',
'./bower_components/bootstrap/dist/css/**/*bootstrap*css',
'./bower_components/bootstrap/dist/fonts/**/*',
'./bower_components/jquery/dist/**/*jquery*js',
'./bower_components/angular/**/*angular*js',
'./bower_components/angular-route/**/*angular*js',
'./bower_components/angular-animate/**/*angular*js',
'./bower_components/angular-bootstrap/**/*bootstrap*js',
'./bower_components/angular-bootstrap/**/*bootstrap*css',
'./bower_components/angular-sanitize/**/*angular*js',
'./bower_components/angular-translate/**/*angular*js',
'./bower_components/angular-ui-grid/**/*ui-grid*',
'./bower_components/ag-grid/dist/**/*ag-grid*',
'./bower_components/ag-grid/dist/**/*.css',
'./bower_components/hashmap/**/*.js'
],
{
base: './bower_components'
}
).pipe(gulp.dest('lib'))
});
gulp.task("move-npm", function () {
return gulp.src(
['./node_modules/ng-table/bundles/**/*ng-table*js',
'./node_modules/ng-table/bundles/**/*ng-table*css',
'./node_modules/ui-grid-auto-fit-columns/dist/**/*Columns*js'
],
{
base: './node_modules'
}
).pipe(gulp.dest('lib'))
});
gulp.task('less', function () {
gulp.src("app/**/*.less")
.pipe(plumber({errorHandler: notify.onError("Error: <%=error.message%>")}))
.pipe(less())
.pipe(gulp.dest("assets/css"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: '.',
},
port: 80
})
});
gulp.task("watch", function () {
gulp.watch("app/**/*.less", ["less"]);
gulp.watch("./**/*.html", browserSync.reload);
gulp.watch("./**/*.css", browserSync.reload);
gulp.watch("app/**/*.js", browserSync.reload);
});
gulp.task('default', ['browserSync', 'watch', 'less']); | zhangjikai/samples | angularjs-table/gulpfile.js | JavaScript | mit | 2,395 |
var NAVTREEINDEX0 =
{
"32_8h.html":[0,0,0,0,0,0,0],
"32_8h.html#a4ba979a6ca3bd355a212e278392b94ab":[0,0,0,0,0,0,0,2],
"32_8h.html#a878911ffecdb5d585e7f64e1c77bdb38":[0,0,0,0,0,0,0,1],
"32_8h.html#ab433e39ce55411c661f37d8a6c05454b":[0,0,0,0,0,0,0,0],
"32_8h_source.html":[0,0,0,0,0,0,0],
"64_8h.html":[0,0,0,0,0,0,1],
"64_8h.html#aa51d332ef1206130096bd3284a91f6b8":[0,0,0,0,0,0,1,1],
"64_8h.html#ab2863e9e9a481f12136abea287711bd5":[0,0,0,0,0,0,1,0],
"64_8h.html#ae967c9dbf4be6ed91ca4885a8a2d811a":[0,0,0,0,0,0,1,2],
"64_8h_source.html":[0,0,0,0,0,0,1],
"_alpha_8h.html":[0,0,0,0,0,1],
"_alpha_8h.html#a0dcfd50aa5526402e91046134fff734c":[0,0,0,0,0,1,1],
"_alpha_8h.html#a52e7f80503730a2fae3d06ef9fd0215c":[0,0,0,0,0,1,0],
"_alpha_8h.html#a754e64c84c1c57fb0ec4ec13385f6b54":[0,0,0,0,0,1,2],
"_alpha_8h_source.html":[0,0,0,0,0,1],
"_architecture_8h.html":[0,0,0,0,2],
"_architecture_8h_source.html":[0,0,0,0,2],
"_arm_8h.html":[0,0,0,0,0,2],
"_arm_8h.html#a5540fcabe8dfe5d19bbf4abbfac5beb4":[0,0,0,0,0,2,0],
"_arm_8h.html#a65f72cde0517728867a4c09a67afeb63":[0,0,0,0,0,2,2],
"_arm_8h.html#aa1f98ae7b11e116535cfadf1ca421821":[0,0,0,0,0,2,1],
"_arm_8h_source.html":[0,0,0,0,0,2],
"_blackfin_8h.html":[0,0,0,0,0,3],
"_blackfin_8h.html#a666183163960c3ec8bb8a6d9326df144":[0,0,0,0,0,3,1],
"_blackfin_8h.html#aab660c78f9f263a40e3cbf92a47e8098":[0,0,0,0,0,3,0],
"_blackfin_8h.html#ab36b9f4ab51546a1110f142b36da26a0":[0,0,0,0,0,3,2],
"_blackfin_8h_source.html":[0,0,0,0,0,3],
"_borland_8h.html":[0,0,0,0,1,0],
"_borland_8h_source.html":[0,0,0,0,1,0],
"_clang_8h.html":[0,0,0,0,1,1],
"_clang_8h_source.html":[0,0,0,0,1,1],
"_compiler_8h.html":[0,0,0,0,3],
"_compiler_8h_source.html":[0,0,0,0,3],
"_convex_8h.html":[0,0,0,0,0,4],
"_convex_8h.html#a2f04a30f0e0b57ab128e5a3e315023e2":[0,0,0,0,0,4,0],
"_convex_8h.html#aae1b16723fa5df1fdcf4c40d9a9c6374":[0,0,0,0,0,4,2],
"_convex_8h.html#ac9b5d211570e7dda28dd7374cc16f25b":[0,0,0,0,0,4,1],
"_convex_8h_source.html":[0,0,0,0,0,4],
"_i_a64_8h.html":[0,0,0,0,0,5],
"_i_a64_8h.html#a1dab459cd10a9dac6b5ec394db9d2b6c":[0,0,0,0,0,5,0],
"_i_a64_8h.html#a4e8c3337da6c8b5f42479dc578076891":[0,0,0,0,0,5,1],
"_i_a64_8h.html#afda61306e71fa761c2b03084b8889a71":[0,0,0,0,0,5,2],
"_i_a64_8h_source.html":[0,0,0,0,0,5],
"_language_8h.html":[0,0,0,0,4],
"_language_8h_source.html":[0,0,0,0,4],
"_library_8h.html":[0,0,0,0,5],
"_library_8h_source.html":[0,0,0,0,5],
"_m68k_8h.html":[0,0,0,0,0,6],
"_m68k_8h.html#a0e543287a5f4ae3e48fb8861780687c9":[0,0,0,0,0,6,2],
"_m68k_8h.html#a187959c94c0a9a25b163b28e76fffe02":[0,0,0,0,0,6,0],
"_m68k_8h.html#a2c778de73020cfba04316444a26c40b9":[0,0,0,0,0,6,1],
"_m68k_8h_source.html":[0,0,0,0,0,6],
"_m_i_p_s_8h.html":[0,0,0,0,0,7],
"_m_i_p_s_8h.html#a1bd75809902e8b5d0292c160d88e6e35":[0,0,0,0,0,7,2],
"_m_i_p_s_8h.html#a3390edf25fc4b47fa023dd47bc6f2bcc":[0,0,0,0,0,7,1],
"_m_i_p_s_8h.html#af1db7990cf48ad44746cb2bffa9dc663":[0,0,0,0,0,7,0],
"_m_i_p_s_8h_source.html":[0,0,0,0,0,7],
"_make_8h.html":[0,0,0,0,6],
"_make_8h.html#a0c79a78ad6e9a81eaa7b94b9b4a9c6ec":[0,0,0,0,6,11],
"_make_8h.html#a17a1f5cf256a69d90b18debef123c962":[0,0,0,0,6,19],
"_make_8h.html#a3369fb52b3b416978715a5da1672ce8d":[0,0,0,0,6,23],
"_make_8h.html#a3481bcd4ce89beb05b47c25020a6b360":[0,0,0,0,6,18],
"_make_8h.html#a42f5f5138b005d886137b1d3aba1d5e8":[0,0,0,0,6,20],
"_make_8h.html#a47e13c4e4aa7ec32cc3ad3c886a25fbc":[0,0,0,0,6,3],
"_make_8h.html#a4c4910e520ba7de34bb6faf973641702":[0,0,0,0,6,14],
"_make_8h.html#a5fe4c750b933bbbef0c31a7a179756de":[0,0,0,0,6,2],
"_make_8h.html#a609ae66a5de95446d5ab703b46aedfdf":[0,0,0,0,6,17],
"_make_8h.html#a75f262c07c8a4f6f87344dcd279e5eaa":[0,0,0,0,6,9],
"_make_8h.html#a7ab55a1ef159f90d5ce32c0a92605621":[0,0,0,0,6,13],
"_make_8h.html#a98d37c249b1b1fb232313339e2687006":[0,0,0,0,6,0],
"_make_8h.html#aa48e83778df95cd4f7c9ac4c29a5e035":[0,0,0,0,6,10],
"_make_8h.html#aaef9256c505692e20c2af8e8485af1ee":[0,0,0,0,6,5],
"_make_8h.html#ab7434daeef9285bbc874be736bf6e67a":[0,0,0,0,6,15],
"_make_8h.html#aba4ba6a18c31571f2c3d1203d33f1208":[0,0,0,0,6,4],
"_make_8h.html#ad2a2d7d212e5f29803a646476ba50f56":[0,0,0,0,6,6],
"_make_8h.html#ad5910fd0819ab21ff9cecd0eae61ec2f":[0,0,0,0,6,7],
"_make_8h.html#ad5bef75a36bb07b94847f9d680c44b23":[0,0,0,0,6,24],
"_make_8h.html#ad6c21f9401934c1f98c0d9592d681e94":[0,0,0,0,6,1],
"_make_8h.html#add6cbce2ee8c4eadaef4564ee36c344d":[0,0,0,0,6,22],
"_make_8h.html#aeb7bb48c1f93cb2573a1d9acfb7228e7":[0,0,0,0,6,12],
"_make_8h.html#af78e4f779e8726b64725a1dce09ee1c8":[0,0,0,0,6,16],
"_make_8h.html#afb1d78d31490e105ee89ed41375f8865":[0,0,0,0,6,8],
"_make_8h.html#aff226bb1c97f309b7758a56cb9f6ea46":[0,0,0,0,6,21],
"_make_8h_source.html":[0,0,0,0,6],
"_o_s_8h.html":[0,0,0,0,7],
"_o_s_8h_source.html":[0,0,0,0,7],
"_p_a-_r_i_s_c_8h.html":[0,0,0,0,0,8],
"_p_a-_r_i_s_c_8h.html#a84cf4d53f95baf68cd6f68970d267625":[0,0,0,0,0,8,1],
"_p_a-_r_i_s_c_8h.html#aa5510d3fa31213cdd61c45db0e56f527":[0,0,0,0,0,8,0],
"_p_a-_r_i_s_c_8h.html#ade818f5ae84c191942a15a5ef6633bb1":[0,0,0,0,0,8,2],
"_p_a-_r_i_s_c_8h_source.html":[0,0,0,0,0,8],
"_p_p_c_8h.html":[0,0,0,0,0,9],
"_p_p_c_8h.html#a3ea9d9c14e5644faaeb78af594b8ac34":[0,0,0,0,0,9,0],
"_p_p_c_8h.html#ace0c9b4ebf4c86daa379e6207e257271":[0,0,0,0,0,9,2],
"_p_p_c_8h.html#af5da70d2f726653f52890e6017ad2a85":[0,0,0,0,0,9,1],
"_p_p_c_8h_source.html":[0,0,0,0,0,9],
"_platform_8h.html":[0,0,0,0,8],
"_platform_8h_source.html":[0,0,0,0,8],
"_predef_8h.html":[0,0,0,1],
"_predef_8h_source.html":[0,0,0,1],
"_pyramid_8h.html":[0,0,0,0,0,10],
"_pyramid_8h.html#a003d38a5397cef998968e870546a47c4":[0,0,0,0,0,10,0],
"_pyramid_8h.html#a78fda716cccabe93a5bf1022bea3f152":[0,0,0,0,0,10,2],
"_pyramid_8h.html#ad3604a2f5822ab85db37d6f69f2f5a9d":[0,0,0,0,0,10,1],
"_pyramid_8h_source.html":[0,0,0,0,0,10],
"_r_s6k_8h.html":[0,0,0,0,0,11],
"_r_s6k_8h.html#a01b0f994d759919d2680e2713cd20187":[0,0,0,0,0,11,4],
"_r_s6k_8h.html#a26a1caf8b87e572bbfaa763305fd5f68":[0,0,0,0,0,11,5],
"_r_s6k_8h.html#a9fc59eea23e8055680a15e2d4669dd2e":[0,0,0,0,0,11,2],
"_r_s6k_8h.html#ac5e3ff18bb64a0b157a28912d4461b63":[0,0,0,0,0,11,0],
"_r_s6k_8h.html#adac400174faa54c61dbaf4b81e8f8cc4":[0,0,0,0,0,11,1],
"_r_s6k_8h.html#aeec9de492e6622884775646920003539":[0,0,0,0,0,11,3],
"_r_s6k_8h_source.html":[0,0,0,0,0,11],
"_s_p_a_r_c_8h.html":[0,0,0,0,0,12],
"_s_p_a_r_c_8h.html#a369650f0dad50942f5da96ad50ee0897":[0,0,0,0,0,12,0],
"_s_p_a_r_c_8h.html#aa8375188ec65a8279574543cf998ca83":[0,0,0,0,0,12,1],
"_s_p_a_r_c_8h.html#accd49160b3750d315f63c203d91449fa":[0,0,0,0,0,12,2],
"_s_p_a_r_c_8h_source.html":[0,0,0,0,0,12],
"_super_h_8h.html":[0,0,0,0,0,13],
"_super_h_8h.html#a32c8af9062a412051b32caa7a1e9fcb2":[0,0,0,0,0,13,2],
"_super_h_8h.html#a4a96a20c66b82f4c5965560a5c2f833a":[0,0,0,0,0,13,1],
"_super_h_8h.html#a9f37049e636f75d69e0cb1a54223cc48":[0,0,0,0,0,13,0],
"_super_h_8h_source.html":[0,0,0,0,0,13],
"_system370_8h.html":[0,0,0,0,0,14],
"_system370_8h.html#a4ec8cdf75619af5282b9b147f72e3e3e":[0,0,0,0,0,14,2],
"_system370_8h.html#a73f0dceb3e42c266fd46d66e7b59b6c4":[0,0,0,0,0,14,1],
"_system370_8h.html#a97f4878648a59d47c84ed3cba72bb2f9":[0,0,0,0,0,14,0],
"_system370_8h_source.html":[0,0,0,0,0,14],
"_system390_8h.html":[0,0,0,0,0,15],
"_system390_8h.html#a366381a5200f75ddd6a5d259639429ed":[0,0,0,0,0,15,1],
"_system390_8h.html#ab6773054083b0cc5bd589e6d4fc8fd8f":[0,0,0,0,0,15,0],
"_system390_8h.html#afd850b507956b0bd651e47a522194aa8":[0,0,0,0,0,15,2],
"_system390_8h_source.html":[0,0,0,0,0,15],
"_version_8h.html":[0,0,0,0,9],
"_version_8h.html#a1943fc8986e9eb1462fe101f046a253f":[0,0,0,0,9,3],
"_version_8h.html#a9b48ebc8cd0009e3be05a077fdb47a8c":[0,0,0,0,9,0],
"_version_8h.html#adab08e76856ccd82dc77cd7ef1e72a2f":[0,0,0,0,9,2],
"_version_8h.html#af244a325f3154449e89f9132242644f4":[0,0,0,0,9,1],
"_version_8h_source.html":[0,0,0,0,9],
"_version_number_8h.html":[0,0,0,0,10],
"_version_number_8h.html#a0856d2a8cba9bab4dd25ecbc1a9c0e6f":[0,0,0,0,10,5],
"_version_number_8h.html#a09c56bfbdd7f49b3aff1f3fc49f42c07":[0,0,0,0,10,1],
"_version_number_8h.html#a67e67fe749bdbc0b3ece960eb918d7de":[0,0,0,0,10,0],
"_version_number_8h.html#a6c9d4aa17ebc0702d59e08bc7c5e7bfa":[0,0,0,0,10,3],
"_version_number_8h.html#a75ec5bc82b8c74169b630e0bcd8b8a5f":[0,0,0,0,10,4],
"_version_number_8h.html#ae401c44edb50813558b3614a8cb118fd":[0,0,0,0,10,2],
"_version_number_8h_source.html":[0,0,0,0,10],
"dir_036e55dac30ae5ec0221dd2642113c11.html":[0,0,0,0],
"dir_1305756c7869c6ecff7f1290492b01f4.html":[0,0,0,0,0],
"dir_85741ce42cef675e2b87e3c48425a3bf.html":[0,0,0],
"dir_b0697b2469dda7ef2f7b7589c860563e.html":[0,0,0,0,0,0],
"dir_b06e777cabdcc7176771e292fb569e55.html":[0,0,0,0,1],
"files.html":[0,0],
"globals.html":[0,1,0],
"globals_defs.html":[0,1,1],
"index.html":[],
"pages.html":[],
"x86_8h.html":[0,0,0,0,0,16],
"x86_8h.html#a8221f51fff881db6b2f60bab4d728aac":[0,0,0,0,0,16,2],
"x86_8h.html#abb5ed72608067c033df1e77df784ae17":[0,0,0,0,0,16,0],
"x86_8h.html#abb5ed72608067c033df1e77df784ae17":[0,0,0,0,0,16,1],
"x86_8h_source.html":[0,0,0,0,0,16],
"z_8h.html":[0,0,0,0,0,17],
"z_8h.html#a0f2d3486e06ba9cf4dd620d1c2a236c2":[0,0,0,0,0,17,2],
"z_8h.html#a145c7f454689ac761a3b9f387bc6b950":[0,0,0,0,0,17,1],
"z_8h.html#abdc2b3e4cda7d86eac50cc38927bea9d":[0,0,0,0,0,17,0],
"z_8h_source.html":[0,0,0,0,0,17]
};
| jpvanoosten/Predef | Documentation/html/navtreeindex0.js | JavaScript | mit | 9,190 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const Lint = require("tslint");
class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile) {
return this.applyWithFunction(sourceFile, walk, undefined);
}
}
exports.Rule = Rule;
function walk(ctx) {
if (ctx.sourceFile.isDeclarationFile)
return;
return ts.forEachChild(ctx.sourceFile, cb);
function cb(node) {
if (node.kind !== ts.SyntaxKind.PropertyDeclaration)
return ts.forEachChild(node, cb);
if (!node.decorators)
return;
const property = node;
for (const decorator of node.decorators) {
const call = decorator.expression.kind == ts.SyntaxKind.CallExpression ? decorator.expression : undefined;
const name = call && call.expression.getText() || decorator.expression.getText();
if (name === 'Prop') {
if (!node.modifiers || !node.modifiers.some((x) => x.kind === ts.SyntaxKind.ReadonlyKeyword))
ctx.addFailureAtNode(property.name, 'Vue property should be readonly');
if (call && call.arguments.length > 0 &&
call.arguments[0].properties.map((x) => x.name.getText()).some((x) => x === 'default' || x === 'required')) {
if (property.questionToken !== undefined)
ctx.addFailureAtNode(property.name, 'Vue property is required and should not be optional.');
}
else if (property.questionToken === undefined)
ctx.addFailureAtNode(property.name, 'Vue property should be optional - it is not required and has no default value.');
}
}
}
}
| f-list/exported | tslint/vuePropsRule.js | JavaScript | mit | 1,767 |
/* *
* 版本:1.0.0.1
* 系统名称: FUI
* 模块名称: JRES
* 文件名称: FUI.FitLayout.js
* 作者:qudc
* 邮箱:qudc@hundsun.com
* 软件版权: 恒生电子股份有限公司
* 功能描述:FFitLayout组件对应的代码。
* 修改记录:
* 修改日期 修改人员 修改说明
* 20121022 hanyin 支持可扩展的组件自适应
* 2013-03-07 qudc 修改resize事件,延迟200毫秒计算布局。
*/
/**
* @name FFitLayout
* @class <b>适配布局容器</b><br/><br/>
* <b>使用场景:</b><br/>
* <ol>
* 使用fit布局,让组件或者DIV自适应其父容器。值适合panel、grid、tree组件.
* </ol>
* <b>功能描述:</b><br/>
* <ol>
* <li>
* </li>
*
* </ol>
*
* <b>示例:</b><br/>
* <pre>
* 无
* </pre>
*
*
*/
/**
* 需要自适应的HTML元素的的ID。<br/>
* 需要保证此元素的父亲只有它一个子元素,否则会造成元素显示异常。
* 可以通过设置FitLayout组件的parentId来指定父元素,否则FitLayout会自动去采用jquery的parent()方法来查找父亲元素。
* @name FFitLayout#forId
* @type String
* @default 无
* @example
* 无
*
*/
/**
* 要自适应的元素的父元素ID。<br/>
* 此值并非必须项:如果没有设置此值,FitLayout组件将会通过jquery的parent()方法来查找父元素。当然,使用parent()方法定位元素远没有通过指定ID来定位元素快,特别是在页面较为复杂的情况下。<br/>
* 另外,如果想要占满整个窗口,则需要设置parentId为"window"。
* @name FFitLayout#parentId
* @type String
* @default null
* @example
* 无
*/
/**@lends FFitLayout# */
(function($, undefined) {
$Utils["FFitLayout"] = function(options) {
/**
* 根据父节点的高宽,重置子容器对象的高宽,如果是fpanel、fgrid、ftree等则调用各组件的setSize方法;否则直接设置元素的高宽值
* @param $parent 父亲元素的jquery对象
* @param $subWidget 要自适应元素的jquery对象
* @param type 自适应元素的类型
*/
this._resizeSubWidget = function($parent, $subWidget, type) {
if (!$parent) {
return;
}
var w = $parent.width();
var h = $parent.height();
var result = $Component.tryCall($subWidget, "setSize", w, h);
if (!result.hasFunc) {
$subWidget.width(w);
$subWidget.height(h);
}
}
options = options || {};
// 本元素的Id
var forId = options.forId || "";
// 父亲元素的Id
var parentId = options.parentId || "";
if (forId == null || forId.length == 0) {
return;
}
// 缓存jQuery对象:elment
var selfEl = $I(forId);
// 缓存jQuery对象:parentElement
var parentEl = null;
// 如果没有指定父元素的ID,则使用jquery的parent()方法定位元素
if (parentId == null || parentId.length == 0) {
parentEl = selfEl.parent();
} else {
if (parentId === "window") {
parentEl = $(window);
} else {
parentEl = $I(parentId);
if (parentEl.size() == 0) {
parentEl = selfEl.parent();
}
}
}
//根据传入的jquery对象,返回組件的類型,只能识别以下组件:fpanel,fgrid,ftree
var subWidgetType = function(widget, op) {
var type = widget.data("ftype");
return type;
}(selfEl, options);
// 绑定resize事件
var ME = this;
var resizeSubWidgetProxy = $.proxy(ME, "_resizeSubWidget", parentEl, selfEl, subWidgetType);
var resizeFn = function() {
if (ME.handler) {
clearTimeout(ME.handler);
}
ME.handler = setTimeout(resizeSubWidgetProxy, 200);
}
$(window).bind('resize', resizeFn);
//$(window).bind('resize', resizeSubWidgetProxy);
// 在父容器上绑定onResize事件,用于一些复杂的嵌套模型
//parentEl.bind("onResize", resizeSubWidgetProxy);
// 主动触发一次执行
this._resizeSubWidget(parentEl, selfEl, subWidgetType);
};
})(jQuery);
| hundsun/fui | fui.web/src/main/webapp/FUI-extend/js/src/FUI.FitLayout.js | JavaScript | mit | 4,320 |
/**
* Created by srinath on 17/9/15.
*/
/**
* Created by srinath on 11/7/15.
*/
let configForDevelopment = {
baseUrl: 'http://dev-media-api.appsflare.com:1337/',
loginUrl: '/oauth/token',
//clientId: '1ESN8EPG1H',
//clientSecret: 'hdW1kHE5mqPPBGgcXzlOh9RxCI7DlR'
//providers: {
// google: {
// clientId: ''
// }
// ,
// linkedin:{
// clientId:''
// },
// facebook:{
// clientId:''
// }
//}
};
export default configForDevelopment;
| appsflare/ludicrum-webapp | config/development/app.config.js | JavaScript | mit | 486 |
'use strict';
const assert = require('chai').assert;
const index = require('../index.js');
const remote = require('../lib/fetch-remote.js');
const local = require('../lib/fetch-local.js');
const sinon = require('sinon');
const mime = require('mime-types');
let sandbox;
function swallow() {}
describe('index.js (Unit)', () => {
beforeEach(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
});
describe('auto()', () => {
it('should always return a promise', () => {
const auto1 = index.auto('non-existant-path');
const auto2 = index.auto();
assert(typeof auto1.then === 'function');
assert(typeof auto2.then === 'function');
Promise.all([auto1, auto2]).catch(swallow);
});
it('it should call local.fetch() to fetch local images', (done) => {
const fetchLocalStub = sandbox.stub(local, 'fetch').callsFake(() => Promise.resolve('image-data'));
const shouldNotBeCalled = sandbox.spy(remote, 'fetch');
index.auto('/several/', '/paths/', '/image.gif').then((data) => {
assert.deepEqual(data, ['image-data', 'data:image/gif;base64,image-data']);
sinon.assert.calledOnce(fetchLocalStub);
sinon.assert.calledWith(fetchLocalStub, '/several/', '/paths/', '/image.gif');
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('it should call remote.fetch() to fetch remote images', (done) => {
const fetchRemoteStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('image-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
index.auto('http://remote.com/image.jpg').then((data) => {
assert.deepEqual(data, ['image-data', 'data:image/jpeg;base64,image-data']);
sinon.assert.calledOnce(fetchRemoteStub);
sinon.assert.calledWith(fetchRemoteStub, { headers: {}, paths: ['http://remote.com/image.jpg'] });
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('it should return a rejected promise if there is an exception parsing the mimeType', (done) => {
const shouldNotBeCalled = sandbox.spy(remote, 'fetch');
sandbox.stub(mime, 'lookup').throws('SomeError');
index.auto('/several/', '/paths/', '/image.gif').catch((e) => {
assert.equal(shouldNotBeCalled.callCount, 0);
assert.equal(e, 'SomeError');
done();
}).catch(e => done(e));
});
it('it should call fetch.remote if first path passed is remote', (done) => {
const fetchRemoteStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('image-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
index.auto('http://thisisremote.com/', '/paths/', '/image.gif').then((data) => {
assert.equal(data[0], 'image-data');
sinon.assert.calledOnce(fetchRemoteStub);
sinon.assert.calledWith(fetchRemoteStub, { headers: {}, paths: ['http://thisisremote.com/', '/paths/', '/image.gif'] });
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('it should call fetch.local if first path passed is local', (done) => {
const fetchLocalStub = sandbox.stub(local, 'fetch').callsFake(() => Promise.resolve('image-data'));
const shouldNotBeCalled = sandbox.spy(remote, 'fetch');
index.auto('/localPath/', '/paths/', '/image.gif').then((data) => {
assert.equal(data[0], 'image-data');
sinon.assert.calledOnce(fetchLocalStub);
sinon.assert.calledWith(fetchLocalStub, '/localPath/', '/paths/', '/image.gif');
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
});
describe('local()', () => {
it('should always return a promise', () => {
const local1 = index.local('non-existant-path');
const local2 = index.local();
assert(typeof local1.then === 'function');
assert(typeof local2.then === 'function');
Promise.all([local1, local2]).catch(swallow);
});
it('should return a rejected promise if there is an issue retrieveing the image', (done) => {
const localFecthStub = sandbox.stub(local, 'fetch')
.callsFake(() => Promise.reject('error getting image'));
index.local('path/to/existing-image.gif').catch((res) => {
assert.equal(res, 'error getting image');
assert(localFecthStub.calledOnce);
done();
}).catch(e => done(e));
});
it('should call local.fetch() for local files', (done) => {
const localFetchStub = sandbox.stub(local, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(remote, 'fetch');
index.local('/root/', '/path/to/existing-image.gif').then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(localFetchStub.calledOnce);
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('should handle multiple paths correctly', (done) => {
const localFetchStub = sandbox.stub(local, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(remote, 'fetch');
index.local('/root/', '/another/path/', '/path/to/existing-image.gif').then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(localFetchStub.calledOnce);
sinon.assert.calledWith(localFetchStub,
'/root/',
'/another/path/',
'/path/to/existing-image.gif'
);
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
});
describe('remote()', () => {
it('should always return a promise', () => {
const remote1 = index.remote('non-existant-path');
const remote2 = index.remote();
assert(typeof remote1.then === 'function');
assert(typeof remote2.then === 'function');
Promise.all([remote1, remote2]).catch(swallow);
});
it('should return a rejected promise if there is an issue retrieveing the file', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.reject('error getting image'));
index.remote('https://domain.com/to/existing-image.gif').catch((reason) => {
assert.equal(reason, 'error getting image');
assert(remoteFecthStub.calledOnce);
done();
}).catch(e => done(e));
});
it('should call remote.fetch() for remote files', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
index.remote('https://domain.com/to/existing-image.gif').then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(remoteFecthStub.calledOnce);
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('should accept an options object as paramenter with the `url` property', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
const url = 'https://domain.com/to/existing-image.gif';
index.remote({ url }).then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(remoteFecthStub.calledOnce);
assert(remoteFecthStub.calledWith({ paths: [url], headers: {} }));
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('should accept an options object as paramenter with the `url` and `headers` properties', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
const url = 'https://domain.com/to/existing-image.gif';
const headers = { test: 'foo' };
index.remote({ url, headers }).then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(remoteFecthStub.calledOnce);
assert(remoteFecthStub.calledWith({ paths: [url], headers }));
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('should accept an options object as paramenter with the `paths` and `headers` properties', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
const paths = ['https://domain.com', '/to/existing-image.gif'];
const headers = { test: 'foo' };
index.remote({ paths, headers }).then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(remoteFecthStub.calledOnce);
assert(remoteFecthStub.calledWith({ paths, headers }));
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('should prioritize `paths` in case both `paths` and `url` are passed', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
const paths = ['https://domain.com', '/to/existing-image.gif'];
const url = 'http://test-url.com';
const headers = { test: 'foo' };
index.remote({ url, paths, headers }).then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(remoteFecthStub.calledOnce);
assert(remoteFecthStub.calledWith({ paths, headers }));
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
it('should properly treat an array of paths passed as parameter', (done) => {
const remoteFecthStub = sandbox.stub(remote, 'fetch').callsFake(() => Promise.resolve('gif-data'));
const shouldNotBeCalled = sandbox.spy(local, 'fetch');
const paths = ['https://domain.com', '/to/existing-image.gif'];
index.remote(...paths).then((res) => {
assert.deepEqual(res, ['gif-data', 'data:image/gif;base64,gif-data']);
assert(remoteFecthStub.calledOnce);
assert(remoteFecthStub.calledWith({ paths, headers: {} }));
assert.equal(shouldNotBeCalled.callCount, 0);
done();
}).catch(e => done(e));
});
});
});
| gamell/fetch-base64 | test/index.js | JavaScript | mit | 10,689 |
angular.module('one4all').directive('actionsButton', [function () {
return {
templateUrl: 'directives/actions-button/actions-button.html',
restrict: 'E',
scope: {
edit: '&edit',
remove: '&remove'
},
link: function ($scope, $element, $attr) {
}
};
}]); | Opiskull/one4all | client/src/common/directives/actions-button/actions-button-directive.js | JavaScript | mit | 332 |
import React, { Component } from 'react';
import { View, Text, Picker, ScrollView, StyleSheet } from 'react-native';
import SpiritStats from './stats';
import SpiritInitiative from './initiative';
import SpiritSkills from './skills';
import Combobox from '../ComboboxWrapper';
import GroupBox from '../GroupBox';
const forces = Array.apply(null, { length: 12 })
.map(Number.call, Number)
.map(i => (
<Picker.Item value={i + 1} label={`Force ${i + 1}`} key={`force-${i+1}`}/>
));
forces.unshift(<Picker.Item value="formula" label="Formula" key="force-formula"/>)
export default class SpiritViewer extends Component {
constructor(props) {
super(props);
this.state = { selected: 'formula' }
this.valueChange = this.valueChange.bind(this);
}
valueChange(selected) {
this.setState({ selected })
}
render() {
return (<View style={styles.container}>
<ScrollView>
<Combobox
prompt="Force"
selectedValue={ this.state.selected }
onValueChange={(e) => this.valueChange(e)} >
{ forces }
</Combobox>
<GroupBox title="Stats">
<SpiritStats { ...this.props.stats } force={this.state.selected} />
</GroupBox>
<GroupBox title="Initiative">
<SpiritInitiative {...this.props.initiative} force={this.state.selected}/>
</GroupBox>
<GroupBox>
<SpiritSkills skills={this.props.skills || []}/>
</GroupBox>
</ScrollView>
</View>);
}
};
const styles = StyleSheet.create({
container: {
flex: 1
}
})
| aaron-edwards/Spirit-Guide | src/components/SpiritViewer/index.js | JavaScript | mit | 1,552 |
/**
* Created by EbyC on 8/24/2014.
*/
'use strict';
angular.module('qas')
.service('MathService', [ function() {
this.add = function(a, b) { return a + b ; };
this.subtract = function(a, b) { return a - b; };
this.multiply = function(a, b) { return a * b; };
this.divide = function(a, b) { return a / b ;};
}])
.service('CalculatorService', function(MathService){
this.square = function(a) { return MathService.multiply(a,a); };
this.cce = function(a) {return a+a*1000;};
this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); };
});
| cliffeby/Quiz040 | modules/qas/client/services/qas.client.service1.js | JavaScript | mit | 646 |
var a00897 =
[
[ "count", "a00897.html#af6a39bfc7e1dc3b6f9c997c1c43fa996", null ],
[ "is_genkey", "a00897.html#ab0cedc80cd8670d02eee4b6e31500f5f", null ],
[ "offset", "a00897.html#ac681806181c80437cfab37335f62ff39", null ],
[ "slot", "a00897.html#ad23984515efd99983fa4baf3754082a1", null ],
[ "zone", "a00897.html#a107ad412023faa68c4ac0c7cfd921a02", null ]
]; | PhillyNJ/SAMD21 | cryptoauthlib/docs/html/a00897.js | JavaScript | mit | 379 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.publish = publish;
exports.handle = handle;
var _util = require('../util');
/**
* Publish the project to a service such as Surge, or AWS
*/
function publish(program, dispatch) {
program.command('publish [domain]').description('publish a website for this project to cloud hosting platforms').option('--domain <domain>', 'which domain to publish this to?').option('--public', 'which folder should we publish? defaults to the projects public path').option('--build', 'run the build process first').option('--build-command', 'which build command').option('--service <domain>', 'which service should we publish to? aws, surge.sh, some other domain', 'surge.sh').action(dispatch(handle));
}
exports.default = publish;
function handle(domain) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var context = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var project = context.project;
domain = domain || options.domain || project.options.domain || project.get('settings.publishing.domain');
options.public = options.public || project.paths.public;
options.service = options.service || project.get('settings.publishing.service');
if (options.service === 'skypager') {
options.service = 'skypager.io';
}
if (options.service === 'blueprint') {
options.service = 'blueprint.io';
}
if (options.service === 'blueprint.io' || options.service === 'skypager.io') {
options.endpoint = 'surge.' + options.service;
surgePlatformHandler(domain, options, context);
} else if (options.service.match(/surge/i)) {
surgeHandler(domain, options, context);
}
}
function surgePlatformHandler(domain) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var context = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var cmd = 'deploy --project ' + options.public + ' --domain ' + domain + ' --endpoint ' + options.endpoint;
var proc = require('child_process').spawn('surge', cmd.split(' '));
process.stdin.pipe(proc.stdin);
proc.stdout.pipe(process.stdout);
proc.stderr.pipe(process.stderr);
}
function surgeHandler(domain) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var context = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var cmd = 'deploy --project ' + options.public + ' --domain ' + options.domain;
var proc = require('child_process').spawn('surge', cmd.split(' '));
process.stdin.pipe(proc.stdin);
proc.stdout.pipe(process.stdout);
proc.stderr.pipe(process.stderr);
}
function awsHandler(domain) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
console.log('TODO: Implement this internally');
}
function abort(msg) {
console.log(msg.red);
process.exit(1);
} | stylish/stylish | packages/skypager-cli/lib/commands/publish.js | JavaScript | mit | 2,967 |
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('machine');
}
});
| hugopeixoto/saopedro | frontend/app/pods/machines/route.js | JavaScript | mit | 136 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Box from './Box';
import Sizes from './Sizes';
class Row extends Component {
render() {
let {
column,
doubling,
className,
...rest
} = this.props;
let cx = classNames(
column ? `${Sizes[column - 1]} column` : null,
{
doubling,
},
'row',
className,
);
return (
<Box
className={cx}
{...rest}
/>
);
}
}
Row.displayName = 'Row';
Row.propTypes = {
column: PropTypes.number,
doubling: PropTypes.bool,
};
export default Row;
| gocreating/react-tocas | src/Row.js | JavaScript | mit | 667 |
import React from "react"
import Helmet from "react-helmet"
import get from "lodash/get"
import { rhythm, scale } from "../utils/typography"
class ComicTemplate extends React.Component {
renderItemInfo () {
const post = this.props.data.markdownRemark
const { itemArtist, itemType } = post.frontmatter
if (itemType) {
return (
<div
itemProp='about' itemScope itemType={`http://schema.org/${itemType}`}>
<p
style={{
...scale(-1 / 5),
display: "block",
color: 'lightslategray',
marginBottom: rhythm(1),
marginTop: rhythm(-1),
textAlign: 'center'
}}
>
{itemArtist ? <span itemProp='artist'>Art by {itemArtist}</span> : <span />}
</p>
</div>
)
} else {
return <div />
}
}
render () {
const post = this.props.data.markdownRemark
const theImage = post.frontmatter.indexImage ? 'https://fogupsomecomics.com' + post.frontmatter.indexImage.childImageSharp.resize.src : null
const isPage = post.frontmatter.layout === 'page'
const siteTitle = get(this.props, "data.site.siteMetadata.title")
const { itemArtist } = post.frontmatter
return (
<div
itemScope
itemType={'http://schema.org/ComicStory'}
>
<Helmet title={`${post.frontmatter.title} | ${siteTitle}`}>
<meta property='og:url' content={`fogupsomecomics.com${post.frontmatter.path}`} />
<meta property='og:type' content='article' />
<meta property='og:title' content={post.frontmatter.title} />
<meta property='og:description' content={post.frontmatter.description} />
<meta name='twitter:site' value='@austinlanari' />
<meta property='twitter:url' content={`fogupsomecomics.com${post.frontmatter.path}`} />
<meta property='twitter:title' content={post.frontmatter.title} />
<meta property='twitter:description' content={post.frontmatter.description} />
<meta name='author' content='Austin Lanari' />
<meta name='og:image' content={theImage || ''} />
<meta name='twitter:image' content={theImage || ''} />
<meta name='twitter:card' value='summary_large_image' />
</Helmet>
<span itemProp='author' style={{display: 'none'}}>Austin Lanari</span>
<span itemProp='publisher' style={{display: 'none'}}>Foggy at Best</span>
<span itemProp='artist' style={{display: 'none'}}>{itemArtist}</span>
<span itemProp='image' style={{display: 'none'}} itemScope itemType='http://schema.org/ImageObject'>
<span itemProp='url'>
{theImage}
</span>
<meta itemProp='height' content='500' />
<meta itemProp='width' content='500' />
<span />
</span>
<h1
style={{paddingTop: 0, marginTop: 30, textAlign: 'center'}}
itemProp="headline"
>
{post.frontmatter.title === 'About' ? 'Hey' : post.frontmatter.title}
</h1>
{this.renderItemInfo()}
<div
dangerouslySetInnerHTML={{ __html: post.html }}
itemProp='articleBody'
/>
</div>
)
}
}
export default ComicTemplate
export const pageQuery = graphql`
query ComicByPath($slug: String!) {
site {
siteMetadata {
title
author
}
}
markdownRemark(fields: { slug: { eq: $slug }}) {
id
html
fields {
slug
}
frontmatter {
title
path
date(formatString: "MMMM DD, YYYY"),
indexImage {
childImageSharp {
resize(width: 500, height: 500){
src
}
}
},
layout,
itemTitle,
itemAuthor,
itemType,
itemArtist,
itemPublisher,
description
}
}
}
`
| foggy1/FuSC | src/templates/comic.js | JavaScript | mit | 3,965 |
'use strict'
const api = module.exports = require('express').Router()
api
.get('/heartbeat', (req, res) => res.send({ok: true}))
.use('/auth', require('./auth'))
.use('/users', require('./users'))
.use('/products', require('./products'))
.use('/cart', require('./cartitems'))
.use('/categories', require('./categories'))
// No routes matched? 404.
api.use((req, res) => res.status(404).end())
| limitless-leggings/limitless-leggings | server/api.js | JavaScript | mit | 408 |
(function() {
"use strict";
var template = '<div class="vue-info" :style="{\'font-size\': size + \'px\'}">\
<i class=\"fa fa-question vue-info-hint\"></i>\
<span class="vue-info-message" :class="[direction]">\
<slot></slot>\
</span>\
</div>';
App.ui.components.std.info = Vue.extend({
template: template,
props: {
'size': {
default: '12'
},
'direction': {
default: ''
}
}
});
})();
| codelation/codelation_ui | app/assets/javascripts/codelation_ui/std/components/info.js | JavaScript | mit | 554 |
/* Solutions for Basic Algorithm Scripting at www.freecodecamp.org */
/*
* Reverse the provided string.
*
* You may need to turn the string into an array before you can reverse it.
*
* Your result must be a string.
*
* reverseString("hello") should become "olleh".
*/
function reverseString(str) {
return str.split('').reverse().join('');
}
/*
* Return the factorial of the provided integer.
*
* If the integer is represented with the letter n, a factorial is
* the product of all positive integers less than or equal to n.
*
* Factorials are often represented with the shorthand notation n!
*
* For example: 5! = 1 * 2 * 3 * 4 * 5 = 120
*/
function factorialize(num) {
if (num === 0) {
return 1;
} else {
num = num * factorialize(num - 1);
}
return num;
}
/*
* Return true if the given string is a palindrome. Otherwise, return false.
*
* A palindrome is a word or sentence that's spelled the same way both
* forward and backward, ignoring punctuation, case, and spacing.
*
* Note:
* You'll need to remove all non-alphanumeric characters (punctuation,
* spaces and symbols) and turn everything lower case in order to check
* for palindromes.
*
* We'll pass strings with varying formats, such as "racecar", "RaceCar",
* and "race CAR" among others.
*
* We'll also pass strings with special symbols, such as "2A3*3a2",
* "2A3 3a2", and "2_A3*3#A2".
*
* palindrome("eye") should return true.
*/
function palindrome(str) {
str = str.replace(/[\W_]/gi, '').toLowerCase();
return (str === str.split('').reverse().join('')) ? true : false;
}
/*
* Return the length of the longest word in the provided sentence.
*
* Your response should be a number.
*/
function findLongestWord(str) {
str = str.split(' ');
let longestWord = '';
for (let i = 0; i < str.length; i++) {
if (str[i].length > longestWord.length) {
longestWord = str[i];
}
}
return longestWord.length;
}
/*
* Return the provided string with the first letter of each word capitalized.
* Make sure the rest of the word is in lower case.
*
* For the purpose of this exercise, you should also capitalize connecting
* words like "the" and "of".
*/
function titleCase(str) {
str = str.split(' ');
for (let i = 0; i < str.length; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1, str.length + 1).toLowerCase();
}
return str.join(' ');
}
/*
* Return an array consisting of the largest number from each provided
* sub-array. For simplicity, the provided array will contain exactly 4
* sub-arrays.
*/
function largestOfFour(arr) {
let outputArr = [];
for (let i = 0; i < arr.length; i++) {
let largestNum = 0;
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] > largestNum) {
largestNum = arr[i][j];
}
}
outputArr.push(largestNum);
}
return outputArr;
}
/*
* Check if a string (first argument, str) ends with the given target
* string (second argument, target).
*
* This challenge can be solved with the .endsWith() method, which
* was introduced in ES2015. But for the purpose of this challenge,
* we would like you to use one of the JavaScript substring methods instead.
*/
function confirmEnding(str, target) {
return (str.substr(-target.length) === target) ? true : false;
}
/*
* Repeat a given string (first argument) num times (second argument).
* Return an empty string if num is not a positive number.
*/
function repeatStringNumTimes(str, num) {
return (num < 0) ? '' : str.repeat(num);
}
/*
* Truncate a string (first argument) if it is longer than the given
* maximum string length (second argument). Return the truncated string
* with a ... ending.
*
* Note that inserting the three dots to the end will add to the
* string length.
*
* However, if the given maximum string length num is less than or
* equal to 3, then the addition of the three dots does not add to the
* string length in determining the truncated string.
*/
function truncateString(str, num) {
const dots = '...';
if (str.length > num && num > 3) {
str = str.slice(0, num - 3) + dots;
} else if (str.length > num && num <= 3) {
str = str.slice(0, num) + dots;
} else {
return str;
}
return str;
}
/*
* Write a function that splits an array (first argument) into groups
* the length of size (second argument) and returns them as a
* two-dimensional array.
*/
| J-kaizen/kaizen | javascript/FCCAlgos/basic-algos.js | JavaScript | mit | 4,421 |
'use strict';
var imjv = require('is-my-json-valid');
var schemas = {};
var validator = {
validate(schema, data) {
var v = imjv(schema, {schemas});
var valid = v(data);
validator.errors = v.errors;
return valid;
},
addSchema(schema, id) {
schemas[id] = schema;
}
};
require('./testValidator')('is-my-json-valid', validator);
| epoberezkin/test-validators | test/is-my-json-valid.js | JavaScript | mit | 356 |
angular
.module('app.services.api', [
'ngResource'
])
.factory('app.services.api', [
'$location',
'$resource',
function($location, $resource) {
var api = $resource('/api/:entity');
return api;
}
])
;
| ericclemmons/genesis-skeleton.com | src/client/app/js/services/apiService.js | JavaScript | mit | 241 |