<commit_before>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var should = require("should");
var fs = require('fs-extra');
var path = require('path');

var localfilesystemLibrary = require("../../../../../red/runtime/storage/localfilesystem/library");

describe('storage/localfilesystem/library', function() {
    var userDir = path.join(__dirname,".testUserHome");
    beforeEach(function(done) {
        fs.remove(userDir,function(err) {
            fs.mkdir(userDir,done);
        });
    });
    afterEach(function(done) {
        fs.remove(userDir,done);
    });

    it('should return an empty list of library objects',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            localfilesystemLibrary.getLibraryEntry('object','').then(function(flows) {
                flows.should.eql([]);
                done();
            }).otherwise(function(err) {
                done(err);
            });
        }).otherwise(function(err) {
            done(err);
        });
    });

    it('should return an empty list of library objects (path=/)',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            localfilesystemLibrary.getLibraryEntry('object','/').then(function(flows) {
                flows.should.eql([]);
                done();
            }).otherwise(function(err) {
                done(err);
            });
        }).otherwise(function(err) {
            done(err);
        });
    });

    it('should return an error for a non-existent library object',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            localfilesystemLibrary.getLibraryEntry('object','A/B').then(function(flows) {
                should.fail(null,null,"non-existent flow");
            }).otherwise(function(err) {
                should.exist(err);
                done();
            });
        }).otherwise(function(err) {
            done(err);
        });
    });

    function createObjectLibrary(type) {
        type = type ||"object";
        var objLib = path.join(userDir,"lib",type);
        try {
            fs.mkdirSync(objLib);
        } catch(err) {
        }
        fs.mkdirSync(path.join(objLib,"A"));
        fs.mkdirSync(path.join(objLib,"B"));
        fs.mkdirSync(path.join(objLib,"B","C"));
        if (type === "functions" || type === "object") {
            fs.writeFileSync(path.join(objLib,"file1.js"),"// abc: def\n// not a metaline \n\n Hi",'utf8');
            fs.writeFileSync(path.join(objLib,"B","file2.js"),"// ghi: jkl\n// not a metaline \n\n Hi",'utf8');
        }
        if (type === "flows" || type === "object") {
            fs.writeFileSync(path.join(objLib,"B","flow.json"),"Hi",'utf8');
        }
    }

    it('should return a directory listing of library objects',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary();

            localfilesystemLibrary.getLibraryEntry('object','').then(function(flows) {
                flows.should.eql([ 'A', 'B', { abc: 'def', fn: 'file1.js' } ]);
                localfilesystemLibrary.getLibraryEntry('object','B').then(function(flows) {
                    flows.should.eql([ 'C', { ghi: 'jkl', fn: 'file2.js' }, { fn: 'flow.json' } ]);
                    localfilesystemLibrary.getLibraryEntry('object','B/C').then(function(flows) {
                        flows.should.eql([]);
                        done();
                    }).otherwise(function(err) {
                        done(err);
                    });
                }).otherwise(function(err) {
                    done(err);
                });
            }).otherwise(function(err) {
                done(err);
            });
        }).otherwise(function(err) {
            done(err);
        });
    });

    it('should load a flow library object with .json unspecified', function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary("flows");
            localfilesystemLibrary.getLibraryEntry('flows','B/flow').then(function(flows) {
                flows.should.eql("Hi");
                done();
            }).otherwise(function(err) {
                done(err);
            });
        });

    });

    it('should return a library object',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary();
            localfilesystemLibrary.getLibraryEntry('object','B/file2.js').then(function(body) {
                body.should.eql("// not a metaline \n\n Hi");
                done();
            }).otherwise(function(err) {
                done(err);
            });
        }).otherwise(function(err) {
            done(err);
        });
    });

    it('should return a newly saved library function',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary("functions");
            localfilesystemLibrary.getLibraryEntry('functions','B').then(function(flows) {
                flows.should.eql([ 'C', { ghi: 'jkl', fn: 'file2.js' } ]);
                var ft = path.join("B","D","file3.js");
                localfilesystemLibrary.saveLibraryEntry('functions',ft,{mno:'pqr'},"// another non meta line\n\n Hi There").then(function() {
                    setTimeout(function() {
                        localfilesystemLibrary.getLibraryEntry('functions',path.join("B","D")).then(function(flows) {
                            flows.should.eql([ { mno: 'pqr', fn: 'file3.js' } ]);
                            localfilesystemLibrary.getLibraryEntry('functions',ft).then(function(body) {
                                body.should.eql("// another non meta line\n\n Hi There");
                                done();
                            }).otherwise(function(err) {
                                done(err);
                            });
                        }).otherwise(function(err) {
                            done(err);
                        })
                    }, 50);
                }).otherwise(function(err) {
                    done(err);
                });
            }).otherwise(function(err) {
                done(err);
            });
        }).otherwise(function(err) {
            done(err);
        });
    });

    it('should return a newly saved library flow',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary("flows");
            localfilesystemLibrary.getLibraryEntry('flows','B').then(function(flows) {
                flows.should.eql([ 'C', {fn:'flow.json'} ]);
                var ft = path.join("B","D","file3");
                localfilesystemLibrary.saveLibraryEntry('flows',ft,{mno:'pqr'},"Hi").then(function() {
                    setTimeout(function() {
                        localfilesystemLibrary.getLibraryEntry('flows',path.join("B","D")).then(function(flows) {
                            flows.should.eql([ { mno: 'pqr', fn: 'file3.json' } ]);
                            localfilesystemLibrary.getLibraryEntry('flows',ft+".json").then(function(body) {
                                body.should.eql("Hi");
                                done();
                            }).otherwise(function(err) {
                                done(err);
                            });
                        }).otherwise(function(err) {
                            done(err);
                        })
                    }, 50);
                }).otherwise(function(err) {
                    done(err);
                });
            }).otherwise(function(err) {
                done(err);
            });
        }).otherwise(function(err) {
            done(err);
        });
    });
});
<commit_msg>Fix the error that "otherwise is not a function" (#1513)<commit_after>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var should = require("should");
var fs = require('fs-extra');
var path = require('path');

var localfilesystemLibrary = require("../../../../../red/runtime/storage/localfilesystem/library");

describe('storage/localfilesystem/library', function() {
    var userDir = path.join(__dirname,".testUserHome");
    beforeEach(function(done) {
        fs.remove(userDir,function(err) {
            fs.mkdir(userDir,done);
        });
    });
    afterEach(function(done) {
        fs.remove(userDir,done);
    });

    it('should return an empty list of library objects',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            localfilesystemLibrary.getLibraryEntry('object','').then(function(flows) {
                flows.should.eql([]);
                done();
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });

    it('should return an empty list of library objects (path=/)',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            localfilesystemLibrary.getLibraryEntry('object','/').then(function(flows) {
                flows.should.eql([]);
                done();
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });

    it('should return an error for a non-existent library object',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            localfilesystemLibrary.getLibraryEntry('object','A/B').then(function(flows) {
                should.fail(null,null,"non-existent flow");
            }).catch(function(err) {
                should.exist(err);
                done();
            });
        }).catch(function(err) {
            done(err);
        });
    });

    function createObjectLibrary(type) {
        type = type ||"object";
        var objLib = path.join(userDir,"lib",type);
        try {
            fs.mkdirSync(objLib);
        } catch(err) {
        }
        fs.mkdirSync(path.join(objLib,"A"));
        fs.mkdirSync(path.join(objLib,"B"));
        fs.mkdirSync(path.join(objLib,"B","C"));
        if (type === "functions" || type === "object") {
            fs.writeFileSync(path.join(objLib,"file1.js"),"// abc: def\n// not a metaline \n\n Hi",'utf8');
            fs.writeFileSync(path.join(objLib,"B","file2.js"),"// ghi: jkl\n// not a metaline \n\n Hi",'utf8');
        }
        if (type === "flows" || type === "object") {
            fs.writeFileSync(path.join(objLib,"B","flow.json"),"Hi",'utf8');
        }
    }

    it('should return a directory listing of library objects',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary();

            localfilesystemLibrary.getLibraryEntry('object','').then(function(flows) {
                flows.should.eql([ 'A', 'B', { abc: 'def', fn: 'file1.js' } ]);
                localfilesystemLibrary.getLibraryEntry('object','B').then(function(flows) {
                    flows.should.eql([ 'C', { ghi: 'jkl', fn: 'file2.js' }, { fn: 'flow.json' } ]);
                    localfilesystemLibrary.getLibraryEntry('object','B/C').then(function(flows) {
                        flows.should.eql([]);
                        done();
                    }).catch(function(err) {
                        done(err);
                    });
                }).catch(function(err) {
                    done(err);
                });
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });

    it('should load a flow library object with .json unspecified', function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary("flows");
            localfilesystemLibrary.getLibraryEntry('flows','B/flow').then(function(flows) {
                flows.should.eql("Hi");
                done();
            }).catch(function(err) {
                done(err);
            });
        });

    });

    it('should return a library object',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary();
            localfilesystemLibrary.getLibraryEntry('object','B/file2.js').then(function(body) {
                body.should.eql("// not a metaline \n\n Hi");
                done();
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });

    it('should return a newly saved library function',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary("functions");
            localfilesystemLibrary.getLibraryEntry('functions','B').then(function(flows) {
                flows.should.eql([ 'C', { ghi: 'jkl', fn: 'file2.js' } ]);
                var ft = path.join("B","D","file3.js");
                localfilesystemLibrary.saveLibraryEntry('functions',ft,{mno:'pqr'},"// another non meta line\n\n Hi There").then(function() {
                    setTimeout(function() {
                        localfilesystemLibrary.getLibraryEntry('functions',path.join("B","D")).then(function(flows) {
                            flows.should.eql([ { mno: 'pqr', fn: 'file3.js' } ]);
                            localfilesystemLibrary.getLibraryEntry('functions',ft).then(function(body) {
                                body.should.eql("// another non meta line\n\n Hi There");
                                done();
                            }).catch(function(err) {
                                done(err);
                            });
                        }).catch(function(err) {
                            done(err);
                        })
                    }, 50);
                }).catch(function(err) {
                    done(err);
                });
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });

    it('should return a newly saved library flow',function(done) {
        localfilesystemLibrary.init({userDir:userDir}).then(function() {
            createObjectLibrary("flows");
            localfilesystemLibrary.getLibraryEntry('flows','B').then(function(flows) {
                flows.should.eql([ 'C', {fn:'flow.json'} ]);
                var ft = path.join("B","D","file3");
                localfilesystemLibrary.saveLibraryEntry('flows',ft,{mno:'pqr'},"Hi").then(function() {
                    setTimeout(function() {
                        localfilesystemLibrary.getLibraryEntry('flows',path.join("B","D")).then(function(flows) {
                            flows.should.eql([ { mno: 'pqr', fn: 'file3.json' } ]);
                            localfilesystemLibrary.getLibraryEntry('flows',ft+".json").then(function(body) {
                                body.should.eql("Hi");
                                done();
                            }).catch(function(err) {
                                done(err);
                            });
                        }).catch(function(err) {
                            done(err);
                        })
                    }, 50);
                }).catch(function(err) {
                    done(err);
                });
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });
});
<|endoftext|>


<commit_before>(function () {
	'use strict';
	var gui = require('nw.gui');
	var url = require('url');
	var pkg = require('../package.json');

	var LOCAL_STORAGE_KEY_CURRENT_DOMAIN = 'currentDomain';
	var SLACK_DOMAIN = 'slack.com';
	var SLACK_LOGIN_URL = 'https://slack.com/signin';
	var webslack = {};

	var win = gui.Window.get();
	var validSlackSubdomain = /(.+)\.slack.com/i;
	var validSlackRedirect = /(.+\.)?slack-redir.net/i;

	win.on('new-win-policy', function (frame, urlStr, policy) {
		var openRequest = url.parse(urlStr);

		if (validSlackRedirect.test(openRequest.host)) {
			gui.Shell.openExternal(urlStr);
			policy.ignore();
			console.log('Allowing browser to handle: ' + JSON.stringify(openRequest));
		}
	});

	function newLocationToProcess(locationToProcess) {
		var locationHostname = url.parse(locationToProcess).hostname;

		if (validSlackSubdomain.test(locationHostname)) {
			var subdomain = validSlackSubdomain.exec(locationHostname);
			if (subdomain[1] && subdomain[1].length > 1) {
				var subdomainFiltered = subdomain[1];

				if (subdomainFiltered !== localStorage.getItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN)) {
					localStorage.setItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN, subdomainFiltered);
				}
			}
		} else if (locationHostname === SLACK_DOMAIN) {
			localStorage.removeItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN);
		}
	}

	function handleLoadIframe(url) {
		var bodyElement = document.body;

		// Remove all the body's children nodes
		while (bodyElement.firstChild) {
			bodyElement.removeChild(bodyElement.firstChild);
		}

		var iframeDomElement = document.createElement('iframe');

		iframeDomElement.setAttribute('src', url);
		iframeDomElement.setAttribute('frameBorder', '0');
		iframeDomElement.setAttribute('nwdisable', '');
		iframeDomElement.setAttribute('nwfaketop', '');

		bodyElement.appendChild(iframeDomElement);
	}

	win.on('document-start', function (frame) {
		if (frame && frame.contentWindow) {
			newLocationToProcess(frame.contentWindow.location.href);
		}
	});

	webslack.load = function () {
		if (localStorage.getItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN)) {
			handleLoadIframe('https://' + localStorage.getItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN) + '.slack.com/');
		} else {
			handleLoadIframe(SLACK_LOGIN_URL);
		}
	};

	var isMinimized = false;
	win.on('minimize', function () {
		isMinimized = true;
	});
	win.on('restore', function () {
		isMinimized = false;
	});
	function toggleVisibility() {
		if (isMinimized) {
			win.restore();
		} else {
			win.minimize();
		}
	}

	var tray = new gui.Tray({
		title: pkg.window.title,
		icon: pkg.window.icon,
		click: toggleVisibility
	});
	var trayMenu = new gui.Menu();
	trayMenu.append(new gui.MenuItem({
		label: 'Show/Hide window',
		click: toggleVisibility
	}));
	trayMenu.append(new gui.MenuItem({
		type: 'separator'
	}));
	trayMenu.append(new gui.MenuItem({
		label: 'Exit',
		click: function () {
			process.exit();
		}
	}));
	tray.menu = trayMenu;

	window.webslack = webslack;
})();
<commit_msg>Fix download interaction<commit_after>(function () {
	'use strict';
	var gui = require('nw.gui');
	var url = require('url');
	var pkg = require('../package.json');

	var LOCAL_STORAGE_KEY_CURRENT_DOMAIN = 'currentDomain';
	var SLACK_DOMAIN = 'slack.com';
	var SLACK_LOGIN_URL = 'https://slack.com/signin';
	var webslack = {};

	var win = gui.Window.get();
	var validSlackSubdomain = /(.+)\.slack.com/i;
	var slackDownloadHostname = 'files.slack.com';

	win.on('new-win-policy', function (frame, urlStr, policy) {
		// Determine where the request is to
		var openRequest = url.parse(urlStr);

		// If the request is for a file, download it
		// DEV: Files can be found on `files.slack.com`
		//   https://files.slack.com/files-pri/{{id}}/download/tmp.txt
		if (openRequest.hostname === slackDownloadHostname) {
			policy.forceDownload();
			console.log('Downloading file: ', urlStr);
			return;
		}

		// Otherwise, open the window via our browser
		// DEV: An example request is a redirect
		//   https://slack-redir.net/link?url=http%3A%2F%2Fgoogle.com%2F
		gui.Shell.openExternal(urlStr);
		policy.ignore();
		console.log('Allowing browser to handle: ' + JSON.stringify(openRequest));
	});

	function newLocationToProcess(locationToProcess) {
		var locationHostname = url.parse(locationToProcess).hostname;

		if (validSlackSubdomain.test(locationHostname)) {
			var subdomain = validSlackSubdomain.exec(locationHostname);
			if (subdomain[1] && subdomain[1].length > 1) {
				var subdomainFiltered = subdomain[1];

				if (subdomainFiltered !== localStorage.getItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN)) {
					localStorage.setItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN, subdomainFiltered);
				}
			}
		} else if (locationHostname === SLACK_DOMAIN) {
			localStorage.removeItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN);
		}
	}

	function handleLoadIframe(urlStr) {
		var bodyElement = document.body;

		// Remove all the body's children nodes
		while (bodyElement.firstChild) {
			bodyElement.removeChild(bodyElement.firstChild);
		}

		var iframeDomElement = document.createElement('iframe');

		iframeDomElement.setAttribute('src', urlStr);
		iframeDomElement.setAttribute('frameBorder', '0');
		iframeDomElement.setAttribute('nwdisable', '');
		iframeDomElement.setAttribute('nwfaketop', '');

		bodyElement.appendChild(iframeDomElement);
	}

	win.on('document-start', function (frame) {
		if (frame && frame.contentWindow) {
			newLocationToProcess(frame.contentWindow.location.href);
		}
	});

	webslack.load = function () {
		if (localStorage.getItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN)) {
			handleLoadIframe('https://' + localStorage.getItem(LOCAL_STORAGE_KEY_CURRENT_DOMAIN) + '.slack.com/');
		} else {
			handleLoadIframe(SLACK_LOGIN_URL);
		}
	};

	var isMinimized = false;
	win.on('minimize', function () {
		isMinimized = true;
	});
	win.on('restore', function () {
		isMinimized = false;
	});
	function toggleVisibility() {
		if (isMinimized) {
			win.restore();
		} else {
			win.minimize();
		}
	}

	var tray = new gui.Tray({
		title: pkg.window.title,
		icon: pkg.window.icon,
		click: toggleVisibility
	});
	var trayMenu = new gui.Menu();
	trayMenu.append(new gui.MenuItem({
		label: 'Show/Hide window',
		click: toggleVisibility
	}));
	trayMenu.append(new gui.MenuItem({
		type: 'separator'
	}));
	trayMenu.append(new gui.MenuItem({
		label: 'Exit',
		click: function () {
			process.exit();
		}
	}));
	tray.menu = trayMenu;

	window.webslack = webslack;
})();
<|endoftext|>


<commit_before>'use strict';

// Mode
if (window.mode)var mode = window.mode;
else var mode = urlParam('mode');
if (window.urlencodedXML) var urlencodedXML = window.urlencodedXML;
else var urlencodedXML = urlParam('diagramXML');

// Includes
var fs = require('fs');
var $ = require('jquery'),
    BpmnModeler = require('bpmn-js/lib/Modeler'),
    BpmnViewer = require('bpmn-js/lib/Viewer');

var forEach = require('lodash/collection/forEach');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');

// Reference to the custom Modules
var AofCustomizationModules = require('./../aof-customization/index'), // affects activities
    aofModdleExtention = require('./../aof-customization/moddleExtensions/aof');

// Helper Functions

function openDiagram(renderer, xml) {
    renderer.importXML(xml, function (err) {

        if (err) {
            container
                .removeClass('with-diagram')
                .addClass('with-error');

            container.find('.error pre').text(err.message);

            console.error(err);
        } else {
            container
                .removeClass('with-error')
                .addClass('with-diagram');

            var elementRegistry = renderer.get('elementRegistry');
            var canvasObject = renderer.get('canvas');

            // Mark AppEnsembleApps grey
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:UserTask" && element.businessObject.isAppEnsembleApp == true )//&& element.businessObject.$attrs['aof:realizedBy'] && element.businessObject.$attrs['aof:realizedBy'] != "")
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensembleapp');
                }
            );

            // Mark AppEnsembles
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:Participant" && (element.businessObject.$attrs['aof:isAppEnsemble'] && element.businessObject.$attrs['aof:isAppEnsemble'] == "true") || (element.businessObject.isAppEnsemble == true))
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensemble');
                }
            );

            // Load available Apps for UserTasks
            if(mode!="view") {
                var appAssignerObject = renderer.get('appAssigner');
                appAssignerObject.getOptionEntities();
            }
        }

    });
}

function saveSVG(done) {
    renderer.saveSVG(done);
}

function saveDiagram(done) {
    renderer.saveXML({format: true}, function (err, xml) {
        done(err, xml);
    });
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

// Mode and data processing
if (mode == "view") {
    var renderer = new BpmnViewer({container: canvas});
}
else {

    var propertiesPanelModule = require('bpmn-js-properties-panel');
    var propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/aof');

    var renderer = new BpmnModeler({
        container: canvas,
        additionalModules: [propertiesPanelModule, propertiesProviderModule, AofCustomizationModules],
        moddleExtensions: {aof: aofModdleExtention},
        propertiesPanel: {
            parent: '#js-properties-panel'
        }
    });
}
if (mode == "view" || mode == "edit") {
    var newDiagramXML = decodeURIComponent(urlencodedXML);
}
else {
    var newDiagramXML = fs.readFileSync(__dirname + '/../../resources/newDiagram.bpmn', 'utf-8');
}

// bootstrap diagram functions

$(document).on('ready', function () {
    openDiagram(renderer, newDiagramXML);
    window.onbeforeunload = function () {
        return "Do you really want to leave this page? There might be a loss of unsaved data!"
    }
});

// jQuery references
var downloadSvgLink = $('#js-download-svg');
var saveandCloseLink = $('#js-save-appensemble-and-close');
var saveLink = $('#js-save-appensemble');
var closeLink = $('#close-modeler');

// actions definition
if (mode == "view") {
    saveLink.remove();
    saveandCloseLink.remove();
    downloadSvgLink.remove();
}
else {
    saveLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
');
                    setTimeout(function () {
                        $.when($('.alert-box').fadeOut(500))
                            .done(function () {
                                $('.alert-box').remove();
                            });
                    }, 2000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });

    saveandCloseLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
 Closing Modeler in 3 seconds.×
');
                    window.onbeforeunload = function () {
                    }
                    setTimeout(function () {
                        $('#close-seconds').text("2")
                    }, 1000);
                    setTimeout(function () {
                        $('#close-seconds').text("1")
                    }, 2000);
                    setTimeout(function () {
                        window.location.href = document.referrer
                    }, 3000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });
}

closeLink.click(function () {
    window.location.href = document.referrer;
})

$('.top-bar-section .right a').click(function (e) {
    if (!$(this).is('.active')) {
        e.preventDefault();
        e.stopPropagation();
    }
});

// export helper functions
function setEncoded_dl(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': '/api/actions/app-ensembles/add?data=' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

// Update routine
var _ = require('lodash');

var exportArtifacts = _.debounce(function () {
    saveDiagram(function (err, xml) {
        setEncoded(saveLink, 'diagram.bpmn', err ? null : xml);
    });
    saveDiagram(function (err, xml) {
        setEncoded(saveandCloseLink, 'diagram.bpmn', err ? null : xml);
    });
    saveSVG(function (err, svg) {
        setEncoded_dl(downloadSvgLink, 'diagram.svg', err ? null : svg);
    });
}, 500);

renderer.on('commandStack.changed', exportArtifacts);<commit_msg>Renewed dependecies<commit_after>'use strict';

// Mode
if (window.mode)var mode = window.mode;
else var mode = urlParam('mode');
if (window.urlencodedXML) var urlencodedXML = window.urlencodedXML;
else var urlencodedXML = urlParam('diagramXML');

// Includes
var fs = require('fs');
var $ = require('jquery'),
    BpmnModeler = require('bpmn-js/lib/Modeler'),
    BpmnViewer = require('bpmn-js/lib/Viewer');

var forEach = require('lodash/collection/forEach');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');

// Reference to the custom Modules
var AofCustomizationModules = require('./../aof-customization/index'), // affects activities
    aofModdleExtention = require('./../aof-customization/moddleExtensions/aof');

// Helper Functions

function openDiagram(renderer, xml) {
    renderer.importXML(xml, function (err) {

        if (err) {
            container
                .removeClass('with-diagram')
                .addClass('with-error');

            container.find('.error pre').text(err.message);

            console.error(err);
        } else {
            container
                .removeClass('with-error')
                .addClass('with-diagram');

            var elementRegistry = renderer.get('elementRegistry');
            var canvasObject = renderer.get('canvas');

            // Mark AppEnsembleApps grey
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:UserTask" && element.businessObject.isAppEnsembleApp == true )//&& element.businessObject.$attrs['aof:realizedBy'] && element.businessObject.$attrs['aof:realizedBy'] != "")
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensembleapp');
                }
            );

            // Mark AppEnsembles
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:Participant" && (element.businessObject.$attrs['aof:isAppEnsemble'] && element.businessObject.$attrs['aof:isAppEnsemble'] == "true") || (element.businessObject.isAppEnsemble == true))
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensemble');
                }
            );

            // Load available Apps for UserTasks
            if(mode!="view") {
                var ProviderObject = renderer.get('propertiesProvider');
                ProviderObject.getAppURLs();
            }
        }

    });
}

function saveSVG(done) {
    renderer.saveSVG(done);
}

function saveDiagram(done) {
    renderer.saveXML({format: true}, function (err, xml) {
        done(err, xml);
    });
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

// Mode and data processing
if (mode == "view") {
    var renderer = new BpmnViewer({container: canvas});
}
else {

    var propertiesPanelModule = require('bpmn-js-properties-panel');
    var propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/aof');

    var renderer = new BpmnModeler({
        container: canvas,
        additionalModules: [propertiesPanelModule, propertiesProviderModule, AofCustomizationModules],
        moddleExtensions: {aof: aofModdleExtention},
        propertiesPanel: {
            parent: '#js-properties-panel'
        }
    });
}
if (mode == "view" || mode == "edit") {
    var newDiagramXML = decodeURIComponent(urlencodedXML);
}
else {
    var newDiagramXML = fs.readFileSync(__dirname + '/../../resources/newDiagram.bpmn', 'utf-8');
}

// bootstrap diagram functions

$(document).on('ready', function () {
    openDiagram(renderer, newDiagramXML);
    window.onbeforeunload = function () {
        return "Do you really want to leave this page? There might be a loss of unsaved data!"
    }
});

// jQuery references
var downloadSvgLink = $('#js-download-svg');
var saveandCloseLink = $('#js-save-appensemble-and-close');
var saveLink = $('#js-save-appensemble');
var closeLink = $('#close-modeler');

// actions definition
if (mode == "view") {
    saveLink.remove();
    saveandCloseLink.remove();
    downloadSvgLink.remove();
}
else {
    saveLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
');
                    setTimeout(function () {
                        $.when($('.alert-box').fadeOut(500))
                            .done(function () {
                                $('.alert-box').remove();
                            });
                    }, 2000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });

    saveandCloseLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
 Closing Modeler in 3 seconds.×
');
                    window.onbeforeunload = function () {
                    }
                    setTimeout(function () {
                        $('#close-seconds').text("2")
                    }, 1000);
                    setTimeout(function () {
                        $('#close-seconds').text("1")
                    }, 2000);
                    setTimeout(function () {
                        window.location.href = document.referrer
                    }, 3000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });
}

closeLink.click(function () {
    window.location.href = document.referrer;
})

$('.top-bar-section .right a').click(function (e) {
    if (!$(this).is('.active')) {
        e.preventDefault();
        e.stopPropagation();
    }
});

// export helper functions
function setEncoded_dl(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': '/api/actions/app-ensembles/add?data=' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

// Update routine
var _ = require('lodash');

var exportArtifacts = _.debounce(function () {
    saveDiagram(function (err, xml) {
        setEncoded(saveLink, 'diagram.bpmn', err ? null : xml);
    });
    saveDiagram(function (err, xml) {
        setEncoded(saveandCloseLink, 'diagram.bpmn', err ? null : xml);
    });
    saveSVG(function (err, svg) {
        setEncoded_dl(downloadSvgLink, 'diagram.svg', err ? null : svg);
    });
}, 500);

renderer.on('commandStack.changed', exportArtifacts);<|endoftext|>


<commit_before>function show(el) {
  el.style.display = "block";
}

function hide(el) {
  el.style.display = "none";
}

function activate(el) {
  el.className = "active";
}

function deactivate(el) {
  el.className = "";
}

module.exports = {
  show,
  hide,
  activate,
  deactivate
};
<commit_msg>implement requestAnimationFrame-based animate utility function<commit_after>function show(el) {
  el.style.display = "block";
}

function hide(el) {
  el.style.display = "none";
}

function activate(el) {
  el.className = "active";
}

function deactivate(el) {
  el.className = "";
}

function animate(options) {
  var { duration, onUpdate, onFinish } = options;

  if (isNaN(duration)) {
    throw "duration is not a number";
  }

  var start = null;

  requestAnimationFrame(loop);

  function loop(timestamp) {
    if (!start) start = timestamp;

    var progress = timestamp - start;

    var t = Math.min(progress / duration , 1);
    onUpdate(t);

    if (progress < duration) {
      requestAnimationFrame(loop);
    } else {
      if (onFinish) {
        onFinish();
      }
    }
  }
}

module.exports = {
  show: show,
  hide: hide,
  activate: activate,
  deactivate: deactivate,
  animate: animate
};
<|endoftext|>


<commit_before>/**
 * ffmpeg video conversion
 *
 * MIT Licensed, see License.txt
 *
 * https://github.com/fluent-ffmpeg/node-fluent-ffmpeg
 *
 */

// utilities module
var utilities = require('./bower_components/chrisweb-utilities/utilities');

var Fluent = require('fluent-ffmpeg');

var fs = require('fs');

var path = require('path');

utilities.log('[VIDEO CONVERTOR]');

// windows only
if (typeof(process.env.FFMPEG_PATH) === 'undefined') {

    process.env.FFMPEG_PATH = 'C:\ffmpeg\bin\ffmpeg.exe';

    utilities.log('FFMPEG_PATH not found, setting it by default to "' + process.env.FFMPEG_PATH.toUpperCase() + '"', 'fontColor:red');

}

if (typeof(process.env.FFPROBE_PATH) === 'undefined') {

    process.env.FFPROBE_PATH = 'C:\ffmpeg\bin\ffprobe.exe';

    utilities.log('FFPROBE_PATH not found, setting it by default to "' + process.env.FFPROBE_PATH.toUpperCase() + '"', 'fontColor:red');

}

var videoDirectory = 'videos';

var files = fs.readdirSync(videoDirectory);

var fluentCommand = new Fluent();

for (var i in files) {

    if (path.extname(files[i]) === '.mov') {

        var videoSource = videoDirectory + '/' + files[i];

        utilities.log('videoSource: ' + videoSource);

        var videoOutputWebm = videoDirectory + '/hompage-video_' + i + '.webm';
        var videoOutputMpeg = videoDirectory + '/hompage-video_' + i + '.mp4';

        utilities.log('videoOutputWebm: ' + videoOutputWebm);
        utilities.log('videoOutputMpeg: ' + videoOutputMpeg);

        var fluentCommand = new Fluent();

        // video input
        fluentCommand.input(videoSource)
                    // specify input format
                    .inputFormat('mov')
                    // disable audio as we dont need it for the intro videos
                    .noAudio();
                    // specify output frame rate
                    //.fps(29.7)

        // second output as webm
        fluentCommand.outputFormat('webm') // set output format
                    .output(videoOutputWebm)
                    // specify output frame rate
                    //.fps(29.7)

        // first ouput as mpeg
        fluentCommand.outputFormat('mp4') // set output format
                    .output(videoOutputMpeg)
                    // specify output frame rate
                    //.fps(29.7)

        fluentCommand.on('start', function(commandLine) {

            utilities.log('Spawned Ffmpeg with command: ' + commandLine, 'fontColor:green');

        });

        fluentCommand.on('codecData', function(data) {

            utilities.log('codecData:');
            utilities.log('codecData:');

            utilities.log('format: ' + data.format);
            utilities.log('duration: ' + data.duration);
            utilities.log('audio: ' + data.audio);
            utilities.log('audio_details: ' + data.audio_details);
            utilities.log('video: ' + data.video);
            utilities.log('video_details: ' + data.video_details);

        });

        fluentCommand.on('progress', function(progress) {

            utilities.log('Processing: ' + progress.percent + '% done');

        });

        fluentCommand.on('error', function(err) {

            utilities.log('An error occurred: ' + err.message, 'fontColor:red');

        });

        fluentCommand.on('end', function() {

            utilities.log('Processing finished !');

        });

        fluentCommand.run();

    }

}<commit_msg>delete previously encoded videos<commit_after>/**
 * ffmpeg video conversion
 *
 * MIT Licensed, see License.txt
 *
 * https://github.com/fluent-ffmpeg/node-fluent-ffmpeg
 *
 */

// utilities module
var utilities = require('./bower_components/chrisweb-utilities/utilities');

var Fluent = require('fluent-ffmpeg');

var fs = require('fs');

var path = require('path');

utilities.log('[VIDEO CONVERTOR]');

// windows only
if (typeof(process.env.FFMPEG_PATH) === 'undefined') {

    process.env.FFMPEG_PATH = 'C:\ffmpeg\bin\ffmpeg.exe';

    utilities.log('FFMPEG_PATH not found, setting it by default to "' + process.env.FFMPEG_PATH.toUpperCase() + '"', 'fontColor:red');

}

if (typeof(process.env.FFPROBE_PATH) === 'undefined') {

    process.env.FFPROBE_PATH = 'C:\ffmpeg\bin\ffprobe.exe';

    utilities.log('FFPROBE_PATH not found, setting it by default to "' + process.env.FFPROBE_PATH.toUpperCase() + '"', 'fontColor:red');

}

var videoDirectory = 'videos';

var fluentCommand = new Fluent();

// remove previous versions of the videos
var files = fs.readdirSync(videoDirectory);

for (var i in files) {

    if (path.extname(files[i]) === '.mp4' || path.extname(files[i]) === '.webm') {

        fs.unlink(files[i], function (error) {

            if (error) {

                console.log('error while deleting: ' + files[i] + ', error: ' + error);

            } else {

                console.log('deleted: ' + files[i]);

            }

        });

    }

}

// encode the videos
var files = fs.readdirSync(videoDirectory);

for (var i in files) {

    if (path.extname(files[i]) === '.mov') {

        var videoSource = videoDirectory + '/' + files[i];

        utilities.log('videoSource: ' + videoSource);

        var videoOutputWebm = videoDirectory + '/hompage-video_' + i + '.webm';
        var videoOutputMp4 = videoDirectory + '/hompage-video_' + i + '.mp4';

        utilities.log('videoOutputWebm: ' + videoOutputWebm);
        utilities.log('videoOutputMp4: ' + videoOutputMp4);

        var fluentCommand = new Fluent();

        // video input
        fluentCommand.input(videoSource)
                    // specify input format
                    //.inputFormat('mov')
                    // disable audio as we dont need it for the intro videos
                    .noAudio();
                    // specify output frame rate
                    //.fps(29.7)

        // second output as webm
        fluentCommand.outputFormat('webm') // set output format
                    .output(videoOutputWebm);
                    // specify output frame rate
                    //.fps(29.7)

        // first ouput as mp4
        fluentCommand.outputFormat('mp4') // set output format
                    .output(videoOutputMp4);
                    // specify output frame rate
                    //.fps(29.7)

        fluentCommand.on('start', function(commandLine) {

            utilities.log('Spawned Ffmpeg with command: ' + commandLine, 'fontColor:green');

        });

        fluentCommand.on('codecData', function(data) {

            utilities.log('codecData:');

            utilities.log('format: ' + data.format);
            utilities.log('duration: ' + data.duration);
            utilities.log('audio: ' + data.audio);
            utilities.log('audio_details: ' + data.audio_details);
            utilities.log('video: ' + data.video);
            utilities.log('video_details: ' + data.video_details);

        });

        fluentCommand.on('progress', function(progress) {

            utilities.log('Processing: ' + progress.percent + '% done');

        });

        fluentCommand.on('error', function(err) {

            utilities.log('An error occurred: ' + err.message, 'fontColor:red');

        });

        fluentCommand.on('end', function() {

            utilities.log('Processing finished !');

        });

        fluentCommand.run();

    }

}<|endoftext|>


<commit_before>function Yeti(options) {
  this.x = 4;
  this.y = 10;
  this.width = 43;
  this.height = 32;
  this.aggressive = false;
  this.context = options.context;
  this.position = 0;
}

Yeti.prototype.attack = function(skier, skierImg) {
  this.position += 1;
  if (this.position > 16) {
    return this.position = 0;
  }

  var direction = skier.x - this.x;

  if (this.position < 8 && direction > 0) {
    this.context.drawImage(
      skierImg,
      64,
      113,
      25,
      41,
      this.x,
      this.y,
      this.height,
      this.width
    );
  } else if (this.position > 8 && direction > 0){
    this.context.drawImage(
      skierImg,
      90,
      113,
      32,
      41,
      this.x,
      this.y,
      this.height,
      this.width
    );
  } else if (this.position < 8 && direction < 0){
    this.context.drawImage(
      skierImg,
      64,
      159,
      32,
      41,
      this.x,
      this.y,
      this.height,
      this.width
    );
  } else {
    this.context.drawImage(
      skierImg,
      90,
      159,
      32,
      41,
      this.x,
      this.y,
      this.height,
      this.width
    );
  }
  this.rotation = Math.atan2(skier.y - this.y, skier.x - this.x);
  this.x += Math.cos(this.rotation);
  this.y += Math.sin(this.rotation);
  return this;
};

module.exports = Yeti;
<commit_msg>Refactor yeti running.<commit_after>function Yeti(options) {
  this.x = 4;
  this.y = 10;
  this.width = 43;
  this.height = 32;
  this.aggressive = false;
  this.context = options.context;
  this.position = 0;
}

Yeti.prototype.attack = function(skier, skierImg) {
  posYeti(this);
  var direction = skier.x - this.x;

  if (this.position < 8 && direction > 0) {
    yetiRunning(64, 113, 25, this, skierImg);
  } else if (this.position > 8 && direction > 0) {
    yetiRunning(90, 113, 32, this, skierImg);
  } else if (this.position < 8 && direction < 0) {
    yetiRunning(64, 159, 25, this, skierImg);
  } else {
    yetiRunning(90, 159, 32, this, skierImg);
  }

  this.rotation = Math.atan2(skier.y - this.y, skier.x - this.x);
  this.x += Math.cos(this.rotation);
  this.y += Math.sin(this.rotation);
  return this;
};

function posYeti(yeti) {
  yeti.position += 1;
  if (yeti.position > 16) {
    return yeti.position = 0;
  }
}

function yetiRunning(posx, posy, width, yeti, skierImg) {
  yeti.context.drawImage(
  skierImg,
  posx,
  posy,
  width,
  41,
  yeti.x,
  yeti.y,
  yeti.height,
  yeti.width
  );
}

module.exports = Yeti;
<|endoftext|>


<commit_before>/*
 * Video.js Hotkeys
 * https://github.com/ctd1500/videojs-hotkeys
 *
 * Copyright (c) 2015 Chris Dougherty
 * Licensed under the Apache-2.0 license.
 */

(function(window, videojs) {
  'use strict';

  window['videojs_hotkeys'] = { version: "0.2.3" };
  var hotkeys = function(options) {
    var player = this;
    var def_options = {
      volumeStep: 0.1,
      seekStep: 5,
      enableMute: true,
      enableFullscreen: true,
      enableNumbers: true
    };
    options = options || {};

    // Set default player tabindex to handle keydown and doubleclick events
    if (!player.el().hasAttribute('tabIndex')) {
      player.el().setAttribute('tabIndex', '-1');
    }

    player.on('play', function() {
      // Fix allowing the YouTube plugin to have hotkey support.
      var ifblocker = player.el().querySelector('.iframeblocker');
      if (ifblocker &&
          ifblocker.style.display == "") {
        ifblocker.style.display = "block";
        ifblocker.style.bottom = "39px";
      }
    });

    var keyDown = function keyDown(event) {
      var volumeStep = options.volumeStep || def_options.volumeStep;
      var seekStep = options.seekStep || def_options.seekStep;
      var enableMute = options.enableMute || def_options.enableMute;
      var enableFull = options.enableFullscreen || def_options.enableFullscreen;
      var enableNumbers = options.enableNumbers || def_options.enableNumbers;

      // When controls are disabled, hotkeys will be disabled as well
      if (player.controls()) {

        // Don't catch keys if any control buttons are focused
        var activeEl = document.activeElement;
        if (activeEl == player.el() ||
            activeEl == player.el().querySelector('.vjs-tech') ||
            activeEl == player.el().querySelector('.vjs-control-bar') ||
            activeEl == player.el().querySelector('.iframeblocker')) {

          // Spacebar toggles play/pause
          if (event.which === 32) {
            event.preventDefault();
            if (player.paused()) {
              player.play();
            } else {
              player.pause();
            }
          }

          // Seeking with the left/right arrow keys
          else if (event.which === 37) { // Left Arrow
            event.preventDefault();
            var curTime = player.currentTime() - seekStep;

            // The flash player tech will allow you to seek into negative
            // numbers and break the seekbar, so try to prevent that.
            if (player.currentTime() <= seekStep) {
              curTime = 0;
            }
            player.currentTime(curTime);
          } else if (event.which === 39) { // Right Arrow
            event.preventDefault();
            player.currentTime(player.currentTime() + seekStep);
          }

          // Volume control with the up/down arrow keys
          else if (event.which === 40) { // Down Arrow
            event.preventDefault();
            player.volume(player.volume() - volumeStep);
          } else if (event.which === 38) { // Up Arrow
            event.preventDefault();
            player.volume(player.volume() + volumeStep);
          }

          // Toggle Mute with the M key
          else if (event.which === 77) {
            if (enableMute) {
              if (player.muted()) {
                player.muted(false);
              } else {
                player.muted(true);
              }
            }
          }

          // Toggle Fullscreen with the F key
          else if (event.which === 70) {
            if (enableFull) {
              if (player.isFullscreen()) {
                player.exitFullscreen();
              } else {
                player.requestFullscreen();
              }
            }
          }

          else if ([48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58].indexOf(event.which) > -1) {
            if (enableNumbers){
              var number = event.which - 48;
              event.preventDefault();
              player.currentTime(player.duration() * number * 0.1);
            }
          }

        }
      }
    };

    var doubleClick = function doubleClick(event) {
      var enableFull = options.enableFullscreen || def_options.enableFullscreen;

      // When controls are disabled, hotkeys will be disabled as well
      if (player.controls()) {

        // Don't catch clicks if any control buttons are focused
        var activeEl = event.relatedTarget || event.toElement || document.activeElement;
        if (activeEl == player.el() ||
            activeEl == player.el().querySelector('.vjs-tech') ||
            activeEl == player.el().querySelector('.iframeblocker')) {

          if (enableFull) {
            if (player.isFullscreen()) {
              player.exitFullscreen();
            } else {
              player.requestFullscreen();
            }
          }
        }
      }
    };

    player.on('keydown', keyDown);
    player.on('dblclick', doubleClick);

    return this;
  };

  videojs.plugin('hotkeys', hotkeys);

})(window, window.videojs);
<commit_msg>Add numpad number key catching for skips.<commit_after>/*
 * Video.js Hotkeys
 * https://github.com/ctd1500/videojs-hotkeys
 *
 * Copyright (c) 2015 Chris Dougherty
 * Licensed under the Apache-2.0 license.
 */

(function(window, videojs) {
  'use strict';

  window['videojs_hotkeys'] = { version: "0.2.3" };
  var hotkeys = function(options) {
    var player = this;
    var def_options = {
      volumeStep: 0.1,
      seekStep: 5,
      enableMute: true,
      enableFullscreen: true,
      enableNumbers: true
    };
    options = options || {};

    // Set default player tabindex to handle keydown and doubleclick events
    if (!player.el().hasAttribute('tabIndex')) {
      player.el().setAttribute('tabIndex', '-1');
    }

    player.on('play', function() {
      // Fix allowing the YouTube plugin to have hotkey support.
      var ifblocker = player.el().querySelector('.iframeblocker');
      if (ifblocker &&
          ifblocker.style.display == "") {
        ifblocker.style.display = "block";
        ifblocker.style.bottom = "39px";
      }
    });

    var keyDown = function keyDown(event) {
      var volumeStep = options.volumeStep || def_options.volumeStep;
      var seekStep = options.seekStep || def_options.seekStep;
      var enableMute = options.enableMute || def_options.enableMute;
      var enableFull = options.enableFullscreen || def_options.enableFullscreen;
      var enableNumbers = options.enableNumbers || def_options.enableNumbers;

      // When controls are disabled, hotkeys will be disabled as well
      if (player.controls()) {

        // Don't catch keys if any control buttons are focused
        var activeEl = document.activeElement;
        if (activeEl == player.el() ||
            activeEl == player.el().querySelector('.vjs-tech') ||
            activeEl == player.el().querySelector('.vjs-control-bar') ||
            activeEl == player.el().querySelector('.iframeblocker')) {

          // Spacebar toggles play/pause
          if (event.which === 32) {
            event.preventDefault();
            if (player.paused()) {
              player.play();
            } else {
              player.pause();
            }
          }

          // Seeking with the left/right arrow keys
          else if (event.which === 37) { // Left Arrow
            event.preventDefault();
            var curTime = player.currentTime() - seekStep;

            // The flash player tech will allow you to seek into negative
            // numbers and break the seekbar, so try to prevent that.
            if (player.currentTime() <= seekStep) {
              curTime = 0;
            }
            player.currentTime(curTime);
          } else if (event.which === 39) { // Right Arrow
            event.preventDefault();
            player.currentTime(player.currentTime() + seekStep);
          }

          // Volume control with the up/down arrow keys
          else if (event.which === 40) { // Down Arrow
            event.preventDefault();
            player.volume(player.volume() - volumeStep);
          } else if (event.which === 38) { // Up Arrow
            event.preventDefault();
            player.volume(player.volume() + volumeStep);
          }

          // Toggle Mute with the M key
          else if (event.which === 77) {
            if (enableMute) {
              if (player.muted()) {
                player.muted(false);
              } else {
                player.muted(true);
              }
            }
          }

          // Toggle Fullscreen with the F key
          else if (event.which === 70) {
            if (enableFull) {
              if (player.isFullscreen()) {
                player.exitFullscreen();
              } else {
                player.requestFullscreen();
              }
            }
          }

          // Number keys from 0-9 skip to a percentage of the video. 0 is 0% and 9 is 90%
          else if ([48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
                    96, 97, 98, 99, 100, 101, 102, 103, 104, 105].indexOf(event.which) > -1) {
            if (enableNumbers) {
              var sub = 48;
              if (event.which >= 96) {
                sub = 96;
              }
              var number = event.which - sub;
              event.preventDefault();
              player.currentTime(player.duration() * number * 0.1);
            }
          }

        }
      }
    };

    var doubleClick = function doubleClick(event) {
      var enableFull = options.enableFullscreen || def_options.enableFullscreen;

      // When controls are disabled, hotkeys will be disabled as well
      if (player.controls()) {

        // Don't catch clicks if any control buttons are focused
        var activeEl = event.relatedTarget || event.toElement || document.activeElement;
        if (activeEl == player.el() ||
            activeEl == player.el().querySelector('.vjs-tech') ||
            activeEl == player.el().querySelector('.iframeblocker')) {

          if (enableFull) {
            if (player.isFullscreen()) {
              player.exitFullscreen();
            } else {
              player.requestFullscreen();
            }
          }
        }
      }
    };

    player.on('keydown', keyDown);
    player.on('dblclick', doubleClick);

    return this;
  };

  videojs.plugin('hotkeys', hotkeys);

})(window, window.videojs);
<|endoftext|>


<commit_before>/**
 * Created by ArunaTebel on 12/12/2015.
 */
var OFFLINK_CACHE = [
    '/app/view1/view1.html',
    '/app/view2/view2.html',
    '/app/view1/fallback.html',
    '/app.css'
];<commit_msg>Remove old cache<commit_after>/**
 * Created by ArunaTebel on 12/12/2015.
 */
var OFFLINK_CACHE = [
    '/app/view1/view1.html',
    '/app/view2/view2.html',
    '/app/view1/fallback.html',
    '/app/app.css'
];<|endoftext|>


<commit_before>/*global jsobj */
/*jslint plusplus: true */

(function (jsobj) {
	"use strict";

	function Grid() {
		var blocks = [],	// 9 blocks of 9 cells each
			vrows = [],		// 9 vertical rows of 9 cells each
			hrows = [],		// 9 horizontal rows of 9 cells each
			rules,
			i,
			newCell,
			allgroups,
			gridState = 'init',
			solvedThisRound = 0,
			solvedTotal = 0,
			me = this;

		function cellUpdated() {
			solvedThisRound++;
			// only fire a grid update once the grid is ready - not during seeding
			if (gridState === 'ready') {
				me.trigger("update", newCell);
			}
		}

		// *** CREATE GRID OBJECT ***

		// create 9 blocks, vrows, hrows
		for (i = 0; i < 9; i++) {
			blocks.push(new jsobj.CellGroup('block', i, me));
			vrows.push(new jsobj.CellGroup('col', i, me));
			hrows.push(new jsobj.CellGroup('row', i, me));
		}

		// create 81 cells each tied to correct block, vrow, hrow
		for (i = 0; i < 81; i++) {
			newCell = new jsobj.Cell(this);
			newCell.setRowH(hrows[Math.floor(i / 9)]);		// every 9 consecutive cells make an hrow
			newCell.setRowV(vrows[i % 9]);					// every 9th cell belongs to the same vrow
			newCell.setBlock(blocks[Math.floor(i / 3) % 3 + Math.floor(i / 27) * 3]);	// every 3rd set of 3 consecutive cells up to 9 make a block
			newCell.on("update", cellUpdated);
		}

		gridState = 'unseeded';

		this.state = function () {
			return gridState;
		};

		this.rows = hrows;
		this.cols = vrows;

		this.vRow = function (index) {
			return vrows[index];
		};

		this.hRow = function (index) {
			return hrows[index];
		};

		this.block = function (index) {
			return blocks[index];
		};

		this.allGroups = function () {
			if (allgroups === undefined) {
				allgroups = hrows.concat(vrows).concat(blocks);
			}
			return allgroups;
		};

		this.addSeeds = function (seeds) {
			var row, col, seed;

			for (row = 0; row < seeds.length; row++) {
				for (col = 0; col < seeds[row].length; col++) {
					seed = seeds[row][col];
					if (seed !== undefined && typeof seed === 'number') {
						hrows[row].cells()[col].setValue(seed);
					}
				}
			}

			gridState = 'ready';
			return this;
		};

		this.solve = function () {
			var rule;

			if (solvedTotal > 0) {
				return;
			}

			// add rules to list - just a default rule for now, allow user to pass in rules later
			rules = [ jsobj.ruleLastInGroup ];

			// continually run all rules in the list until a full run causes no solutions.
			while (solvedThisRound > 0) {
				solvedTotal += solvedThisRound;
				solvedThisRound = 0;
				for (rule = 0; rule < rules.length; rule++) {
					rules[rule](me);
				}
			}

			gridState = (solvedTotal === 81 ? 'complete' : 'incomplete');
			return this;
		};
	}

	jsobj.Grid = function () {
		return jsobj.EventAware(new Grid());
	};
}(jsobj));<commit_msg>grid solve() checks rule progress<commit_after>/*global jsobj */
/*jslint plusplus: true */

(function (jsobj) {
	"use strict";

	function Grid() {
		var blocks = [],	// 9 blocks of 9 cells each
			vrows = [],		// 9 vertical rows of 9 cells each
			hrows = [],		// 9 horizontal rows of 9 cells each
			rules,
			i,
			newCell,
			allgroups,
			gridState = 'init',
			cellsSolved = 0,
			me = this;

		function cellUpdated() {
			cellsSolved++;
			// only fire a grid update once the grid is ready - not during seeding
			if (gridState === 'ready') {
				me.trigger("update", newCell);
			}
		}

		// *** CREATE GRID OBJECT ***

		// create 9 blocks, vrows, hrows
		for (i = 0; i < 9; i++) {
			blocks.push(new jsobj.CellGroup('block', i, me));
			vrows.push(new jsobj.CellGroup('col', i, me));
			hrows.push(new jsobj.CellGroup('row', i, me));
		}

		// create 81 cells each tied to correct block, vrow, hrow
		for (i = 0; i < 81; i++) {
			newCell = new jsobj.Cell(this);
			newCell.setRowH(hrows[Math.floor(i / 9)]);		// every 9 consecutive cells make an hrow
			newCell.setRowV(vrows[i % 9]);					// every 9th cell belongs to the same vrow
			newCell.setBlock(blocks[Math.floor(i / 3) % 3 + Math.floor(i / 27) * 3]);	// every 3rd set of 3 consecutive cells up to 9 make a block
			newCell.on("update", cellUpdated);
		}

		gridState = 'unseeded';

		this.state = function () {
			return gridState;
		};

		this.rows = hrows;
		this.cols = vrows;

		this.vRow = function (index) {
			return vrows[index];
		};

		this.hRow = function (index) {
			return hrows[index];
		};

		this.block = function (index) {
			return blocks[index];
		};

		this.allGroups = function () {
			if (allgroups === undefined) {
				allgroups = hrows.concat(vrows).concat(blocks);
			}
			return allgroups;
		};

		this.addSeeds = function (seeds) {
			var row, col, seed;

			for (row = 0; row < seeds.length; row++) {
				for (col = 0; col < seeds[row].length; col++) {
					seed = seeds[row][col];
					if (seed !== undefined && typeof seed === 'number') {
						hrows[row].cells()[col].setValue(seed);
					}
				}
			}

			gridState = 'ready';
			return this;
		};

		this.solve = function () {
			var rule, progress = true;

			if (gridState === 'complete' || gridState === 'incomplete') {
				return;
			}

			// add rules to list - just a default rule for now, allow user to pass in rules later
			rules = [ jsobj.ruleLastInGroup ];

			// continually run all rules in the list until a full run causes no progress.
			while (progress && cellsSolved !== 81) {
				progress = false;
				for (rule = 0; rule < rules.length && cellsSolved !== 81; rule++) {
					progress = progress || rules[rule](me);
				}
			}

			gridState = (cellsSolved === 81 ? 'complete' : 'incomplete');
			return this;
		};
	}

	jsobj.Grid = function () {
		return jsobj.EventAware(new Grid());
	};
}(jsobj));<|endoftext|>


<commit_before>/*global define*/
define([
        './loadWithXhr'
    ], function(
        loadWithXhr) {
    "use strict";

    /**
     * Asynchronously loads the given URL as text.  Returns a promise that will resolve to
     * a String once loaded, or reject if the URL failed to load.  The data is loaded
     * using XMLHttpRequest, which means that in order to make requests to another origin,
     * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
     *
     * @exports loadText
     *
     * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
     * @param {Object} [headers] HTTP headers to send with the request.
     * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
     *
     *
     * @example
     * // load text from a URL, setting a custom header
     * Cesium.loadText('http://someUrl.com/someJson.txt', {
     *   'X-Custom-Header' : 'some value'
     * }).then(function(text) {
     *     // Do something with the text
     * }).otherwise(function(error) {
     *     // an error occurred
     * });
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
     * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
     * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
     */
    function loadText(url, headers) {
        return loadWithXhr({
            url : url,
            headers : headers
        });
    }

    return loadText;
});
<commit_msg>Update loadText.js<commit_after>/*global define*/
define([
        './loadWithXhr'
    ], function(
        loadWithXhr) {
    "use strict";

    /**
     * Asynchronously loads the given URL as text.  Returns a promise that will resolve to
     * a String once loaded, or reject if the URL failed to load.  The data is loaded
     * using XMLHttpRequest, which means that in order to make requests to another origin,
     * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
     *
     * @exports loadText
     *
     * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
     * @param {Object} [headers] HTTP headers to send with the request.
     * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
     *
     *
     * @example
     * // load text from a URL, setting a custom header
     * Cesium.loadText('http://someUrl.com/someJson.txt', {
     *   'X-Custom-Header' : 'some value'
     * }).then(function(text) {
     *     // Do something with the text
     * }).otherwise(function(error) {
     *     // an error occurred
     * });
     *
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
     * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
     * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
     */
    function loadText(url, headers) {
        return loadWithXhr({
            url : url,
            headers : headers
        });
    }

    return loadText;
});
<|endoftext|>


<commit_before>/**
 * Converts from degrees to radians
 * @param {number} degrees - The quantity in degrees
 * @return {number} The quantity, now in radians
 */
Math.radians = function (degrees) {
	return (degrees * Math.PI) / 180
}

/**
 * Converts from radians to degrees
 * @param {number} radians - The quantity in radians
 * @return {number} The quantity, now in degrees
 */
Math.degrees = function (radians) {
	return (radians * 180) / Math.PI
}

/**
 * A module containing map-related helper functions
 * @module util/map
 */
module.exports = {

	/**
	 * Gets the surface distance between two Earth coordinates in meters
	 * @function
	 * @param {number} lat1 The latitude of the first point
	 * @param {number} lon1 The longitude of the first point
	 * @param {number} lat2 The latitude of the second point
	 * @param {number} lon2 The longitude of the second point
	 * @return {number|null} Null if any of the inputs were null. Otherwise, the distance in meters (rounded down the nearest integer)
	 */
	getDistance(lat1, lon1, lat2, lon2) {
		if (lat1 && lon1 && lat2 && lon2) {
			const Phi1 = Math.radians(lat1)
			const Phi2 = Math.radians(lat2)
			const DeltaLambda = Math.radians(lon2 - lon1)
			const EarthRadius = 6371000	// Earth radius in meters

			const DistanceMeters = Math.acos( (Math.sin(Phi1) * Math.sin(Phi2)) + (Math.cos(Phi1) * Math.cos(Phi2) * Math.cos(DeltaLambda)) ) * EarthRadius

			return Math.floor(DistanceMeters)
		} else {
			return null
		}
	},

	/**
	 * Gets the coordinates of the midpoint between two coordinates
	 * @function
	 * @param {number} lat1 The latitude of the first point
	 * @param {number} lon1 The longitude of the first point
	 * @param {number} lat2 The latitude of the second point
	 * @param {number} lon2 The longitude of the second point
	 * @returns {number[]} The midpoint coordinates stored in a 2-length array with the form {latitude, longitude}
	 */
	getMidpointCoords(lat1, lon1, lat2, lon2) {
		if (lat1 && lon1 && lat2 && lon2) {
			lat1 = Math.radians(lat1)
			lon1 = Math.radians(lon1)
			lat2 = Math.radians(lat2)
			lon2 = Math.radians(lon2)
			const bx = Math.cos(lat2) * Math.cos(lon2 - lon1)
			const by = Math.cos(lat2) * Math.sin(lon2 - lon1)
			const lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt(((Math.cos(lat1) + bx) * (Math.cos(lat1) + bx)) + (by ** 2)))
			const lon3 = lon1 + Math.atan2(by, Math.cos(lat1) + bx)
			return [Math.round(Math.degrees(lat3), 5), Math.round(Math.degrees(lon3), 5)]
		} else {
			return null
		}
	}
}
<commit_msg>Resolve an Android issue with exponentiation operators<commit_after>/**
 * Converts from degrees to radians
 * @param {number} degrees - The quantity in degrees
 * @return {number} The quantity, now in radians
 */
Math.radians = function (degrees) {
	return (degrees * Math.PI) / 180
}

/**
 * Converts from radians to degrees
 * @param {number} radians - The quantity in radians
 * @return {number} The quantity, now in degrees
 */
Math.degrees = function (radians) {
	return (radians * 180) / Math.PI
}

/**
 * A module containing map-related helper functions
 * @module util/map
 */
module.exports = {

	/**
	 * Gets the surface distance between two Earth coordinates in meters
	 * @function
	 * @param {number} lat1 The latitude of the first point
	 * @param {number} lon1 The longitude of the first point
	 * @param {number} lat2 The latitude of the second point
	 * @param {number} lon2 The longitude of the second point
	 * @return {number|null} Null if any of the inputs were null. Otherwise, the distance in meters (rounded down the nearest integer)
	 */
	getDistance(lat1, lon1, lat2, lon2) {
		if (lat1 && lon1 && lat2 && lon2) {
			const Phi1 = Math.radians(lat1)
			const Phi2 = Math.radians(lat2)
			const DeltaLambda = Math.radians(lon2 - lon1)
			const EarthRadius = 6371000	// Earth radius in meters

			const DistanceMeters = Math.acos( (Math.sin(Phi1) * Math.sin(Phi2)) + (Math.cos(Phi1) * Math.cos(Phi2) * Math.cos(DeltaLambda)) ) * EarthRadius

			return Math.floor(DistanceMeters)
		} else {
			return null
		}
	},

	/**
	 * Gets the coordinates of the midpoint between two coordinates
	 * @function
	 * @param {number} lat1 The latitude of the first point
	 * @param {number} lon1 The longitude of the first point
	 * @param {number} lat2 The latitude of the second point
	 * @param {number} lon2 The longitude of the second point
	 * @returns {number[]} The midpoint coordinates stored in a 2-length array with the form {latitude, longitude}
	 */
	getMidpointCoords(lat1, lon1, lat2, lon2) {
		if (lat1 && lon1 && lat2 && lon2) {
			lat1 = Math.radians(lat1)
			lon1 = Math.radians(lon1)
			lat2 = Math.radians(lat2)
			lon2 = Math.radians(lon2)
			const bx = Math.cos(lat2) * Math.cos(lon2 - lon1)
			const by = Math.cos(lat2) * Math.sin(lon2 - lon1)
			const lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt(((Math.cos(lat1) + bx) * (Math.cos(lat1) + bx)) + (by * by)))
			const lon3 = lon1 + Math.atan2(by, Math.cos(lat1) + bx)
			return [Math.round(Math.degrees(lat3), 5), Math.round(Math.degrees(lon3), 5)]
		} else {
			return null
		}
	}
}
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';
var url = require('url'),
	exec = require('child_process').exec,
	wn2schema = require('../../mappings/wn2schema').mapping,
	wn2sumo = require('../../mappings/wn2sumo').mapping,
	schema2parent = require('../../mappings/schema2parent').mapping,
	sumo2parent = require('../../mappings/sumo2parent').mapping,
	findParents = function (synset, callback) {
		exec('perl scripts/parents.pl ' + synset, function (error, stout, stderr) {
			if (error) {
				callback(new Error(error));
			} else if (stderr) {
				callback(new Error(stderr));
			} else {
				callback(null, stout);
			}
		});
	},
	addMappings = function (object, callback) {
		var	mapping = {"synset": object.synset};
		if (wn2schema[object.synset]) {
			mapping.schema_dot_org = wn2schema[object.synset];
		}
		if (wn2sumo[object.offset]) {
			mapping.sumo = wn2sumo[object.offset].sumo;
		}
		callback(null, mapping);
	},
	findLinkMapping = function (link, callback) {
		addMappings(link, function (error, mapping) {
			if (error) {
				callback(error);
			} else {
				var siblings = [],
					i,
					addSiblingMappings = function (error, mappings) {
						if (error) {
							console.log("Error received: " + error);
						} else {
							if (mappings) {
								siblings.push(mappings);
							}
						}
					};
				if (link.siblings) {
					for (i = 0; i < link.siblings.length; i += 1) {
						addMappings(link.siblings[i], addSiblingMappings);
					}
				}
				if (siblings.length > 0) {
					mapping.siblings = siblings;
				}
				callback(null, mapping);
			}
		});
	},
	mapSynset = function (synset, callback) {
		var	json,
			i;
		findParents(synset, function (error, data) {
			if (error) {
				callback(error);
			} else {
				json = JSON.parse(data);
				addMappings(json, function (error, mapping) {
					if (error) {
						callback(error);
					} else {
						var addSiblingMappings = function (error, siblings) {
								if (error) {
									console.log(error);
								} else if (siblings) {
									if (!mapping.siblings) {
										mapping.siblings = [];
									}
									mapping.siblings.push(siblings);
								}
							},
							addLinkMappings = function (error, link) {
								if (error) {
									console.log(error);
								} else if (link) {
									if (!mapping.chain) {
										mapping.chain = [];
									}
									mapping.chain.push(link);
								}
							};
						if (json.siblings && json.siblings.length) {
							for (i = 0; i < json.siblings.length; i += 1) {
								addMappings(json.siblings[i], addSiblingMappings);
							}
						}
						if (json.chain && json.chain.length) {
							for (i = 0; i < json.chain.length; i += 1) {
								findLinkMapping(json.chain[i], addLinkMappings);
							}
						}
						callback(null, mapping);
					}
				});
			}
		});
	},
	parSibParsib = function (mapping, callback) {
		var schema_dot_org = mapping.schema_dot_org,
			sumo = mapping.sumo,
			siblings,
			parents,
			sibling,
			parentSiblings,
			i,
			j;
		if (!(schema_dot_org && sumo)) {
			if (mapping.chain) {
				parents = [];
				for (i = 0; i < mapping.chain.length; i += 1) {
					schema_dot_org = schema_dot_org || mapping.chain[i].schema_dot_org;
					sumo = sumo || mapping.chain[i].sumo;
					if (mapping.chain[i].sumo || mapping.chain[i].schema_dot_org) {
						parents.push({"synset": mapping.chain[i].synset, "schema_dot_org": mapping.chain[i].schema_dot_org, "sumo": mapping.chain[i].sumo});
					}
				}
			}
		}
		if (!(schema_dot_org && sumo)) {
			if (mapping.siblings) {
				siblings = [];
				for (i = 0; i < mapping.siblings.length; i += 1) {
					sibling = {"synset": mapping.siblings[i].synset};
					if (mapping.siblings[i].schema_dot_org) {
						schema_dot_org = schema_dot_org || schema2parent[mapping.siblings[i].schema_dot_org];
						sibling.schema_dot_org = schema2parent[mapping.siblings[i].schema_dot_org];
					}
					if (mapping.siblings[i].sumo) {
						sumo = sumo || sumo2parent[mapping.siblings[i].sumo];
						sibling.sumo = sumo2parent[mapping.siblings[i].sumo];
					}
					siblings.push(sibling);
				}
			}
		}
		if (!(schema_dot_org && sumo)) {
			if (mapping.chain) {
				parentSiblings = [];
				siblings = [];
				for (i = 0; i < mapping.chain.length; i += 1) {
					if (mapping.chain[i].siblings) {
						siblings = [];
						for (j = 0; j < mapping.chain[i].siblings.length; j += 1) {
							sibling = {};
							if (mapping.chain[i].siblings[j].schema_dot_org) {
								schema_dot_org = schema_dot_org || schema2parent[mapping.chain[i].siblings[j].schema_dot_org];
								sibling.schema_dot_org = schema2parent[mapping.chain[i].siblings[j].schema_dot_org];
								sibling.synset = mapping.chain[i].synset;
							}
							if (mapping.chain[i].siblings[j].schema_dot_org) {
								sumo = sumo || mapping.chain[i].sumo;
								sibling.sumo = sumo2parent[mapping.chain[i].siblings[j].sumo];
								sibling.synset = mapping.chain[i].synset;
							}
							if (sibling.synset) {
								siblings.push(sibling);
							}
						}
						if (siblings.length) {
							parentSiblings.push(siblings);
						}
					}
				}
			}
		}
		callback(null, {"synset": mapping.synset, "schema_dot_org": schema_dot_org, "sumo": sumo, "parents": parents, "siblings": siblings, "parentSiblings": parentSiblings});
	},
	sibParRec = function (mapping, callback) {
		var schema_dot_org = mapping.schema_dot_org,
			sumo = mapping.sumo,
			counter = 0,
			i,
			sibling,
			siblings = [],
			parent,
			parents = [],
			link,
			parentSiblings = [];

		if (!(schema_dot_org && sumo)) {
			if (mapping.siblings) {
				siblings = [];
				for (i = 0; i < mapping.siblings.length; i += 1) {
					sibling = {"synset": mapping.siblings[i].synset};
					if (mapping.siblings[i].schema_dot_org) {
						schema_dot_org = schema_dot_org || schema2parent[mapping.siblings[i].schema_dot_org];
						sibling.schema_dot_org = schema2parent[mapping.siblings[i].schema_dot_org];
					}
					if (mapping.siblings[i].sumo) {
						sumo = sumo || sumo2parent[mapping.siblings[i].sumo];
						sibling.sumo = sumo2parent[mapping.siblings[i].sumo];
					}
					siblings.push(sibling);
				}
			}
		}
		if (mapping.chain) {
			for (counter = 0; counter < mapping.chain.length; counter += 1) {
				link = mapping.chain[counter];
				parent = {'synset': link.synset, 'schema_dot_org': link.schema_dot_org, 'sumo' : link.sumo, 'siblings': []};
				schema_dot_org = schema_dot_org || link.schema_dot_org;
				sumo = sumo || link.sumo;
				if (link.siblings) {
					for (i = 0; i < link.siblings.length; i += 1) {
						sibling = {"synset": link.siblings[i].synset};
						if (link.siblings[i].schema_dot_org) {
							schema_dot_org = schema_dot_org || schema2parent[link.siblings[i].schema_dot_org];
							sibling.schema_dot_org = schema2parent[link.siblings[i].schema_dot_org];
						}
						if (link.siblings[i].sumo) {
							sumo = sumo || sumo2parent[link.siblings[i].sumo];
							sibling.sumo = sumo2parent[link.siblings[i].sumo];
						}
						if (sibling.sumo || sibling.schema_dot_org) {
							parent.siblings.push(sibling);
						}
					}
				}
			}
			if (parent.sumo || parent.schema_dot_org || parent.siblings) {
				parents.push(parent);
			}
			counter += 1;
		}
		callback(null, {"synset": mapping.synset, "schema_dot_org": schema_dot_org, "sumo": sumo, "parents": parents, "siblings": siblings, "parentSiblings": parentSiblings});
	};
/**
	Finds the closest mappings from a synset to several ontologies using a few different algorithms
	@param {String} synset: a synset in the form synset-<word>-<lexical class>-<sense number>
	@param {Function} callback($error, $result):
	The callback is called when the best mappings have been found for each algorithm
	$error {Object}: The error encountered or null
	$result {Object}: An object of the form
	{
		synset {String}: The synset which was analysed
		[sumo {Array}: The best mappings from the different algorithms to the SUMO ontology]
		[schema_dot_org {Array}: The best mappings from the different algorithms to the schema.org ontology]
		// In addition the discovered mappings are returned for analysis purposes
	}
*/
exports.bestFit = function (synset, callback) {
	var fit = {'synset': synset, sumo: [], schema_dot_org: []};
	mapSynset(synset, function (error, mapping) {
		if (error) {
			callback(error);
		} else {
			sibParRec(mapping, function (recError, recResults) {
				parSibParsib(mapping, function (linError, linResults) {
					if (recError || linError) {
						console.log(recError);
						console.log(linError);
						callback(new Error("Error"));
					} else {
						fit.lin = linResults;
						fit.rec = recResults;
						if (linResults.sumo) {
							fit.sumo.push(linResults.sumo);
						}
						if (linResults.schema_dot_org) {
							fit.schema_dot_org.push(linResults.schema_dot_org);
						}
						if (recResults.sumo) {
							fit.sumo.push(recResults.sumo);
						}
						if (recResults.schema_dot_org) {
							fit.schema_dot_org.push(recResults.schema_dot_org);
						}
						callback(null, fit);
					}
				});
			});
		}
	});
};
/**
*	Creates a mapping tree of the synset.
*	A mapping tree contains all the synsets sibling senses (hyponymes of hypernymes),
*	all the ancestors of the synset, and all the siblings of the ancestors.
*	@param {String} synset: a synset in the form synset-<word>-<lexical class>-<sense number>
*	@param {Function} callback($error, $result):
*	The callback is called when the mapping tree is completed
*	$error {Object}: The error encountered or null
*	$result {Object}: an Object of the form
*	{
*		synset {String}: The synset which was mapped
*		chain {Array}: The ancestor chain, each element is an object in the form:
*		{
*			synset {String}: The ancestor synset
*			[sumo {String}: The mapping to the SUMO ontology]
*			[schema_dot_org {String}: The mapping to the schema.org ontology]
*			siblings {Array}: The sibling senses, each element is an object in the form:
*			{
*				synset {String}: The ancestor synset
*				[sumo {String}: The mapping to the SUMO ontology]
*				[schema_dot_org {String}: The mapping to the schema.org ontology]
*			}
*		}
*		siblings {Array}: The sibling senses, each element is an object in the form:
*		{
*			synset {String}: The ancestor synset
*			[sumo {String}: The mapping to the SUMO ontology]
*			[schema_dot_org {String}: The mapping to the schema.org ontology]
*		}
*		[sumo {String}: The mapping to the SUMO ontology]
*		[schema_dot_org {String}: The mapping to the schema.org ontology]
*	}
*/

exports.mappings = function (synset, callback) {
	mapSynset(synset, callback);
};
/**
*	Finds the hypernyme(s) of the synset
*	@param {String} synset: a synset in the form synset-<word>-<lexical class>-<sense number>
*	@param {Function} callback($error, $result):
*	The callback function is called when the hypernyme(s) of the word has been found
*	$error {Object}: The error encountered or null
*	$result {Object}: An object in the form:
*	{
*		parents {Array}: the hypernyme(s) of the parent
*	}
*/
exports.parent = function (synset, callback) {
	exec('perl scripts/parent.pl ' + synset, function (error, stout, stderr) {
		if (error) {
			callback({"error": error});
		} else if (stderr) {
			callback({"error": stderr});
		} else {
			callback(null, JSON.parse(stout));
		}
	});
};
<commit_msg>Stoped printing the entire possible mapping tree. Only the best fits for the different algorithms<commit_after>/*jslint node: true */
'use strict';
var url = require('url'),
	exec = require('child_process').exec,
	wn2schema = require('../../mappings/wn2schema').mapping,
	wn2sumo = require('../../mappings/wn2sumo').mapping,
	schema2parent = require('../../mappings/schema2parent').mapping,
	sumo2parent = require('../../mappings/sumo2parent').mapping,
	findParents = function (synset, callback) {
		exec('perl scripts/parents.pl ' + synset, function (error, stout, stderr) {
			if (error) {
				callback(new Error(error));
			} else if (stderr) {
				callback(new Error(stderr));
			} else {
				callback(null, stout);
			}
		});
	},
	addMappings = function (object, callback) {
		var	mapping = {"synset": object.synset};
		if (wn2schema[object.synset]) {
			mapping.schema_dot_org = wn2schema[object.synset];
		}
		if (wn2sumo[object.offset]) {
			mapping.sumo = wn2sumo[object.offset].sumo;
		}
		callback(null, mapping);
	},
	findLinkMapping = function (link, callback) {
		addMappings(link, function (error, mapping) {
			if (error) {
				callback(error);
			} else {
				var siblings = [],
					i,
					addSiblingMappings = function (error, mappings) {
						if (error) {
							console.log("Error received: " + error);
						} else {
							if (mappings) {
								siblings.push(mappings);
							}
						}
					};
				if (link.siblings) {
					for (i = 0; i < link.siblings.length; i += 1) {
						addMappings(link.siblings[i], addSiblingMappings);
					}
				}
				if (siblings.length > 0) {
					mapping.siblings = siblings;
				}
				callback(null, mapping);
			}
		});
	},
	mapSynset = function (synset, callback) {
		var	json,
			i;
		findParents(synset, function (error, data) {
			if (error) {
				callback(error);
			} else {
				json = JSON.parse(data);
				addMappings(json, function (error, mapping) {
					if (error) {
						callback(error);
					} else {
						var addSiblingMappings = function (error, siblings) {
								if (error) {
									console.log(error);
								} else if (siblings) {
									if (!mapping.siblings) {
										mapping.siblings = [];
									}
									mapping.siblings.push(siblings);
								}
							},
							addLinkMappings = function (error, link) {
								if (error) {
									console.log(error);
								} else if (link) {
									if (!mapping.chain) {
										mapping.chain = [];
									}
									mapping.chain.push(link);
								}
							};
						if (json.siblings && json.siblings.length) {
							for (i = 0; i < json.siblings.length; i += 1) {
								addMappings(json.siblings[i], addSiblingMappings);
							}
						}
						if (json.chain && json.chain.length) {
							for (i = 0; i < json.chain.length; i += 1) {
								findLinkMapping(json.chain[i], addLinkMappings);
							}
						}
						callback(null, mapping);
					}
				});
			}
		});
	},
	parSibParsib = function (mapping, callback) {
		var schema_dot_org = mapping.schema_dot_org,
			sumo = mapping.sumo,
			siblings,
			parents,
			sibling,
			parentSiblings,
			i,
			j;
		if (!(schema_dot_org && sumo)) {
			if (mapping.chain) {
				parents = [];
				for (i = 0; i < mapping.chain.length; i += 1) {
					schema_dot_org = schema_dot_org || mapping.chain[i].schema_dot_org;
					sumo = sumo || mapping.chain[i].sumo;
					if (mapping.chain[i].sumo || mapping.chain[i].schema_dot_org) {
						parents.push({"synset": mapping.chain[i].synset, "schema_dot_org": mapping.chain[i].schema_dot_org, "sumo": mapping.chain[i].sumo});
					}
				}
			}
		}
		if (!(schema_dot_org && sumo)) {
			if (mapping.siblings) {
				siblings = [];
				for (i = 0; i < mapping.siblings.length; i += 1) {
					sibling = {"synset": mapping.siblings[i].synset};
					if (mapping.siblings[i].schema_dot_org) {
						schema_dot_org = schema_dot_org || schema2parent[mapping.siblings[i].schema_dot_org];
						sibling.schema_dot_org = schema2parent[mapping.siblings[i].schema_dot_org];
					}
					if (mapping.siblings[i].sumo) {
						sumo = sumo || sumo2parent[mapping.siblings[i].sumo];
						sibling.sumo = sumo2parent[mapping.siblings[i].sumo];
					}
					siblings.push(sibling);
				}
			}
		}
		if (!(schema_dot_org && sumo)) {
			if (mapping.chain) {
				parentSiblings = [];
				siblings = [];
				for (i = 0; i < mapping.chain.length; i += 1) {
					if (mapping.chain[i].siblings) {
						siblings = [];
						for (j = 0; j < mapping.chain[i].siblings.length; j += 1) {
							sibling = {};
							if (mapping.chain[i].siblings[j].schema_dot_org) {
								schema_dot_org = schema_dot_org || schema2parent[mapping.chain[i].siblings[j].schema_dot_org];
								sibling.schema_dot_org = schema2parent[mapping.chain[i].siblings[j].schema_dot_org];
								sibling.synset = mapping.chain[i].synset;
							}
							if (mapping.chain[i].siblings[j].schema_dot_org) {
								sumo = sumo || mapping.chain[i].sumo;
								sibling.sumo = sumo2parent[mapping.chain[i].siblings[j].sumo];
								sibling.synset = mapping.chain[i].synset;
							}
							if (sibling.synset) {
								siblings.push(sibling);
							}
						}
						if (siblings.length) {
							parentSiblings.push(siblings);
						}
					}
				}
			}
		}
		callback(null, {"synset": mapping.synset, "schema_dot_org": schema_dot_org, "sumo": sumo, "parents": parents, "siblings": siblings, "parentSiblings": parentSiblings});
	},
	sibParRec = function (mapping, callback) {
		var schema_dot_org = mapping.schema_dot_org,
			sumo = mapping.sumo,
			counter = 0,
			i,
			sibling,
			siblings = [],
			parent,
			parents = [],
			link,
			parentSiblings = [];

		if (!(schema_dot_org && sumo)) {
			if (mapping.siblings) {
				siblings = [];
				for (i = 0; i < mapping.siblings.length; i += 1) {
					sibling = {"synset": mapping.siblings[i].synset};
					if (mapping.siblings[i].schema_dot_org) {
						schema_dot_org = schema_dot_org || schema2parent[mapping.siblings[i].schema_dot_org];
						sibling.schema_dot_org = schema2parent[mapping.siblings[i].schema_dot_org];
					}
					if (mapping.siblings[i].sumo) {
						sumo = sumo || sumo2parent[mapping.siblings[i].sumo];
						sibling.sumo = sumo2parent[mapping.siblings[i].sumo];
					}
					siblings.push(sibling);
				}
			}
		}
		if (mapping.chain) {
			for (counter = 0; counter < mapping.chain.length; counter += 1) {
				link = mapping.chain[counter];
				parent = {'synset': link.synset, 'schema_dot_org': link.schema_dot_org, 'sumo' : link.sumo, 'siblings': []};
				schema_dot_org = schema_dot_org || link.schema_dot_org;
				sumo = sumo || link.sumo;
				if (link.siblings) {
					for (i = 0; i < link.siblings.length; i += 1) {
						sibling = {"synset": link.siblings[i].synset};
						if (link.siblings[i].schema_dot_org) {
							schema_dot_org = schema_dot_org || schema2parent[link.siblings[i].schema_dot_org];
							sibling.schema_dot_org = schema2parent[link.siblings[i].schema_dot_org];
						}
						if (link.siblings[i].sumo) {
							sumo = sumo || sumo2parent[link.siblings[i].sumo];
							sibling.sumo = sumo2parent[link.siblings[i].sumo];
						}
						if (sibling.sumo || sibling.schema_dot_org) {
							parent.siblings.push(sibling);
						}
					}
				}
			}
			if (parent.sumo || parent.schema_dot_org || parent.siblings) {
				parents.push(parent);
			}
			counter += 1;
		}
		callback(null, {"synset": mapping.synset, "schema_dot_org": schema_dot_org, "sumo": sumo, "parents": parents, "siblings": siblings, "parentSiblings": parentSiblings});
	};
/**
	Finds the closest mappings from a synset to several ontologies using a few different algorithms
	@param {String} synset: a synset in the form synset-<word>-<lexical class>-<sense number>
	@param {Function} callback($error, $result):
	The callback is called when the best mappings have been found for each algorithm
	$error {Object}: The error encountered or null
	$result {Object}: An object of the form
	{
		synset {String}: The synset which was analysed
		[sumo {Array}: The best mappings from the different algorithms to the SUMO ontology]
		[schema_dot_org {Array}: The best mappings from the different algorithms to the schema.org ontology]
		// In addition the discovered mappings are returned for analysis purposes
	}
*/
exports.bestFit = function (synset, callback) {
	var fit = {'synset': synset, sumo: [], schema_dot_org: []};
	mapSynset(synset, function (error, mapping) {
		if (error) {
			callback(error);
		} else {
			sibParRec(mapping, function (recError, recResults) {
				parSibParsib(mapping, function (linError, linResults) {
					if (recError || linError) {
						console.log(recError);
						console.log(linError);
						callback(new Error("Error"));
					} else {
						if (linResults.sumo) {
							fit.sumo.push(linResults.sumo);
						}
						if (linResults.schema_dot_org) {
							fit.schema_dot_org.push(linResults.schema_dot_org);
						}
						if (recResults.sumo) {
							fit.sumo.push(recResults.sumo);
						}
						if (recResults.schema_dot_org) {
							fit.schema_dot_org.push(recResults.schema_dot_org);
						}
						fit.lin = {
							'schema_dot_org' : linResults.schema_dot_org,
							'sumo' : linResults.sumo
						};
						fit.rec = {
							'schema_dot_org' : recResults.schema_dot_org,
							'sumo' : recResults.sumo
						};
						callback(null, fit);
					}
				});
			});
		}
	});
};
/**
*	Creates a mapping tree of the synset.
*	A mapping tree contains all the synsets sibling senses (hyponymes of hypernymes),
*	all the ancestors of the synset, and all the siblings of the ancestors.
*	@param {String} synset: a synset in the form synset-<word>-<lexical class>-<sense number>
*	@param {Function} callback($error, $result):
*	The callback is called when the mapping tree is completed
*	$error {Object}: The error encountered or null
*	$result {Object}: an Object of the form
*	{
*		synset {String}: The synset which was mapped
*		chain {Array}: The ancestor chain, each element is an object in the form:
*		{
*			synset {String}: The ancestor synset
*			[sumo {String}: The mapping to the SUMO ontology]
*			[schema_dot_org {String}: The mapping to the schema.org ontology]
*			siblings {Array}: The sibling senses, each element is an object in the form:
*			{
*				synset {String}: The ancestor synset
*				[sumo {String}: The mapping to the SUMO ontology]
*				[schema_dot_org {String}: The mapping to the schema.org ontology]
*			}
*		}
*		siblings {Array}: The sibling senses, each element is an object in the form:
*		{
*			synset {String}: The ancestor synset
*			[sumo {String}: The mapping to the SUMO ontology]
*			[schema_dot_org {String}: The mapping to the schema.org ontology]
*		}
*		[sumo {String}: The mapping to the SUMO ontology]
*		[schema_dot_org {String}: The mapping to the schema.org ontology]
*	}
*/

exports.mappings = function (synset, callback) {
	mapSynset(synset, callback);
};
/**
*	Finds the hypernyme(s) of the synset
*	@param {String} synset: a synset in the form synset-<word>-<lexical class>-<sense number>
*	@param {Function} callback($error, $result):
*	The callback function is called when the hypernyme(s) of the word has been found
*	$error {Object}: The error encountered or null
*	$result {Object}: An object in the form:
*	{
*		parents {Array}: the hypernyme(s) of the parent
*	}
*/
exports.parent = function (synset, callback) {
	exec('perl scripts/parent.pl ' + synset, function (error, stout, stderr) {
		if (error) {
			callback({"error": error});
		} else if (stderr) {
			callback({"error": stderr});
		} else {
			callback(null, JSON.parse(stout));
		}
	});
};
<|endoftext|>