<commit_before>(function(){

/******************************************
             Audio player
******************************************/

function createPlayer(file){
    $('#audio').remove();
    $('#player-hook').append('<audio id="audio" src=""></audio>');
    if (window.webkitURL) {
        console.log('webkit');
        var url = window.webkitURL.createObjectURL(file);
    } else {
        var url = window.URL.createObjectURL(file);
    }
    console.log(url);
    $('#audio')[0].src = url;
    console.log(file.name);
}

// play/pause
function playPause(){
    var playing = !document.getElementById('audio').paused
    if (playing == true){
        document.getElementById('audio').pause();
        $('.play-pause').removeClass('playing');
    } else {
        document.getElementById('audio').play();
        $('.play-pause').addClass('playing');
    };
};

// skip forward
function skip(direction){
    var audio = document.getElementById('audio');
    if (direction == "forwards"){
        audio.currentTime = audio.currentTime+1.5;
    } else if (direction == "backwards") {
        audio.currentTime = audio.currentTime-1.5;
    }
}

// speed
function speed(newSpeed){
    console.log(typeof newSpeed);
    var min = 0.5;
    var max = 2;
    var step = 0.25;
    var newSpeedNumber;
    var currentSpeed = document.getElementById('audio').playbackRate;
    if ((newSpeed == "up") && (currentSpeed < max)){
        newSpeedNumber = currentSpeed+step;
    } else if ((newSpeed == "down") && (currentSpeed > min)){
        newSpeedNumber = currentSpeed-step;
    } else if (newSpeed == "reset"){
        newSpeedNumber = 1;
    } else if (typeof newSpeed == 'number') {
        newSpeedNumber = newSpeed;
    }
    if (typeof(newSpeedNumber) != "undefined") {
        document.getElementById('audio').playbackRate = newSpeedNumber;
        document.getElementById('slider3').value = newSpeedNumber;
    }
}

function initAudioJS(){
    audiojs.events.ready(function() {
      audiojs.createAll();
    });
}

function resetPlayer(){
    location.reload();
}

/******************************************
               Text editor
******************************************/

function adjustPlayerWidth(){
    var cntrls = $('.controls');
    console.log ("Window width: "+$(window).width()+"\nControls offset: "+cntrls.offset().left+"\nControls width: "+cntrls.width()+"\nTitle width: "+$('.title').width() );

    var gap = $(window).width() - (cntrls.offset().left + cntrls.width() + $('.title').outerWidth() );
    $('.scrubber').width( $('.scrubber').width()+gap );
   console.log(gap);
}

function toggleAbout(){
    $('.title').toggleClass('active');
    $('.about').toggleClass('active');
}

function adjustEditorHeight(){
    $('.textbox-container').height( window.innerHeight - 36 );
}

/******************************************
                Timestamp
******************************************/

// get timestamp
// var timestamp;
function getTimestamp(){
    // get timestap
    var time = document.getElementById('audio').currentTime
    var minutes = Math.floor(time / 60);
    var seconds = ("0" + Math.round( time - minutes * 60 ) ).slice(-2);
    return minutes+":"+seconds;
};

function insertTimestamp(){
    insertAtCaret('textbox',"["+getTimestamp()+"]" );
}

// insert text at cursor
function insertAtCaret(areaId,text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
		"ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	}
	else if (br == "ff") strPos = txtarea.selectionStart;

	var front = (txtarea.value).substring(0,strPos);
	var back = (txtarea.value).substring(strPos,txtarea.value.length);
	txtarea.value=front+text+back;
	strPos = strPos + text.length;
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);
		range.select();
	}
	else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}

function saveText(){
    // autosave every second
    var field = document.getElementById("textbox");
    if ( localStorage.getItem("autosave")) {
       field.innerHTML = localStorage.getItem("autosave");
    }
    setInterval(function(){
       localStorage.setItem("autosave", field.innerHTML);
    }, 1000);

}

function loadFileName(){
    // load existing file name
    if ( localStorage.getItem("lastfile") ) {
       document.getElementById("lastfile").innerHTML = "Last file: "+localStorage.getItem("lastfile");
       toggleAbout();
    }
}

function dragListener(){
    var button = $('.file-input-wrapper')[0];
    button.addEventListener('dragover', function(){
        $('.file-input-wrapper').addClass('hover');
    }, false);
    button.addEventListener('dragleave', function(){
        $('.file-input-wrapper').removeClass('hover');
    }, false);

}

/******************************************
                Other
******************************************/

function detectFormats(format){
    var a = document.createElement('audio');
    return !!(a.canPlayType && a.canPlayType('audio/'+format+';').replace(/no/, ''));
}

function listSupportedFormats(){
    var supportedFormats = [];
    var formats = ['mp3', 'ogg', 'webm', 'wav'];
    var i = 0;
    formats.forEach(function(format, index) {
        if (detectFormats(format) == true){
            supportedFormats[i] = format;
            i++;
        }
    });
    return supportedFormats.join(', ');
}

function checkTypeSupport(file){
  var a = document.createElement('audio');
  return !!(a.canPlayType && a.canPlayType(file.type).replace(/no/, ''));
}

function reactToFile(input){
    var file = input.files[0];
    if ( checkTypeSupport( file ) === true ){
        createPlayer( file );
        initAudioJS();
        adjustPlayerWidth();
        toggleControls();
        localStorage.setItem("lastfile", file.name);
        $('.scrubber .loaded').html( file.name );
        console.log('Loading complete.') ;
    } else {
        var msg = "Your browser does not support " + file.type.split("/")[1] + " files. Switch to a different browser or convert your file to another format.";
        $('#formats').html(msg).addClass('warning');
    }

}

function toggleControls(){
    $('.topbar').toggleClass('inputting');
    $('.input').toggleClass('active');
};

function setFormatsMessage(){
    document.getElementById("formats").innerHTML = "Your browser supports the following formats: "+listSupportedFormats()+". You may need to convert your file.";
}

function setStartButton(){
    $('.start').html('Start transcribing').addClass('ready');
}

/******************************************
             Initialisation
******************************************/

function init(){
    saveText();
    loadFileName();
    setFormatsMessage();
    adjustEditorHeight();
    dragListener();
    setStartButton();
}

init();

$(window).resize(function() {
    adjustEditorHeight();
    adjustPlayerWidth();
});

/******************************************
             User Interaction
******************************************/

    // keyboard shortcuts
    Mousetrap.bind('escape', function(e) {
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            // internet explorer
            e.returnValue = false;
        }
        playPause();
        return false;
    });
    Mousetrap.bind('f1', function(e) {
        skip('backwards');
        return false;
    });
    Mousetrap.bind('f2', function(e) {
        skip('forwards');
        return false;
    });
    Mousetrap.bind('f3', function(e) {
        speed('down');
        return false;
    });
    Mousetrap.bind('f4', function(e) {
        speed('up');
        return false;
    });
    Mousetrap.bind('mod+j', function(e) {
        document.execCommand('insertHTML',false,
        '[' + getTimestamp() + '] '
        );
        console.log(tsHTML);
        return false;
    });
    Mousetrap.bind('mod+s', function(e) {
        alert("No need to manually save - your transcript is automatically backed up continuously.")
        return false;
    });

    Mousetrap.bind('mod+b', function(e) {
        document.execCommand('bold',false,null);
        return false;
    });

    Mousetrap.bind('mod+i', function(e) {
        document.execCommand('italic',false,null);
        return false;
    });

    $('.play-pause').click(function(){
        playPause();
    });

    $('.skip-backwards').click(function(){
        skip('backwards');
    });
    $('.skip-forwards').click(function(){
        skip('forwards');
    });

    $( ".speed" ).click(function() {
        if ($('.speed-box').not(':hover').length) {
            $(this).toggleClass('fixed');
            console.log ($('.speed-box').not(':hover').length);
        }
    });

    $('.button.refresh').click(function(){
        resetPlayer();
    });

    $( "#slider3" ).change(function() {
      speed(this.valueAsNumber);
    });

    $('.title').click(function(){
        toggleAbout();
    });

    $('.about .start.ready').click(function(){
        toggleAbout();
    });

    $('#attach').change(function() {
        reactToFile(this);
    });
    // $('.timestamp').click(function(){
    //     setFromTimestamp( $(this) );
    // });

// End UI

})(); // end script

function splitTimestamp(hms){
    var a = hms.split(':');
    var seconds = (+a[0]) * 60 + (+a[1]);
    return seconds;
}

$('.timestamp *:not(:has("*"))').click(function(){
    var clickts = $(this).data('timestamp');
});

function setFromTimestamp(clickts, element){
    console.log(element.childNodes.length);
    if (element.childNodes.length == 1) {
        document.getElementById('audio').currentTime = splitTimestamp(clickts);
    }
}
<commit_msg>Prevent browser keyboard shortcuts<commit_after>(function(){

/******************************************
             Audio player
******************************************/

function createPlayer(file){
    $('#audio').remove();
    $('#player-hook').append('<audio id="audio" src=""></audio>');
    if (window.webkitURL) {
        console.log('webkit');
        var url = window.webkitURL.createObjectURL(file);
    } else {
        var url = window.URL.createObjectURL(file);
    }
    console.log(url);
    $('#audio')[0].src = url;
    console.log(file.name);
}

// play/pause
function playPause(){
    var playing = !document.getElementById('audio').paused
    if (playing == true){
        document.getElementById('audio').pause();
        $('.play-pause').removeClass('playing');
    } else {
        document.getElementById('audio').play();
        $('.play-pause').addClass('playing');
    };
};

// skip forward
function skip(direction){
    var audio = document.getElementById('audio');
    if (direction == "forwards"){
        audio.currentTime = audio.currentTime+1.5;
    } else if (direction == "backwards") {
        audio.currentTime = audio.currentTime-1.5;
    }
}

// speed
function speed(newSpeed){
    console.log(typeof newSpeed);
    var min = 0.5;
    var max = 2;
    var step = 0.25;
    var newSpeedNumber;
    var currentSpeed = document.getElementById('audio').playbackRate;
    if ((newSpeed == "up") && (currentSpeed < max)){
        newSpeedNumber = currentSpeed+step;
    } else if ((newSpeed == "down") && (currentSpeed > min)){
        newSpeedNumber = currentSpeed-step;
    } else if (newSpeed == "reset"){
        newSpeedNumber = 1;
    } else if (typeof newSpeed == 'number') {
        newSpeedNumber = newSpeed;
    }
    if (typeof(newSpeedNumber) != "undefined") {
        document.getElementById('audio').playbackRate = newSpeedNumber;
        document.getElementById('slider3').value = newSpeedNumber;
    }
}

function initAudioJS(){
    audiojs.events.ready(function() {
      audiojs.createAll();
    });
}

function resetPlayer(){
    location.reload();
}

/******************************************
               Text editor
******************************************/

function adjustPlayerWidth(){
    var cntrls = $('.controls');
    console.log ("Window width: "+$(window).width()+"\nControls offset: "+cntrls.offset().left+"\nControls width: "+cntrls.width()+"\nTitle width: "+$('.title').width() );

    var gap = $(window).width() - (cntrls.offset().left + cntrls.width() + $('.title').outerWidth() );
    $('.scrubber').width( $('.scrubber').width()+gap );
   console.log(gap);
}

function toggleAbout(){
    $('.title').toggleClass('active');
    $('.about').toggleClass('active');
}

function adjustEditorHeight(){
    $('.textbox-container').height( window.innerHeight - 36 );
}

/******************************************
                Timestamp
******************************************/

// get timestamp
// var timestamp;
function getTimestamp(){
    // get timestap
    var time = document.getElementById('audio').currentTime
    var minutes = Math.floor(time / 60);
    var seconds = ("0" + Math.round( time - minutes * 60 ) ).slice(-2);
    return minutes+":"+seconds;
};

function insertTimestamp(){
    insertAtCaret('textbox',"["+getTimestamp()+"]" );
}

// insert text at cursor
function insertAtCaret(areaId,text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
		"ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	}
	else if (br == "ff") strPos = txtarea.selectionStart;

	var front = (txtarea.value).substring(0,strPos);
	var back = (txtarea.value).substring(strPos,txtarea.value.length);
	txtarea.value=front+text+back;
	strPos = strPos + text.length;
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);
		range.select();
	}
	else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}

function saveText(){
    // autosave every second
    var field = document.getElementById("textbox");
    if ( localStorage.getItem("autosave")) {
       field.innerHTML = localStorage.getItem("autosave");
    }
    setInterval(function(){
       localStorage.setItem("autosave", field.innerHTML);
    }, 1000);

}

function loadFileName(){
    // load existing file name
    if ( localStorage.getItem("lastfile") ) {
       document.getElementById("lastfile").innerHTML = "Last file: "+localStorage.getItem("lastfile");
       toggleAbout();
    }
}

function dragListener(){
    var button = $('.file-input-wrapper')[0];
    button.addEventListener('dragover', function(){
        $('.file-input-wrapper').addClass('hover');
    }, false);
    button.addEventListener('dragleave', function(){
        $('.file-input-wrapper').removeClass('hover');
    }, false);

}

/******************************************
                Other
******************************************/

function detectFormats(format){
    var a = document.createElement('audio');
    return !!(a.canPlayType && a.canPlayType('audio/'+format+';').replace(/no/, ''));
}

function listSupportedFormats(){
    var supportedFormats = [];
    var formats = ['mp3', 'ogg', 'webm', 'wav'];
    var i = 0;
    formats.forEach(function(format, index) {
        if (detectFormats(format) == true){
            supportedFormats[i] = format;
            i++;
        }
    });
    return supportedFormats.join(', ');
}

function checkTypeSupport(file){
  var a = document.createElement('audio');
  return !!(a.canPlayType && a.canPlayType(file.type).replace(/no/, ''));
}

function reactToFile(input){
    var file = input.files[0];
    if ( checkTypeSupport( file ) === true ){
        createPlayer( file );
        initAudioJS();
        adjustPlayerWidth();
        toggleControls();
        localStorage.setItem("lastfile", file.name);
        $('.scrubber .loaded').html( file.name );
        console.log('Loading complete.') ;
    } else {
        var msg = "Your browser does not support " + file.type.split("/")[1] + " files. Switch to a different browser or convert your file to another format.";
        $('#formats').html(msg).addClass('warning');
    }

}

function toggleControls(){
    $('.topbar').toggleClass('inputting');
    $('.input').toggleClass('active');
};

function setFormatsMessage(){
    document.getElementById("formats").innerHTML = "Your browser supports the following formats: "+listSupportedFormats()+". You may need to convert your file.";
}

function setStartButton(){
    $('.start').html('Start transcribing').addClass('ready');
}

/******************************************
             Initialisation
******************************************/

function init(){
    saveText();
    loadFileName();
    setFormatsMessage();
    adjustEditorHeight();
    dragListener();
    setStartButton();
}

init();

$(window).resize(function() {
    adjustEditorHeight();
    adjustPlayerWidth();
});

/******************************************
             User Interaction
******************************************/

    // keyboard shortcuts
    function pd(e){
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            // internet explorer
            e.returnValue = false;
        }
    }

    Mousetrap.bind('escape', function(e) {
        pd(e);
        playPause();
        return false;
    });
    Mousetrap.bind('f1', function(e) {
        pd(e);
        skip('backwards');
        return false;
    });
    Mousetrap.bind('f2', function(e) {
        pd(e);
        skip('forwards');
        return false;
    });
    Mousetrap.bind('f3', function(e) {
        pd(e);
        speed('down');
        return false;
    });
    Mousetrap.bind('f4', function(e) {
        pd(e);
        speed('up');
        return false;
    });
    Mousetrap.bind('mod+j', function(e) {
        pd(e);
        document.execCommand('insertHTML',false,
        '[' + getTimestamp() + '] '
        );
        console.log(tsHTML);
        return false;
    });
    Mousetrap.bind('mod+s', function(e) {
        pd(e);
        alert("No need to manually save - your transcript is automatically backed up continuously.")
        return false;
    });

    Mousetrap.bind('mod+b', function(e) {
        pd(e);
        document.execCommand('bold',false,null);
        return false;
    });

    Mousetrap.bind('mod+i', function(e) {
        pd(e);
        document.execCommand('italic',false,null);
        return false;
    });

    $('.play-pause').click(function(){
        playPause();
    });

    $('.skip-backwards').click(function(){
        skip('backwards');
    });
    $('.skip-forwards').click(function(){
        skip('forwards');
    });

    $( ".speed" ).click(function() {
        if ($('.speed-box').not(':hover').length) {
            $(this).toggleClass('fixed');
            console.log ($('.speed-box').not(':hover').length);
        }
    });

    $('.button.refresh').click(function(){
        resetPlayer();
    });

    $( "#slider3" ).change(function() {
      speed(this.valueAsNumber);
    });

    $('.title').click(function(){
        toggleAbout();
    });

    $('.about .start.ready').click(function(){
        toggleAbout();
    });

    $('#attach').change(function() {
        reactToFile(this);
    });
    // $('.timestamp').click(function(){
    //     setFromTimestamp( $(this) );
    // });

// End UI

})(); // end script

function splitTimestamp(hms){
    var a = hms.split(':');
    var seconds = (+a[0]) * 60 + (+a[1]);
    return seconds;
}

$('.timestamp *:not(:has("*"))').click(function(){
    var clickts = $(this).data('timestamp');
});

function setFromTimestamp(clickts, element){
    console.log(element.childNodes.length);
    if (element.childNodes.length == 1) {
        document.getElementById('audio').currentTime = splitTimestamp(clickts);
    }
}
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const botVorweg = "";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(botVorweg+'101100111001101...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say(botVorweg+'Wenn Andreas gerade online ist, sieht er dieses Gespräch und kann beitreten.')
                .then(() => 'vorname');
        }
    },

    vorname: {
        prompt: (bot) => bot.say(botVorweg+'Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {
            var vorname = message.text;
            return bot.setProp('vorname', vorname)
                .then(() => bot.say(botVorweg+`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {
        prompt: (bot) => bot.say(botVorweg+'Und mit Nachnamen?'),
        receive: (bot, message) => {
            var nachname = message.text;
            return bot.setProp('nachname', nachname)
                .then(() => bot.say(botVorweg+`${nachname}, danke.`))
                .then(() => bot.say(botVorweg+'Sie können hier jederzeit eine Nachricht an Andreas eingeben.'))
                .then(() => bot.say(botVorweg+'Unterhalten Sie sich solange mit mir! Bitte schreiben Sie --bot:'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            var wollen = message.text;
            var befehl = wollen;
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

         // System
            if (befehl == "--BOT")          { bot.say(botVorweg+'Andreas hat mir viel beigebracht - Sie können das durch Schreiben der mit -- beginnenden Wörter abrufen!'); }
            if (befehl == "--BOT")          { bot.say(botVorweg+'Wollen Sie etwas über seine --Person oder --Neues von ihm erfahren? Oder auf anderem Wege --Kontakt  aufnehmen?'); }
            if (befehl == "--ABBRECHEN")    { bot.say(botVorweg+'Text: Abbruch.'); }

         // Über mich
            if (befehl == "--PERSON")       { bot.say(botVorweg+'Andreas ist 38 Jahre alt und lebt in Hamburg. Hier sein --Lebenslauf und ein --Foto.'); }
            if (befehl == "--LEBENSLAUF")   { bot.say(botVorweg+'Tabellarisches und ausformuliertes Curriculum Vitae: %[Lebenslauf öffnen](http://sefzig.net/link/Lebenslauf/)'); }
            if (befehl == "--FOTO")         { bot.say(botVorweg+'[Bild:http://sefzig.net/text/seiten/SefzignetStartseite/dateien/SefzignetStartseiteFotoLogos.png] Andreas Sefzig mit Logo'); }
            if (befehl == "--NEUES")        { bot.say(botVorweg+'Text: Neues.'); }

         // Kontakt
            if (befehl == "--KONTAKT")      { bot.say(botVorweg+'Sie erreichen Andreas über andreas@sefzig.net, in seinem --Slackteam, auf --Twitter und auf --Xing. %[Kontakt-Seite öffnen](http://sefzig.net/link/Kontakt/)'); }
            if (befehl == "--SLACKTEAM")    { bot.say(botVorweg+'Andreas betreibt ein offenes Slack-Team, in dem man sich über Marketing-Technologie unterhält. %[Offenes Slack-Team öffnen](http://sefzig.net/link/Slack/)'); }
            if (befehl == "--XING")         { bot.say(botVorweg+'Andreas ist bei Xing: Er ist seit 2004 angemeldet und gehört mit über 500 Kontakten zu den 5% der bestvernetzten Mitglieder. %[Xing-Profil öffnen](http://sefzig.net/link/Xing/)'); bot.say(botVorweg+'[Bild:http://sefzig.net/text/seiten/SefzigBot/dateien/xing_vernetzt.png]'); }
            if (befehl == "--TWITTER")      { bot.say(botVorweg+'Andreas ist auf Twitter: %[Twitter-Profil öffnen](http://sefzig.net/link/Twitter/)'); }

         // Vorlage
            if (befehl == "--VORLAGE")      { bot.say(botVorweg+'Text: Vorlage.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>Tests<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const botVorweg = "/sefzigbot";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(botVorweg+'101100111001101...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say(botVorweg+'Wenn Andreas gerade online ist, sieht er dieses Gespräch und kann beitreten.')
                .then(() => 'vorname');
        }
    },

    vorname: {
        prompt: (bot) => bot.say(botVorweg+'Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {
            var vorname = message.text;
            return bot.setProp('vorname', vorname)
                .then(() => bot.say(botVorweg+`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {
        prompt: (bot) => bot.say(botVorweg+'Und mit Nachnamen?'),
        receive: (bot, message) => {
            var nachname = message.text;
            return bot.setProp('nachname', nachname)
                .then(() => bot.say(botVorweg+`${nachname}, danke.`))
                .then(() => bot.say(botVorweg+'Sie können hier jederzeit eine Nachricht an Andreas eingeben.'))
                .then(() => bot.say(botVorweg+'Unterhalten Sie sich solange mit mir! Bitte schreiben Sie --bot:'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            var wollen = message.text;
            var befehl = wollen;
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

         // System
            if (befehl == "--BOT")          { bot.say(botVorweg+'Andreas hat mir viel beigebracht - Sie können das durch Schreiben der mit -- beginnenden Wörter abrufen!'); }
            if (befehl == "--BOT")          { bot.say(botVorweg+'Wollen Sie etwas über seine --Person oder --Neues von ihm erfahren? Oder auf anderem Wege --Kontakt  aufnehmen?'); }
            if (befehl == "--ABBRECHEN")    { bot.say(botVorweg+'Text: Abbruch.'); }

         // Über mich
            if (befehl == "--PERSON")       { bot.say(botVorweg+'Andreas ist 38 Jahre alt und lebt in Hamburg. Hier sein --Lebenslauf und ein --Foto.'); }
            if (befehl == "--LEBENSLAUF")   { bot.say(botVorweg+'Tabellarisches und ausformuliertes Curriculum Vitae: %[Lebenslauf öffnen](http://sefzig.net/link/Lebenslauf/)'); }
            if (befehl == "--FOTO")         { bot.say(botVorweg+'[Bild:http://sefzig.net/text/seiten/SefzignetStartseite/dateien/SefzignetStartseiteFotoLogos.png] Andreas Sefzig mit Logo'); }
            if (befehl == "--NEUES")        { bot.say(botVorweg+'Text: Neues.'); }

         // Kontakt
            if (befehl == "--KONTAKT")      { bot.say(botVorweg+'Sie erreichen Andreas über andreas@sefzig.net, in seinem --Slackteam, auf --Twitter und auf --Xing. %[Kontakt-Seite öffnen](http://sefzig.net/link/Kontakt/)'); }
            if (befehl == "--SLACKTEAM")    { bot.say(botVorweg+'Andreas betreibt ein offenes Slack-Team, in dem man sich über Marketing-Technologie unterhält. %[Offenes Slack-Team öffnen](http://sefzig.net/link/Slack/)'); }
            if (befehl == "--XING")         { bot.say(botVorweg+'Andreas ist bei Xing: Er ist seit 2004 angemeldet und gehört mit über 500 Kontakten zu den 5% der bestvernetzten Mitglieder. %[Xing-Profil öffnen](http://sefzig.net/link/Xing/)'); bot.say(botVorweg+'[Bild:http://sefzig.net/text/seiten/SefzigBot/dateien/xing_vernetzt.png]'); }
            if (befehl == "--TWITTER")      { bot.say(botVorweg+'Andreas ist auf Twitter: %[Twitter-Profil öffnen](http://sefzig.net/link/Twitter/)'); }

         // Vorlage
            if (befehl == "--VORLAGE")      { bot.say(botVorweg+'Text: Vorlage.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>var module = angular.module('arpege', ['ui.bootstrap']);

// General clock to fire various events
// TODO: this could be a service broadcasting the tick event
var clock = {
    refresh: 1000,
    elapsedtime: 0,
    // callbacks to be called on each tick
    callbacks: [],
    tick: function() {
      clock.elapsedtime += clock.refresh;
      // Call the callbacks so they will do their things
      for(var i = 0; i<clock.callbacks.length; i++) {
        clock.callbacks[i]();
      }
    }
};

setInterval('clock.tick()', clock.refresh);

module.service('Character', function($rootScope){
  this.level = 1;
  this.experience = 0;

  this.levelup = function() {
    this.level += 1;
    console.log('new level'+this.level);
    $rootScope.$broadcast('NewLevel');
  };

  this.addXp = function(xp) {
    this.experience += xp;
    $rootScope.$broadcast('CharXpChange');
  };

  this.levelMaxXP = function() {
    return this.level*100+((this.level*this.level)*10);
  };

});

// We will probably need a CharacterController to display things like XP,
// Health, Level
var LevelCtrl = function($scope, Character) {
  $scope.level = Character.level;

  $scope.$on('NewLevel', function(){
    $scope.level = Character.level;
    $scope.$apply();
  });

  $scope.$on('CharXpChange', function(){
    $scope.xp = Character.experience;
    $scope.maxXp = Character.levelMaxXP();
    $scope.$apply();
  });
};

// TODO: This is the experience bar, we probably need a mainController to fire various events depending on the ticks and actions in progress
var ProgressDemoCtrl = function ($scope, Character) {
  $scope.max = 100;
  $scope.progress = 0;
  $scope.lastLevelMax = 0;

// TODO: change this to a reaction on the tick event.
  $scope.tick = function() {
    Character.addXp(Character.level*10);
    $scope.progress = (((Character.experience - $scope.lastLevelMax)*100)/(Character.levelMaxXP()-$scope.lastLevelMax));

    if(Character.experience > Character.levelMaxXP()) {
      $scope.lastLevelMax = Character.levelMaxXP();
      Character.levelup();
      $scope.progress = 0;
    }
    console.log($scope.progress+'/'+$scope.max+','+Character.level);
    // apply change to the view
    $scope.$apply();
  };
  clock.callbacks.push($scope.tick);

};
<commit_msg>Refine xp progress<commit_after>var module = angular.module('arpege', ['ui.bootstrap']);

// General clock to fire various events
// TODO: this could be a service broadcasting the tick event
var clock = {
    refresh: 1000,
    elapsedtime: 0,
    // callbacks to be called on each tick
    callbacks: [],
    tick: function() {
      clock.elapsedtime += clock.refresh;
      // Call the callbacks so they will do their things
      for(var i = 0; i<clock.callbacks.length; i++) {
        clock.callbacks[i]();
      }
    }
};

setInterval('clock.tick()', clock.refresh);

module.service('Character', function($rootScope){
  this.level = 1;
  this.experience = 0;

  this.levelup = function() {
    this.level += 1;
    console.log('new level'+this.level);
    $rootScope.$broadcast('NewLevel');
  };

  this.addXp = function(xp) {
    this.experience += xp;
    $rootScope.$broadcast('CharXpChange');
  };

  this.levelMaxXP = function() {
    return this.level*100+((this.level*this.level)*10);
  };

});

// We will probably need a CharacterController to display things like XP,
// Health, Level
var LevelCtrl = function($scope, Character) {
  $scope.level = Character.level;

  $scope.$on('NewLevel', function(){
    $scope.level = Character.level;
    $scope.$apply();
  });

  $scope.$on('CharXpChange', function(){
    $scope.xp = Character.experience;
    $scope.maxXp = Character.levelMaxXP();
    $scope.$apply();
  });
};

// TODO: This is the experience bar, we probably need a mainController to fire various events depending on the ticks and actions in progress
var ProgressDemoCtrl = function ($scope, Character) {
  $scope.max = 100;
  $scope.progress = 0;
  $scope.lastLevelMax = 0;

// TODO: change this to a reaction on the tick event.
  $scope.tick = function() {
    Character.addXp(Character.level*10);
    $scope.progress = Math.round(Number(((Character.experience - $scope.lastLevelMax)*100)/(Character.levelMaxXP()-$scope.lastLevelMax)));

    if(Character.experience > Character.levelMaxXP()) {
      $scope.lastLevelMax = Character.levelMaxXP();
      Character.levelup();
      $scope.progress = Math.round(Number(((Character.experience - $scope.lastLevelMax)*100)/(Character.levelMaxXP()-$scope.lastLevelMax)));
    }
    console.log($scope.progress+'/'+$scope.max+','+Character.level);
    // apply change to the view
    $scope.$apply();
  };
  clock.callbacks.push($scope.tick);

};
<|endoftext|>


<commit_before>console.log("running preTest");
mocha.setup("bdd");
<commit_msg>remove some mildly annoying deubgging code<commit_after>//console.log("running preTest");
mocha.setup("bdd");
<|endoftext|>


<commit_before>// ==UserScript==
// @name         UTS Timetable Generator
// @author       szdc
// @namespace    http://github.com/szdc
// @version      0.1
// @description  Timetable generator for UTS students
// @match        https://mysubjects.uts.edu.au/aplus2015/aptimetable*
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
// @copyright    2015+, szdc
// ==/UserScript==

$(document).ready(function () {
  'use strict';

  var subjects   = [],
      activities = [];

  init();

  function init() {
    // Find the table rows that hold the timetable data
    var table = $('table[cellspacing="1"] tr');

    // Process each row
    table.each(processRow);
    console.log('Subjects found: ' + subjects.length);

    // Get all activity groups.
    var activityGroups = getAllActivityGroups();
    console.log('Total activity groups: ' + activityGroups.length);

    // Get all timetable combinations
    var timetableCombinations = cartesianProductOf(activityGroups);
    console.log('Timetable combinations: ' + timetableCombinations.length);

    // Get all valid timetable combinations
    var validTimetables = timetableCombinations.filter(Timetable.isValid);
    console.log('Valid timetables: ' + validTimetables.length);
  }

  /**
   * Processes a timetable row.
   */
  function processRow() {
    var isSubjectHeader = $(this).find('td > a').length > 0,
        isActivityRow   = $(this).attr('bgcolor') === '#eeeeee';

    if (isSubjectHeader) {
      // New subject
      subjects.push(Subject.fromTableRow($(this)));
    } else if (isActivityRow) {
      // New activity under the latest subject
      var subject = subjects[subjects.length - 1];
      subject.addActivity(Activity.fromTableRow($(this), subject));
    }
  }

  /**
   * Gets an array of all activity groups.
   */
  function getAllActivityGroups() {
    return subjects.reduce(function (activityGroups, subject) {
      var groups = subject.getActivityGroups(),
          keys = Object.keys(groups);

      keys.forEach(function (key) {
        activityGroups.push(groups[key]);
      });

      return activityGroups;
    }, []);
  }

  /**
   * Returns the cartesian product of N arrays.
   */
  function cartesianProductOf(arr) {
    return arr.reduce(function(a, b) {
      var ret = [];
      a.forEach(function(a) {
        b.forEach(function(b) {
          ret.push(a.concat([b]));
        });
      });
      return ret;
    }, [[]]);
  }
});

/**
 * Represents a UTS subject.
 */
function Subject(name, code, semester) {
  if (arguments.length < 3) {
    throw new Error('Too few arguments supplied to create the Subject object.');
  }

  var activityGroups = {};

  /**
   * Adds an activity.
   */
  function addActivity(activity) {
    var type = activity.getType(),
        activities = activityGroups[type];
    if (typeof activityGroups[type] === 'undefined') {
      activityGroups[type] = [];
    }

    var existingActivity = getExistingActivity(activityGroups[type], activity);
    if (existingActivity) {
      existingActivity.addNumbers(activity.getNumbers());
    } else {
      activityGroups[type].push(activity);
    }
  }

  /**
   * Retrieves an activity from the array if it matches the
   * activity given.
   */
  function getExistingActivity(existingActivities, activity) {
    for (var i = 0; i < existingActivities.length; i++) {
      var existingActivity = existingActivities[i];
      if (existingActivity.matches(activity)) {
        return existingActivity;
      }
    }
    return null;
  }

  return {
    addActivity: addActivity,
    getActivityGroups: function () { return activityGroups; },
    getCode: function () { return code; }
  };
}

/**
 * Creates a new Subject object from a table row.
 */
Subject.fromTableRow = function (row) {
  var content = row.find('b:first');

  var name     = content.text().substr(content.text().indexOf(':') + 1).trim(),
      code     = content.children('a').attr('href').match(/\d+/)[0],
      semester = /AUT/.test(content.text()) ? 'autumn' : 'spring';

  return new Subject(name, code, semester);
};

/**
 * Represents a UTS subject activity.
 */
function Activity(type, numbers, day, startTime, duration, finishTime, subject) {
  if (arguments.length < 5) {
    throw new Error('Too few arguments supplied to create the Activity object.');
  }

  /**
   * Determines if two activities clash.
   */
  function hasTimeClashWith(activity) {
    var timeClashExists = startTime < activity.getFinishTime() && finishTime > activity.getStartTime();
    return timeClashExists;
  }

  /**
   * Determines if two activities are essentially identical.
   */
  function matches(activity) {
    return type === activity.getType() && day === activity.getDay() &&
      startTime === activity.getStartTime() && finishTime === activity.getFinishTime() &&
      subject === activity.getSubject();
  }

  /**
   * Appends activity numbers to the numbers array.
   */
  function addNumbers(numbersArray) {
    numbers = numbers.concat(numbersArray);
  }

  function toString() {
    return day + ' ' + startTime + '-' + finishTime + ': ' + subject.getCode() + ' ' + type + ' ' + numbers.join(',') + ' (' + duration + ')';
  }

  return {
    hasTimeClashWith: hasTimeClashWith,
    getStartTime: function () { return startTime; },
    getFinishTime: function () { return finishTime; },
    getType: function () { return type; },
    getNumbers: function () { return numbers; },
    getDay: function () { return day; },
    getSubject: function () { return subject; },
    matches: matches,
    addNumbers: addNumbers,
    toString: toString
  };
}

/**
 * Creates a new Activity object from a table row.
 */
Activity.fromTableRow = function (row, subject) {
  var cells = row.children().map(function() {return this.innerHTML;});

  var type       = cells[0],
      numbers    = [cells[1]],
      day        = cells[2],
      startTime  = cells[3],
      duration   = cells[4],
      finishTime = new Date('1/1/2015 ' + startTime).addMinutes(duration).get24hrTime(),
      startTime = parseInt(startTime.replace(':', ''));

  return new Activity(type, numbers, day, startTime, duration, finishTime, subject);
};

/**
 * Compares two activities.
 */
Activity.compare = function (a, b) {
  var days = { "Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, "Sun": 6 };

  if (a.getDay() === b.getDay()) {
    return a.getStartTime() - b.getStartTime();
  } else {
    return days[a.getDay()] - days[b.getDay()];
  }
};

function Timetable() {}

/**
 * Determines if an array of activities forms a valid timetable.
 */
Timetable.isValid = function (activities) {
  var invalidTimes = {
    "Mon": [], "Tue": [], "Wed": [], "Thu": [], "Fri": [], "Sat": [], "Sun": []
  };

  var valid = activities.every(function (activity) {
    var conflicts = invalidTimes[activity.getDay()];

    if (conflicts.length === 0) {
      conflicts.push(activity);
      return true;
    }

    for (var i = 0; i < conflicts.length; i++) {
      var existingActivity = conflicts[i];
      if (activity.hasTimeClashWith(existingActivity)) {
        return false;
      }
    }
    conflicts.push(activity);
    return true;
  });

  return valid;
};

/**
 * Adds minutes to the date object.
 */
Date.prototype.addMinutes = function (minutes) {
  return new Date(this.getTime() + parseInt(minutes) * 60000);
};

/**
 * Returns the 24hr-formatted time.
 */
Date.prototype.get24hrTime = function () {
  return this.getHours() * 100 + this.getMinutes();
};

<commit_msg>Added TimetableList and Timetable objects to support filtering and better object-orientation.<commit_after>// ==UserScript==
// @name         UTS Timetable Generator
// @author       szdc
// @namespace    http://github.com/szdc
// @version      0.1
// @description  Timetable generator for UTS students
// @match        https://mysubjects.uts.edu.au/aplus2015/aptimetable*
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
// @copyright    2015+, szdc
// ==/UserScript==

$(document).ready(function () {
  'use strict';

  var subjects   = [],
      activities = [];

  init();

  function init() {
    // Find the table rows that hold the timetable data
    var table = $('table[cellspacing="1"] tr');

    // Process each row
    table.each(processRow);
    console.log('Subjects found: ' + subjects.length);

    // Get all activity groups.
    var activityGroups = getAllActivityGroups();
    console.log('Total activity groups: ' + activityGroups.length);

    // Get all timetable combinations
    var timetableCombinations = cartesianProductOf(activityGroups);
    timetableCombinations = timetableCombinations.map(function (timetable) {
      return new Timetable(timetable);
    });
    console.log('Timetable combinations: ' + timetableCombinations.length);

    var timetableList = new TimetableList(timetableCombinations);
  }

  /**
   * Processes a timetable row.
   */
  function processRow() {
    var isSubjectHeader = $(this).find('td > a').length > 0,
        isActivityRow   = $(this).attr('bgcolor') === '#eeeeee';

    if (isSubjectHeader) {
      // New subject
      subjects.push(Subject.fromTableRow($(this)));
    } else if (isActivityRow) {
      // New activity under the latest subject
      var subject = subjects[subjects.length - 1];
      subject.addActivity(Activity.fromTableRow($(this), subject));
    }
  }

  /**
   * Gets an array of all activity groups.
   */
  function getAllActivityGroups() {
    return subjects.reduce(function (activityGroups, subject) {
      var groups = subject.getActivityGroups(),
          keys = Object.keys(groups);

      keys.forEach(function (key) {
        activityGroups.push(groups[key]);
      });

      return activityGroups;
    }, []);
  }

  /**
   * Returns the cartesian product of N arrays.
   */
  function cartesianProductOf(arr) {
    return arr.reduce(function(a, b) {
      var ret = [];
      a.forEach(function(a) {
        b.forEach(function(b) {
          ret.push(a.concat([b]));
        });
      });
      return ret;
    }, [[]]);
  }
});

/**
 * Represents a UTS subject.
 */
function Subject(name, code, semester) {
  if (arguments.length < 3) {
    throw new Error('Too few arguments supplied to create the Subject object.');
  }

  var activityGroups = {};

  /**
   * Adds an activity.
   */
  function addActivity(activity) {
    var type = activity.getType(),
        activities = activityGroups[type];
    if (typeof activityGroups[type] === 'undefined') {
      activityGroups[type] = [];
    }

    var existingActivity = getExistingActivity(activityGroups[type], activity);
    if (existingActivity) {
      existingActivity.addNumbers(activity.getNumbers());
    } else {
      activityGroups[type].push(activity);
    }
  }

  /**
   * Retrieves an activity from the array if it matches the
   * activity given.
   */
  function getExistingActivity(existingActivities, activity) {
    for (var i = 0; i < existingActivities.length; i++) {
      var existingActivity = existingActivities[i];
      if (existingActivity.matches(activity)) {
        return existingActivity;
      }
    }
    return null;
  }

  return {
    addActivity: addActivity,
    getActivityGroups: function () { return activityGroups; },
    getCode: function () { return code; }
  };
}

/**
 * Creates a new Subject object from a table row.
 */
Subject.fromTableRow = function (row) {
  var content = row.find('b:first');

  var name     = content.text().substr(content.text().indexOf(':') + 1).trim(),
      code     = content.children('a').attr('href').match(/\d+/)[0],
      semester = /AUT/.test(content.text()) ? 'autumn' : 'spring';

  return new Subject(name, code, semester);
};

/**
 * Represents a UTS subject activity.
 */
function Activity(type, numbers, day, startTime, duration, finishTime, subject) {
  if (arguments.length < 5) {
    throw new Error('Too few arguments supplied to create the Activity object.');
  }

  /**
   * Determines if two activities clash.
   */
  function hasTimeClashWith(activity) {
    var timeClashExists = startTime < activity.getFinishTime() && finishTime > activity.getStartTime();
    return timeClashExists;
  }

  /**
   * Determines if two activities are essentially identical.
   */
  function matches(activity) {
    return type === activity.getType() && day === activity.getDay() &&
      startTime === activity.getStartTime() && finishTime === activity.getFinishTime() &&
      subject === activity.getSubject();
  }

  /**
   * Appends activity numbers to the numbers array.
   */
  function addNumbers(numbersArray) {
    numbers = numbers.concat(numbersArray);
  }

  function toString() {
    return day + ' ' + startTime + '-' + finishTime + ': ' + subject.getCode() + ' ' + type + ' ' + numbers.join(',') + ' (' + duration + ')';
  }

  return {
    hasTimeClashWith: hasTimeClashWith,
    getStartTime: function () { return startTime; },
    getFinishTime: function () { return finishTime; },
    getType: function () { return type; },
    getNumbers: function () { return numbers; },
    getDay: function () { return day; },
    getSubject: function () { return subject; },
    matches: matches,
    addNumbers: addNumbers,
    toString: toString
  };
}

/**
 * Creates a new Activity object from a table row.
 */
Activity.fromTableRow = function (row, subject) {
  var cells = row.children().map(function() {return this.innerHTML;});

  var type       = cells[0],
      numbers    = [cells[1]],
      day        = cells[2],
      startTime  = cells[3],
      duration   = cells[4],
      finishTime = new Date('1/1/2015 ' + startTime).addMinutes(duration).get24hrTime(),
      startTime = parseInt(startTime.replace(':', ''));

  return new Activity(type, numbers, day, startTime, duration, finishTime, subject);
};

/**
 * Compares two activities.
 */
Activity.compare = function (a, b) {
  var days = { "Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, "Sun": 6 };

  if (a.getDay() === b.getDay()) {
    return a.getStartTime() - b.getStartTime();
  } else {
    return days[a.getDay()] - days[b.getDay()];
  }
};

function TimetableList(timetables) {
  if (arguments.length < 1) {
    throw new Error('Too few arguments supplied to create the TimetableList object.');
  }

  // Get all valid timetable combinations
  timetables = timetables.filter(function (timetable) {
    return timetable.isValid();
  });
  console.log('Valid timetables: ' + timetables.length);

  function filterByDays(numberOfdays, exact) {
    exact = exact || false;

    return timetables.filter(function (timetable) {
      var days = timetable.getDays();

      if (exact) {
        return days.length === numberOfdays;
      } else {
        return days.length <= numberOfdays;
      }
    });
  }

  return {
    getTimetables: function () { return timetables; },
    filterByDays: filterByDays
  };
}

function Timetable(activities) {
  /**
   * Returns an array of days that the timetable spans.
   */
  function getDays() {
    return activities.reduce(function (days, activity) {
      var day = activity.getDay();

      if (days.indexOf(day) === -1) {
        days.push(day);
      }

      return days;
    }, []);
  }

  function isValid() {
    var invalidTimes = {
      "Mon": [], "Tue": [], "Wed": [], "Thu": [], "Fri": [], "Sat": [], "Sun": []
    };

    var valid = activities.every(function (activity) {
      var conflicts = invalidTimes[activity.getDay()];

      if (conflicts.length === 0) {
        conflicts.push(activity);
        return true;
      }

      for (var i = 0; i < conflicts.length; i++) {
        var existingActivity = conflicts[i];
        if (activity.hasTimeClashWith(existingActivity)) {
          return false;
        }
      }
      conflicts.push(activity);
      return true;
    });

    return valid;
  }

  function sort(compareFn) {
    activities.sort(compareFn);
  }

  return {
    getActvities: function () { return activities; },
    getDays: getDays,
    isValid: isValid,
    sort: sort
  };
}

/**
 * Adds minutes to the date object.
 */
Date.prototype.addMinutes = function (minutes) {
  return new Date(this.getTime() + parseInt(minutes) * 60000);
};

/**
 * Returns the 24hr-formatted time.
 */
Date.prototype.get24hrTime = function () {
  return this.getHours() * 100 + this.getMinutes();
};

<|endoftext|>


<commit_before>function getFormElements(form) {
	return Object.keys(form)
		.filter(key => form[key] instanceof HTMLElement)
		.map(key => form[key]);
}

function calculateScore(form, scoreMap, testProperties) {
	let formElements = getFormElements(form);

	form.score = 0;

	scoreMap.forEach(entry => {
		let regex = entry[0],
			score = entry[1];

		formElements.forEach(element => {
			testProperties.forEach(prop => {
				form.score += regex.test(element[prop]) ? score : 0
			});
		});
	});

	return form;
}

function getDomain() {
	return location.hostname;
}

function getCredentials(domain) {
	return new Promise((resolve, reject) => {
		chrome.runtime.sendMessage({ 'action': 'get', domain }, data => {
			if(data && data.props && data.props.credentials)
				resolve(data.props.credentials);
			else
				reject('No matching entry found');
		});
	});
}

function setFormData(form, credentials) {
	if(!form || !credentials)
		return;

	for(let credential in credentials) {
		let value = credentials[credential];

		if(form[credential] && value)
			form[credential].value = value;
	}
}

function autofill(form) {
	let domain = getDomain();

	return getCredentials(domain).then(setFormData.bind(null, form));
}

function formInputsObj(form, map) {
	let inputs = $(form).find('input'),
		obj = { };

	for(let name in map) {
		let typeFilter = map[name].type.map(type => `[type=${type}]`).join(','),
			regexMap = map[name].regexMap,
			nominated = inputs.filter(typeFilter), // .filter(':visible') needs some revision
			scores;

		let matches = nominated
			.get() // Convert to JavaScript Array
			.map(input => ({ 'element': input, 'score': 0 }))
			.map(input => {
				for(let prop in regexMap) {
					regexMap[prop].forEach(entry => {
						let regex = entry[0],
							score = entry[1];

						if(regex.test(input.element[prop]))
							input.score += score;
					});
				}

				return input;
			})
			.filter(input => input.score > 0)
			.sort((a, b) => b.score - a.score)
			.map(input => input.element)
			.slice(0, map[name].maxAmount || 1);

		obj[name] = $(matches);
	}

	return obj;
}<commit_msg>Function to calculate the score of an element as defined in #fa4ce3c<commit_after>function getFormElements(form) {
	return Object.keys(form)
		.filter(key => form[key] instanceof HTMLElement)
		.map(key => form[key]);
}

function elementScore(element, regexMap) {
	let score = 0;

	for(let prop in regexMap) {
		regexMap[prop].forEach(pair => {
			let regex = pair[0],
				reward = pair[1];

			if(regex.test(element[prop]))
				score += reward;
		});
	}

	return score;
}

function getAllForms() {
	return Array.from(document.forms).map(element => {
		let inputs = formInputsObj(element, rules.inputs);

		return Object.assign({ element }, inputs);
	});
}

function calculateScore(form, scoreMap, testProperties) {
	let formElements = getFormElements(form);

	form.score = 0;

	scoreMap.forEach(entry => {
		let regex = entry[0],
			score = entry[1];

		formElements.forEach(element => {
			testProperties.forEach(prop => {
				form.score += regex.test(element[prop]) ? score : 0
			});
		});
	});

	return form;
}

function getDomain() {
	return location.hostname;
}

function getCredentials(domain) {
	return new Promise((resolve, reject) => {
		chrome.runtime.sendMessage({ 'action': 'get', domain }, data => {
			if(data && data.props && data.props.credentials)
				resolve(data.props.credentials);
			else
				reject('No matching entry found');
		});
	});
}

function setFormData(form, credentials) {
	if(!form || !credentials)
		return;

	for(let credential in credentials) {
		let value = credentials[credential];

		if(form[credential] && value)
			form[credential].value = value;
	}
}

function autofill(form) {
	let domain = getDomain();

	return getCredentials(domain).then(setFormData.bind(null, form));
}

function formInputsObj(form, map) {
	let inputs = $(form).find('input'),
		obj = { };

	for(let name in map) {
		let typeFilter = map[name].type.map(type => `[type=${type}]`).join(','),
			regexMap = map[name].regexMap,
			nominated = inputs.filter(typeFilter), // .filter(':visible') needs some revision
			scores;

		let matches = nominated
			.get() // Convert to JavaScript Array
			.map(input => ({ 'element': input, 'score': 0 }))
			.map(input => {
				for(let prop in regexMap) {
					regexMap[prop].forEach(entry => {
						let regex = entry[0],
							score = entry[1];

						if(regex.test(input.element[prop]))
							input.score += score;
					});
				}

				return input;
			})
			.filter(input => input.score > 0)
			.sort((a, b) => b.score - a.score)
			.map(input => input.element)
			.slice(0, map[name].maxAmount || 1);

		obj[name] = $(matches);
	}

	return obj;
}<|endoftext|>


<commit_before>sap.ui.define([
	"sap/ui/rta/RuntimeAuthoring",
	"sap/ui/rta/plugin/Plugin",
	"sap/ui/fl/Utils",
	"sap/ui/fl/registry/Settings",
	"sap/ui/fl/write/api/PersistenceWriteAPI",
	"sap/ui/thirdparty/sinon-4"
], function(
	RuntimeAuthoring,
	Plugin,
	FlexUtils,
	FlexSettings,
	PersistenceWriteAPI,
	sinon
) {
	"use strict";

	var sandbox = sinon.sandbox.create();
	var oManifest = {
		"sap.app" : {
			applicationVersion : {
				version : "1.2.3"
			}
		}
	};

	var oMockedAppComponent = {
		getManifestEntry: function () {
			return {};
		},
		getMetadata: function () {
			return {
				getName: function () {
					return "someName";
				},
				getManifest: function () {
					return oManifest;
				}
			};
		},
		getManifest: function () {
			return oManifest;
		},
		getModel: function () {},
		getLocalId: function() {}
	};

	var Util = {
		_createStartRtaFunction: function(oRuntimeAuthoring) {
			return function() {
				return Promise.all([
					new Promise(function (fnResolve) {
						oRuntimeAuthoring.attachStart(fnResolve);
					}),
					oRuntimeAuthoring.start()
				]);
			};
		},

		_defineTestStubs: function() {
			sandbox.stub(FlexSettings, "getInstance").returns(Promise.resolve({
				isProductiveSystem: function() { return false; }
			}));
			sandbox.stub(FlexUtils, "getAppComponentForControl").returns(oMockedAppComponent);
			sandbox.stub(PersistenceWriteAPI, "getResetAndPublishInfo").resolves({
				isResetEnabled: true,
				isPublishEnabled: false
			});
		},

		startRta: function(oHorizontalLayout, aPlugins) {
			var oRuntimeAuthoring = new RuntimeAuthoring({
				rootControl: oHorizontalLayout,
				showToolbars: false
			});
			if (aPlugins && Array.isArray(aPlugins)) {
				if (!aPlugins.length) {
					aPlugins.push(new Plugin("abc"));
				}
				oRuntimeAuthoring.setPlugins(aPlugins);
			}
			Util._defineTestStubs(oRuntimeAuthoring);

			// will result in custom timer in webPageTest
			window.performance.mark("rta.start.starts");

			return oRuntimeAuthoring.start()
			.then(function() {
				var sMeasureName = "RTA start function called";
				//will result in custom timer in webPageTest
				window.performance.mark("rta.start.ends");
				window.performance.measure(sMeasureName, "rta.start.starts", "rta.start.ends");
				sap.ui.rta.startTime = window.performance.getEntriesByName(sMeasureName)[0].duration;
				jQuery.sap.log.info(sMeasureName, sap.ui.rta.startTime + "ms");
				//visual change at the end
				var oOverlay = sap.ui.dt.OverlayRegistry.getOverlay(oHorizontalLayout);
				oOverlay.setSelected(true);
			})
			.then(function() {
				sandbox.restore();
			});
		},

		startRtaWithoutStretch: function(oRootControl) {
			var oRuntimeAuthoring = new RuntimeAuthoring({
				rootControl: oRootControl
			});
			var mPlugins = oRuntimeAuthoring.getDefaultPlugins();
			delete mPlugins["stretch"];
			oRuntimeAuthoring.setPlugins(mPlugins);

			Util._defineTestStubs(oRuntimeAuthoring);

			// will result in custom timer in webPageTest
			window.performance.mark("rta.start.starts");

			return oRuntimeAuthoring.start()
			.then(function() {
				var sMeasureName = "RTA start function called";
				//will result in custom timer in webPageTest
				window.performance.mark("rta.start.ends");
				window.performance.measure(sMeasureName, "rta.start.starts", "rta.start.ends");
				sap.ui.rta.startTime = window.performance.getEntriesByName(sMeasureName)[0].duration;
				jQuery.sap.log.info(sMeasureName, sap.ui.rta.startTime + "ms");
				//visual change at the end
				var oOverlay = sap.ui.dt.OverlayRegistry.getOverlay(oRootControl);
				oOverlay.setSelected(true);
			})
			.then(function() {
				sandbox.restore();
			});
		},

		startRtaConstructorOnly: function(oHorizontalLayout) {
			var iRtaStartCounter = 1000;
			var sMeasureName = "RTA init function called " + iRtaStartCounter + " times";
			window.performance.clearMeasures();

			// will result in custom timer in webPageTest
			window.performance.mark("rta.init.starts");

			for (var i = 0; i < iRtaStartCounter; i++) {
				/* eslint no-new: 0 */
				new RuntimeAuthoring({
					rootControl : oHorizontalLayout
				});
			}

			//will result in custom timer in webPageTest
			window.performance.mark("rta.init.ends");
			window.performance.measure(sMeasureName, "rta.init.starts", "rta.init.ends");
			sap.ui.rta.creationTime = window.performance.getEntriesByName(sMeasureName)[0].duration;
			jQuery.sap.log.info(sMeasureName, sap.ui.rta.creationTime + "ms");
		}
	};

	window.startRta = Util.startRta;
	window.startRtaConstructorOnly = Util.startRtaConstructorOnly;

	return Util;
}, true);
<commit_msg>[FIX] sap.ui.rta - removed warning on start rta in performance test<commit_after>sap.ui.define([
	"sap/ui/rta/RuntimeAuthoring",
	"sap/ui/rta/plugin/Plugin",
	"sap/ui/fl/Utils",
	"sap/ui/fl/registry/Settings",
	"sap/ui/fl/write/api/PersistenceWriteAPI",
	"sap/ui/thirdparty/sinon-4"
], function(
	RuntimeAuthoring,
	Plugin,
	FlexUtils,
	FlexSettings,
	PersistenceWriteAPI,
	sinon
) {
	"use strict";

	var sandbox = sinon.sandbox.create();
	var oManifest = {
		"sap.app" : {
			id : "sap.ui.rta.test",
			applicationVersion : {
				version : "1.2.3"
			}
		}
	};

	var oMockedAppComponent = {
		getManifestEntry: function () {
			return {};
		},
		getMetadata: function () {
			return {
				getName: function () {
					return "someName";
				},
				getManifest: function () {
					return oManifest;
				}
			};
		},
		getManifest: function () {
			return oManifest;
		},
		getModel: function () {},
		getLocalId: function() {}
	};

	var Util = {
		_createStartRtaFunction: function(oRuntimeAuthoring) {
			return function() {
				return Promise.all([
					new Promise(function (fnResolve) {
						oRuntimeAuthoring.attachStart(fnResolve);
					}),
					oRuntimeAuthoring.start()
				]);
			};
		},

		_defineTestStubs: function() {
			sandbox.stub(FlexSettings, "getInstance").returns(Promise.resolve({
				isProductiveSystem: function() { return false; }
			}));
			sandbox.stub(FlexUtils, "getAppComponentForControl").returns(oMockedAppComponent);
			sandbox.stub(PersistenceWriteAPI, "getResetAndPublishInfo").resolves({
				isResetEnabled: true,
				isPublishEnabled: false
			});
		},

		startRta: function(oHorizontalLayout, aPlugins) {
			var oRuntimeAuthoring = new RuntimeAuthoring({
				rootControl: oHorizontalLayout,
				showToolbars: false
			});
			if (aPlugins && Array.isArray(aPlugins)) {
				if (!aPlugins.length) {
					aPlugins.push(new Plugin("abc"));
				}
				oRuntimeAuthoring.setPlugins(aPlugins);
			}
			Util._defineTestStubs(oRuntimeAuthoring);

			// will result in custom timer in webPageTest
			window.performance.mark("rta.start.starts");

			return oRuntimeAuthoring.start()
			.then(function() {
				var sMeasureName = "RTA start function called";
				//will result in custom timer in webPageTest
				window.performance.mark("rta.start.ends");
				window.performance.measure(sMeasureName, "rta.start.starts", "rta.start.ends");
				sap.ui.rta.startTime = window.performance.getEntriesByName(sMeasureName)[0].duration;
				jQuery.sap.log.info(sMeasureName, sap.ui.rta.startTime + "ms");
				//visual change at the end
				var oOverlay = sap.ui.dt.OverlayRegistry.getOverlay(oHorizontalLayout);
				oOverlay.setSelected(true);
			})
			.then(function() {
				sandbox.restore();
			});
		},

		startRtaWithoutStretch: function(oRootControl) {
			var oRuntimeAuthoring = new RuntimeAuthoring({
				rootControl: oRootControl
			});
			var mPlugins = oRuntimeAuthoring.getDefaultPlugins();
			delete mPlugins["stretch"];
			oRuntimeAuthoring.setPlugins(mPlugins);

			Util._defineTestStubs(oRuntimeAuthoring);

			// will result in custom timer in webPageTest
			window.performance.mark("rta.start.starts");

			return oRuntimeAuthoring.start()
			.then(function() {
				var sMeasureName = "RTA start function called";
				//will result in custom timer in webPageTest
				window.performance.mark("rta.start.ends");
				window.performance.measure(sMeasureName, "rta.start.starts", "rta.start.ends");
				sap.ui.rta.startTime = window.performance.getEntriesByName(sMeasureName)[0].duration;
				jQuery.sap.log.info(sMeasureName, sap.ui.rta.startTime + "ms");
				//visual change at the end
				var oOverlay = sap.ui.dt.OverlayRegistry.getOverlay(oRootControl);
				oOverlay.setSelected(true);
			})
			.then(function() {
				sandbox.restore();
			});
		},

		startRtaConstructorOnly: function(oHorizontalLayout) {
			var iRtaStartCounter = 1000;
			var sMeasureName = "RTA init function called " + iRtaStartCounter + " times";
			window.performance.clearMeasures();

			// will result in custom timer in webPageTest
			window.performance.mark("rta.init.starts");

			for (var i = 0; i < iRtaStartCounter; i++) {
				/* eslint no-new: 0 */
				new RuntimeAuthoring({
					rootControl : oHorizontalLayout
				});
			}

			//will result in custom timer in webPageTest
			window.performance.mark("rta.init.ends");
			window.performance.measure(sMeasureName, "rta.init.starts", "rta.init.ends");
			sap.ui.rta.creationTime = window.performance.getEntriesByName(sMeasureName)[0].duration;
			jQuery.sap.log.info(sMeasureName, sap.ui.rta.creationTime + "ms");
		}
	};

	window.startRta = Util.startRta;
	window.startRtaConstructorOnly = Util.startRtaConstructorOnly;

	return Util;
}, true);
<|endoftext|>


<commit_before>var _ = require('lodash');
var bodyParser = require('body-parser');
var express = require('express');
var fs = require('fs');

var app = express();

var port = 8088;

var router = express.Router();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
	res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
	next();
});

router.get('/', function(req, res) {
	console.log('GET: /');
	res.sendStatus(200);
});

router.get('/patient', function(req, res) {
	console.log('GET: /patient');

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		res.json(JSON.parse(data));
	});
});

router.get('/patient/:id', function(req, res) {
	console.log(`GET: /patient/${req.params.id}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		var patient = _.find(patients, patient => patient.id == req.params.id);

		res.json(patient);
	});
});

router.post('/patient/', function(req, res) {
	console.log(`POST: /patient/${JSON.stringify(req.body)}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		patients.push(req.body);

		fs.writeFile('./data/patients.json', JSON.stringify(patients));

		res.sendStatus(200);
	});
});

router.delete('/patient/:id', function(req, res) {
	console.log(`DELETE: /patient/${req.params.id}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		_.remove(patients, patient => patient.id == req.params.id);

		fs.writeFile('./data/patients.json', JSON.stringify(patients));

		res.sendStatus(200);
	});

});

router.get('/product', function(req, res) {
	console.log('GET: /product');

    fs.readFile('./data/products.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		res.json(JSON.parse(data));
	});
});

router.post('/patient/:id/menu', function(req, res) {
	console.log(`POST: /patient/${req.params.id}/menu`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		var patient = _.find(patients, patient => patient.id == req.params.id);

		patient.menus.push(req.body);

		fs.writeFile('./data/patients.json', JSON.stringify(patients));

		res.sendStatus(200);
	});
});

app.use('/api', router);

app.listen(port);
console.log('Api is running on port: ' + port);<commit_msg>Api for getting patient menu.<commit_after>var _ = require('lodash');
var bodyParser = require('body-parser');
var express = require('express');
var fs = require('fs');

var app = express();

var port = 8088;

var router = express.Router();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
	res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
	next();
});

router.get('/', function(req, res) {
	console.log('GET: /');
	res.sendStatus(200);
});

router.get('/patient', function(req, res) {
	console.log('GET: /patient');

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		res.json(JSON.parse(data));
	});
});

router.get('/patient/:id', function(req, res) {
	console.log(`GET: /patient/${req.params.id}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		var patient = _.find(patients, patient => patient.id == req.params.id);

		res.json(patient);
	});
});

router.post('/patient/', function(req, res) {
	console.log(`POST: /patient/${JSON.stringify(req.body)}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		patients.push(req.body);

		fs.writeFile('./data/patients.json', JSON.stringify(patients));

		res.sendStatus(200);
	});
});

router.delete('/patient/:id', function(req, res) {
	console.log(`DELETE: /patient/${req.params.id}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		_.remove(patients, patient => patient.id == req.params.id);

		fs.writeFile('./data/patients.json', JSON.stringify(patients));

		res.sendStatus(200);
	});

});

router.get('/product', function(req, res) {
	console.log('GET: /product');

    fs.readFile('./data/products.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		res.json(JSON.parse(data));
	});
});

router.post('/patient/:id/menu', function(req, res) {
	console.log(`POST: /patient/${req.params.id}/menu`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		var patient = _.find(patients, patient => patient.id == req.params.id);

		patient.menus.push(req.body);

		fs.writeFile('./data/patients.json', JSON.stringify(patients));

		res.sendStatus(200);
	});
});

router.get('/patient/:patientId/menu/:menuId', function(req, res) {
	console.log(`GET: /patient/${req.params.patientId}/menu/${req.params.menuId}`);

	fs.readFile('./data/patients.json', 'utf8', function (err, data) {
		if(err) {
			console.log(err);
		}

		var patients = JSON.parse(data);

		var patient = _.find(patients, patient => patient.id == req.params.patientId);

		var menu = _.find(patient.menus, menu => menu.id == req.params.menuId);

		res.json(menu);
	});
});

app.use('/api', router);

app.listen(port);
console.log('Api is running on port: ' + port);<|endoftext|>


<commit_before>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

/**
 * @class The application running and listening on a specific port.
 *
 * @extends BaseApplication
 *
 * @param {Object} options Options to specify the behaviour
 * @param {Number} options.port The port, which should be used when launching the application server.
 *
 * @since 0.1
 * @author DracoBlue
 */
ServerApplication = function(options) {
    this.setOptions(options);

    /**
     * The Http-Server listening for new connections.
     *
     * @private
     */
    this.server = null;
};

process.mixin(true, ServerApplication.prototype, BaseApplication.prototype);

/**
 * Runs the application.
 */
ServerApplication.prototype.run = function() {
    var http = require("http");

    this.server = http.createServer(function(req, res) {
        var context = {
            status: 200,
            headers: {
                'Content-Type': 'text/plain'
            }
        };

        ContextToolkit.applyRequestHeaders(context, req.headers);

        var response = null;

        try {
            response = BaseApplication.executePath(req.uri.full.substr(1), context);
        } catch (e) {
            context.status = 404;
            var sys = require("sys");
            response = "Page not found!" + sys.inspect(e);
        }

        res.sendHeader(context.status, context.headers);
        res.sendBody(response);

        res.finish();
    });

    this.server.listen(this.options["port"]);
};<commit_msg>Also fetching the message body, if the request is not GET.<commit_after>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

/**
 * @class The application running and listening on a specific port.
 *
 * @extends BaseApplication
 *
 * @param {Object} options Options to specify the behaviour
 * @param {Number} options.port The port, which should be used when launching the application server.
 *
 * @since 0.1
 * @author DracoBlue
 */
ServerApplication = function(options) {
    this.setOptions(options);

    /**
     * The Http-Server listening for new connections.
     *
     * @private
     */
    this.server = null;
};

process.mixin(true, ServerApplication.prototype, BaseApplication.prototype);

/**
 * Runs the application.
 */
ServerApplication.prototype.run = function() {
    var http = require("http");

    var finishRequest = function(req, res, body) {
        var context = {
            status: 200,
            headers: {
                'Content-Type': 'text/plain'
            }
        };

        ContextToolkit.applyRequestHeaders(context, req.headers);

        var response = null;

        try {
            response = BaseApplication.executePath(req.uri.full.substr(1), context);
        } catch (e) {
            context.status = 404;
            var sys = require("sys");
            response = "Page not found!" + sys.inspect(e);
        }

        res.sendHeader(context.status, context.headers);
        res.sendBody(response);

        res.finish();
    };

    this.server = http.createServer(function(req, res, body) {
        if (req.method == "GET") {
            finishRequest(req, res);
        }

        var body = [];

        req.addListener("body", function(content) {
            if (content !== null) {
                body.push(content);
            }
        });

        req.addListener("complete",  function() {
            finishRequest(req, res, body.join());
        });
    });

    this.server.listen(this.options["port"]);
};
<|endoftext|>


<commit_before>var path = require('path');
var extend = require('extend');
var certPath = path.join(process.env.programdata, '/Qlik/Sense/Repository/Exported Certificates/.Local Certificates');

var logPath = path.join(__dirname,'/../log/');
var logFile = logPath + 'QMCUtilities.log';

var globalHostname='localhost';
var friendlyHostname;
var certPathBackup = "f:/my documents/_git/qliksenseqmcutility/certs";

if(certPathBackup !== undefined)
{
	certPath = certPathBackup;
}

var config = {
    certificates: {
		certPath: certPath,
		client: path.resolve(certPath, 'client.pem'),
		client_key: path.resolve(certPath,'client_key.pem'),
		server: path.resolve(certPath, 'server.pem'),
		server_key: path.resolve(certPath, 'server_key.pem'),
		root: path.resolve(certPath,'root.pem')
	},
    logging: {
		logPath: logPath,
		logFile: logFile,
		logLevel: 'info'
	},
    thisServer: {
        port: 9945,
        hostname: friendlyHostname !== undefined ? friendlyHostname : globalHostname,
        routePath: path.join(__dirname, '/../routes/'),
		publicPath: path.join(__dirname, '/../public/'),
        bowerPath: path.join(__dirname, '/../bower_components/'),
        dataPath: path.join(__dirname, '/../data/'),
		appPath: path.join(__dirname, '/../app/'),
		pluginPath: path.join(__dirname, '/../plugins/')
    },
	qrs: {
		hostname: friendlyHostname !== undefined ? friendlyHostname : globalHostname
	}
}

module.exports = config;<commit_msg>removed certPath backup location<commit_after>var path = require('path');
var extend = require('extend');
var certPath = path.join(process.env.programdata, '/Qlik/Sense/Repository/Exported Certificates/.Local Certificates');

var logPath = path.join(__dirname,'/../log/');
var logFile = logPath + 'QMCUtilities.log';

var globalHostname='localhost';
var friendlyHostname;
var certPathBackup;

if(certPathBackup !== undefined)
{
	certPath = certPathBackup;
}

var config = {
    certificates: {
		certPath: certPath,
		client: path.resolve(certPath, 'client.pem'),
		client_key: path.resolve(certPath,'client_key.pem'),
		server: path.resolve(certPath, 'server.pem'),
		server_key: path.resolve(certPath, 'server_key.pem'),
		root: path.resolve(certPath,'root.pem')
	},
    logging: {
		logPath: logPath,
		logFile: logFile,
		logLevel: 'info'
	},
    thisServer: {
        port: 9945,
        hostname: friendlyHostname !== undefined ? friendlyHostname : globalHostname,
        routePath: path.join(__dirname, '/../routes/'),
		publicPath: path.join(__dirname, '/../public/'),
        bowerPath: path.join(__dirname, '/../bower_components/'),
        dataPath: path.join(__dirname, '/../data/'),
		appPath: path.join(__dirname, '/../app/'),
		pluginPath: path.join(__dirname, '/../plugins/')
    },
	qrs: {
		hostname: friendlyHostname !== undefined ? friendlyHostname : globalHostname
	}
}

module.exports = config;<|endoftext|>


<commit_before>/****************************************
 *     PENN STATE DIRECTORY API         *
 ****************************************/
(function() {

    var express = require('express');
    var app = express();
    var request = require('request');
    var querystring = require('querystring');
    var cheerio = require('cheerio');

    /**
     * psd-api namespace
     *
     */
    var psd = function(options) {
        var pub = {};
        var priv = {};
        /* Search configuration */
        priv.config = {
            year: "" // student year --> undergraduate
        };

        /* Selectors used for searching HTML */
        priv.selectors = {
            matches: "b", // the number of matches for each student
            desc: "th", // the descriptions of the student such as name,email,..etc
            data: "td" // the data for the descriptions
        };

        /* Generates new query object for the form */
        priv.newQuery = function(firstName, lastName, userId, email) {
            return {
                'cn': firstName,
                'sn': lastName,
                'userid': userId,
                'email': email
            };
        };
        /* Penn State Directory link for scraping */
        var dirLink = 'http://www.work.psu.edu/cgi-bin/ldap/ldap_query.cgi';

        /* Validates the passed in parameter options */
        priv.validateOptions = function(str) {
            return /^[a-zA-Z]+$/.test(str);
        };
        priv.studentInfo = {};

        /* Gets the students information passed in as options */
        priv.getStudentInfo = function() {
            /* Determines if the option parameter is an object */
            if (typeof options === "object") {
                /* Checks every value in the options object and Incase the string contains non-alphabet characters */
                for (var optKey in options) {
                    if ((typeof options[optKey] != "string") || (priv.validateOptions(options[optKey]) === false)) {
                        throw new Error("Invalid Object format!");
                    }
                }
                Object.assign(priv.studentInfo, options);
            }

            /* Checks if the passed in parameter is a string to initialize the studentInfo object */
            else if (typeof options === "string") {
                var input = options.split(" ");
                if (input.length === 2) {
                    priv.studentInfo.firstName = input[0];
                    priv.studentInfo.lastName = input[1];
                }
                else priv.studentInfo.firstName = input[0];
            }
            console.log(priv.studentInfo);
        }();
        /* Form object that contains the form data that will be sent in the post request */
        var form = {
            data: priv.newQuery(priv.studentInfo.firstName, priv.studentInfo.lastName, "", "")
        };
        var stringFormData = querystring.stringify(form.data);
        var contentLength = stringFormData.length;

        /* Request options that contain the appropriate request headers, url, body, and method for sending the post request */
        priv.reqOptions = {
            headers: {
                'Content-Length': contentLength,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            url: dirLink,
            body: stringFormData,
            method: 'POST'
        };

        priv.student = {};
        priv.desc = [];
        priv.data = [];
        /* Removes all line breaks in the data retrieved */
        priv.removeLinBr = function(arr) {
            for(var str in arr){
                arr[str] = arr[str].replace(/\n+/g, '');
            }
        };
        /* Callback that executes after the student information is returned */
        var callback = function(err, res, html) {
            if (err) {
                throw new Error('Error in retrieving student informaton');
            }

            /* Library used to parse html  */
            var $ = cheerio.load(res.body);

            /* Finds if there is a match */
            if ($(priv.selectors.matches).text().indexOf("0 matches", 0) == 0) {
                console.error("Student was not found!");
            }
            else {
                /* Queries the student page for the table headers and table data */
                $(priv.selectors.desc).each(function() {
                    priv.desc.push($(this).text());
                });

                $(priv.selectors.data).each(function() {
                    priv.data.push($(this).text());
                });

                priv.desc.shift();
                priv.removeLinBr(priv.desc);
                priv.removeLinBr(priv.data);
                console.log(priv.desc);
                console.log(priv.data);
            }
        };

        /* Sends the request  */
        request(priv.reqOptions, callback);
    };

    /* Starts the psd-api */
    psd({
        firstName: "Hozaifa",
        lastName: "Abdalla"
    });

    app.listen(process.env.PORT, process.env.IP);
}).call(this);
<commit_msg>It works with multiple students<commit_after>/****************************************
 *     PENN STATE DIRECTORY API         *
 ****************************************/
(function() {

    var express = require('express');
    var app = express();
    var request = require('request');
    var querystring = require('querystring');
    var cheerio = require('cheerio');

    /**
     * psd-api namespace
     *
     */
    var getStudentInfo = function(options) {
        var pub = {};
        var priv = {};
        /* Search configuration */
        priv.config = {
            year: "" // student year --> undergraduate
        };

        /* Selectors used for searching HTML */
        priv.selectors = {
            matches: "b", // the number of matches for each student
            desc: "th", // the descriptions of the student such as name,email,..etc
            data: "td" // the data for the descriptions
        };

        /* Generates new query object for the form */
        priv.newQuery = function(firstName, lastName, userId, email) {
            return {
                'cn': firstName,
                'sn': lastName,
                'userid': userId,
                'email': email
            };
        };
        /* Penn State Directory link for scraping */
        var dirLink = 'http://www.work.psu.edu/cgi-bin/ldap/ldap_query.cgi';

        /* Validates the passed in parameter options */
        priv.validateOptions = function(str) {
            return /^[a-zA-Z]+$/.test(str);
        };

        priv.studentInfo = {};
        /* Initializes the students information passed in as options */
        priv.initStudentInfo = function() {
            /* Determines if the option parameter is an object */
            if (typeof options === "object") {
                /* Checks every value in the options object and Incase the string contains non-alphabet characters */
                for (var optKey in options) {
                    if ((typeof options[optKey] != "string") || (priv.validateOptions(options[optKey]) === false)) {
                        throw new Error("Invalid Object format!");
                    }
                }
                Object.assign(priv.studentInfo, options);
            }

            /* Checks if the passed in parameter is a string to initialize the studentInfo object */
            else if (typeof options === "string") {
                var input = options.split(" ");
                if (input.length === 2) {
                    priv.studentInfo.firstName = input[0];
                    priv.studentInfo.lastName = input[1];
                }
                else priv.studentInfo.firstName = input[0];
            }
        }();
        /* Form object that contains the form data that will be sent in the post request */
        var form = {
            data: priv.newQuery(priv.studentInfo.firstName, priv.studentInfo.lastName, "", "")
        };
        var stringFormData = querystring.stringify(form.data);
        var contentLength = stringFormData.length;

        /* Request options that contain the appropriate request headers, url, body, and method for sending the post request */
        priv.reqOptions = {
            headers: {
                'Content-Length': contentLength,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            url: dirLink,
            body: stringFormData,
            method: 'POST'
        };

        priv.student = {};
        priv.desc = [];
        priv.data = [];
        /* Removes all line breaks in the data retrieved */
        priv.removeLinBr = function(arr) {
            for (var str in arr) {
                arr[str] = arr[str].replace(/\n+/g, '');
            }
        };
        /* Callback that executes after the student information is returned */
        var callback = function(err, res, html) {
            if (err) {
                throw new Error('Error in retrieving student informaton');
            }

            /* Library used to parse html  */
            var $ = cheerio.load(res.body);

            /* Finds if there is a match */
            if ($(priv.selectors.matches).text().indexOf("0 matches", 0) == 0) {
                console.error("Student was not found!");
            }
            else {
                /* Queries the student page for the table headers and table data */
                $(priv.selectors.desc).each(function() {
                    priv.desc.push($(this).text());
                });

                $(priv.selectors.data).each(function() {
                    priv.data.push($(this).text());
                });
                // console.log(html);
                priv.desc.shift();
                priv.removeLinBr(priv.desc);
                priv.removeLinBr(priv.data);
                // console.log(priv.desc);
                console.log(priv.data);
            }

        };

        /* Sends the request  */
        request(priv.reqOptions, callback);
    };

    /* Allows you to pass in array of students for searching */
    var psd = function(input) {
        if (Array.isArray(input)) {
            for (var student in input) {
                console.log("student is " + input[student]);
                getStudentInfo(input[student]);
            };
        }
        else if (typeof input === 'object') {
            getStudentInfo(input);
        }
        else if (typeof input === 'string') {
            getStudentInfo(input);
        }
    };
    /* Starts the psd-api */
    psd([{
        firstName: "Hozaifa",
        lastName: "Abdalla"
    }, {
        firstName: "Yehya",
        lastName: "Awad"
    },{
        firstName: "Kenneth",
        lastName: "Schnall"
    }]);

    app.listen(process.env.PORT, process.env.IP);
}).call(this);
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const he = require('he');

const app = require('../app');
const vex = require('../vex');
const dbinfo = require('../dbinfo');

const db = app.db;
const addFooter = app.addFooter;
const getTeamId = vex.getTeamId;
const validTeamId = vex.validTeamId;
const getTeam = vex.getTeam;
const decodeProgram = dbinfo.decodeProgram;
const decodeSeason = dbinfo.decodeSeason;
const decodeSeasonUrl = dbinfo.decodeSeasonUrl;

const emojiToRegex = {
	'🥇': /^((?:Excellence Award)|(?:Tournament Champions)|(?:(?:Robot|Programming) Skills Winner))/,
	'🥈': /^((?:Tournament Finalists)|(?:(?:Robot|Programming) Skills Finalist))/,
	'🥉': /^((?:Tournament Semifinalists)|(?:(?:Robot|Programming) Skills Third Place))/,
	'🏅': /^(.+?)(?=\s+\(|$)/
};

const awardsOmitted = '\n**[Older awards omitted.]**';

module.exports = async (message, args) => {
	let teamId = getTeamId(message, args);
	if (validTeamId(teamId)) {
		try {
			let team = await getTeam(teamId);
			team = team[0];
			if (team) {
				teamId = team._id.id;
				const prog = isNaN(teamId.charAt(0)) ? 4 : 1;
				try {
					const awards = await db.collection('awards').aggregate()
						.match({'_id.team': {prog: prog, id: teamId}})
						.lookup({from: 'events', localField: '_id.event', foreignField: '_id', as: 'events'})
						.project({sku: '$_id.event', name: '$_id.name', event: {$arrayElemAt: ['$events', 0]}})
						.sort({'event.season': -1, 'event.end': -1, sku: -1})
						.project({sku: 1, name: 1, event: '$event.name', season: '$event.season'}).toArray();
					if (awards.length) {
						const descriptionHeader = `**${awards.length} Award${awards.length === 1 ? '' : 's'}**`;
						const eventsBySeason = {};
						const seasonHeaders = {};
						let sku;
						let event;
						let season = awards[0].season;
						let awardCount = 0;

						for (let i = 0; i < awards.length; i++) {
							award = awards[i];
							if (award.sku !== sku) {
								if (event) {
									if (eventsBySeason.hasOwnProperty(season)) {
										eventsBySeason[season].push(event);
									} else {
										eventsBySeason[season] = [event];
									}
								}
								event = `\n[${he.decode(award.event)}](https://vexdb.io/events/view/${award.sku}?t=awards)`;
								sku = award.sku;
							}
							let awardEmoji = '🏅';
							let awardName = award.name;

							for (let [emoji, regex] of Object.entries(emojiToRegex)) {
								let matches = awardName.match(regex);
								if (matches) {
									awardEmoji = emoji;
									awardName = matches[0];
									break;
								}
							}
							event += `\n${awardEmoji}${awardName}`;

							if (award.season !== season) {
								seasonHeaders[season] = `\n***[${decodeSeason(season)}](${decodeSeasonUrl(season)})*** (${awardCount})`
								season = award.season;
								awardCount = 1;
							} else {
								awardCount++;
							}
						}
						if (eventsBySeason.hasOwnProperty(season)) {
							eventsBySeason[season].push(event);
						} else {
							eventsBySeason[season] = [event];
						}
						seasonHeaders[season] = `\n***[${decodeSeason(season)}](${decodeSeasonUrl(season)})*** (${awardCount})`

						let description = descriptionHeader;
						let atLimit = false;
						let linesRemaining = 30 - (3 + Object.keys(seasonHeaders).length);
						let charsRemaining = 2048 - (descriptionHeader.length + awardsOmitted);
						Object.values(seasonHeaders).forEach(header => charsRemaining -= header.length);

						for (let [season, header] of Object.entries(seasonHeaders)) {
							description += header;

							if (!atLimit) {
								for (let i = 0; i < eventsBySeason[season].length; i++) {
									const event = eventsBySeason[season][i];
									charsRemaining -= event.length;
									linesRemaining -= event.split('\n').length - 1;
									if (charsRemaining < 0 || linesRemaining < 0) {
										if (i) {
											description += awardsOmitted;
										}
										atLimit = true;
										break;
									}
									description += event;
								}
							}
						}
						const embed = new Discord.RichEmbed()
							.setColor('PURPLE')
							.setTitle(`${decodeProgram(team.prog)} ${teamId}`)
							.setURL(`https://vexdb.io/teams/view/${teamId}?t=awards`)
							.setDescription(description);
						try {
							const reply = await message.channel.send({embed});
							addFooter(message, embed, reply);
						} catch (err) {
							console.error(err);
						}
					} else {
						message.reply('that team has never won an award.').catch(console.error);
					}
				} catch (err) {
					console.error(err);
				}
			} else {
				message.reply('that team ID has never been registered.').catch(console.error);
			}
		} catch (err) {
			console.error(err);
		}
	} else {
		message.reply('please provide a valid team ID, such as **24B** or **BNS**.').catch(console.error);
	}
};
<commit_msg>Fixed awards.<commit_after>const Discord = require('discord.js');
const he = require('he');

const app = require('../app');
const vex = require('../vex');
const dbinfo = require('../dbinfo');

const db = app.db;
const addFooter = app.addFooter;
const getTeamId = vex.getTeamId;
const validTeamId = vex.validTeamId;
const getTeam = vex.getTeam;
const decodeProgram = dbinfo.decodeProgram;
const decodeSeason = dbinfo.decodeSeason;
const decodeSeasonUrl = dbinfo.decodeSeasonUrl;

const emojiToRegex = {
	'🥇': /^((?:Excellence Award)|(?:Tournament Champions)|(?:(?:Robot|Programming) Skills Winner))/,
	'🥈': /^((?:Tournament Finalists)|(?:(?:Robot|Programming) Skills Finalist))/,
	'🥉': /^((?:Tournament Semifinalists)|(?:(?:Robot|Programming) Skills Third Place))/,
	'🏅': /^(.+?)(?=\s+\(|$)/
};

const awardsOmitted = '\n**[Older awards omitted.]**';

module.exports = async (message, args) => {
	let teamId = getTeamId(message, args);
	if (validTeamId(teamId)) {
		try {
			let team = await getTeam(teamId);
			team = team[0];
			if (team) {
				teamId = team._id.id;
				const prog = isNaN(teamId.charAt(0)) ? 4 : 1;
				try {
					const awards = await db.collection('awards').aggregate()
						.match({'_id.team.prog': prog, '_id.team.id': teamId})
						.lookup({from: 'events', localField: '_id.event', foreignField: '_id', as: 'events'})
						.project({sku: '$_id.event', name: '$_id.name', event: {$arrayElemAt: ['$events', 0]}})
						.sort({'event.season': -1, 'event.end': -1, sku: -1})
						.project({sku: 1, name: 1, event: '$event.name', season: '$event.season'}).toArray();
					if (awards.length) {
						const descriptionHeader = `**${awards.length} Award${awards.length === 1 ? '' : 's'}**`;
						const eventsBySeason = {};
						const seasonHeaders = {};
						let sku;
						let event;
						let season = awards[0].season;
						let awardCount = 0;

						for (let i = 0; i < awards.length; i++) {
							award = awards[i];
							if (award.sku !== sku) {
								if (event) {
									if (eventsBySeason.hasOwnProperty(season)) {
										eventsBySeason[season].push(event);
									} else {
										eventsBySeason[season] = [event];
									}
								}
								event = `\n[${he.decode(award.event)}](https://vexdb.io/events/view/${award.sku}?t=awards)`;
								sku = award.sku;
							}
							let awardEmoji = '🏅';
							let awardName = award.name;

							for (let [emoji, regex] of Object.entries(emojiToRegex)) {
								let matches = awardName.match(regex);
								if (matches) {
									awardEmoji = emoji;
									awardName = matches[0];
									break;
								}
							}
							event += `\n${awardEmoji}${awardName}`;

							if (award.season !== season) {
								seasonHeaders[season] = `\n***[${decodeSeason(season)}](${decodeSeasonUrl(season)})*** (${awardCount})`
								season = award.season;
								awardCount = 1;
							} else {
								awardCount++;
							}
						}
						if (eventsBySeason.hasOwnProperty(season)) {
							eventsBySeason[season].push(event);
						} else {
							eventsBySeason[season] = [event];
						}
						seasonHeaders[season] = `\n***[${decodeSeason(season)}](${decodeSeasonUrl(season)})*** (${awardCount})`

						let description = descriptionHeader;
						let atLimit = false;
						let linesRemaining = 30 - (3 + Object.keys(seasonHeaders).length);
						let charsRemaining = 2048 - (descriptionHeader.length + awardsOmitted);
						Object.values(seasonHeaders).forEach(header => charsRemaining -= header.length);

						for (let [season, header] of Object.entries(seasonHeaders)) {
							description += header;

							if (!atLimit) {
								for (let i = 0; i < eventsBySeason[season].length; i++) {
									const event = eventsBySeason[season][i];
									charsRemaining -= event.length;
									linesRemaining -= event.split('\n').length - 1;
									if (charsRemaining < 0 || linesRemaining < 0) {
										if (i) {
											description += awardsOmitted;
										}
										atLimit = true;
										break;
									}
									description += event;
								}
							}
						}
						const embed = new Discord.RichEmbed()
							.setColor('PURPLE')
							.setTitle(`${decodeProgram(team.prog)} ${teamId}`)
							.setURL(`https://vexdb.io/teams/view/${teamId}?t=awards`)
							.setDescription(description);
						try {
							const reply = await message.channel.send({embed});
							addFooter(message, embed, reply);
						} catch (err) {
							console.error(err);
						}
					} else {
						message.reply('that team has never won an award.').catch(console.error);
					}
				} catch (err) {
					console.error(err);
				}
			} else {
				message.reply('that team ID has never been registered.').catch(console.error);
			}
		} catch (err) {
			console.error(err);
		}
	} else {
		message.reply('please provide a valid team ID, such as **24B** or **BNS**.').catch(console.error);
	}
};
<|endoftext|>