<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var timeout = randomIntFromInterval(0, max_sleep) * 1000
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    setTimeout(commit, timeout, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep) * 1000
    counter<commit_msg>Incompatible dimensions found, Cthuhlu Error 666<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var timeout = randomIntFromInterval(0, max_sleep) * 1000
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    setTimeout(commit, timeout, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep) * 1000
    counter = counter + step
    setTimeo<|endoftext|>


<commit_before>/* jslint vars: true */
/*jslint indent: 3 */
/* global moment, $  */
'use strict';

var chill = function() {

   /* intialiase the pikaday module */
   function initPikaday(locale) {
      var i18n_trad = {
         fr: {
            previousMonth : 'Mois précédent',
            nextMonth     : 'Mois suivant',
            months        : ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
            weekdays      : ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
            weekdaysShort : ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam']
         },
         nl: {
            previousMonth : 'Vorig maand',
            nextMonth     : 'Volgende maand',
            months        : ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'],
            weekdays      : ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag'],
            weekdaysShort : ['Zon','Ma','Di','Wo','Do','Vri','Zat']
         }
      };

      var pikaday_options = {
         format: 'D-M-YYYY',
         yearRange: [parseInt(moment().format('YYYY')) - 100, parseInt(moment().format('YYYY'))],
      };

      if(locale in i18n_trad) {
         pikaday_options.i18n = i18n_trad[locale];
      }

      $('.datepicker').pikaday(
         pikaday_options
      );
   }

   /* emulate the position:sticky */
   function emulateSticky() {
      var need_emulation = false;

      $('.sticky-form-buttons').each(function(i,stick_element) {
         if($(stick_element).css('position') !== 'sticky') {
            need_emulation = true;
            stick_element.init_offset_top = $(stick_element).offset().top;
         }
      });

      function emulate() {
         $('.sticky-form-buttons').each(function(i,stick_element) {
            if (($(window).scrollTop() + $(window).height()) < stick_element.init_offset_top) {
               //sticky at bottom
               $(stick_element).css('position','fixed');
               $(stick_element).css('bottom','0');
               $(stick_element).css('top','');
               $(stick_element).css('width',$(stick_element).parent().outerWidth());
            } else if (stick_element.init_offset_top < $(window).scrollTop()) {
               //sticky at top
               $(stick_element).css('position','fixed');
               $(stick_element).css('top','0');
               $(stick_element).css('bottom','');
               $(stick_element).css('width',$(stick_element).parent().outerWidth());
            } else {
               //no sticky
               $(stick_element).css('position','initial');
               $(stick_element).css('bottom','');
               $(stick_element).css('width','');
               $(stick_element).css('top','');
            }
         });
      }

      if(need_emulation) {
         $(window).scroll(function() {
            emulate();
         });

         emulate();
      }
   }

   /**
   * Protect to leave a page where the form  'form_id' has unsaved changes by displaying
   * a popup-containing a warning.
   *
   * @param{string} form_id A identification string of the form
   * @param{string} unsaved_data_message The string to display in the warning pop-up
   * @return nothing
   */
   function protectUnsavedDataForFrom(form_id, unsaved_data_message) {
      var form_submitted = false;
      var unsaved_data = false;

      $(form_id)
         .submit(function() {
            form_submitted = true;
         })
         .on('reset', function() {
            unsaved_data = false;
         });

      $.each($(form_id).find(':input'), function(i,e) {
         $(e).change(function() {
            unsaved_data = true;
         });
      });

      $(window).bind('beforeunload', function(){
         if((!form_submitted) && unsaved_data) {
            return unsaved_data_message;
         }
      });
   }

   /* Enable the following behavior : when the user change the value
   of an other field, its checkbox is checked.
   */
   function checkOtherValueOnChange() {
      $('.input-text-other-value').each(function() {
         $(this).change(function() {
            var checkbox = $(this).parent().find('input[type=checkbox][value=_other]')[0];
            $(checkbox).prop('checked', ($(this).val() !== ''));
         });
      });
   }

   return {
      initPikaday: initPikaday,
      emulateSticky: emulateSticky,
      checkOtherValueOnChange: checkOtherValueOnChange,
      protectUnsavedDataForFrom: protectUnsavedDataForFrom,
   };
} ();<commit_msg>js code for display an alert message when leaving a page containing an unsubmitted form - refs #391<commit_after>/* jslint vars: true */
/*jslint indent: 3 */
/* global moment, $  */
'use strict';

var chill = function() {

   /* intialiase the pikaday module */
   function initPikaday(locale) {
      var i18n_trad = {
         fr: {
            previousMonth : 'Mois précédent',
            nextMonth     : 'Mois suivant',
            months        : ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
            weekdays      : ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
            weekdaysShort : ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam']
         },
         nl: {
            previousMonth : 'Vorig maand',
            nextMonth     : 'Volgende maand',
            months        : ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'],
            weekdays      : ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag'],
            weekdaysShort : ['Zon','Ma','Di','Wo','Do','Vri','Zat']
         }
      };

      var pikaday_options = {
         format: 'D-M-YYYY',
         yearRange: [parseInt(moment().format('YYYY')) - 100, parseInt(moment().format('YYYY'))],
      };

      if(locale in i18n_trad) {
         pikaday_options.i18n = i18n_trad[locale];
      }

      $('.datepicker').pikaday(
         pikaday_options
      );
   }

   /* emulate the position:sticky */
   function emulateSticky() {
      var need_emulation = false;

      $('.sticky-form-buttons').each(function(i,stick_element) {
         if($(stick_element).css('position') !== 'sticky') {
            need_emulation = true;
            stick_element.init_offset_top = $(stick_element).offset().top;
         }
      });

      function emulate() {
         $('.sticky-form-buttons').each(function(i,stick_element) {
            if (($(window).scrollTop() + $(window).height()) < stick_element.init_offset_top) {
               //sticky at bottom
               $(stick_element).css('position','fixed');
               $(stick_element).css('bottom','0');
               $(stick_element).css('top','');
               $(stick_element).css('width',$(stick_element).parent().outerWidth());
            } else if (stick_element.init_offset_top < $(window).scrollTop()) {
               //sticky at top
               $(stick_element).css('position','fixed');
               $(stick_element).css('top','0');
               $(stick_element).css('bottom','');
               $(stick_element).css('width',$(stick_element).parent().outerWidth());
            } else {
               //no sticky
               $(stick_element).css('position','initial');
               $(stick_element).css('bottom','');
               $(stick_element).css('width','');
               $(stick_element).css('top','');
            }
         });
      }

      if(need_emulation) {
         $(window).scroll(function() {
            emulate();
         });

         emulate();
      }
   }

   /**
   * Display an alert message when the user wants to leave a page containing a given form
   * in a given state.
   *
   * The action of displaying the form be parametrised as :
   * - always display the alert message when leaving
   * - only display the alert message when the form contains some modified fields.
   *
   * @param{string} form_id An identification string of the form
   * @param{string} alert_message The alert message to display
   * @param{boolean} check_unsaved_data If true display the alert message only when the form
   * contains some modified fields otherwise always display the alert when leaving
   * @return nothing
   */
   function _generalDisplayAlertWhenLeavingForm(form_id, alert_message, check_unsaved_data) {
      var form_submitted = false;
      var unsaved_data = false;

      $(form_id)
         .submit(function() {
            form_submitted = true;
         })
         .on('reset', function() {
            unsaved_data = false;
         });

      $.each($(form_id).find(':input'), function(i,e) {
         $(e).change(function() {
            unsaved_data = true;
         });
      });

      $(window).bind('beforeunload', function(){
         if((!form_submitted) && (unsaved_data || !check_unsaved_data)) {
            return alert_message;
         }
      });
   }

   /**
   * Display an alert message when the user wants to leave a page containing a given
   * modified form.
   *
   * @param{string} form_id An identification string of the form
   * @param{string} alert_message The alert message to display
   * @return nothing
   */
   function displayAlertWhenLeavingModifiedForm(form_id, alert_message) {
      _generalDisplayAlertWhenLeavingForm(form_id, alert_message, true);
   }

   /**
   * Display an alert message when the user wants to leave a page containing a given
   * form that was not submitted.
   *
   * @param{string} form_id An identification string of the form
   * @param{string} alert_message The alert message to display
   * @return nothing
   */
   function displayAlertWhenLeavingUnsubmittedForm(form_id, alert_message) {
      _generalDisplayAlertWhenLeavingForm(form_id, alert_message, false);
   }

   /* Enable the following behavior : when the user change the value
   of an other field, its checkbox is checked.
   */
   function checkOtherValueOnChange() {
      $('.input-text-other-value').each(function() {
         $(this).change(function() {
            var checkbox = $(this).parent().find('input[type=checkbox][value=_other]')[0];
            $(checkbox).prop('checked', ($(this).val() !== ''));
         });
      });
   }

   return {
      initPikaday: initPikaday,
      emulateSticky: emulateSticky,
      checkOtherValueOnChange: checkOtherValueOnChange,
      displayAlertWhenLeavingModifiedForm: displayAlertWhenLeavingModifiedForm,
      displayAlertWhenLeavingUnsubmittedForm: displayAlertWhenLeavingUnsubmittedForm,
   };
} ();<|endoftext|>


<commit_before>
var express = require('express');
var app = express();
var request = require('request');
var config = require('config');
var Yelp = require('yelp');
var path = require('path');

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

var yelp = new Yelp({
	consumer_key: config.get('Yelp.consumerKey'),
	consumer_secret: config.get('Yelp.consumerSecret'),
	token: config.get('Yelp.token'),
	token_secret: config.get('Yelp.tokenSecret'),
});

app.get('/', function (req, res) {
	res.sendFile(path.join(__dirname+'/index.html'));
});

app.get('/search', function (req, res) {

	var city = req.query.city;
	var results = {
		success: true,
		error: null,
		locations: []
	};

	yelp.search({ term: 'pizza', location: city }).then(function (response) {
		var businesses = response.businesses;

		for (var i = 0; i < businesses.length; i++) {
			results.locations.push(businesses[i]);
		}

		res.send(results);
	}).catch(function (err) {
		results.success = true,
		results.error = error;
		res.send(results);
	});
});

app.listen(3000, function () {
	console.log('Example app listening on port 3000!');
});
<commit_msg>Changing port in order to work with Heroku<commit_after>
var express = require('express');
var app = express();
var request = require('request');
var config = require('config');
var Yelp = require('yelp');
var path = require('path');

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

var yelp = new Yelp({
	consumer_key: config.get('Yelp.consumerKey'),
	consumer_secret: config.get('Yelp.consumerSecret'),
	token: config.get('Yelp.token'),
	token_secret: config.get('Yelp.tokenSecret'),
});

app.get('/', function (req, res) {
	res.sendFile(path.join(__dirname+'/index.html'));
});

app.get('/search', function (req, res) {

	var city = req.query.city;
	var results = {
		success: true,
		error: null,
		locations: []
	};

	yelp.search({ term: 'pizza', location: city }).then(function (response) {
		var businesses = response.businesses;

		for (var i = 0; i < businesses.length; i++) {
			results.locations.push(businesses[i]);
		}

		res.send(results);
	}).catch(function (err) {
		results.success = true,
		results.error = error;
		res.send(results);
	});
});

app.listen(80, function () {
	console.log('Example app listening on port 80!');
});
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        expect(ioPackage.common.authors).to.exist;
        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length).to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0]).to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors).to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('Testing for set authors field in io-package skipped because template adapter');
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        expect(fileContentReadme.indexOf('## License'), 'The README.md needs to have a section ## License').not.equal(-1);
        expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## Changelog').not.equal(-1);
        expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## License').to.be.below(fileContentReadme.indexOf('## License'));
        done();
    });
});
<|endoftext|>


<commit_before>import {d3} from "nbpresent-deps";

import {ManualLayout} from "../layout/manual";
import {TreemapLayout} from "../layout/treemap";

import {Toolbar} from "../toolbar";
import {PARTS, PART_SELECT} from "../parts";

let PREFIX = [
  "-webkit-",
  "-moz-",
  "-ms-",
  "-o-",
  ""
];

export class Presenter {
  constructor(tree) {
    this.tree = tree;

    this.cellManager = this.makeCellManager();

    this.initUI();

    this.presenting = this.tree.select(["presenter", "presenting"]);
    this.current = this.tree.select(["selectedSlide"]);

    this.tree.on("update", () => this.update());
    this.presenting.on("update", () => this.present());
    this.current.on("update", () => this.update());
  }

  makeCellManager() {
    throw new Error("Not implemented");
  }

  initUI(){
    this.$ui = d3.select("body")
      .append("div")
      .classed({nbpresent_presenter: 1})
      .style({display: "none"});

    this.initToolbar();
  }

  toolbarIcons(){
    return [
      [{
        icon: "fast-backward",
        click: () => this.current.set(this.tree.get(["sortedSlides", 0]).key),
        tip: "Back to Start"
      }],
      [{
        icon: "step-backward",
        click: () => this.current.set(this.current.get() - 1),
        tip: "Previous Slide"
      }],
      [{
        icon: "step-forward",
        click: () => this.current.set(this.current.get() + 1),
        tip: "Next Slide"
      }]
    ];
  }

  initToolbar(){
    let toolbar = new Toolbar();

    toolbar
      .btnGroupClass("btn-group-vertical")
      .btnClass("btn-invert btn-lg")
      .tipOptions({container: "body", placement: "bottom"});

    // TODO: Make this overlay (Jupyter-branded Reveal Compass)
    this.$toolbar = this.$ui.append("div")
      .classed({presenter_toolbar: 1})
      .datum(this.toolbarIcons())
      .call(toolbar.update);
  }

  layoutClass(slide){
    console.log("layoutClass", slide.value.layout);
    return {
      manual: ManualLayout,
      treemap: TreemapLayout
    }[slide.value.layout || "manual"];
  }

  updateLayout(slide){
    let LayoutClass = this.layoutClass(slide);

    console.log(this.layout && this.layout.slide.key);

    if(this.layout &&
      this.layout.key() == LayoutClass.clsKey() &&
      this.layout.slide.key === slide.key
    ){
      this.layout.slide = slide;
    }else{
      this.layout = new LayoutClass(
        this.tree,
        slide,
        document.documentElement
      );
    }
    this.layout.init();
  }

  present() {
    this.current.set(null);
    this.current.set(0);
  }

  getCells() {
    return this.cellManager.getCells();
  }

  update() {
    let that = this;
    let presenting = this.presenting.get();

    this.$ui
      .style({
        "display": presenting ? "block" : "none"
      })
      .style({
        opacity: +presenting,
      });

    let slide = this.tree.get("sortedSlides")[this.current.get()];

    // TODO: handle cleanup
    // transition = this.layout && this.layout.destroy()

    if(!slide){
      return this.current.set(0);
    }

    this.updateLayout(slide);

    if(!presenting){
      return this.clean(true);
    }

    let cells = this.getCells();

    d3.selectAll(this.allPartSelect())
      .classed({nbpresent_unpresent: 1, nbpresent_present: 0});

    d3.entries(slide.value.regions)
      .filter(({value}) => value.content)
      .map((region) => {
        let {content} = region.value,
          cell = cells[content.cell];

        if(!cell){
          return;
        }

        let $el = d3.select(cell.element[0]),
          part = $el.select(PART_SELECT[content.part]);

        part
          .classed({
            nbpresent_unpresent: 0,
            nbpresent_present: 1
          })
          .each(() => that.layout.update(region, part));
      });

    this.clean();
  }

  allPartSelect(){
    return d3.entries(PART_SELECT)
      .map(({value}) => `.cell ${value}`)
      .join(", ");
  }

  clean(force){
    let that = this;

    if(force){
      d3.selectAll(this.allPartSelect())
        .classed({nbpresent_unpresent: 1, nbpresent_present: 0});
    }

    d3.selectAll(".nbpresent_unpresent")
      .call(that.layout && this.layout.clean || () => 0)
      .classed({nbpresent_unpresent: 0, nbpresent_present: 0});
  }
}
<commit_msg>unborking current slide<commit_after>import {d3} from "nbpresent-deps";

import {ManualLayout} from "../layout/manual";
import {TreemapLayout} from "../layout/treemap";

import {Toolbar} from "../toolbar";
import {PARTS, PART_SELECT} from "../parts";

let PREFIX = [
  "-webkit-",
  "-moz-",
  "-ms-",
  "-o-",
  ""
];

export class Presenter {
  constructor(tree) {
    this.tree = tree;

    this.cellManager = this.makeCellManager();

    this.initUI();

    this.presenting = this.tree.select(["presenter", "presenting"]);
    this.current = this.tree.select(["selectedSlide"]);

    this.tree.on("update", () => this.update());
    this.presenting.on("update", () => this.present());
    this.current.on("update", () => this.update());
  }

  makeCellManager() {
    throw new Error("Not implemented");
  }

  initUI(){
    this.$ui = d3.select("body")
      .append("div")
      .classed({nbpresent_presenter: 1})
      .style({display: "none"});

    this.initToolbar();
  }

  toolbarIcons(){
    let that = this;

    return [
      [{
        icon: "fast-backward",
        click: () => that.current.set(this.tree.get(["sortedSlides", 0, "key"])),
        tip: "Back to Start"
      }],
      [{
        icon: "step-backward",
        click: () => {
          let current = that.tree.get(["slides", this.current.get()]);
          this.current.set(current.prev);
        },
        tip: "Previous Slide"
      }],
      [{
        icon: "step-forward",
        click: () => {
          let slides = that.tree.get(["slides"]),
            current = slides[that.current.get()];

          d3.entries(slides).map((d)=> {
            if(d.value.prev === current.id){
              that.current.set(d.key);
            }
          });
        },
        tip: "Next Slide"
      }]
    ];
  }

  initToolbar(){
    let toolbar = new Toolbar();

    toolbar
      .btnGroupClass("btn-group-vertical")
      .btnClass("btn-invert btn-lg")
      .tipOptions({container: "body", placement: "bottom"});

    // TODO: Make this overlay (Jupyter-branded Reveal Compass)
    this.$toolbar = this.$ui.append("div")
      .classed({presenter_toolbar: 1})
      .datum(this.toolbarIcons())
      .call(toolbar.update);
  }

  layoutClass(slide){
    console.log("layoutClass", slide.value.layout);
    return {
      manual: ManualLayout,
      treemap: TreemapLayout
    }[slide.value.layout || "manual"];
  }

  updateLayout(slide){
    let LayoutClass = this.layoutClass(slide);

    console.log(this.layout && this.layout.slide.key);

    if(this.layout &&
      this.layout.key() == LayoutClass.clsKey() &&
      this.layout.slide.key === slide.key
    ){
      this.layout.slide = slide;
    }else{
      this.layout = new LayoutClass(
        this.tree,
        slide,
        document.documentElement
      );
    }
    this.layout.init();
  }

  present() {
    this.update();
  }

  getCells() {
    return this.cellManager.getCells();
  }

  update() {
    let that = this;
    let presenting = this.presenting.get();

    this.$ui
      .style({
        "display": presenting ? "block" : "none"
      })
      .style({
        opacity: +presenting,
      });

    let current = this.current.get(),
      slide = this.tree.get(["sortedSlides", (d) => d.key == current]);

    // TODO: handle cleanup
    // transition = this.layout && this.layout.destroy()

    if(!slide){
      return this.current.set(this.tree.get(["sortedSlides", 0, "key"]));
    }

    this.updateLayout(slide);

    if(!presenting){
      return this.clean(true);
    }

    let cells = this.getCells();

    d3.selectAll(this.allPartSelect())
      .classed({nbpresent_unpresent: 1, nbpresent_present: 0});

    d3.entries(slide.value.regions)
      .filter(({value}) => value.content)
      .map((region) => {
        let {content} = region.value,
          cell = cells[content.cell];

        if(!cell){
          return;
        }

        let $el = d3.select(cell.element[0]),
          part = $el.select(PART_SELECT[content.part]);

        part
          .classed({
            nbpresent_unpresent: 0,
            nbpresent_present: 1
          })
          .each(() => that.layout.update(region, part));
      });

    this.clean();
  }

  allPartSelect(){
    return d3.entries(PART_SELECT)
      .map(({value}) => `.cell ${value}`)
      .join(", ");
  }

  clean(force){
    let that = this;

    if(force){
      d3.selectAll(this.allPartSelect())
        .classed({nbpresent_unpresent: 1, nbpresent_present: 0});
    }

    d3.selectAll(".nbpresent_unpresent")
      .call(that.layout && this.layout.clean || () => 0)
      .classed({nbpresent_unpresent: 0, nbpresent_present: 0});
  }
}
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env<commit_msg>Updated the readme again<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter + step
    if (process.env.<|endoftext|>


<commit_before>var whatwedoTable = {
    /**
     * Anklickbare Tabellenzeilen
     */
    clickableRows: function() {
        $(document).on('click', '.whatwedo_table tr[data-href], .dataTable tr[data-href]', function(e) {
            var $this = $(this);

            if (!$this.closest('.whatwedo_table').hasClass('whatwedo_table__editable')) {
                if($(e.target).is('td')) {
                    window.document.location = $this.data("href");
                }
            }
        });

    },

    /**
     * current ongoing AJAX request
     */
    currentRequest: null,

    /**
     * loads updated data from the database
     * @param url
     * @param data
     * @param failCallback
     * @param method
     * @param animate
     */
    loadContent: function(url, data, failCallback, method, animate, replace, showLoad, callback) {
        if (typeof data === 'undefined') {
            data = null;
        }

        if (typeof method === 'undefined') {
            method = 'GET';
        }

        if (typeof animate === 'undefined') {
            animate = true;
        }

        if (typeof replace === 'undefined') {
            replace = true;
        }

        if (typeof showLoad === 'undefined') {
            showLoad = true;
        }

        if (typeof callback === 'undefined') {
            callback = jQuery.noop;
        }

        var $whatwedoTable = $('#whatwedo_table');

        if (showLoad) {
            $whatwedoTable.addClass('loading');
        }

        if (whatwedoTable.currentRequest !== null) {
            whatwedoTable.currentRequest.abort();
        }

        this.currentRequest = $.ajax({
            url: url,
            data: data,
            method: method
        })
            .done(function(html) {
                callback(html);

                if (!replace) {
                    return;
                }

                history.pushState({
                    'type': 'table',
                    'url': url,
                    'data': data
                }, null, url);

                $whatwedoTable.replaceWith(html);
                whatwedoTable.tableHeader();

                if (animate) {
                    $("html, body").animate({ scrollTop: $('#whatwedo_table').offset().top - 100 }, 250);
                }
            })
            .fail(failCallback)
            .always(function() {
                whatwedoTable.currentRequest = null;
            });
    },

    handleDataLoadEnabled: true,

    handleDataLoad: function(event) {
        if (!whatwedoTable.handleDataLoadEnabled) {
            return;
        }

        var href = this.getAttribute('href');
        var $this = $(this);

        event.preventDefault();

        // Bugfix for Firefox
        var additionalName = null;
        var additionalValue = null;
        var action = null;

        if ($this.prop("tagName") !== 'FORM') {
            if ($this.prop("tagName") === 'BUTTON') {
                additionalName = $this.attr('name');
                additionalValue = $this.attr('value');
            }
            if ($this.prop("tagName") === 'A') {
                action = $this.attr('href');
            } else {
                $this = $($this.parents('form'));
                action = $this.attr('action');
            }
        } else {
            if (typeof $this.attr('action') !== 'undefined') {
                action = $this.attr('action');
            }
        }

        $this.find('input[data-handle-data-load]').remove();

        if (action) {
            var formParams = {};
            $this
                .serializeArray()
                .forEach(function(item) {
                    if (formParams[item.name]) {
                        formParams[item.name] = [formParams[item.name]];
                        formParams[item.name].push(item.value)
                    } else {
                        formParams[item.name] = item.value
                    }
                });

            if (typeof additionalName !== 'undefined'
                && typeof additionalValue !== 'undefined'
                && additionalName
                && additionalValue) {
                $('<input/>')
                    .attr('type', 'hidden')
                    .attr('data-handle-data-load', 1)
                    .attr('name', additionalName)
                    .attr('value', additionalValue)
                    .appendTo($this);
                formParams[additionalName] = additionalValue;
            }

            if (typeof formParams['filter_name'] !== 'undefined') {
                $this.submit();
                return;
            }

            whatwedoTable.loadContent(action, $this.serialize(), function() {
                $this.submit();
            });
        }
        else if (typeof $this.attr('href') !== 'undefined') {
            whatwedoTable.loadContent($this.attr('href'), null, function() {
                window.location.href = $this.attr('href');
            });
        }
        else if (typeof href !== 'undefined') {
            whatwedoTable.loadContent(href, null, function() {
                window.location.href = href;
            });
        }
    },

    filters: function($table) {
        // Template
        var filterTemplate = $('#whatwedo_table__' + $table.data('identifier') + '__filters__template__block').text();

        // jQuery Elemente
        var $whatwedoTableFilters = null;

        // Functiosn
        var optionNameMatcher = /filter_([\w\d]+)\[(\d)\]\[(\d)\]/i;

        var findCurrentBlocksBlockIteratorNumber = function($blocksContainer) {
            var optionName = $blocksContainer.find('.whatwedo_table__filters__block:last select:first').attr('name');
            if (!optionNameMatcher.test(optionName)) {
                return 0;
            }
            var result = optionNameMatcher.exec(optionName);

            result = parseInt(result[3]);
            if (isNaN(result)) {
                return 0;
            }

            return result;
        };

        var findCurrentBlockIteratorNumber = function($blocksContainer) {
            var optionName = $blocksContainer.find('.whatwedo_table__filters__block:last select:first').attr('name');
            if (!optionNameMatcher.test(optionName)) {
                return 0;
            }
            var result = optionNameMatcher.exec(optionName);

            result = parseInt(result[2]);
            if (isNaN(result)) {
                return 0;
            }

            return result;
        };

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-filter-action="add-and"]', function(e) {
            e.preventDefault();
            var $this = $(this);
            var $blocksContainer = $this.closest('.whatwedo_table__filters__blocks');
            var currentBlockIteratorNumber = findCurrentBlockIteratorNumber($blocksContainer);
            var currentBlocksBlockIteratorNumber = findCurrentBlocksBlockIteratorNumber($blocksContainer);
            var block = filterTemplate
                .replace(/{iBlock}/g, currentBlockIteratorNumber.toString())
                .replace(/{i}/g, (currentBlocksBlockIteratorNumber + 1).toString());
            $blocksContainer.append(block);
        });

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-filter-action="add-or"]', function(e) {
            e.preventDefault();
            var $lastBlocksContainer = $('#whatwedo_table_' + $table.data('identifier')).find('.whatwedo_table__filters__blocks:last');
            var currentBlockIteratorNumber = findCurrentBlockIteratorNumber($lastBlocksContainer);
            var block = filterTemplate
                .replace(/{iBlock}/g, (currentBlockIteratorNumber + 1).toString())
                .replace(/{i}/g, '1');
            block = '

oder
' + block + '
';

            $lastBlocksContainer.after(block);
        });

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-filter-action="remove"]', function(e) {
            e.preventDefault();
            var $this = $(this);
            var $block = $this.closest('.whatwedo_table__filters__block');

            var $blocksContainer = $block.closest('.whatwedo_table__filters__blocks');

            $block.remove();

            if ($blocksContainer.find('.whatwedo_table__filters__block').length === 0) {
                $blocksContainer.remove();
                $('#whatwedo_table__filters').submit();
            }
        });

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-toggle="filter"]', function() {
            var $whatwedoTableFilters = $('#whatwedo_table_' + $table.data('identifier') + ' .whatwedo_table__filters');

            if ($whatwedoTableFilters.hasClass('active')) {
                $whatwedoTableFilters.slideUp();
                $whatwedoTableFilters.removeClass('active')
            } else {
                $whatwedoTableFilters.slideDown();
                $whatwedoTableFilters.addClass('active');
            }
        });

        $(document).on('change', '#whatwedo_table_' + $table.data('identifier') + ' select[name^="' + $table.data('identifier') + '_filter_column"]', function() {
            var $this = $(this);
            var $parentBlock = $this.parents('.whatwedo_table__filters_filter');
            var $choosenOption = $this.find(":selected");

            // Operator
            var $operator = $parentBlock.find('select[name^="' + $table.data('identifier') + '_filter_operator"]');
            $operator.empty();
            $.each($choosenOption.data('operator-options'), function(key, name) {
                $operator.append('<option value=' + key + '>' + name + '</option>')
            });

            // Field
            var $field = $parentBlock.find('[name^="' + $table.data('identifier') + '_filter_value"]');

            if (typeof $field.data('select2') !== 'undefined') {
                $field.select2('destroy');
            }
            var fieldName = $field.attr('name');
            var template = $choosenOption.data('value-template');
            $field.replaceWith(template.replace(/{name}/g, fieldName));
            $field = $parentBlock.find('[name^="' + $table.data('identifier') + '_filter_value"]');

            if ($field.prop('tagName') === 'SELECT'
                && typeof $field.attr('data-disable-interactive') === 'undefined') {
                if (typeof $field.attr('data-ajax-select') === 'undefined') {
                    whatwedo_select2.select2($field[0]);
                } else {
                    whatwedo_select2.ajaxSelect2($field[0]);
                }
            }
        });

        $(document).on('submit', '.whatwedo_table__save', function() {
            return whatwedoTable.updateFormFilterValues($table);
        });

        $('.whatwedo_table__filters_filter').keypress(function(e){
            if (e.which === 13) { // enter key pressed
                e.preventDefault();
                $('#whatwedo_table_' + $table.data('identifier') + ' .whatwedo_table__show_results').trigger('click');
            }
        });
    },

    tableHeader: function() {
        $('.whatwedo_table_inner[data-fixed-header]').stickyTableHeaders({
            fixedOffset: 105
        });
    },

    setLimit: function($table) {
      var buildUrl = function(base, key, value) {
        var sep = (base.indexOf('?') > -1) ? '&' : '?';
        return base + sep + key + '=' + value;
      };

      $('#whatwedo_table_' + $table.data('identifier') +' select[name="limit"]').change(function(e) {
            window.location.href = buildUrl(buildUrl(window.location.href, $table.data('identifier') + '_page', 1), $table.data('identifier') + '_limit', $(this).val());
            e.preventDefault();
        });
    },

    updateFormFilterValues: function($table) {
        if ($('input[name$=filter_name]').val() === '') {
            alert('Filter Name darf nicht leer sein');
            return false;
        }
        var data = $table.find('.whatwedo_table__filters').serializeArray();
        var identifier = $table.data('identifier');
        var retArray = {};
        retArray[identifier + '_filter_operator'] = [[], []];
        retArray[identifier + '_filter_value'] = [[], []];
        retArray[identifier + '_filter_column'] = [[], []];
        for (var i = 0; i < data.length; i++) {
            var name = data[i]['name'];
            if (name.startsWith(identifier+'_filter_operator') || name.startsWith(identifier+'_filter_value') || name.startsWith(identifier+'_filter_column')) {
                var matches = name.match(/(.+)\[(\d+)\]\[(\d+)\]$/);
                if (typeof retArray[matches[1]][matches[2]] === 'undefined') {
                    retArray[matches[1]][matches[2]] = [];
                }
                retArray[matches[1]][matches[2]][matches[3]] = data[i]['value'];
            }
        }
        $('input[name$=filter_conditions]').val(JSON.stringify(retArray))
        return true;
    },

    initExport: function() {
        $(document).ready(function(){
            $('[data-whatwedo-table-export-csv-current]').on('click', function(event) {
                event.preventDefault();
                var trs = $(this).parents('#whatwedo_table').find('tr[data-href]');
                var q = '';
                for (var i = 0; i < trs.length; i++) {
                    q += i == 0 ? '?' : '&';
                    q += 'ids[]=' + $(trs[i]).data('href').match(/[0-9]+$/g);
                }
                window.location.href = $(this).data('export') + q;
            });
            $('[data-whatwedo-table-export-csv-all]').on('click', function(event) {
                event.preventDefault();
                window.location.href = $(this).data('export') + '?ids[]=-1';
            })
        });
    },

    /**
     * initialize class
     */
    init: function() {
        var _ = this;

        $('.whatwedo_table').each(function() {
            var $table = $(this);

            _.clickableRows();
            _.filters($table);
            _.tableHeader();
            _.setLimit($table);
            _.initExport($table);
        });
    }
};

$(document).ready(function() {
    whatwedoTable.init();
});
<commit_msg>refactor(js): cleanup<commit_after>var whatwedoTable = {
    clickableRows: function() {
        $(document).on('click', '.whatwedo_table tr[data-href], .dataTable tr[data-href]', function(e) {
            var $this = $(this);

            if (!$this.closest('.whatwedo_table').hasClass('whatwedo_table__editable')) {
                if($(e.target).is('td')) {
                    window.document.location = $this.data("href");
                }
            }
        });

    },

    currentRequest: null,

    loadContent: function(url, data, failCallback, method, animate, replace, showLoad, callback) {
        if (typeof data === 'undefined') {
            data = null;
        }

        if (typeof method === 'undefined') {
            method = 'GET';
        }

        if (typeof animate === 'undefined') {
            animate = true;
        }

        if (typeof replace === 'undefined') {
            replace = true;
        }

        if (typeof showLoad === 'undefined') {
            showLoad = true;
        }

        if (typeof callback === 'undefined') {
            callback = jQuery.noop;
        }

        var $whatwedoTable = $('#whatwedo_table');

        if (showLoad) {
            $whatwedoTable.addClass('loading');
        }

        if (whatwedoTable.currentRequest !== null) {
            whatwedoTable.currentRequest.abort();
        }

        this.currentRequest = $.ajax({
            url: url,
            data: data,
            method: method
        })
            .done(function(html) {
                callback(html);

                if (!replace) {
                    return;
                }

                history.pushState({
                    'type': 'table',
                    'url': url,
                    'data': data
                }, null, url);

                $whatwedoTable.replaceWith(html);
                whatwedoTable.tableHeader();

                if (animate) {
                    $("html, body").animate({ scrollTop: $('#whatwedo_table').offset().top - 100 }, 250);
                }
            })
            .fail(failCallback)
            .always(function() {
                whatwedoTable.currentRequest = null;
            });
    },

    handleDataLoadEnabled: true,

    handleDataLoad: function(event) {
        if (!whatwedoTable.handleDataLoadEnabled) {
            return;
        }

        var href = this.getAttribute('href');
        var $this = $(this);

        event.preventDefault();

        // Bugfix for Firefox
        var additionalName = null;
        var additionalValue = null;
        var action = null;

        if ($this.prop("tagName") !== 'FORM') {
            if ($this.prop("tagName") === 'BUTTON') {
                additionalName = $this.attr('name');
                additionalValue = $this.attr('value');
            }
            if ($this.prop("tagName") === 'A') {
                action = $this.attr('href');
            } else {
                $this = $($this.parents('form'));
                action = $this.attr('action');
            }
        } else {
            if (typeof $this.attr('action') !== 'undefined') {
                action = $this.attr('action');
            }
        }

        $this.find('input[data-handle-data-load]').remove();

        if (action) {
            var formParams = {};
            $this
                .serializeArray()
                .forEach(function(item) {
                    if (formParams[item.name]) {
                        formParams[item.name] = [formParams[item.name]];
                        formParams[item.name].push(item.value)
                    } else {
                        formParams[item.name] = item.value
                    }
                });

            if (typeof additionalName !== 'undefined'
                && typeof additionalValue !== 'undefined'
                && additionalName
                && additionalValue) {
                $('<input/>')
                    .attr('type', 'hidden')
                    .attr('data-handle-data-load', 1)
                    .attr('name', additionalName)
                    .attr('value', additionalValue)
                    .appendTo($this);
                formParams[additionalName] = additionalValue;
            }

            if (typeof formParams['filter_name'] !== 'undefined') {
                $this.submit();
                return;
            }

            whatwedoTable.loadContent(action, $this.serialize(), function() {
                $this.submit();
            });
        }
        else if (typeof $this.attr('href') !== 'undefined') {
            whatwedoTable.loadContent($this.attr('href'), null, function() {
                window.location.href = $this.attr('href');
            });
        }
        else if (typeof href !== 'undefined') {
            whatwedoTable.loadContent(href, null, function() {
                window.location.href = href;
            });
        }
    },

    filters: function($table) {
        var filterTemplate = $('#whatwedo_table__' + $table.data('identifier') + '__filters__template__block').text();

        var optionNameMatcher = /filter_([\w\d]+)\[(\d)\]\[(\d)\]/i;

        var findCurrentBlocksBlockIteratorNumber = function($blocksContainer) {
            var optionName = $blocksContainer.find('.whatwedo_table__filters__block:last select:first').attr('name');
            if (!optionNameMatcher.test(optionName)) {
                return 0;
            }
            var result = optionNameMatcher.exec(optionName);

            result = parseInt(result[3]);
            if (isNaN(result)) {
                return 0;
            }

            return result;
        };

        var findCurrentBlockIteratorNumber = function($blocksContainer) {
            var optionName = $blocksContainer.find('.whatwedo_table__filters__block:last select:first').attr('name');
            if (!optionNameMatcher.test(optionName)) {
                return 0;
            }
            var result = optionNameMatcher.exec(optionName);

            result = parseInt(result[2]);
            if (isNaN(result)) {
                return 0;
            }

            return result;
        };

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-filter-action="add-and"]', function(e) {
            e.preventDefault();
            var $this = $(this);
            var $blocksContainer = $this.closest('.whatwedo_table__filters__blocks');
            var currentBlockIteratorNumber = findCurrentBlockIteratorNumber($blocksContainer);
            var currentBlocksBlockIteratorNumber = findCurrentBlocksBlockIteratorNumber($blocksContainer);
            var block = filterTemplate
                .replace(/{iBlock}/g, currentBlockIteratorNumber.toString())
                .replace(/{i}/g, (currentBlocksBlockIteratorNumber + 1).toString());
            $blocksContainer.append(block);
        });

        // TODO: fix for empty filters (i.e. $lastBlocksContainer undefined)
        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-filter-action="add-or"]', function(e) {
            e.preventDefault();
            var $lastBlocksContainer = $('#whatwedo_table_' + $table.data('identifier')).find('.whatwedo_table__filters__blocks:last');
            var currentBlockIteratorNumber = findCurrentBlockIteratorNumber($lastBlocksContainer);
            var block = filterTemplate
                .replace(/{iBlock}/g, (currentBlockIteratorNumber + 1).toString())
                .replace(/{i}/g, '1');
            block = '

oder
' + block + '
';

            $lastBlocksContainer.after(block);
        });

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-filter-action="remove"]', function(e) {
            e.preventDefault();
            var $this = $(this);
            var $block = $this.closest('.whatwedo_table__filters__block');

            var $blocksContainer = $block.closest('.whatwedo_table__filters__blocks');

            $block.remove();

            if ($blocksContainer.find('.whatwedo_table__filters__block').length === 0) {
                $blocksContainer.remove();
                $('#whatwedo_table__filters').submit();
            }
        });

        $(document).on('click', '#whatwedo_table_' + $table.data('identifier') + ' [data-toggle="filter"]', function() {
            var $whatwedoTableFilters = $('#whatwedo_table_' + $table.data('identifier') + ' .whatwedo_table__filters');

            if ($whatwedoTableFilters.hasClass('active')) {
                $whatwedoTableFilters.slideUp();
                $whatwedoTableFilters.removeClass('active')
            } else {
                $whatwedoTableFilters.slideDown();
                $whatwedoTableFilters.addClass('active');
            }
        });

        $(document).on('change', '#whatwedo_table_' + $table.data('identifier') + ' select[name^="' + $table.data('identifier') + '_filter_column"]', function() {
            var $this = $(this);
            var $parentBlock = $this.parents('.whatwedo_table__filters_filter');
            var $choosenOption = $this.find(":selected");

            var $operator = $parentBlock.find('select[name^="' + $table.data('identifier') + '_filter_operator"]');
            $operator.empty();
            $.each($choosenOption.data('operator-options'), function(key, name) {
                $operator.append('<option value=' + key + '>' + name + '</option>')
            });

            var $field = $parentBlock.find('[name^="' + $table.data('identifier') + '_filter_value"]');

            if (typeof $field.data('select2') !== 'undefined') {
                $field.select2('destroy');
            }
            var fieldName = $field.attr('name');
            var template = $choosenOption.data('value-template');
            $field.replaceWith(template.replace(/{name}/g, fieldName));
            $field = $parentBlock.find('[name^="' + $table.data('identifier') + '_filter_value"]');

            if ($field.prop('tagName') === 'SELECT'
                && typeof $field.attr('data-disable-interactive') === 'undefined') {
                if (typeof $field.attr('data-ajax-select') === 'undefined') {
                    whatwedo_select2.select2($field[0]);
                } else {
                    whatwedo_select2.ajaxSelect2($field[0]);
                }
            }
        });

        $(document).on('submit', '.whatwedo_table__save', function() {
            return whatwedoTable.updateFormFilterValues($table);
        });

        $('.whatwedo_table__filters_filter').keypress(function(e){
            if (e.which === 13) { // enter key pressed
                e.preventDefault();
                $('#whatwedo_table_' + $table.data('identifier') + ' .whatwedo_table__show_results').trigger('click');
            }
        });
    },

    tableHeader: function() {
        $('.whatwedo_table_inner[data-fixed-header]').stickyTableHeaders({
            fixedOffset: 50
        });
    },

    setLimit: function($table) {
      var buildUrl = function(base, key, value) {
        var sep = (base.indexOf('?') > -1) ? '&' : '?';
        return base + sep + key + '=' + value;
      };

      $('#whatwedo_table_' + $table.data('identifier') +' select[name="limit"]').change(function(e) {
            window.location.href = buildUrl(buildUrl(window.location.href, $table.data('identifier') + '_page', 1), $table.data('identifier') + '_limit', $(this).val());
            e.preventDefault();
        });
    },

    updateFormFilterValues: function($table) {
        if ($('input[name$=filter_name]').val() === '') {
            alert('Filter Name darf nicht leer sein');
            return false;
        }
        var data = $table.find('.whatwedo_table__filters').serializeArray();
        var identifier = $table.data('identifier');
        var retArray = {};
        retArray[identifier + '_filter_operator'] = [[], []];
        retArray[identifier + '_filter_value'] = [[], []];
        retArray[identifier + '_filter_column'] = [[], []];
        for (var i = 0; i < data.length; i++) {
            var name = data[i]['name'];
            if (name.startsWith(identifier+'_filter_operator') || name.startsWith(identifier+'_filter_value') || name.startsWith(identifier+'_filter_column')) {
                var matches = name.match(/(.+)\[(\d+)\]\[(\d+)\]$/);
                if (typeof retArray[matches[1]][matches[2]] === 'undefined') {
                    retArray[matches[1]][matches[2]] = [];
                }
                retArray[matches[1]][matches[2]][matches[3]] = data[i]['value'];
            }
        }
        $('input[name$=filter_conditions]').val(JSON.stringify(retArray))
        return true;
    },

    initExport: function() {
        $(document).ready(function(){
            $('[data-whatwedo-table-export-csv-current]').on('click', function(event) {
                event.preventDefault();
                var trs = $(this).parents('#whatwedo_table').find('tr[data-href]');
                var q = '';
                for (var i = 0; i < trs.length; i++) {
                    q += i == 0 ? '?' : '&';
                    q += 'ids[]=' + $(trs[i]).data('href').match(/[0-9]+$/g);
                }
                window.location.href = $(this).data('export') + q;
            });
            $('[data-whatwedo-table-export-csv-all]').on('click', function(event) {
                event.preventDefault();
                window.location.href = $(this).data('export') + '?ids[]=-1';
            })
        });
    },

    /**
     * initialize class
     */
    init: function() {
        var _ = this;

        _.clickableRows();
        _.tableHeader();
        _.initExport();
        $('.whatwedo_table').each(function() {
            var $table = $(this);

            _.filters($table);
            _.setLimit($table);
        });
    }
};

$(document).ready(function() {
    whatwedoTable.init();
});
<|endoftext|>


<commit_before>import BarChart from '../BaseCharts/Bar'

export default BarChart.extend({
  props: ['player', 'opponent'],

  ready () {
    this.render({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          data: [40, 39, 10, 40, 39, 80, 40]
        },
        {
          label: 'Data Two',
          backgroundColor: '#f87979',
          data: [0, 0, 0, 39.30, 39.30, 39.30]
        }
      ]
    })
  }
})
<commit_msg>🔥 Remove props in barchart example<commit_after>import BarChart from '../BaseCharts/Bar'

export default BarChart.extend({
  ready () {
    this.render({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          data: [40, 39, 10, 40, 39, 80, 40]
        },
        {
          label: 'Data Two',
          backgroundColor: '#f87979',
          data: [0, 0, 0, 39.30, 39.30, 39.30]
        }
      ]
    })
  }
})
<|endoftext|>


<commit_before>import React from 'react';
import PropTable from './components/propTable';
import { storiesOf } from '@storybook/react';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import { withKnobs, select, number } from '@storybook/addon-knobs/react';
import { ProgressTracker } from '../components';

import { steps } from '../static/progressTracker/steps';

const colors = ['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby'];

storiesOf('ProgressTracker', module)
  .addDecorator((story, context) => withInfo({ TableComponent: PropTable })(story)(context))
  .addDecorator(withKnobs)
  .addDecorator(checkA11y)
  .add('Basic', () => (
    <ProgressTracker color={select('Color', colors, 'neutral')} activeStep={number('Active step', 1)}>
      {steps.map(step => {
        return <ProgressTracker.ProgressStep label={step.label} />;
      })}
    </ProgressTracker>
  ));
<commit_msg>give story input a range<commit_after>import React from 'react';
import PropTable from './components/propTable';
import { storiesOf } from '@storybook/react';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import { withKnobs, select, number } from '@storybook/addon-knobs/react';
import { ProgressTracker } from '../components';

import { steps } from '../static/progressTracker/steps';

const colors = ['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby'];
const options = {
  range: true,
  min: 0,
  max: steps.length,
  step: 1,
};

storiesOf('ProgressTracker', module)
  .addDecorator((story, context) => withInfo({ TableComponent: PropTable })(story)(context))
  .addDecorator(withKnobs)
  .addDecorator(checkA11y)
  .add('Basic', () => (
    <ProgressTracker color={select('Color', colors, 'neutral')} activeStep={number('Active step', 1, options)}>
      {steps.map(step => {
        return <ProgressTracker.ProgressStep label={step.label} />;
      })}
    </ProgressTracker>
  ));
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD <commit_msg>Fixing punctuation<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD =<|endoftext|>


<commit_before>'use strict'

/* IMPORT */

const {packages, workspace} = global.atom
const {registerSpawnCommand} = require(packages.resolvePackagePath('quick-spawn'))

/* DO THINGS */

// NOTE:
//  → Not every function-calls below is necessary
//  → Keep only what you need
registerWorkspaceBash()

/* DEFINE HOW TO DO THINGS */

// DESCRIPTION: registerWorkspaceBash
function registerWorkspaceBash () {
  return registerSpawnCommand({
    execCmd: 'bash',
    atomCmd: 'simple-bash:workspace',
    atomTarget: 'atom-workspace',
    workingDirectory: () => workspace.getActivePaneItem().getDirectoryPath(),
    attached: false,
    suspended: true,
    viewStdIO: ['stdin', 'stdout', 'stderr'],
    type: 'tab',
    atomKeybinding: 'ctrl-shift-b s w',
    exitOnClose: true,
    closeOnExit: true,
    detachedTextBox: 'none'
  })
}
<commit_msg>Documenting<commit_after>'use strict'

/* IMPORT */

const {packages, workspace} = global.atom
const {registerSpawnCommand} = require(packages.resolvePackagePath('quick-spawn'))

/* DO THINGS */

// NOTE:
//  → Not every function-calls below is necessary
//  → Keep only what you need
registerWorkspaceBash()

/* DEFINE HOW TO DO THINGS */

// DESCRIPTION: registerWorkspaceBash
//  → Distinct:
//   * Registers for workspace
//   * Uses getTabDirectory() as first current-working-directory
//  → Returns 1 subscription
function registerWorkspaceBash () {
  return registerSpawnCommand({
    execCmd: 'bash', // required; program needs to be executed
    atomCmd: 'simple-bash:workspace', // required; registers an atom-command, appears as "Simple Bash: Workspace" in Command-Palette
    atomTarget: 'atom-workspace', // required; determines where to attach the atom-command
    workingDirectory: getTabDirectory, // optional; determines Bash's first working-directory, you can change it later by 'cd new-wdir'
    attached: false, // optional, default to false; determines whether Bash process should be attached to Atom process
    suspended: true, // optional, default to true; if false, Bash would be started right after quick-spawn's activation
    viewStdIO: ['stdin', 'stdout', 'stderr'], // optional, determines whether stdin, stdout and stderr should be shown; shows all three by default
    type: 'tab', // optional, default to 'tab'
    atomKeybinding: 'ctrl-shift-b s w', // optional
    exitOnClose: true, // optional, default to true; should the spawned process be terminated when close the view
    closeOnExit: true, // optional, default to false; should the view be closed when bash exits
    detachedTextBox: 'none', // optional, default to 'none'
    __proto__: null // optional (of course); avoid the mess from Object.prototype
  })
}

// DESCRIPTION: getTabDirectory
function getTabDirectory () {
  return workspace.getActivePaneItem().getDirectoryPath()
}
<|endoftext|>