<commit_before>/*
 * DealPort
 * Copyright (c) 2014  DealPort B.V.
 *
 * This file is part of DealPort
 *
 * DealPort is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * DealPort is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with DealPort.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, the following supplemental terms apply, based on section 7 of
 * the GNU Affero General Public License (version 3):
 * a) Preservation of all legal notices and author attributions
 */

'use strict';
var P = require('bluebird');
var domv = require('domv');

var PrimusClientHandler = require('./PrimusClientHandler');
var BaseDocument = require('./view/BaseDocument');
var ClientContext = require('./ClientContext');
var FrontController = require('./controller/FrontController');
var router = require('./controller/router');
var resources = require('./resource/client');
var ga = require('./google-analytics');
var debugMode = false;

var document = global.document;
var location = global.location;
var context;
var front;
var statePromise = P.resolve();
var queuedState; // The user wants to switch to a new state during a state transfer
var queuedStateByUI = false;
var history = global.history;
var initialState = null;
var replacingStateWith = null;
var primusHandler;
var contextResources;

function isSupported()
{
        // todo add more checks
        return domv.isSupported(document);
}

function pushHistoryState(state, newState)
{
        var url = router.stringify(state);
        if (newState)
        {
                history.pushState({state: state}, context.document.title, url);
        }
        else
        {
                history.replaceState({state: state}, context.document.title, url);
        }
}

function gaPageView(state)
{
        var url = router.stringify(state);
        ga('send', 'pageview', {
                'page': url,
                'title': context.document.title
        });
}

function isStateTransferPending()
{
        return statePromise &&
               statePromise.isPending();
}

var stateTransitionDone;

function doQueuedState()
{
        var state = queuedState;
        var byUI = queuedStateByUI;

        if (!state)
        {
                return;
        }

        var previousState = front.getFullStateList();
        var newState = router.isNewHistoryState(previousState, state);

        console.info('Entering new state from queue', state, newState);

        queuedState = null;
        queuedStateByUI = false;

        context.document.stateTransitionPending = true;
        statePromise = front.state(state)
        .done(function()
        {
                if (byUI)
                {
                        pushHistoryState(replacingStateWith || state, newState);
                        gaPageView(replacingStateWith || state);
                        replacingStateWith = null;
                }

                stateTransitionDone();
        });
}

function stateTransitionDone()
{
        console.log('State transition is done');
        context.document.stateTransitionPending = false;
        setTimeout(doQueuedState, 0);
}

function handleHistoryState(historyState, initial)
{
        var state;
        if (!historyState || !historyState.state)
        {
                return false;
        }

        state = historyState.state;
        state = state.map(router.wakeup, router);

        console.info('Entering', initial ? 'initial' : 'new', 'state from history', state);

        if (isStateTransferPending())
        {
                console.warn('A previous state transfer is pending, this state will be queued', state);
                // (overwrite the previous queued state)
                queuedState = state;
                queuedStateByUI = false;
                return false;
        }

        context.document.stateTransitionPending = true;
        return front.state(state, initial);
}

function newStateByUser(state)
{
        var previousState = front.getFullStateList();
        var newState = router.isNewHistoryState(previousState, state);

        console.info('Entering new state by UI', state, newState);

        if (isStateTransferPending())
        {
                console.warn('A previous state transfer is pending, this state will be queued', state);
                // (overwrite the previous queued state)
                queuedState = state;
                queuedStateByUI = true;
                return false;
        }

        context.document.stateTransitionPending = true;

        return front.state(state)
        .catch(ga.logException)
        .finally(function()
        {
                pushHistoryState(replacingStateWith || state, newState);
                gaPageView(replacingStateWith || state);
                replacingStateWith = null;
        });
}

function setupNavigation()
{
        var states, path;
        front = new FrontController(context);

        global.tstContext = context; // todo testing
        global.tstFront = front;

        global.onpopstate = function(e)
        {
                // if e.state is null, we should go back to the initial (wrapped) state
                var p = handleHistoryState(e.state || initialState, false);
                if (p)
                {
                        statePromise = p.done(stateTransitionDone);
                }
        };

        context.document.on('domv-stateselect', function(e)
        {
                var p;

                e.preventDefault(); // prevent browser <a> click action
                p = newStateByUser(e.state);
                if (p)
                {
                        statePromise = p.done(stateTransitionDone);
                }
        });

        if (history.state)
        {
                initialState = history.state;
                statePromise = handleHistoryState(history.state, true);
        }
        else
        {
                path = location.pathname + location.search;
                states = context.router.parse(path);
                initialState = {state: states};
                console.info('Wrapping initial state from location', path, states);
                context.document.stateTransitionPending = true;
                statePromise = front.state(states, true);
        }

        gaPageView(initialState.state);

        statePromise = statePromise.catch(ga.logException)
        .done(stateTransitionDone);
}

var contextNewState = P.method(function(states)
{
        console.info('Controller triggered a state transition to', states);
        // newStateByUser handles isStateTransferPending
        var p = newStateByUser(states);
        if (p)
        {
                statePromise = p;
                return statePromise.then(stateTransitionDone).return(front);
        }

        return P.resolve(front);
});

var contextReplaceState = function(states)
{
        console.info('Controller triggered a state replacement to', states);
        if (isStateTransferPending())
        {
                replacingStateWith = states;
        }
        else
        {
                pushHistoryState(states, false); // false = replaceState
        }
};

function loaded()
{
        var baseDocument = new BaseDocument(document.documentElement, router);
        var mySessionID = baseDocument.getJSONData('mySessionID');
        var myCsrfToken = baseDocument.getJSONData('myCsrfToken');

        primusHandler = new PrimusClientHandler(mySessionID, debugMode);

        primusHandler.initialize().then(function(initializeData)
        {
                contextResources = resources(primusHandler.primus, primusHandler.share);

                context = new ClientContext(false);
                context.router = router;
                context.document = baseDocument;
                context.resource = contextResources;
                context.user = initializeData.user;
                context.sessionID = mySessionID;
                context.csrfToken = myCsrfToken;
                context.newState = contextNewState;
                context.replaceState = contextReplaceState;

                setupNavigation();

        }).catch(ga.logException);
}

function browserInitialize()
{
        debugMode = document.documentElement.hasAttribute('data-debug-mode');
        if (debugMode)
        {
                console.info('Debug mode enabled');
                P.longStackTraces();
                ga.debugMode = true;
                require('./resource/Resource').debugLogging = true;
        }

        if (document.documentElement.hasAttribute('data-ga'))
        {
                ga('create', document.documentElement.getAttribute('data-ga'));
        }

        ga('set', 'appName', document.documentElement.getAttribute('data-name'));
        ga('set', 'appVersion', document.documentElement.getAttribute('data-version'));

        if (!isSupported())
        {
                ga('send', 'exception', {
                        'exDescription': 'Browser failed client-side feature detection',
                        'exFatal': true
                });

                if (global.console)
                {
                        console.error('Browser did not pass capability check, aborting');
                }
                return;
        }

        if (typeof global.console === 'undefined')
        {
                global.console = {
                        log: function(){},
                        info: function(){},
                        warn: function(){},
                        error: function(){}
                };
        }

        if (document.readyState === 'loading')
        {
                document.addEventListener('DOMContentLoaded', loaded);
        }
        else
        {
                loaded();
        }
}

module.exports = browserInitialize;
<commit_msg>Expose a few globals if debug mode is turned on<commit_after>/*
 * DealPort
 * Copyright (c) 2014  DealPort B.V.
 *
 * This file is part of DealPort
 *
 * DealPort is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * DealPort is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with DealPort.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, the following supplemental terms apply, based on section 7 of
 * the GNU Affero General Public License (version 3):
 * a) Preservation of all legal notices and author attributions
 */

'use strict';
var P = require('bluebird');
var domv = require('domv');

var PrimusClientHandler = require('./PrimusClientHandler');
var BaseDocument = require('./view/BaseDocument');
var ClientContext = require('./ClientContext');
var FrontController = require('./controller/FrontController');
var router = require('./controller/router');
var resources = require('./resource/client');
var ga = require('./google-analytics');
var debugMode = false;

var document = global.document;
var location = global.location;
var context;
var front;
var statePromise = P.resolve();
var queuedState; // The user wants to switch to a new state during a state transfer
var queuedStateByUI = false;
var history = global.history;
var initialState = null;
var replacingStateWith = null;
var primusHandler;
var contextResources;

function isSupported()
{
        // todo add more checks
        return domv.isSupported(document);
}

function pushHistoryState(state, newState)
{
        var url = router.stringify(state);
        if (newState)
        {
                history.pushState({state: state}, context.document.title, url);
        }
        else
        {
                history.replaceState({state: state}, context.document.title, url);
        }
}

function gaPageView(state)
{
        var url = router.stringify(state);
        ga('send', 'pageview', {
                'page': url,
                'title': context.document.title
        });
}

function isStateTransferPending()
{
        return statePromise &&
               statePromise.isPending();
}

var stateTransitionDone;

function doQueuedState()
{
        var state = queuedState;
        var byUI = queuedStateByUI;

        if (!state)
        {
                return;
        }

        var previousState = front.getFullStateList();
        var newState = router.isNewHistoryState(previousState, state);

        console.info('Entering new state from queue', state, newState);

        queuedState = null;
        queuedStateByUI = false;

        context.document.stateTransitionPending = true;
        statePromise = front.state(state)
        .done(function()
        {
                if (byUI)
                {
                        pushHistoryState(replacingStateWith || state, newState);
                        gaPageView(replacingStateWith || state);
                        replacingStateWith = null;
                }

                stateTransitionDone();
        });
}

function stateTransitionDone()
{
        console.log('State transition is done');
        context.document.stateTransitionPending = false;
        setTimeout(doQueuedState, 0);
}

function handleHistoryState(historyState, initial)
{
        var state;
        if (!historyState || !historyState.state)
        {
                return false;
        }

        state = historyState.state;
        state = state.map(router.wakeup, router);

        console.info('Entering', initial ? 'initial' : 'new', 'state from history', state);

        if (isStateTransferPending())
        {
                console.warn('A previous state transfer is pending, this state will be queued', state);
                // (overwrite the previous queued state)
                queuedState = state;
                queuedStateByUI = false;
                return false;
        }

        context.document.stateTransitionPending = true;
        return front.state(state, initial);
}

function newStateByUser(state)
{
        var previousState = front.getFullStateList();
        var newState = router.isNewHistoryState(previousState, state);

        console.info('Entering new state by UI', state, newState);

        if (isStateTransferPending())
        {
                console.warn('A previous state transfer is pending, this state will be queued', state);
                // (overwrite the previous queued state)
                queuedState = state;
                queuedStateByUI = true;
                return false;
        }

        context.document.stateTransitionPending = true;

        return front.state(state)
        .catch(ga.logException)
        .finally(function()
        {
                pushHistoryState(replacingStateWith || state, newState);
                gaPageView(replacingStateWith || state);
                replacingStateWith = null;
        });
}

function setupNavigation()
{
        var states, path;
        front = new FrontController(context);

        if (debugMode)
        {
                // do not add it to window directly to make sure other scripts are not accidentally using globals
                global.dbg = {
                        Promise: P,
                        domv: domv,
                        router: router,
                        context: context,
                        front: front
                };
        }

        global.onpopstate = function(e)
        {
                // if e.state is null, we should go back to the initial (wrapped) state
                var p = handleHistoryState(e.state || initialState, false);
                if (p)
                {
                        statePromise = p.done(stateTransitionDone);
                }
        };

        context.document.on('domv-stateselect', function(e)
        {
                var p;

                e.preventDefault(); // prevent browser <a> click action
                p = newStateByUser(e.state);
                if (p)
                {
                        statePromise = p.done(stateTransitionDone);
                }
        });

        if (history.state)
        {
                initialState = history.state;
                statePromise = handleHistoryState(history.state, true);
        }
        else
        {
                path = location.pathname + location.search;
                states = context.router.parse(path);
                initialState = {state: states};
                console.info('Wrapping initial state from location', path, states);
                context.document.stateTransitionPending = true;
                statePromise = front.state(states, true);
        }

        gaPageView(initialState.state);

        statePromise = statePromise.catch(ga.logException)
        .done(stateTransitionDone);
}

var contextNewState = P.method(function(states)
{
        console.info('Controller triggered a state transition to', states);
        // newStateByUser handles isStateTransferPending
        var p = newStateByUser(states);
        if (p)
        {
                statePromise = p;
                return statePromise.then(stateTransitionDone).return(front);
        }

        return P.resolve(front);
});

var contextReplaceState = function(states)
{
        console.info('Controller triggered a state replacement to', states);
        if (isStateTransferPending())
        {
                replacingStateWith = states;
        }
        else
        {
                pushHistoryState(states, false); // false = replaceState
        }
};

function loaded()
{
        var baseDocument = new BaseDocument(document.documentElement, router);
        var mySessionID = baseDocument.getJSONData('mySessionID');
        var myCsrfToken = baseDocument.getJSONData('myCsrfToken');

        primusHandler = new PrimusClientHandler(mySessionID, debugMode);

        primusHandler.initialize().then(function(initializeData)
        {
                contextResources = resources(primusHandler.primus, primusHandler.share);

                context = new ClientContext(false);
                context.router = router;
                context.document = baseDocument;
                context.resource = contextResources;
                context.user = initializeData.user;
                context.sessionID = mySessionID;
                context.csrfToken = myCsrfToken;
                context.newState = contextNewState;
                context.replaceState = contextReplaceState;

                setupNavigation();

        }).catch(ga.logException);
}

function browserInitialize()
{
        debugMode = document.documentElement.hasAttribute('data-debug-mode');
        if (debugMode)
        {
                console.info('Debug mode enabled');
                P.longStackTraces();
                ga.debugMode = true;
                require('./resource/Resource').debugLogging = true;
        }

        if (document.documentElement.hasAttribute('data-ga'))
        {
                ga('create', document.documentElement.getAttribute('data-ga'));
        }

        ga('set', 'appName', document.documentElement.getAttribute('data-name'));
        ga('set', 'appVersion', document.documentElement.getAttribute('data-version'));

        if (!isSupported())
        {
                ga('send', 'exception', {
                        'exDescription': 'Browser failed client-side feature detection',
                        'exFatal': true
                });

                if (global.console)
                {
                        console.error('Browser did not pass capability check, aborting');
                }
                return;
        }

        if (typeof global.console === 'undefined')
        {
                global.console = {
                        log: function(){},
                        info: function(){},
                        warn: function(){},
                        error: function(){}
                };
        }

        if (document.readyState === 'loading')
        {
                document.addEventListener('DOMContentLoaded', loaded);
        }
        else
        {
                loaded();
        }
}

module.exports = browserInitialize;
<|endoftext|>


<commit_before>function setInterest(targeturl, state, csrftoken)
{
  $.post(targeturl,
  {
    csrfmiddlewaretoken:csrftoken,
    state:state
  });
}

function toggleInterest(o, targeturl, csrftoken)
{
  if (o.value == "1")
  {
    o.value="0";
  }
  else
  {
    o.value="1";
  }
  setInterest(targeturl, o.value, csrftoken);
}

$(document).ready(function(){
    var GRADEABLE_SUB_KINDS = ['numbers', 'equation'];

    var elements = $("#div_id_number_max_value,#div_id_number_min_value,#div_id_number_precision,#div_id_enable_auto_grading");
    var sub_kind_field = $('#id_sub_kind');
    if ($.inArray($(sub_kind_field).val(), GRADEABLE_SUB_KINDS) == -1 ) {
      elements.hide();

    }

    sub_kind_field.on('change', function(e){
        //  show and hide numbers related fields
        if ($.inArray($(this).val(), GRADEABLE_SUB_KINDS) != -1 ) {
          elements.show();
        } else {
          elements.hide();
          $("#id_enable_auto_grading").prop('checked', false);
        }
    })
});
<commit_msg>Fix for nnumbers to show\hide fields<commit_after>function setInterest(targeturl, state, csrftoken)
{
  $.post(targeturl,
  {
    csrfmiddlewaretoken:csrftoken,
    state:state
  });
}

function toggleInterest(o, targeturl, csrftoken)
{
  if (o.value == "1")
  {
    o.value="0";
  }
  else
  {
    o.value="1";
  }
  setInterest(targeturl, o.value, csrftoken);
}

$(document).ready(function(){
    var GRADEABLE_SUB_KINDS = ['numbers', 'equation'];

    var number_elements = $("#div_id_number_max_value,#div_id_number_min_value,#div_id_number_value");
    var grading_elements = $("#div_id_enable_auto_grading");
    var sub_kind_field = $('#id_sub_kind');

    if (sub_kind_field.val() !== 'numbers') {
      number_elements.hide();
    }

    if ($.inArray(sub_kind_field.val(), GRADEABLE_SUB_KINDS) == -1 ) {
        grading_elements.hide();
    }

    sub_kind_field.on('change', function(e){
        //  show and hide numbers related fields
        if ($.inArray($(this).val(), GRADEABLE_SUB_KINDS) != -1 ) {
          grading_elements.show();
        } else {
          grading_elements.hide();
          $("#id_enable_auto_grading").prop('checked', false);
        }
    })
});
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var exec = require('child_process').exec;
var handlebars = require('express-handlebars')
  .create({ defaultLayout: 'main' });

var app = express();

//setup handlebars templating engine
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

//setup body-parser to get data from forms
app.use(bodyParser.urlencoded({ extended: true }));

app.set('port', process.env.PORT || 3000);

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.render('home');
});

app.post('/download', function(req, res){
  var url = req.body.url;
  var filename = '';
  exec('youtube-dl --get-filename ' + url, function(error, stdout, stderr){
    if(error){
      console.error('ERROR1:',stderr);
    } else {
      filename = stdout.replace('\n', '');
      exec('youtube-dl ' + url, function(error, stdout, stderr){
        if(error){
          console.error('ERROR2:', stderr);
        } else {
          var filepath = __dirname + '/' + filename;
          var musicFilename = filename.split('.')[0] + '.mp3';
          var musicFilepath = __dirname + '/' + musicFilename;
          exec('ffmpeg -i ' + filename.replace(/ /g, '\\ ') + ' -vn ' + musicFilename.replace(/ /g, '\\ '), function(error, stdout, stderr){
            if(error){
              console.error('ERROR3:',stderr);
            } else {
              res.download(musicFilepath, musicFilename, function(error){
                if(error) {
                  console.error(err);
                }
                exec('rm -rf ' + filename.replace(/ /g, '\\ ') + ' ' + musicFilename.replace(/ /g, '\\ '), function(error, stdout, stderr){
                  if(error){
                    console.error(error);
                  }
                });
              });
            }
          });
        }
      });
    }
  });
});

app.use(function(req, res){
  res.status(404);
  res.render('404');
});

app.use(function(err, req, res, next){
  res.status(500);
  res.render('500');
});

app.listen(app.get('port'), function(){
  console.log('Express started on http://localhost:' +
              app.get('port') +
              '\npress Ctrl-C to terminate');
});
<commit_msg>Changes use of ffmpeg to use avconv instead<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var exec = require('child_process').exec;
var handlebars = require('express-handlebars')
  .create({ defaultLayout: 'main' });

var app = express();

//setup handlebars templating engine
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

//setup body-parser to get data from forms
app.use(bodyParser.urlencoded({ extended: true }));

app.set('port', process.env.PORT || 3000);

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.render('home');
});

app.post('/download', function(req, res){
  var url = req.body.url;
  var filename = '';
  exec('youtube-dl --get-filename ' + url, function(error, stdout, stderr){
    if(error){
      console.error('ERROR1:',stderr);
    } else {
      filename = stdout.replace('\n', '');
      exec('youtube-dl ' + url, function(error, stdout, stderr){
        if(error){
          console.error('ERROR2:', stderr);
        } else {
          var filepath = __dirname + '/' + filename;
          var musicFilename = filename.split('.')[0] + '.mp3';
          var musicFilepath = __dirname + '/' + musicFilename;
          exec('avconv -i ' + filename.replace(/ /g, '\\ ').replace(/\'/g, '\\\'') + ' -vn -c:a copy ' + musicFilename.replace(/ /g, '\\ ').replace(/\'/g,'\\\''), function(error, stdout, stderr){
            if(error){
              console.error('ERROR3:',stderr);
            } else {
              res.download(musicFilepath, musicFilename, function(error){
                if(error) {
                  console.error(err);
                }
                exec('rm -rf ' + filename.replace(/ /g, '\\ ') + ' ' + musicFilename.replace(/ /g, '\\ '), function(error, stdout, stderr){
                  if(error){
                    console.error(error);
                  }
                });
              });
            }
          });
        }
      });
    }
  });
});

app.use(function(req, res){
  res.status(404);
  res.render('404');
});

app.use(function(err, req, res, next){
  res.status(500);
  res.render('500');
});

app.listen(app.get('port'), function(){
  console.log('Express started on http://localhost:' +
              app.get('port') +
              '\npress Ctrl-C to terminate');
});
<|endoftext|>


<commit_before>var textdatabase = [];
var hashtable = {};
var aggression = 5;

var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('mthesaur.txt'), true);
xhr.onreadystatechange = function()
{
	if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200)
	{
		var temptextdatabase = xhr.responseText.split("\n");
        //console.log(temptextdatabase);
        for(var i = 0; i < temptextdatabase.length; i++) {
        	var line = temptextdatabase[i].split(",");
        	textdatabase.push(line);
        	for(var j = 0; j < line.length; j++) {
        		if(line[j].length > aggression) {
        			for(var k = 0; k < line.length; k++) {
        				if(line[k].length <= aggression) {
        					hashtable[line[j]] = line[k];
        					break;
        				}
        			}
        		}
        	}
        }
        walk(document.body);
    }
};
xhr.send();
document.body.addEventListener('DOMNodeInserted', function(event) {
	walk(event.target);});

function trim1 (str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function getSynonyms(word) {
	if(typeof word === 'undefined')
		return [word];
	word = word.toLowerCase();
	//TODO: FIX THIS BECAUSE IT ISN'T WORKING
	/*for(var i = 0; i < textdatabase.length; i++ ) {
		var line = textdatabase[i];
		//console.log(line);
		for(var j = 0; j < line.length; j++) {
			var test = line[j];
			if(trim1(test)===trim1(word)) {
				console.log("found: "+test+", "+word.length);
				return line;
			}
		}
	}*/
	if(hashtable.hasOwnProperty(word))
		return [hashtable[word]];
	return [word];
}
//DELETE THIS ASAP******************************************

function walk(node) {
	//console.log(textdatabase[0]);
	var ent = document.createTreeWalker(
		node,
		NodeFilter.SHOW_TEXT,
		null,
		false
		);
	while(ent.nextNode()) {
		var current = ent.currentNode;
		current.textContent = process(current.textContent);
	}
}

function process(text){

	var processedText = text;
	var words = text.split(" ");

	//console.log(words);
	for(var i = 0; i < words.length; i++) {
		var word = words[i];
		if(typeof word != 'undefined' && word.length > aggression) {
			//console.log(word.length+": "+word);
			var synonyms = getSynonyms(word);
			//console.log(word+": ");
			//console.log(synonyms);
			if(typeof synonyms != 'undefined') {
				//console.log("replacing "+word+" with "+ synonyms[0]);
				processedText = processedText.replace(word, synonyms[0]);
			}
		}
	}
	return processedText;
}<commit_msg>Cleaned up a lot<commit_after>var textdatabase = [];
var hashtable = {};
var aggression = 5;

var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('mthesaur.txt'), true);
xhr.onreadystatechange = function()
{
	if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200)
	{
		var temptextdatabase = xhr.responseText.split("\n");

        for(var i = 0; i < temptextdatabase.length; i++) {
        	var line = temptextdatabase[i].split(",");

        	textdatabase.push(line);

        	for(var j = 0; j < line.length; j++) {
        		if(line[j].length > aggression) {
        			for(var k = 0; k < line.length; k++) {
        				if(line[k].length <= aggression) {
        					hashtable[line[j]] = line[k];
        					break;
        				}
        			}
        		}
        	}
        }
        walk(document.body);
    }
};
xhr.send();

document.body.addEventListener('DOMNodeInserted', function(event) {
	walk(event.target);});

function trim (str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function getSynonyms(word) {
	if(typeof word === 'undefined')
		return [word];

	word = word.toLowerCase();

	if(hashtable.hasOwnProperty(word))
		return [hashtable[word]];

	return [word];
}

function walk(node) {
	var ent = document.createTreeWalker(
		node, NodeFilter.SHOW_TEXT, null, false);

	while(ent.nextNode()) {
		var current = ent.currentNode;
		current.textContent = process(current.textContent);
	}
}

function process(text){

	var processedText = text;
	var words = text.split(" ");

	for(var i = 0; i < words.length; i++) {
		var word = words[i];

		if(typeof word != 'undefined' && word.length > aggression) {

			var synonyms = getSynonyms(word);

			if(typeof synonyms != 'undefined') {
				for(var j = 0; j < synonyms.length; j++){
					if(synonyms[j].length <= aggression) {
						processedText = processedText.replace(word, synonyms[j]);
						break;
					}
				}
			}
		}
	}
	return processedText;
}<|endoftext|>


<commit_before>//= require jquery.ui.dialog.js
$(document).ready(function() {
  click_on_overlay = function(pop_up_div) {
    $('div.ui-widget-overlay').on('click', function(){
      $('div.ui-widget-overlay').remove();
      pop_up_div.dialog("close");
    });
  }

  ModalPopUp = function(pop_up_div) {
    var self = {
      init: function() {
        pop_up_div.dialog({
          autoOpen: false,
          modal: true,
          width:700,
          closeText: "X",
          dialogClass:"quick_view_container",
          close: function(event, ui) {
            pop_up_div.remove();
            $('#easy_zoom').remove();
          }
        });
      },
      show: function() {
        pop_up_div.dialog("open");
        click_on_overlay(pop_up_div);
      }
    }
    self.init();
    return self;
  }

  $('.reveal_xml').click(function() {
    ct_id = $(this).attr('data-ct-id');
    var quick_view = new ModalPopUp($("

").attr('id', 'quick_view_popup').html($("#xml_response_" + ct_id).clone()));
    $('#quick_view_popup .xml_response').removeClass('hidden');
    quick_view.show();
  })
});
<commit_msg>remove close text from dialog pop up to avoid double x<commit_after>//= require jquery.ui.dialog.js
$(document).ready(function() {
  click_on_overlay = function(pop_up_div) {
    $('div.ui-widget-overlay').on('click', function(){
      $('div.ui-widget-overlay').remove();
      pop_up_div.dialog("close");
    });
  }

  ModalPopUp = function(pop_up_div) {
    var self = {
      init: function() {
        pop_up_div.dialog({
          autoOpen: false,
          modal: true,
          width:700,
          closeText: "",
          dialogClass:"quick_view_container",
          close: function(event, ui) {
            pop_up_div.remove();
            $('#easy_zoom').remove();
          }
        });
      },
      show: function() {
        pop_up_div.dialog("open");
        click_on_overlay(pop_up_div);
      }
    }
    self.init();
    return self;
  }

  $('.reveal_xml').click(function() {
    ct_id = $(this).attr('data-ct-id');
    var quick_view = new ModalPopUp($("

").attr('id', 'quick_view_popup').html($("#xml_response_" + ct_id).clone()));
    $('#quick_view_popup .xml_response').removeClass('hidden');
    quick_view.show();
  })
});
<|endoftext|>


<commit_before>var log = require('db-migrate/lib/log');
var deasync = require('deasync');

var migrationTemplate = [
  "var dbm = require('db-migrate');\nvar type = dbm.dataType;}\n\nexports.up = function(db, callback) {\n",
  "};\n\nexports.down = function(db, callback) {\n",
  "};\n"
];

Builder = function( driver, migrationsDir ) {
  this.counter = 0;
  this.diff = Array();
  this.avTables = Array();
  this.driver = driver;
  this.max = 6;//7-8
  this.migrationsDir = migrationsDir;

  require('./util');
};

Builder.prototype = {

   //ToDo: enums for types
   //Create DataMap for Arrays
   build: function( config, callback )
   {
      var self = this;

      var caps = this.driver.capabilities;
      log.verbose( 'Driver provides:', caps );

      if( caps.indexOf('tables') !== -1 || caps.indexOf('views') !== -1 )
         this.driver.getTables( config, function( db, dbdiff )
         {
            if( db.length === 0 &&
              ( dbdiff.length === 0 && config.diffDump ) )
            {
               return ++self.counter;
            }

            self.diff['tables'] = self.diffArr( db[0], dbdiff[0] );
            self.diff['views'] = self.diffArr( db[1], dbdiff[1] );

            var tableList = Array();
            tableList['tables'] = [ db[0], dbdiff[0] ];
            tableList['views'] = [ db[1], dbdiff[1] ];

            self.avTables = self.subArr( db[0], self.diff['tables'][1] );

            self.driver.getColumns( config, tableList, self, self.columns );
            if( caps.indexOf('indizies') !== -1 )
              self.driver.getIndizies( config, tableList, self, self.indizies );
            else
              --this.max;

            if( caps.indexOf('engines') !== -1 )
              self.driver.getEngine( config, self, self.engines );
            else
              --this.max;

            if( caps.indexOf('foreign_keys') !== -1 )
              self.driver.getFK( config, tableList, self, self.foreign_keys );
            else
              --this.max;

            ++self.counter;
         });
       else
        this.max -= 3;

      if( caps.indexOf('functions') !== -1 || caps.indexOf('procedures') !== -1 )
         this.driver.getFn( config, function( db, dbdiff )
         {
            if( db.length === 0 &&
              ( dbdiff.length === 0 && config.diffDump ) )
            {
               return ++self.counter;
            }

            //ToDo: We don't only want to check if it exist or not,
            //but to check if it was modified. For this purpose
            //we need additional information so I'm going to
            //modify the way how db-migrate behaves.
            //
            //For now this implementation wont take any action, later.
            self.diff['fn'] = self.diffArr( db, dbdiff );
            ++self.counter;
         });
       else
        --this.max;

       while( self.counter < this.max ) deasync.sleep(100);

       log.verbose('Collected Data Overview:', self.diff);
   },

   columns: function( self, db )
   {
      var self = self || this;

      if( !self.diff['columns'] )
         self.diff['columns'] = Array();

      for( var i = 0; i < self.avTables.length; ++i )
         self.diff['columns'][self.avTables[i]] = self.diffArr( db[0][self.avTables[i]] , db[1][self.avTables[i]] );

       //ToDo: Implement differences within columns
       //Yet it just checks if the column is in both tables

      ++self.counter;
   },

   indizies: function( self, db )
   {
      var self = self || this;

      if( !self.diff['tablespecific'] )
         self.diff['tablespecific'] = Array();

      for( var i = 0; i < self.avTables.length; ++i )
      {
        var keys = Array(), lost_keys = Array(),
        chg_keys = Array(), available_keys = Array();

        if( db[0][self.avTables[i]] || db[1][self.avTables[i]] )
        {
          if( !self.diff['tablespecific'][self.avTables[i]] )
            self.diff['tablespecific'][self.avTables[i]] = Array();

          //diff on key name
          keys = self.diffArr( db[0][self.avTables[i]], db[1][self.avTables[i]] );

          //collecting data
          available_keys[0] = self.matchArr( db[0][self.avTables[i]], keys[0] );
          available_keys[1] = self.matchArr( db[1][self.avTables[i]], keys[1] );

          for( var o = 0; o < 2; ++o )
          {
            available_keys[o] = self.buildArr( available_keys[o] );

            if( available_keys[o] )
              Object.keys(available_keys[o]).forEach(function(key) {
                available_keys[o][key] = self.moveItem( available_keys[o][key], 2, 0 );
              });
          }

          new_keys = self.buildArr( keys[0] );

          if( new_keys )
            Object.keys(new_keys).forEach(function(key) {
              new_keys[key] = self.moveItem( new_keys[key], 2, 0 );
            });

          lost_keys = self.buildArr( keys[1] );

          if( lost_keys )
            Object.keys(lost_keys).forEach(function(key) {
              lost_keys[key] = self.moveItem( lost_keys[key], 2, 0 );
            });
          //end collecting

          //diff on key index name
          if( available_keys[0] )
            Object.keys(available_keys[0]).forEach(function(key) {
              chg_keys[key] = self.diffArr( available_keys[0][key], available_keys[1][key] );
              chg_keys[key].push( cavailable_keys[0][key].identicalTo( available_keys[1][key] ) );
              //ToDo: Implement full row matching
            });

          self.diff['tablespecific'][self.avTables[i]]['indizies'] = [ new_keys, lost_keys, chg_keys ];
        }
      }

      ++self.counter;
   },

   foreign_keys: function( self, db )
   {
      var self = self || this;

      if( !self.diff['tablespecific'] )
         self.diff['tablespecific'] = Array();

      for( var i = 0; i < self.avTables.length; ++i )
      {
        var keys = Array(), new_keys = Array(), chg_keys = Array();
        lost_keys = Array(), available_keys = Array();

        if( db[0][self.avTables[i]] || db[1][self.avTables[i]] )
        {
          if( !self.diff['tablespecific'][self.avTables[i]] )
            self.diff['tablespecific'][self.avTables[i]] = Array();

          //diff on key name
          keys = self.diffArr( db[0][self.avTables[i]], db[1][self.avTables[i]] );

          //collecting data
          available_keys[0] = self.matchArr( db[0][self.avTables[i]], keys[0] );
          available_keys[1] = self.matchArr( db[1][self.avTables[i]], keys[1] );

          for( var o = 0; o < 2; ++o )
          {
            available_keys[o] = self.buildArr( available_keys[o] );

            if( available_keys[o] )
              Object.keys(available_keys[o]).forEach(function(key) {
                available_keys[o][key] = self.moveItem( available_keys[o][key], 2, 0 );
              });
          }

          new_keys = self.buildArr( keys[0] );
          lost_keys = self.buildArr( keys[1] );
          //end collecting

          //diff on foreign key column name
          if( available_keys[0] )
            Object.keys(available_keys[0]).forEach(function(key) {
              chg_keys[key] = self.diffArr( available_keys[0][key], available_keys[1][key] );

              //ToDo: Implement full row matching
            });

          console.log( available_keys );

          self.diff['tablespecific'][self.avTables[i]]['foreign_keys'] = [ new_keys, lost_keys, chg_keys ];
        }
      }

      ++self.counter;
   },

   engines: function( self, db )
   {
      var self = self || this;

      if( !self.diff['tablespecific'] )
         self.diff['tablespecific'] = Array();

       db[0] = self.buildArr( db[0] );
       db[1] = self.buildArr( db[1] );

      for( var i = 0; i < self.avTables.length; ++i )
      {
        var engine = '', chg_engine = '';

        if( db[0][self.avTables[i]] || db[1][self.avTables[i]] )
        {
          if( !self.diff['tablespecific'][self.avTables[i]] )
            self.diff['tablespecific'][self.avTables[i]] = Array();

          if( db[1][self.avTables[i]] )
          {
            if( db[0][self.avTables[i]][0][0] !== db[1][self.avTables[i]][0][0] )
              chg_engine = db[0][self.avTables[i]][0][0];
            else
              engine = db[0][self.avTables[i]][0][0];
          }
          else
            engine = db[0][self.avTables[i]][0][0];

          self.diff['tablespecific'][self.avTables[i]]['engine'] = [ engine, chg_engine ];
        }
      }

      ++self.counter;
   },

   /**
     * Subtracts matching Items from array.
     *
     * @return array
     */
   subArr: function( arr, sub )
   {
      var substracted = Array();

      if( !arr )
        return arr;

      var tmp = Array();
      if( typeof( arr[0] ) === 'object' )
      {
         for( var i = 0; i < arr.length; ++i )
         {
           if( arr.length > i )
             tmp.push( arr[i][0] );
         }
      }
      else
      {
        tmp = arr;
      }

      for( var i = 0; i < arr.length; ++i )
      {
          if( sub.indexOf( tmp[i] ) === -1 )
            substracted.push( arr[i] );
      }

      return substracted;
   },

   /**
     * Returns an array of all matching elements from both arrays.
     *
     * @return array
     */
   matchArr: function( arr, match )
   {
      var matched = Array();

      if( !arr )
        return arr;

      var tmp = Array();
      if( typeof( arr[0] ) === 'object' )
      {
         for( var i = 0; i < arr.length; ++i )
         {
           if( arr.length > i )
             tmp.push( arr[i][0] );
         }
      }
      else
      {
        tmp = arr;
      }

      for( var i = 0; i < arr.length; ++i )
      {
          if( match.indexOf( tmp[i] ) !== -1 )
            matched.push( arr[i] );
      }

      return matched;
   },

   /**
     * Builds an array out of all matching elements of provided index.
     * Index defaults to zero if not specified.
     *
     * @return array
     */
   buildArr: function( arr, index )
   {
      var index = index || 0;
      var builded = Array();

      if( !arr )
        return arr;

      for( var i = 0; i < arr.length; ++i )
      {
        var copy = arr[i].slice(index+1, arr[i].length);
        var in_index = arr[i][index];
        if( !builded[in_index] )
          builded[in_index] = Array();

        builded[in_index].push( copy );
      }

      return builded;
   },

   /**
     * Moves an index within an array to another position, for all array elements.
     *
     * @return array
     */
   moveItem: function( arr, index, position, overwrite )
   {
      var overwrite = overwrite || false;
      var inc = ( overwrite ) ? 1 : 2;
      var moved = Array();

      for( var i = 0; i < arr.length; ++i  )
      {
        moved[i] = Array();

        for( var o = 0; o < arr[i].length; ++o )
        {
          if( i < position )
            moved[i][o] = arr[i][o];
          else if( o === position )
          {
            moved[i][o] = arr[i][index];
            if( !overwrite )
              moved[i][o+1] = arr[i][o];
          }
          else if( o < index )
            moved[i][o+inc] = arr[i][o];
          else if( o === index )
            moved[i][o] = arr[i][o-1];
          else
            moved[i][o] = arr[i][o];
        }
      }

      return moved;
   },

   /**
     * Makes a diff betwee arr and diff and sorts it in deleted
     * and available.
     *
     * Array [0] = added, [1] = deleted
     *
     * @return array
     */
   diffArr: function( arr, diff )
   {
      var differences = Array();
      differences[0] = Array();
      differences[1] = Array();

      if( !diff )
      {
         differences[0] = arr;
      }
      else if( !arr )
      {
        differences[1] = diff;
      }
      else if( arr )
      {
         var tmp = Array();
         var len = ( diff.length > arr.length ) ? diff.length : arr.length;
         if( typeof( arr[0] ) === 'object' )
         {
            tmp[0] = Array();
            tmp[1] = Array();
            for( var i = 0; i < len; ++i )
            {
              if( arr.length > i )
                tmp[0].push( arr[i][0] );

              if( diff.length > i )
                tmp[1].push( diff[i][0] );
            }
         }
         else
         {
           tmp[0] = arr;
           tmp[1] = diff;
         }

          for( var i = 0; i < len; ++i )
          {
             if( tmp[1].length > i && tmp[0].indexOf( tmp[1][i] ) === -1 )
                differences[1].push( diff[i] );

             if( tmp[0].length > i && tmp[1].indexOf( tmp[0][i] ) === -1 )
                differences[0].push( arr[i] );
          }
      }

      return differences;
   },

   diffObjKeys: function( obj, diff )
   {
      var differences = Array();
      differences[0] = Array();
      differences[1] = Array();

      if( !diff )
      {
         differences[0] = obj;
      }
      else if( !obj )
      {
        differences[1] = diff;
      }
      else if( obj )
      {
        //ToDo
      }

      return differences;
   },

   close: function()
   {
      if( this.driver )
         this.driver.close();
   }

};
module.exports = Builder;
<commit_msg>some handsome bugs<commit_after>var log = require('db-migrate/lib/log');
var deasync = require('deasync');

var migrationTemplate = [
  "var dbm = require('db-migrate');\nvar type = dbm.dataType;}\n\nexports.up = function(db, callback) {\n",
  "};\n\nexports.down = function(db, callback) {\n",
  "};\n"
];

Builder = function( driver, migrationsDir ) {
  this.counter = 0;
  this.diff = Array();
  this.avTables = Array();
  this.driver = driver;
  this.max = 6;//7-8
  this.migrationsDir = migrationsDir;

  require('./util');
};

Builder.prototype = {

   //ToDo: enums for types
   //Create DataMap for Arrays
   build: function( config, callback )
   {
      var self = this;

      var caps = this.driver.capabilities;
      log.verbose( 'Driver provides:', caps );

      if( caps.indexOf('tables') !== -1 || caps.indexOf('views') !== -1 )
         this.driver.getTables( config, function( db, dbdiff )
         {
            if( db.length === 0 &&
              ( dbdiff.length === 0 && config.diffDump ) )
            {
               return ++self.counter;
            }

            self.diff['tables'] = self.diffArr( db[0], dbdiff[0] );
            self.diff['views'] = self.diffArr( db[1], dbdiff[1] );

            var tableList = Array();
            tableList['tables'] = [ db[0], dbdiff[0] ];
            tableList['views'] = [ db[1], dbdiff[1] ];

            self.avTables = self.subArr( db[0], self.diff['tables'][1] );

            self.driver.getColumns( config, tableList, self, self.columns );
            if( caps.indexOf('indizies') !== -1 )
              self.driver.getIndizies( config, tableList, self, self.indizies );
            else
              --this.max;

            if( caps.indexOf('engines') !== -1 )
              self.driver.getEngine( config, self, self.engines );
            else
              --this.max;

            if( caps.indexOf('foreign_keys') !== -1 )
              self.driver.getFK( config, tableList, self, self.foreign_keys );
            else
              --this.max;

            ++self.counter;
         });
       else
        this.max -= 3;

      if( caps.indexOf('functions') !== -1 || caps.indexOf('procedures') !== -1 )
         this.driver.getFn( config, function( db, dbdiff )
         {
            if( db.length === 0 &&
              ( dbdiff.length === 0 && config.diffDump ) )
            {
               return ++self.counter;
            }

            //ToDo: We don't only want to check if it exist or not,
            //but to check if it was modified. For this purpose
            //we need additional information so I'm going to
            //modify the way how db-migrate behaves.
            //
            //For now this implementation wont take any action, later.
            self.diff['fn'] = self.diffArr( db, dbdiff );
            ++self.counter;
         });
       else
        --this.max;

       while( self.counter < this.max ) deasync.sleep(100);

       log.verbose('Collected Data Overview:', self.diff);
   },

   columns: function( self, db )
   {
      var self = self || this;

      if( !self.diff['columns'] )
         self.diff['columns'] = Array();

      for( var i = 0; i < self.avTables.length; ++i )
         self.diff['columns'][self.avTables[i]] = self.diffArr( db[0][self.avTables[i]] , db[1][self.avTables[i]] );

       //ToDo: Implement differences within columns
       //Yet it just checks if the column is in both tables

      ++self.counter;
   },

   indizies: function( self, db )
   {
      var self = self || this;

      if( !self.diff['tablespecific'] )
         self.diff['tablespecific'] = Array();

      for( var i = 0; i < self.avTables.length; ++i )
      {
        var keys = Array(), lost_keys = Array(),
        chg_keys = Array(), available_keys = Array();

        if( db[0][self.avTables[i]] || db[1][self.avTables[i]] )
        {
          if( !self.diff['tablespecific'][self.avTables[i]] )
            self.diff['tablespecific'][self.avTables[i]] = Array();

          //diff on key name
          keys = self.diffArr( db[0][self.avTables[i]], db[1][self.avTables[i]] );

          //collecting data
          available_keys[0] = self.matchArr( db[0][self.avTables[i]], keys[0] );
          available_keys[1] = self.matchArr( db[1][self.avTables[i]], keys[1] );

          for( var o = 0; o < 2; ++o )
          {
            available_keys[o] = self.buildArr( available_keys[o] );

            if( available_keys[o] )
              Object.keys(available_keys[o]).forEach(function(key) {
                available_keys[o][key] = self.moveItem( available_keys[o][key], 2, 0 );
              });
          }

          new_keys = self.buildArr( keys[0] );

          if( new_keys )
            Object.keys(new_keys).forEach(function(key) {
              new_keys[key] = self.moveItem( new_keys[key], 2, 0 );
            });

          lost_keys = self.buildArr( keys[1] );

          if( lost_keys )
            Object.keys(lost_keys).forEach(function(key) {
              lost_keys[key] = self.moveItem( lost_keys[key], 2, 0 );
            });
          //end collecting

          //diff on key index name
          if( available_keys[0] )
            Object.keys(available_keys[0]).forEach(function(key) {
              chg_keys[key] = self.diffArr( available_keys[0][key], available_keys[1][key] );
              chg_keys[key].push( cavailable_keys[0][key].identicalTo( available_keys[1][key] ) );
              //ToDo: Implement full row matching
            });

          self.diff['tablespecific'][self.avTables[i]]['indizies'] = [ new_keys, lost_keys, chg_keys ];
        }
      }

      ++self.counter;
   },

   foreign_keys: function( self, db )
   {
      var self = self || this;

      if( !self.diff['tablespecific'] )
         self.diff['tablespecific'] = Array();

      for( var i = 0; i < self.avTables.length; ++i )
      {
        var keys = Array(), new_keys = Array(), chg_keys = Array();
        lost_keys = Array(), available_keys = Array();

        if( db[0][self.avTables[i]] || db[1][self.avTables[i]] )
        {
          if( !self.diff['tablespecific'][self.avTables[i]] )
            self.diff['tablespecific'][self.avTables[i]] = Array();

          //diff on key name
          keys = self.diffArr( db[0][self.avTables[i]], db[1][self.avTables[i]] );

          //collecting data
          available_keys[0] = self.matchArr( db[0][self.avTables[i]], keys[0] );
          available_keys[1] = self.matchArr( db[1][self.avTables[i]], keys[1] );

          for( var o = 0; o < 2; ++o )
            available_keys[o] = self.buildArr( available_keys[o] );

          new_keys = self.buildArr( keys[0] );
          lost_keys = self.buildArr( keys[1] );
          //end collecting

          //diff on foreign key column name
          if( available_keys[0] )
            Object.keys(available_keys[0]).forEach(function(key) {
              chg_keys[key] = self.diffArr( available_keys[0][key], available_keys[1][key] );

              //ToDo: Implement full row matching
            });

          self.diff['tablespecific'][self.avTables[i]]['foreign_keys'] = [ new_keys, lost_keys, chg_keys ];
        }
      }

      ++self.counter;
   },

   engines: function( self, db )
   {
      var self = self || this;

      if( !self.diff['tablespecific'] )
         self.diff['tablespecific'] = Array();

       db[0] = self.buildArr( db[0] );
       db[1] = self.buildArr( db[1] );

      for( var i = 0; i < self.avTables.length; ++i )
      {
        var engine = '', chg_engine = '';

        if( db[0][self.avTables[i]] || db[1][self.avTables[i]] )
        {
          if( !self.diff['tablespecific'][self.avTables[i]] )
            self.diff['tablespecific'][self.avTables[i]] = Array();

          if( db[1][self.avTables[i]] )
          {
            if( db[0][self.avTables[i]][0][0] !== db[1][self.avTables[i]][0][0] )
              chg_engine = db[0][self.avTables[i]][0][0];
            else
              engine = db[0][self.avTables[i]][0][0];
          }
          else
            engine = db[0][self.avTables[i]][0][0];

          self.diff['tablespecific'][self.avTables[i]]['engine'] = [ engine, chg_engine ];
        }
      }

      ++self.counter;
   },

   /**
     * Subtracts matching Items from array.
     *
     * @return array
     */
   subArr: function( arr, sub )
   {
      var substracted = Array();

      if( !arr )
        return arr;

      var tmp = Array();
      if( typeof( arr[0] ) === 'object' )
      {
         tmp[0] = Array();
         tmp[1] = Array();
         for( var i = 0; i < arr.length; ++i )
         {
           if( arr.length > i )
              tmp[0].push( arr[i][0] );

           if( sub.length > i )
              tmp[1].push( sub[i][0] );
         }
      }
      else
      {
        tmp[0] = arr;
        tmp[1] = sub;
      }

      for( var i = 0; i < arr.length; ++i )
      {
          if( tmp[1].indexOf( tmp[0][i] ) === -1 )
            substracted.push( arr[i] );
      }

      return substracted;
   },

   /**
     * Returns an array of all matching elements from both arrays.
     *
     * @return array
     */
   matchArr: function( arr, match )
   {
      var matched = Array();

      if( !arr )
        return arr;

      var tmp = Array();
      if( typeof( arr[0] ) === 'object' )
      {
         tmp[0] = Array();
         tmp[1] = Array();
         for( var i = 0; i < arr.length; ++i )
         {
           if( arr.length > i )
              tmp[0].push( arr[i][0] );

           if( match.length > i )
              tmp[1].push( match[i][0] );
         }
      }
      else
      {
        tmp[0] = arr;
        tmp[1] = match;
      }

      for( var i = 0; i < arr.length; ++i )
      {
          if( tmp[1].indexOf( tmp[0][i] ) !== -1 )
            matched.push( arr[i] );
      }

      return matched;
   },

   /**
     * Builds an array out of all matching elements of provided index.
     * Index defaults to zero if not specified.
     *
     * @return array
     */
   buildArr: function( arr, index )
   {
      var index = index || 0;
      var builded = Array();

      if( !arr )
        return arr;

      for( var i = 0; i < arr.length; ++i )
      {
        var copy = arr[i].slice(index+1, arr[i].length);
        var in_index = arr[i][index];
        if( !builded[in_index] )
          builded[in_index] = Array();

        builded[in_index].push( copy );
      }

      return builded;
   },

   /**
     * Moves an index within an array to another position, for all array elements.
     *
     * @return array
     */
   moveItem: function( arr, index, position, overwrite )
   {
      var overwrite = overwrite || false;
      var inc = ( overwrite ) ? 1 : 2;
      var moved = Array();

      for( var i = 0; i < arr.length; ++i  )
      {
        moved[i] = Array();

        for( var o = 0; o < arr[i].length; ++o )
        {
          if( i < position )
            moved[i][o] = arr[i][o];
          else if( o === position )
          {
            moved[i][o] = arr[i][index];
            if( !overwrite )
              moved[i][o+1] = arr[i][o];
          }
          else if( o < index )
            moved[i][o+inc] = arr[i][o];
          else if( o === index )
            moved[i][o] = arr[i][o-1];
          else
            moved[i][o] = arr[i][o];
        }
      }

      return moved;
   },

   /**
     * Makes a diff betwee arr and diff and sorts it in deleted
     * and available.
     *
     * Array [0] = added, [1] = deleted
     *
     * @return array
     */
   diffArr: function( arr, diff )
   {
      var differences = Array();
      differences[0] = Array();
      differences[1] = Array();

      if( !diff )
      {
         differences[0] = arr;
      }
      else if( !arr )
      {
        differences[1] = diff;
      }
      else if( arr )
      {
         var tmp = Array();
         var len = ( diff.length > arr.length ) ? diff.length : arr.length;
         if( typeof( arr[0] ) === 'object' )
         {
            tmp[0] = Array();
            tmp[1] = Array();
            for( var i = 0; i < len; ++i )
            {
              if( arr.length > i )
                tmp[0].push( arr[i][0] );

              if( diff.length > i )
                tmp[1].push( diff[i][0] );
            }
         }
         else
         {
           tmp[0] = arr;
           tmp[1] = diff;
         }

          for( var i = 0; i < len; ++i )
          {
             if( tmp[1].length > i && tmp[0].indexOf( tmp[1][i] ) === -1 )
                differences[1].push( diff[i] );

             if( tmp[0].length > i && tmp[1].indexOf( tmp[0][i] ) === -1 )
                differences[0].push( arr[i] );
          }
      }

      return differences;
   },

   diffObjKeys: function( obj, diff )
   {
      var differences = Array();
      differences[0] = Array();
      differences[1] = Array();

      if( !diff )
      {
         differences[0] = obj;
      }
      else if( !obj )
      {
        differences[1] = diff;
      }
      else if( obj )
      {
        //ToDo
      }

      return differences;
   },

   close: function()
   {
      if( this.driver )
         this.driver.close();
   }

};
module.exports = Builder;
<|endoftext|>


<commit_before>/**
 * Created by szentsas on 1/28/17.
 * #icbuggy
 */

function FlappyGameState() {

    var delta;
    var deltameter = new DeltaTimeMeter();
    var player;
    var consth = 0.1, constv = 0.01;
    var noOfObstacles=0;

    var obstacles = [];
    var obstacles2 = [];

    //setup

     this.setup = function() {

        //player
        player = new jaws.Sprite({image: "img/flappy_player.png", x: jaws.width * 0.1, y: jaws.height / 2, scale: 2})
        player.isAlive = true;
        player.v=0;

        jaws.on_keydown("esc",  function() { jaws.switchGameState(MenuState) });

        //obstacles
         obstacles.push(new jaws.Sprite({x: jaws.width*3/2,
             y: (Math.random()*0.7+0.2)*jaws.height,
             image: "img/flappy_obstacle.png"}));
         obstacles2.push(new jaws.Sprite({x: obstacles[obstacles.length-1].x,
             y: obstacles[obstacles.length-1].y-1.3*jaws.height,
             image: "img/flappy_obstacle2.png"}));
        /*for(var i = jaws.width / 3; i<=jaws.width*4/3; i+= (jaws.width / 3)) {
            obstacles.push(new jaws.Sprite({x: i,
                y: (Math.random()*0.7+0.2)*jaws.height,
                image: "img/flappy_obstacle.png"}));
            noOfObstacles++;
        }

         for(var i=0;i<obstacles.length;i++) {
             obstacles2.push(new jaws.Sprite({x: obstacles[i].x,
                 y: obstacles[i].y-1.3*jaws.height,
                 image: "img/flappy_obstacle2.png"}));
         }*/
    }

    //update

    this.update = function() {
        //get delta
        delta = deltameter.getDeltaTime();

        //get audio sample
        audio = updateAudioInput();

        //update player velocity
        if(audio.valid && audio.confidence > 20) {
            player.v = (Math.log(audio.frequency) - Math.log(1300));
        }
        /*
        if(jaws.pressed("down")) {
            player.v=10;
        } else if(jaws.pressed("up")) {
            player.v=-10;
        } else {
            player.v=0;
        }*/

        //update player position
        player.y += player.v * delta * constv;
        player.y=Math.max(player.y, 0);
        player.y=Math.min(player.y, jaws.height-19);

        //collide detection & :`(
        jaws.collide(player, obstacles, function(a, b) {a.isAlive=false});
        jaws.collide(player, obstacles2, function(a, b) {a.isAlive=false});
        if(!player.isAlive) {
            console.log("MEGHALTÁÁÁÁL!!");
            jaws.switchGameState(MenuState);
        }

        //delete old obstacles outside of canvas
        while (OutOfCanvas(obstacles[0])) {
            obstacles.splice(0, 1);
            obstacles2.splice(0, 1);
        }

        //spwn new obstacles
        if(obstacles[obstacles.length -1].x < jaws.width*3/2) {
            obstacles.push(new jaws.Sprite({x: obstacles[obstacles.length -1].x + jaws.width/2,
                                            y: (Math.random()*0.7+0.2)*jaws.height,
                                            image: "img/flappy_obstacle.png"}));

            obstacles2.push(new jaws.Sprite({x: obstacles[obstacles.length-1].x,
                y: obstacles[obstacles.length-1].y-1.3*jaws.height,
                image: "img/flappy_obstacle2.png"}));

            noOfObstacles++;
        }
        /*console.log('obstacles:')
        console.log(obstacles[0].x)
        console.log(obstacles[obstacles.length-1].x)*/

    }

    //draw

    this.draw = function() {
        jaws.clear();                               //clear canvas
        player.draw();                              //draw player
        for (i=0; i<(obstacles.length); i++) {
                    obstacles[i].x -= delta*consth;
                    obstacles2[i].x -= delta*consth;
                    obstacles[i].draw();            //draw (and update :( ) all obstacles
                    obstacles2[i].draw();
        }

    }

    //detects if something is very much left of the canvas
    function OutOfCanvas(a) {
        return (a.x< (-jaws.width/3));
    }
}
<commit_msg>fix<commit_after>/**
 * Created by szentsas on 1/28/17.
 * #icbuggy
 */

function FlappyGameState() {

    var delta;
    var deltameter = new DeltaTimeMeter();
    var player;
    var consth = 0.1, constv = 0.4;
    var noOfObstacles=0;

    var obstacles = [];
    var obstacles2 = [];

    //setup

     this.setup = function() {

        //player
        player = new jaws.Sprite({image: "img/flappy_player.png", x: jaws.width * 0.1, y: jaws.height / 2, scale: 2})
        player.isAlive = true;
        player.v=0;

        jaws.on_keydown("esc",  function() { jaws.switchGameState(MenuState) });

        //obstacles
         obstacles.push(new jaws.Sprite({x: jaws.width*3/2,
             y: (Math.random()*0.7+0.2)*jaws.height,
             image: "img/flappy_obstacle.png"}));
         obstacles2.push(new jaws.Sprite({x: obstacles[obstacles.length-1].x,
             y: obstacles[obstacles.length-1].y-1.3*jaws.height,
             image: "img/flappy_obstacle2.png"}));
        /*for(var i = jaws.width / 3; i<=jaws.width*4/3; i+= (jaws.width / 3)) {
            obstacles.push(new jaws.Sprite({x: i,
                y: (Math.random()*0.7+0.2)*jaws.height,
                image: "img/flappy_obstacle.png"}));
            noOfObstacles++;
        }

         for(var i=0;i<obstacles.length;i++) {
             obstacles2.push(new jaws.Sprite({x: obstacles[i].x,
                 y: obstacles[i].y-1.3*jaws.height,
                 image: "img/flappy_obstacle2.png"}));
         }*/
    }

    //update

    this.update = function() {
        //get delta
        delta = deltameter.getDeltaTime();

        //get audio sample
        audio = updateAudioInput();

        //update player velocity
        if(audio.valid && audio.overThreshold) {
            player.v = -audio.normalizedValue * constv;
            console.log("normal")
           } else {
            player.v=Math.max((Math.abs(player.v)-delta), 0)*Math.sign(player.v);
            console.log("not normal")
        }
           /*
        if(jaws.pressed("down")) {
            player.v=10;
        } else if(jaws.pressed("up")) {
            player.v=-10;
        } else {
            player.v=0;
        }*/

        //update player position
        player.y += player.v * delta * constv;
        player.y=Math.max(player.y, 0);
        player.y=Math.min(player.y, jaws.height-19);

        //collide detection & :`(
        jaws.collide(player, obstacles, function(a, b) {a.isAlive=false});
        jaws.collide(player, obstacles2, function(a, b) {a.isAlive=false});
        if(!player.isAlive) {
            console.log("MEGHALTÁÁÁÁL!!");
            jaws.switchGameState(MenuState);
        }

        //delete old obstacles outside of canvas
        while (OutOfCanvas(obstacles[0])) {
            obstacles.splice(0, 1);
            obstacles2.splice(0, 1);
        }

        //spwn new obstacles
        if(obstacles[obstacles.length -1].x < jaws.width*3/2) {
            obstacles.push(new jaws.Sprite({x: obstacles[obstacles.length -1].x + jaws.width/2,
                                            y: (Math.random()*0.7+0.2)*jaws.height,
                                            image: "img/flappy_obstacle.png"}));

            obstacles2.push(new jaws.Sprite({x: obstacles[obstacles.length-1].x,
                y: obstacles[obstacles.length-1].y-1.3*jaws.height,
                image: "img/flappy_obstacle2.png"}));

            noOfObstacles++;
        }
        /*console.log('obstacles:')
        console.log(obstacles[0].x)
        console.log(obstacles[obstacles.length-1].x)*/

    }

    //draw

    this.draw = function() {
        jaws.clear();                               //clear canvas
        player.draw();                              //draw player
        for (i=0; i<(obstacles.length); i++) {
                    obstacles[i].x -= delta*consth;
                    obstacles2[i].x -= delta*consth;
                    obstacles[i].draw();            //draw (and update :( ) all obstacles
                    obstacles2[i].draw();
        }
        console.log("draw\n");

    }

    //detects if something is very much left of the canvas
    function OutOfCanvas(a) {
        return (a.x< (-jaws.width/3));
    }
}
<|endoftext|>


<commit_before>/*
Copyright 2015-2019 The OmniDB Team
This file is part of OmniDB.
OmniDB is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
OmniDB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with OmniDB. If not, see http://www.gnu.org/licenses/.
*/

function composedPath(el) {
    var path = [];
    while (el) {
        path.push(el);
        if (el.tagName === 'HTML') {
            path.push(document);
            path.push(window);
            return path;
       }
       el = el.parentElement;
    }
}

function createTabControl({ p_div, p_hierarchy }) {

	// Get an element's exact position
	function getPosition(el) {
		var xPos = 0;
		var yPos = 0;

		while (el) {
			if (el.tagName == "BODY") {
				var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
				var yScroll = el.scrollTop || document.documentElement.scrollTop;

				xPos += (el.offsetLeft - xScroll + el.clientLeft);
				yPos += (el.offsetTop - yScroll + el.clientTop);
			}
			else {
				xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
				yPos += (el.offsetTop - el.scrollTop + el.clientTop);
			}

			el = el.offsetParent;
		}

		return {
			x: xPos,
			y: yPos
		};
	}

  // Initializing HTML elements
	var v_div = document.getElementById(p_div);
  v_div.innerHTML = '';

  var v_nav = document.createElement('nav');
  var v_div_tab_list = document.createElement('div');
  v_div_tab_list.className = 'nav nav-tabs';
  v_nav.appendChild(v_div_tab_list);
  var v_div_tab_content_list = document.createElement('div');
  v_div_tab_content_list.className = 'omnidb__tab-content omnidb__tab-content--primary tab-content';

  var v_tab_menu = document.createElement('div');
  v_tab_menu.className = 'omnidb__tab-menu';

  if (p_hierarchy != undefined) {
    let css_tab_menu_variations = [
      'omnidb__tab-menu--',
      'omnidb__theme-bg--menu-'
    ];
    for (let i = 0; i < css_tab_menu_variations.length; i++) {
      v_tab_menu.classList.add(css_tab_menu_variations[i] + p_hierarchy);
    }
  }

  v_tab_menu.appendChild(v_nav);
  v_div.appendChild(v_tab_menu);
  v_div.appendChild(v_div_tab_content_list);

	var v_tabControl = {
		id: p_div,
		tabColor: null,
		selectedTab: null,
		selectedDiv: null,
		selectedA: null,
		tabListContentDiv: v_div_tab_content_list,
		tabList : [],
		tabListDiv : v_div_tab_list,
		tabCounter : 0,
		tag: new Object(),
    selectTabIndex : function(p_index) {

			if (this.tabList[p_index].selectable) {

				if (this.selectedTab!=null)
					this.selectedTab.selected = false;

				this.tabList[p_index].selected = true;

				this.selectedTab = this.tabList[p_index];

        //$(this.tabList[p_index].elementA).tab('show');

				if (this.selectedDiv!=null) {
          this.selectedDiv.classList.remove('active');
          this.selectedA.classList.remove('active');
				}

				this.tabList[p_index].elementA.classList.add('active');
				this.tabList[p_index].elementDiv.classList.add('active');

				this.selectedA = this.tabList[p_index].elementA;
				this.selectedDiv = this.tabList[p_index].elementDiv;

				if(this.tabList[p_index].selectFunction != null) {
					this.tabList[p_index].selectFunction();
				}
			}

		},
    disableTabIndex : function(p_index) {
      this.tabList[p_index].elementA.classList.add('disabled');
		},
    enableTabIndex : function(p_index) {
      console.log(this.tabList[p_index].elementA.classList)
      this.tabList[p_index].elementA.classList.remove('disabled');
      console.log(this.tabList[p_index].elementA.classList)
      console.log(this.tabList[p_index].elementA)
		},
    disableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = false;
		},
    enableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = true;
		},
		selectTab : function(p_tab) {

			if (this.selectedTab!=p_tab) {
				if (p_tab.selectable) {

					if (this.selectedTab!=null)
						this.selectedTab.selected = false;

					p_tab.selected = true;

					this.selectedTab = p_tab;

					if (this.selectedDiv!=null) {
						this.selectedDiv.classList.remove('active');
						this.selectedA.classList.remove('active');
					}

					p_tab.elementA.classList.add('active');
					p_tab.elementDiv.classList.add('active');

					this.selectedA = p_tab.elementA;
					this.selectedDiv = p_tab.elementDiv;

					if(p_tab.selectFunction != null) {
						p_tab.selectFunction();
					}
				}
			}
		},
    disableTab : function(p_tab) {
      p_tab.elementA.classList.add('disabled');
		},
    enableTab : function(p_tab) {
      p_tab.elementA.classList.remove('disabled');
		},
    disableSelectableTab : function(p_tab) {
      p_tab.selectable = false;
		},
    enableSelectableTab : function(p_tab) {
      p_tab.selectable = true;
		},
		disableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = 'none';
			}
		},
		enableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = '';
			}
		},
		removeTabIndex : function(p_index) {
			var v_tab = this.tabList[p_index];

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			this.tabList.splice(p_index, 1);
		},
    removeLastTab : function() {
      this.removeTabIndex(this.tabList.length-1);
		},
		removeTab : function(p_tab) {

			var v_tab = p_tab;

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			var v_index = this.tabList.indexOf(p_tab);

      var v_current_index = this.tabList.indexOf(this.selectedTab);

      if (v_index == v_current_index) {
  			if (v_index > 0)
  				this.selectTabIndex(v_index-1);
  			else if (this.tabList[v_index+1]!=null)
  				this.selectTabIndex(v_index+1);
      }

			this.tabList.splice(this.tabList.indexOf(p_tab), 1);

		},
		renameTab : function(p_tab,p_name) {

			var v_span = p_tab.elementA.childNodes[0];
			v_span.innerHTML = p_name;

			p_tab.text = p_name;

		},
		createTab : function({
      p_clickFunction = null,
      p_close = true,
      p_closeFunction = null,
      p_dblClickFunction = null,
      p_disabled = false,
      p_icon = false,
      p_isDraggable = true,
      p_name = '',
      p_selectFunction = null,
      p_selectable = true
    }) {
			var v_control = this;
			var v_index = this.tabCounter;

			this.tabCounter++;

			var v_tab = {
				id : p_div + '_tab' + v_index,
				seq: v_index,
				text: p_name,
				selected : false,
				elementA : null,
				elementDiv : null,
				elementClose: null,
				tag: null,
				clickFunction: p_clickFunction,
				dblClickFunction : p_dblClickFunction,
				closeFunction: p_closeFunction,
				selectFunction: p_selectFunction,
				selectable: p_selectable,
        disabled: p_disabled,
				removeTab: function() { v_control.removeTab(this); },
				renameTab: function(p_name) { v_control.renameTab(this,p_name); },
				disableClose: function() { v_control.disableClose(this) },
				enableClose: function() { v_control.enableClose(this) },
				isDraggable: p_isDraggable
			};

			var v_a = document.createElement('a');
      v_a.setAttribute('id','a_' + p_div + '_tab' + v_index);
      v_a.setAttribute('data-toggle','tab');
      v_a.setAttribute('role','tab');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('href','#' + 'div_' + p_div + '_tab' + v_index);
      v_a.setAttribute('aria-controls','div_' + p_div + '_tab' + v_index);

      if (p_disabled)
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link disabled';
      else
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link';

      var v_close = document.createElement('i');
      v_close.className = 'fas fa-times tab-icon icon-close omnidb__tab-menu__link-close';

			v_tab.elementClose = v_close;

			v_close.onclick = function(e) {
        e.stopPropagation();
        e.preventDefault();
        if (v_tab.closeFunction!=null) {
          v_tab.closeFunction(e,v_tab);
        }
			};
			v_a.innerHTML = '' +
                        ((p_icon !== false) ? '' + p_icon + '' : '') +
                        '' + p_name + '' +
                      '';
      if (p_close) {
  			v_a.appendChild(v_close);
      }

			v_a.ondblclick = function(e) {

				if (v_tab.dblClickFunction!=null)
					v_tab.dblClickFunction(v_tab);
			};

			var v_div = document.createElement('div');
      v_div.className = 'tab-pane';
      v_div.setAttribute('id','div_' + p_div + '_tab' + v_index);
      v_div.setAttribute('role','tabpanel');
      v_div.setAttribute('aria-labelledby','a_' + p_div + '_tab' + v_index);

			v_tab.elementA = v_a;
			v_tab.elementDiv = v_div;

			v_a.onclick = function(e) {

        e.stopPropagation();
        e.preventDefault();
        if (v_tab.selectable)
				    v_control.selectTab(v_tab);

				if (v_tab.clickFunction!=null)
					v_tab.clickFunction(e);
			};

			this.tabListDiv.appendChild(v_a);
			this.tabListContentDiv.appendChild(v_div);

			this.tabList.push(v_tab);

			return v_tab;
		},
	};

	return v_tabControl;

}

//Create a HTML element specified by parameter 'p_type'
function createSimpleElement(p_type,p_id,p_class) {
	element = document.createElement(p_type);
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	return element;
}

//Create img element
function createImgElement(p_id,p_class,p_src) {
	element = document.createElement('img');
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	if (p_src!=undefined)
		element.src = p_src;
	return element;
}
<commit_msg>Fixed tab-link-content class for hierarchy attr<commit_after>/*
Copyright 2015-2019 The OmniDB Team
This file is part of OmniDB.
OmniDB is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
OmniDB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with OmniDB. If not, see http://www.gnu.org/licenses/.
*/

function composedPath(el) {
    var path = [];
    while (el) {
        path.push(el);
        if (el.tagName === 'HTML') {
            path.push(document);
            path.push(window);
            return path;
       }
       el = el.parentElement;
    }
}

function createTabControl({ p_div, p_hierarchy }) {

	// Get an element's exact position
	function getPosition(el) {
		var xPos = 0;
		var yPos = 0;

		while (el) {
			if (el.tagName == "BODY") {
				var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
				var yScroll = el.scrollTop || document.documentElement.scrollTop;

				xPos += (el.offsetLeft - xScroll + el.clientLeft);
				yPos += (el.offsetTop - yScroll + el.clientTop);
			}
			else {
				xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
				yPos += (el.offsetTop - el.scrollTop + el.clientTop);
			}

			el = el.offsetParent;
		}

		return {
			x: xPos,
			y: yPos
		};
	}

  // Initializing HTML elements
	var v_div = document.getElementById(p_div);
  v_div.innerHTML = '';

  var v_nav = document.createElement('nav');
  var v_div_tab_list = document.createElement('div');
  v_div_tab_list.className = 'nav nav-tabs';
  v_nav.appendChild(v_div_tab_list);
  var v_div_tab_content_list = document.createElement('div');
  v_div_tab_content_list.className = 'tab-content omnidb__tab-content';

  var v_tab_menu = document.createElement('div');
  v_tab_menu.className = 'omnidb__tab-menu';

  if (p_hierarchy != undefined) {
    let css_tab_menu_variations = [
      'omnidb__tab-menu--',
      'omnidb__theme-bg--menu-'
    ];
    for (let i = 0; i < css_tab_menu_variations.length; i++) {
      v_tab_menu.classList.add(css_tab_menu_variations[i] + p_hierarchy);
    }
    v_div_tab_content_list.classList.add('omnidb__tab-content--' + p_hierarchy);
  }

  v_tab_menu.appendChild(v_nav);
  v_div.appendChild(v_tab_menu);
  v_div.appendChild(v_div_tab_content_list);

	var v_tabControl = {
		id: p_div,
		tabColor: null,
		selectedTab: null,
		selectedDiv: null,
		selectedA: null,
		tabListContentDiv: v_div_tab_content_list,
		tabList : [],
		tabListDiv : v_div_tab_list,
		tabCounter : 0,
		tag: new Object(),
    selectTabIndex : function(p_index) {

			if (this.tabList[p_index].selectable) {

				if (this.selectedTab!=null)
					this.selectedTab.selected = false;

				this.tabList[p_index].selected = true;

				this.selectedTab = this.tabList[p_index];

        //$(this.tabList[p_index].elementA).tab('show');

				if (this.selectedDiv!=null) {
          this.selectedDiv.classList.remove('active');
          this.selectedA.classList.remove('active');
				}

				this.tabList[p_index].elementA.classList.add('active');
				this.tabList[p_index].elementDiv.classList.add('active');

				this.selectedA = this.tabList[p_index].elementA;
				this.selectedDiv = this.tabList[p_index].elementDiv;

				if(this.tabList[p_index].selectFunction != null) {
					this.tabList[p_index].selectFunction();
				}
			}

		},
    disableTabIndex : function(p_index) {
      this.tabList[p_index].elementA.classList.add('disabled');
		},
    enableTabIndex : function(p_index) {
      console.log(this.tabList[p_index].elementA.classList)
      this.tabList[p_index].elementA.classList.remove('disabled');
      console.log(this.tabList[p_index].elementA.classList)
      console.log(this.tabList[p_index].elementA)
		},
    disableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = false;
		},
    enableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = true;
		},
		selectTab : function(p_tab) {

			if (this.selectedTab!=p_tab) {
				if (p_tab.selectable) {

					if (this.selectedTab!=null)
						this.selectedTab.selected = false;

					p_tab.selected = true;

					this.selectedTab = p_tab;

					if (this.selectedDiv!=null) {
						this.selectedDiv.classList.remove('active');
						this.selectedA.classList.remove('active');
					}

					p_tab.elementA.classList.add('active');
					p_tab.elementDiv.classList.add('active');

					this.selectedA = p_tab.elementA;
					this.selectedDiv = p_tab.elementDiv;

					if(p_tab.selectFunction != null) {
						p_tab.selectFunction();
					}
				}
			}
		},
    disableTab : function(p_tab) {
      p_tab.elementA.classList.add('disabled');
		},
    enableTab : function(p_tab) {
      p_tab.elementA.classList.remove('disabled');
		},
    disableSelectableTab : function(p_tab) {
      p_tab.selectable = false;
		},
    enableSelectableTab : function(p_tab) {
      p_tab.selectable = true;
		},
		disableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = 'none';
			}
		},
		enableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = '';
			}
		},
		removeTabIndex : function(p_index) {
			var v_tab = this.tabList[p_index];

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			this.tabList.splice(p_index, 1);
		},
    removeLastTab : function() {
      this.removeTabIndex(this.tabList.length-1);
		},
		removeTab : function(p_tab) {

			var v_tab = p_tab;

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			var v_index = this.tabList.indexOf(p_tab);

      var v_current_index = this.tabList.indexOf(this.selectedTab);

      if (v_index == v_current_index) {
  			if (v_index > 0)
  				this.selectTabIndex(v_index-1);
  			else if (this.tabList[v_index+1]!=null)
  				this.selectTabIndex(v_index+1);
      }

			this.tabList.splice(this.tabList.indexOf(p_tab), 1);

		},
		renameTab : function(p_tab,p_name) {

			var v_span = p_tab.elementA.childNodes[0];
			v_span.innerHTML = p_name;

			p_tab.text = p_name;

		},
		createTab : function({
      p_clickFunction = null,
      p_close = true,
      p_closeFunction = null,
      p_dblClickFunction = null,
      p_disabled = false,
      p_icon = false,
      p_isDraggable = true,
      p_name = '',
      p_selectFunction = null,
      p_selectable = true
    }) {
			var v_control = this;
			var v_index = this.tabCounter;

			this.tabCounter++;

			var v_tab = {
				id : p_div + '_tab' + v_index,
				seq: v_index,
				text: p_name,
				selected : false,
				elementA : null,
				elementDiv : null,
				elementClose: null,
				tag: null,
				clickFunction: p_clickFunction,
				dblClickFunction : p_dblClickFunction,
				closeFunction: p_closeFunction,
				selectFunction: p_selectFunction,
				selectable: p_selectable,
        disabled: p_disabled,
				removeTab: function() { v_control.removeTab(this); },
				renameTab: function(p_name) { v_control.renameTab(this,p_name); },
				disableClose: function() { v_control.disableClose(this) },
				enableClose: function() { v_control.enableClose(this) },
				isDraggable: p_isDraggable
			};

			var v_a = document.createElement('a');
      v_a.setAttribute('id','a_' + p_div + '_tab' + v_index);
      v_a.setAttribute('data-toggle','tab');
      v_a.setAttribute('role','tab');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('href','#' + 'div_' + p_div + '_tab' + v_index);
      v_a.setAttribute('aria-controls','div_' + p_div + '_tab' + v_index);

      if (p_disabled)
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link disabled';
      else
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link';

      var v_close = document.createElement('i');
      v_close.className = 'fas fa-times tab-icon icon-close omnidb__tab-menu__link-close';

			v_tab.elementClose = v_close;

			v_close.onclick = function(e) {
        e.stopPropagation();
        e.preventDefault();
        if (v_tab.closeFunction!=null) {
          v_tab.closeFunction(e,v_tab);
        }
			};
			v_a.innerHTML = '' +
                        ((p_icon !== false) ? '' + p_icon + '' : '') +
                        '' + p_name + '' +
                      '';
      if (p_close) {
  			v_a.appendChild(v_close);
      }

			v_a.ondblclick = function(e) {

				if (v_tab.dblClickFunction!=null)
					v_tab.dblClickFunction(v_tab);
			};

			var v_div = document.createElement('div');
      v_div.className = 'tab-pane';
      v_div.setAttribute('id','div_' + p_div + '_tab' + v_index);
      v_div.setAttribute('role','tabpanel');
      v_div.setAttribute('aria-labelledby','a_' + p_div + '_tab' + v_index);

			v_tab.elementA = v_a;
			v_tab.elementDiv = v_div;

			v_a.onclick = function(e) {

        e.stopPropagation();
        e.preventDefault();
        if (v_tab.selectable)
				    v_control.selectTab(v_tab);

				if (v_tab.clickFunction!=null)
					v_tab.clickFunction(e);
			};

			this.tabListDiv.appendChild(v_a);
			this.tabListContentDiv.appendChild(v_div);

			this.tabList.push(v_tab);

			return v_tab;
		},
	};

	return v_tabControl;

}

//Create a HTML element specified by parameter 'p_type'
function createSimpleElement(p_type,p_id,p_class) {
	element = document.createElement(p_type);
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	return element;
}

//Create img element
function createImgElement(p_id,p_class,p_src) {
	element = document.createElement('img');
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	if (p_src!=undefined)
		element.src = p_src;
	return element;
}
<|endoftext|>


<commit_before>"use strict";

var child_process = require("child_process"),
    fs = require("fs");

var output = child_process.spawnSync("eslint", "-c lib/eslint.json --rulesdir lib/rules -f compact test/fixtures".split(" "), { encoding: "utf8" });

if (output.status === 1)
{
    var fixture = fs.readFileSync("test/fixtures/errors.txt", "utf8");

    if (fixture === output.stdout)
        process.exit(0);
}

process.exit(1);
<commit_msg>Fixed test, show a message<commit_after>"use strict";

var child_process = require("child_process"),
    fs = require("fs");

var result = child_process.spawnSync("node_modules/.bin/eslint", "-c lib/eslint.json --rulesdir lib/rules -f compact test/fixtures".split(" "), { encoding: "utf8" });

if (result.status === 1)
{
    var fixture = fs.readFileSync("test/fixtures/errors.txt", "utf8");

    if (fixture === result.stdout)
    {
        console.log("test passed");
        process.exit(0);
    }
}

console.log("test failed with status ", result.status);
process.exit(1);
<|endoftext|>