<commit_before>var gulp = require('gulp')
var shell = require('gulp-shell')
var jison = require('gulp-jison')
var filelog = require('gulp-filelog')

gulp.task('jison', function () {
  return gulp.src('./src/**/*.jison')
    .pipe(filelog('Jison file:'))
    .pipe(jison({ moduleType: 'commonjs' }))
    .pipe(gulp.dest('./src/'))
})

gulp.task('jison_legacy', shell.task([
  'node node_modules/jison/lib/cli.js src/diagrams/classDiagram/parser/classDiagram.jison -o src/diagrams/classDiagram/parser/classDiagram.js',
  'node node_modules/jison/lib/cli.js src/diagrams/sequenceDiagram/parser/sequenceDiagram.jison -o src/diagrams/sequenceDiagram/parser/sequenceDiagram.js',
  'node node_modules/jison/lib/cli.js src/diagrams/example/parser/example.jison -o src/diagrams/example/parser/example.js',
  'node node_modules/jison/lib/cli.js src/diagrams/flowchart/parser/flow.jison -o src/diagrams/flowchart/parser/flow.js',
  'node node_modules/jison/lib/cli.js src/diagrams/flowchart/parser/dot.jison -o src/diagrams/flowchart/parser/dot.js',
  'node node_modules/jison/lib/cli.js src/diagrams/gitGraph/parser/gitGraph.jison -o src/diagrams/gitGraph/parser/gitGraph.js',
  'node node_modules/jison/lib/cli.js src/diagrams/gantt/parser/gantt.jison -o src/diagrams/gantt/parser/gantt.js'
]))
<commit_msg>jison token-stack<commit_after>var gulp = require('gulp')
var shell = require('gulp-shell')
var jison = require('gulp-jison')
var filelog = require('gulp-filelog')

gulp.task('jison', function () {
  return gulp.src('./src/**/*.jison')
    .pipe(filelog('Jison file:'))
    .pipe(jison({ moduleType: 'commonjs', 'token-stack': true }))
    .pipe(gulp.dest('./src/'))
})

gulp.task('jison_legacy', shell.task([
  'node node_modules/jison/lib/cli.js src/diagrams/classDiagram/parser/classDiagram.jison -o src/diagrams/classDiagram/parser/classDiagram.js',
  'node node_modules/jison/lib/cli.js src/diagrams/sequenceDiagram/parser/sequenceDiagram.jison -o src/diagrams/sequenceDiagram/parser/sequenceDiagram.js',
  'node node_modules/jison/lib/cli.js src/diagrams/example/parser/example.jison -o src/diagrams/example/parser/example.js',
  'node node_modules/jison/lib/cli.js src/diagrams/flowchart/parser/flow.jison -o src/diagrams/flowchart/parser/flow.js',
  'node node_modules/jison/lib/cli.js src/diagrams/flowchart/parser/dot.jison -o src/diagrams/flowchart/parser/dot.js',
  'node node_modules/jison/lib/cli.js src/diagrams/gitGraph/parser/gitGraph.jison -o src/diagrams/gitGraph/parser/gitGraph.js',
  'node node_modules/jison/lib/cli.js src/diagrams/gantt/parser/gantt.jison -o src/diagrams/gantt/parser/gantt.js'
]))
<|endoftext|>


<commit_before>var gulp = require('gulp');

gulp.task(
	'serve',
	[
		'watch',
		'webserver'
	]
);
<commit_msg>build when serving<commit_after>var gulp = require('gulp');

gulp.task(
	'serve',
	[
		'build',
		'watch',
		'webserver'
	]
);
<|endoftext|>


<commit_before>'use strict';

import config         from '../config';
import gulp           from 'gulp';
import handlebars     from 'gulp-compile-handlebars';
import inject         from 'gulp-inject';
import handleErrors   from '../util/handleErrors';
import browserSync    from 'browser-sync';

gulp.task( 'views', function () {

  const templateData = {
    title:        config.site.title,
    description:  config.site.description,
    keywords:     config.site.keywords
  };

  return gulp.src( config.views.src )

    // Compile handlebar templates
    .pipe( handlebars( templateData, config.handlebars ) )

    // Display any errors
    .on( 'error', handleErrors )

    // Write to destination
    .pipe( gulp.dest( config.views.dest ) )

    // Inject source files
    .pipe( inject( gulp.src( [config.styles.dest + '/*.css', config.scripts.dest + '/*.js'], { read: false } ), { relative: true }))

    // Write to destination
    .pipe( gulp.dest( config.views.dest ) )

    // Refresh browser stream
    .pipe(browserSync.stream({ once: true }));

});<commit_msg>Unchanged views are now ignored<commit_after>'use strict';

import config         from '../config';
import changed        from 'gulp-changed';
import gulp           from 'gulp';
import handlebars     from 'gulp-compile-handlebars';
import inject         from 'gulp-inject';
import handleErrors   from '../util/handleErrors';
import browserSync    from 'browser-sync';

gulp.task( 'views', function () {

  const templateData = {
    title:        config.site.title,
    description:  config.site.description,
    keywords:     config.site.keywords
  };

  return gulp.src( config.views.src )

    // Ignore unchanged files
    .pipe( changed( config.views.dest ) )

    // Compile handlebar templates
    .pipe( handlebars( templateData, config.handlebars ) )

    // Display any errors
    .on( 'error', handleErrors )

    // Write to destination
    .pipe( gulp.dest( config.views.dest ) )

    // Inject source files
    .pipe( inject( gulp.src( [config.styles.dest + '/*.css', config.scripts.dest + '/*.js'], { read: false } ), { relative: true }))

    // Write to destination
    .pipe( gulp.dest( config.views.dest ) )

    // Refresh browser stream
    .pipe(browserSync.stream({ once: true }));

});<|endoftext|>


<commit_before>define([
  'lodash',
  'app/plugins/sdk',
  'app/core/utils/kbn',
  'app/core/time_series',
  './rendering',
  './legend',
],
function (_, sdk, kbn, TimeSeries, rendering) {
  'use strict';

    // Set and populate defaults
  var panelDefaults = {
    pieType: 'pie',
    legend: {
      show: true, // disable/enable legend
      values: false, // disable/enable legend values
      min: false,
      max: false,
      current: false,
      total: false,
      avg: false
    },
    links: [],
    datasource: null,
    maxDataPoints: 3,
    interval: null,
    targets: [{}],
    cacheTimeout: null,
    nullText: null,
    nullPointMode: 'connected',
    legendType: 'rightSide',
    format: 'short'
  };

  var PieChartCtrl = (function(_super) {

    function PieChartCtrl($scope, $injector, $rootScope) {
      _super.call(this, $scope, $injector);
      this.$rootScope = $rootScope;

      _.defaults(this.panel, panelDefaults);
      _.defaults(this.panel.legend, panelDefaults.legend);
    }

    PieChartCtrl.prototype = Object.create(_super.prototype);
    PieChartCtrl.prototype.constructor = PieChartCtrl;

    PieChartCtrl.templateUrl = 'public/plugins/piechart/module.html';

    PieChartCtrl.prototype.initEditMode = function() {
      _super.prototype.initEditMode.call(this);
      this.icon =  "fa fa-dashboard";
      this.addEditorTab('Options', 'public/plugins/piechart/editor.html', 2);
      this.unitFormats = kbn.getUnitFormats();
    };

    PieChartCtrl.prototype.setUnitFormat = function(subItem) {
      this.panel.format = subItem.value;
      this.render();
    };

    PieChartCtrl.prototype.refreshData = function(datasource) {
      return this.issueQueries(datasource)
      .then(this.dataHandler.bind(this))
      .catch(function(err) {
        this.series = [];
        this.render();
        throw err;
      }.bind(this));
    };

    PieChartCtrl.prototype.dataHandler = function(results) {
      this.series = _.map(results.data, this.seriesHandler.bind(this));
      this.render();
    };

    PieChartCtrl.prototype.seriesHandler = function(seriesData) {
      var series = new TimeSeries({
        datapoints: seriesData.datapoints,
        alias: seriesData.target
      });

      series.flotpairs = series.getFlotPairs(this.panel.nullPointMode);
      return series;
    };

    PieChartCtrl.prototype.getDecimalsForValue = function(value) {
      if (_.isNumber(this.panel.decimals)) {
        return { decimals: this.panel.decimals, scaledDecimals: null };
      }

      var delta = value / 2;
      var dec = -Math.floor(Math.log(delta) / Math.LN10);

      var magn = Math.pow(10, -dec);
      var norm = delta / magn; // norm is between 1.0 and 10.0
      var size;

      if (norm < 1.5) {
        size = 1;
      } else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25) {
          size = 2.5;
          ++dec;
        }
      } else if (norm < 7.5) {
        size = 5;
      } else {
        size = 10;
      }

      size *= magn;

      // reduce starting decimals if not needed
      if (Math.floor(value) === value) { dec = 0; }

      var result = {};
      result.decimals = Math.max(0, dec);
      result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;

      return result;
    };

    PieChartCtrl.prototype.render = function() {
      var data = [];

      if (this.series && this.series.length > 0) {
        for (var i=0; i < this.series.length; i++) {
          data.push({label: this.series[i].alias, data: this.series[i].stats.current, color: this.$rootScope.colors[i]});
        }
      }

      this.data = data;
      this.broadcastRender(data);
    };

    PieChartCtrl.prototype.setValues = function(data) {
      data.flotpairs = [];

      if (this.series && this.series.length > 0) {
        var lastPoint = _.last(this.series[0].datapoints);
        var lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;

        if (_.isString(lastValue)) {
          data.value = 0;
          data.valueFormated = lastValue;
          data.valueRounded = 0;
        } else {
          data.value = this.series[0].stats[this.panel.valueName];
          data.flotpairs = this.series[0].flotpairs;

          var decimalInfo = this.getDecimalsForValue(data.value);
          data.valueFormated = formatValue(data.value);
          data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
        }
      }

      if (data.value === null || data.value === void 0) {
        data.valueFormated = "no value";
      }
    };

    PieChartCtrl.prototype.formatValue = function(value) {
      var decimalInfo = this.getDecimalsForValue(value);
      var formatFunc = kbn.valueFormats[this.panel.format];
      if (formatFunc) {
        return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals);
      }
      return value;
    };

    PieChartCtrl.prototype.removeValueMap = function(map) {
      var index = _.indexOf(this.panel.valueMaps, map);
      this.panel.valueMaps.splice(index, 1);
      this.render();
    };

    PieChartCtrl.prototype.addValueMap = function() {
      this.panel.valueMaps.push({value: '', op: '=', text: '' });
    };

    PieChartCtrl.prototype.legendValuesOptionChanged = function() {
      var legend = this.panel.legend;
      legend.values = legend.min || legend.max || legend.avg || legend.current || legend.total;
      this.render();
    };

    PieChartCtrl.prototype.link = function(scope, elem, attrs, ctrl) {
      rendering.link(scope, elem, attrs, ctrl);
    };

    return PieChartCtrl;

  })(sdk.MetricsPanelCtrl);

  return {
    PanelCtrl: PieChartCtrl
  };
});
<commit_msg>fix(paths): fixes broken view path<commit_after>define([
  'lodash',
  'app/plugins/sdk',
  'app/core/utils/kbn',
  'app/core/time_series',
  './rendering',
  './legend',
],
function (_, sdk, kbn, TimeSeries, rendering) {
  'use strict';

    // Set and populate defaults
  var panelDefaults = {
    pieType: 'pie',
    legend: {
      show: true, // disable/enable legend
      values: false, // disable/enable legend values
      min: false,
      max: false,
      current: false,
      total: false,
      avg: false
    },
    links: [],
    datasource: null,
    maxDataPoints: 3,
    interval: null,
    targets: [{}],
    cacheTimeout: null,
    nullText: null,
    nullPointMode: 'connected',
    legendType: 'rightSide',
    format: 'short'
  };

  var PieChartCtrl = (function(_super) {

    function PieChartCtrl($scope, $injector, $rootScope) {
      _super.call(this, $scope, $injector);
      this.$rootScope = $rootScope;

      _.defaults(this.panel, panelDefaults);
      _.defaults(this.panel.legend, panelDefaults.legend);
    }

    PieChartCtrl.prototype = Object.create(_super.prototype);
    PieChartCtrl.prototype.constructor = PieChartCtrl;
    PieChartCtrl.templateUrl = 'module.html';

    PieChartCtrl.prototype.initEditMode = function() {
      _super.prototype.initEditMode.call(this);
      this.icon =  "fa fa-dashboard";
      this.addEditorTab('Options', 'public/plugins/piechart-panel/editor.html', 2);
      this.unitFormats = kbn.getUnitFormats();
    };

    PieChartCtrl.prototype.setUnitFormat = function(subItem) {
      this.panel.format = subItem.value;
      this.render();
    };

    PieChartCtrl.prototype.refreshData = function(datasource) {
      return this.issueQueries(datasource)
      .then(this.dataHandler.bind(this))
      .catch(function(err) {
        this.series = [];
        this.render();
        throw err;
      }.bind(this));
    };

    PieChartCtrl.prototype.dataHandler = function(results) {
      this.series = _.map(results.data, this.seriesHandler.bind(this));
      this.render();
    };

    PieChartCtrl.prototype.seriesHandler = function(seriesData) {
      var series = new TimeSeries({
        datapoints: seriesData.datapoints,
        alias: seriesData.target
      });

      series.flotpairs = series.getFlotPairs(this.panel.nullPointMode);
      return series;
    };

    PieChartCtrl.prototype.getDecimalsForValue = function(value) {
      if (_.isNumber(this.panel.decimals)) {
        return { decimals: this.panel.decimals, scaledDecimals: null };
      }

      var delta = value / 2;
      var dec = -Math.floor(Math.log(delta) / Math.LN10);

      var magn = Math.pow(10, -dec);
      var norm = delta / magn; // norm is between 1.0 and 10.0
      var size;

      if (norm < 1.5) {
        size = 1;
      } else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25) {
          size = 2.5;
          ++dec;
        }
      } else if (norm < 7.5) {
        size = 5;
      } else {
        size = 10;
      }

      size *= magn;

      // reduce starting decimals if not needed
      if (Math.floor(value) === value) { dec = 0; }

      var result = {};
      result.decimals = Math.max(0, dec);
      result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;

      return result;
    };

    PieChartCtrl.prototype.render = function() {
      var data = [];

      if (this.series && this.series.length > 0) {
        for (var i=0; i < this.series.length; i++) {
          data.push({label: this.series[i].alias, data: this.series[i].stats.current, color: this.$rootScope.colors[i]});
        }
      }

      this.data = data;
      this.broadcastRender(data);
    };

    PieChartCtrl.prototype.setValues = function(data) {
      data.flotpairs = [];

      if (this.series && this.series.length > 0) {
        var lastPoint = _.last(this.series[0].datapoints);
        var lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;

        if (_.isString(lastValue)) {
          data.value = 0;
          data.valueFormated = lastValue;
          data.valueRounded = 0;
        } else {
          data.value = this.series[0].stats[this.panel.valueName];
          data.flotpairs = this.series[0].flotpairs;

          var decimalInfo = this.getDecimalsForValue(data.value);
          data.valueFormated = formatValue(data.value);
          data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
        }
      }

      if (data.value === null || data.value === void 0) {
        data.valueFormated = "no value";
      }
    };

    PieChartCtrl.prototype.formatValue = function(value) {
      var decimalInfo = this.getDecimalsForValue(value);
      var formatFunc = kbn.valueFormats[this.panel.format];
      if (formatFunc) {
        return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals);
      }
      return value;
    };

    PieChartCtrl.prototype.removeValueMap = function(map) {
      var index = _.indexOf(this.panel.valueMaps, map);
      this.panel.valueMaps.splice(index, 1);
      this.render();
    };

    PieChartCtrl.prototype.addValueMap = function() {
      this.panel.valueMaps.push({value: '', op: '=', text: '' });
    };

    PieChartCtrl.prototype.legendValuesOptionChanged = function() {
      var legend = this.panel.legend;
      legend.values = legend.min || legend.max || legend.avg || legend.current || legend.total;
      this.render();
    };

    PieChartCtrl.prototype.link = function(scope, elem, attrs, ctrl) {
      rendering.link(scope, elem, attrs, ctrl);
    };

    return PieChartCtrl;

  })(sdk.MetricsPanelCtrl);

  return {
    PanelCtrl: PieChartCtrl
  };
});
<|endoftext|>


<commit_before>function load_songs(textarea) {
    var encoded_uri = textarea.value;
    var decoded = decodeURIComponent(encoded_uri);
    var without_protocol = decoded.replace("irealb://", "");
    var unsplitted = without_protocol.split("==0=0===");
    for(i in unsplitted) {
        song = unsplitted[i].split("=");
        title = song[0];
        author = song[1];
        localStorage[title + " (" + author + ")"] = unsplitted[i]
    }
}
function swap(splitted, i, j) {
    tmp = splitted[i];
    splitted[i] = splitted[j];
    splitted[j] = tmp;
}
function mirror_swap(str, start, size) {
    var splitted = str.split('');
    var count = Math.floor(size / 2);
    for(var i = 0; i < count; i++) {
        swap(splitted, start + i, size + start - i);
    }
    return splitted.join("");
}
function unwarble(warbled) {
    var unwarbled = warbled.replace('1r34LbKcu7', '');
    for(var i = 0; i + 51 < unwarbled.length; i += 50) {
        unwarbled = mirror_swap(mirror_swap(mirror_swap(unwarbled, i + 10, 29), i + 5, 39), i, 49)
    }
    return unwarbled.replace(/XyQ/g, "   ").replace(/Kcl/g, "| x").replace(/LZ/g, "|");
}
function get_sheet(unwarbled) {
    unwarbled = unwarbled.replace(/\*([ABC])/g, "$1");
    unwarbled = unwarbled.replace(/\[/g, " ");
    unwarbled = unwarbled.replace(/T(.)(.)/g, "$1$1");
    unwarbled = unwarbled.replace(/\^/g, "Δ");
    var splitted = unwarbled.split('');
    var open_div = "
";
    var close_div = "
";
    var open_span = "";
    var close_span = "";
    var out = open_div + open_span;
    var bars = 0;
    for(i = 0; i < splitted.length; i++) {
        var c = splitted[i];
        var add = "";
        if(c == "|") {
            c = close_span;
            bars += 1;
            if(bars < 4)
            {
                c += open_span
            }
        }
        else { if(c == "x") { c = "%"; } }
        if(bars == 4 || c == '}' || c == ']') {
            bars = 0;
            add = close_div + open_div + open_span;
        }
        out += c + add;
    }
    return out + close_span + close_div;
}
function line_to_mma_chords(line) {
    var chords = line.split(" ");
    if(chords.length == 2) {
        chords = [chords[0], "/", chords[1]];
    }
    return chords.join(" ");
}
function play_mma(mma) {
  var worker = new Worker("//yazgoo.github.io/pypyjs-mma/worker.js")
  worker.postMessage([mma]);
  console.log('Message posted to worker');
  worker.onmessage = function(e) {
    console.log('Message received from worker');
    console.log(btoa(e.data));
    data = e.data
      console.log("playing " + data);
    play(data);
  }
}
function play_song(unwarbled) {
    var previous = "";
    unwarbled = unwarbled.replace(/T../, '?Groove Mambo\n')
        .replace(/\{/g, "\n?Repeat\n").replace(/}/g, "\n?RepeatEnd\n")
        .replace(/\*./g, "").replace(/N1/g, "\n?RepeatEnding\\2\n").replace("][", "")
        .replace("[", "\n")
        .replace(/N2/g, "").replace("Z", "").replace(/s/g, " ").replace(/,/g, " ")
        .replace(/-/g, "m").replace(/\^/g, "M").replace(/h/g, "dim")
        .replace(/\|/g, "\n").replace(/\]\[/g, "\n").replace(/\[/, "\n")
        .replace(/l/g, "\n")
    splitted = unwarbled.split("\n");
    var previous = "";
    k = 0;
    for(var i = 0; i < splitted.length; i++) {
        var line = splitted[i];
        if(line.length == 0 || line[0] == '?') previous += line.replace(/\?/g, "")
        else {
            previous += "" + k + " " + line_to_mma_chords(line);
            k += 1;
        }
        previous += "\n";
    }
    console.log(previous);
    play_mma(previous);
}
function show_song(title) {
    var song = localStorage[title];
    localStorage["last_song"] = song;
    var splitted = song.split("=");
    var title = splitted[0];
    var author = splitted[1];
    var unwarbled = unwarble(splitted[6]);
    set_content(""+title+" ("+author+")"
            + "<input type=button value='>' onclick=\"play_song('"+unwarbled+"')\"/>

"
            + get_sheet(unwarbled));
}
function show_songs_list(div) {
    div.innerHTML = "";
    for(var i = 0; i < 100;/*localStorage.length*/ i++) {
        var title = localStorage.key(i);
        div.innerHTML += "" + title  + "
";
    }
}
function set_content(str) {
    var content = document.getElementById("content");
    content.innerHTML = str;
}
function show_imports() {
    set_content("<input type=text onchange='load_songs(this)'/>");
}
function show_about() {
    set_content('Mooche is free software (as in freedom).
'
            +'This means it guarantees 4 fundamentals rights:
'
            +'
'
            +'
Freedom 0: The freedom to run the program for any purpose.
'
            +'
Freedom 1: The freedom to study how the program works, and change it to make it do what you wish.
'
            +'
Freedom 2: The freedom to redistribute and make copies so you can help your neighbor.
'
            +'
Freedom 3: The freedom to improve the program, and release your improvements (and modified versions in general) to the public, so that the whole community benefits.
'
            +'
'
            +'')
}
function show_songs() {
    show_songs_list(document.getElementById('content'));
}
function show_songs_or_last_song() {
    if(localStorage["last_song"] != null) {
        show_song("last_song");
    }
    else {
        show_songs();
    }
}

<commit_msg>loading worker.js from rawgit<commit_after>function load_songs(textarea) {
    var encoded_uri = textarea.value;
    var decoded = decodeURIComponent(encoded_uri);
    var without_protocol = decoded.replace("irealb://", "");
    var unsplitted = without_protocol.split("==0=0===");
    for(i in unsplitted) {
        song = unsplitted[i].split("=");
        title = song[0];
        author = song[1];
        localStorage[title + " (" + author + ")"] = unsplitted[i]
    }
}
function swap(splitted, i, j) {
    tmp = splitted[i];
    splitted[i] = splitted[j];
    splitted[j] = tmp;
}
function mirror_swap(str, start, size) {
    var splitted = str.split('');
    var count = Math.floor(size / 2);
    for(var i = 0; i < count; i++) {
        swap(splitted, start + i, size + start - i);
    }
    return splitted.join("");
}
function unwarble(warbled) {
    var unwarbled = warbled.replace('1r34LbKcu7', '');
    for(var i = 0; i + 51 < unwarbled.length; i += 50) {
        unwarbled = mirror_swap(mirror_swap(mirror_swap(unwarbled, i + 10, 29), i + 5, 39), i, 49)
    }
    return unwarbled.replace(/XyQ/g, "   ").replace(/Kcl/g, "| x").replace(/LZ/g, "|");
}
function get_sheet(unwarbled) {
    unwarbled = unwarbled.replace(/\*([ABC])/g, "$1");
    unwarbled = unwarbled.replace(/\[/g, " ");
    unwarbled = unwarbled.replace(/T(.)(.)/g, "$1$1");
    unwarbled = unwarbled.replace(/\^/g, "Δ");
    var splitted = unwarbled.split('');
    var open_div = "
";
    var close_div = "
";
    var open_span = "";
    var close_span = "";
    var out = open_div + open_span;
    var bars = 0;
    for(i = 0; i < splitted.length; i++) {
        var c = splitted[i];
        var add = "";
        if(c == "|") {
            c = close_span;
            bars += 1;
            if(bars < 4)
            {
                c += open_span
            }
        }
        else { if(c == "x") { c = "%"; } }
        if(bars == 4 || c == '}' || c == ']') {
            bars = 0;
            add = close_div + open_div + open_span;
        }
        out += c + add;
    }
    return out + close_span + close_div;
}
function line_to_mma_chords(line) {
    var chords = line.split(" ");
    if(chords.length == 2) {
        chords = [chords[0], "/", chords[1]];
    }
    return chords.join(" ");
}
function play_mma(mma) {
  var worker = new Worker("//rawgit.com/yazgoo/pypyjs-mma/master/worker.js")
  worker.postMessage([mma]);
  console.log('Message posted to worker');
  worker.onmessage = function(e) {
    console.log('Message received from worker');
    console.log(btoa(e.data));
    data = e.data
      console.log("playing " + data);
    play(data);
  }
}
function play_song(unwarbled) {
    var previous = "";
    unwarbled = unwarbled.replace(/T../, '?Groove Mambo\n')
        .replace(/\{/g, "\n?Repeat\n").replace(/}/g, "\n?RepeatEnd\n")
        .replace(/\*./g, "").replace(/N1/g, "\n?RepeatEnding\\2\n").replace("][", "")
        .replace("[", "\n")
        .replace(/N2/g, "").replace("Z", "").replace(/s/g, " ").replace(/,/g, " ")
        .replace(/-/g, "m").replace(/\^/g, "M").replace(/h/g, "dim")
        .replace(/\|/g, "\n").replace(/\]\[/g, "\n").replace(/\[/, "\n")
        .replace(/l/g, "\n")
    splitted = unwarbled.split("\n");
    var previous = "";
    k = 0;
    for(var i = 0; i < splitted.length; i++) {
        var line = splitted[i];
        if(line.length == 0 || line[0] == '?') previous += line.replace(/\?/g, "")
        else {
            previous += "" + k + " " + line_to_mma_chords(line);
            k += 1;
        }
        previous += "\n";
    }
    console.log(previous);
    play_mma(previous);
}
function show_song(title) {
    var song = localStorage[title];
    localStorage["last_song"] = song;
    var splitted = song.split("=");
    var title = splitted[0];
    var author = splitted[1];
    var unwarbled = unwarble(splitted[6]);
    set_content(""+title+" ("+author+")"
            + "<input type=button value='>' onclick=\"play_song('"+unwarbled+"')\"/>

"
            + get_sheet(unwarbled));
}
function show_songs_list(div) {
    div.innerHTML = "";
    for(var i = 0; i < 100;/*localStorage.length*/ i++) {
        var title = localStorage.key(i);
        div.innerHTML += "" + title  + "
";
    }
}
function set_content(str) {
    var content = document.getElementById("content");
    content.innerHTML = str;
}
function show_imports() {
    set_content("<input type=text onchange='load_songs(this)'/>");
}
function show_about() {
    set_content('Mooche is free software (as in freedom).
'
            +'This means it guarantees 4 fundamentals rights:
'
            +'
'
            +'
Freedom 0: The freedom to run the program for any purpose.
'
            +'
Freedom 1: The freedom to study how the program works, and change it to make it do what you wish.
'
            +'
Freedom 2: The freedom to redistribute and make copies so you can help your neighbor.
'
            +'
Freedom 3: The freedom to improve the program, and release your improvements (and modified versions in general) to the public, so that the whole community benefits.
'
            +'
'
            +'')
}
function show_songs() {
    show_songs_list(document.getElementById('content'));
}
function show_songs_or_last_song() {
    if(localStorage["last_song"] != null) {
        show_song("last_song");
    }
    else {
        show_songs();
    }
}

<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-button', 'Integration | Component | sl button', {
    integration: true
});

const template = hbs`
    {{#sl-button}}
        Default Text
    {{/sl-button}}
`;

test( 'Default action is triggered when element is clicked', function( assert ) {
    assert.expect( 1 );

    this.on( 'externalAction', () => {
        assert.ok(
            true,
            'External action was called'
        );
    });

    this.render( hbs`
        {{#sl-button action="externalAction"}}
            Default Text
        {{/sl-button}}
    ` );

    this.$( '>:first-child' ).click();
});

test( 'Button is enabled by default', function( assert ) {
    this.render( template );

    assert.strictEqual(
        this.$( '>:first-child' ).is( ':disabled' ),
        false,
        'Component is disabled by default'
    );
});

test( 'Button is disabled when disabled is set to true', function( assert ) {
    this.render( hbs`
        {{#sl-button disabled=true}}
            Default Text
        {{/sl-button}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).is( ':disabled' ),
        true,
        'Component becomes disabled'
    );
});

test( 'Expected default classes are applied', function( assert ) {
    this.render( template );

    const element = this.$( '>:first-child' );
    const noSizeClassByDefault = !element.hasClass( 'btn-xs' ) &&
                                   !element.hasClass( 'btn-sm' ) &&
                                   !element.hasClass( 'btn-lg' );

    assert.ok(
        element.hasClass( 'btn' ),
        'Has class "btn"'
    );

    assert.ok(
        element.hasClass( 'sl-button' ),
        'Has class "sl-button"'
    );

    assert.ok(
        element.hasClass( 'btn-default' ),
        'Has default theme class'
    );

    assert.ok(
        noSizeClassByDefault,
        'No size class is applied by default'
    );
});

test( 'Class property is supported', function( assert ) {
    this.render( hbs`
        {{#sl-button class='testClass'}}
           Test Button
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'testClass' )
    );
});

test( 'Labels are correctly initialized', function( assert ) {
    const labelText = 'Test';

    this.set( 'label', labelText );
    this.render( hbs`
        {{#sl-button label=label}}
            Default Text
        {{/sl-button}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        labelText,
        'Expected label text is present'
    );
});

test( 'Correct size class is applied', function( assert ) {
    this.render( hbs`
        {{#sl-button size="large"}}
            Default Text
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'btn-lg' ),
        'Has expected class "btn-lg"'
    );
});

test( 'Theme class is applied correctly', function( assert ) {
    this.render( hbs`
        {{#sl-button theme="success"}}
            Default Text
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'btn-success' ),
        'Has expected class "btn-success"'
    );
});

test( 'Label is correct for pending state', function( assert ) {
    const pendingLabelText = 'Pending';
    const changedPendingLabelText = 'Changed pending label text';
    const staticText = 'Static';

    this.set( 'staticText', staticText );

    this.render( hbs`
        {{#sl-button}}
            {{staticText}}
        {{/sl-button}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        staticText,
        'Static text is set initially'
    );

    this.set( 'pendingLabel', pendingLabelText );

    this.render( hbs`
        {{#sl-button pendingLabel=pendingLabel pending=true}}
            Default Text
            {{staticText}}
        {{/sl-button}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        pendingLabelText,
        'Pending text is set while pending'
    );

    this.set( 'pendingLabel', changedPendingLabelText );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        changedPendingLabelText,
        'Pending label text is set correctly when updated dynamically'
    );
});

test( 'Pending class is present when in pending state', function( assert ) {
    this.render( hbs`
        {{#sl-button pendingLabel='pending' pending=true}}
            Default Text
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'pending' )
    );
});

test( 'Tooltip properties are set correctly when title parameter is set', function( assert ) {
    const title = 'test title';

    this.set( 'title', title );

    this.render( hbs`
        {{#sl-button title=title}}
            default text
        {{/sl-button}}
    ` );

    const element = this.$( '>:first-child' );
    const data = element.data();
    const tooltipData = data[ 'bs.tooltip' ];
    const options = tooltipData.getOptions();

    assert.equal(
        tooltipData.enabled,
        true,
        'tooltip is enabled'
    );

    assert.equal(
        tooltipData.getTitle(),
        title,
        'Title text is set correctly'
    );

    assert.equal(
        options.trigger,
        'hover focus',
        'Default trigger is "hover focus"'
    );
});

test( 'Popover properties are set correctly when popover parameter is set', function( assert ) {
    const title = 'test title';
    const popover = 'popover text';

    this.set( 'title', title );
    this.set( 'popover', popover );

    this.render( hbs`
        {{#sl-button title=title popover=popover}}
            default text
        {{/sl-button}}
    ` );

    const element = this.$( '>:first-child' );
    const data = element.data();
    const popoverData = data[ 'bs.popover' ];
    const options = popoverData.getOptions();

    assert.equal(
        popoverData.enabled,
        true,
        'Popover is enabled'
    );

    assert.equal(
        popoverData.getTitle(),
        title,
        'Popover title was set correctly'
    );

    assert.equal(
        popoverData.getContent(),
        popover,
        'Popover text is set correctly'
    );

    assert.equal(
        options.trigger,
        'click',
        'Default trigger is "click"'
    );
});
<commit_msg>Refactored test code<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent( 'sl-button', 'Integration | Component | sl button', {
    integration: true
});

const template = hbs`
    {{#sl-button}}
        Default Text
    {{/sl-button}}
`;

test( 'Default action is triggered when element is clicked', function( assert ) {
    assert.expect( 1 );

    this.on( 'externalAction', () => {
        assert.ok(
            true,
            'External action was called'
        );
    });

    this.render( hbs`
        {{#sl-button action="externalAction"}}
            Default Text
        {{/sl-button}}
    ` );

    this.$( '>:first-child' ).click();
});

test( 'Button is enabled by default', function( assert ) {
    this.render( template );

    assert.strictEqual(
        this.$( '>:first-child' ).is( ':disabled' ),
        false,
        'Component is disabled by default'
    );
});

test( 'Button is disabled when disabled is set to true', function( assert ) {
    this.render( hbs`
        {{#sl-button disabled=true}}
            Default Text
        {{/sl-button}}
    ` );

    assert.strictEqual(
        this.$( '>:first-child' ).is( ':disabled' ),
        true,
        'Component becomes disabled'
    );
});

test( 'Expected default classes are applied', function( assert ) {
    this.render( template );

    const element = this.$( '>:first-child' );
    const classes = [ 'btn-xs', 'btn-sm', 'btn-lg' ];
    const noSizeClassByDefault = classes.every( cls => !element.hasClass( cls ) );

    assert.ok(
        element.hasClass( 'btn' ),
        'Has class "btn"'
    );

    assert.ok(
        element.hasClass( 'sl-button' ),
        'Has class "sl-button"'
    );

    assert.ok(
        element.hasClass( 'btn-default' ),
        'Has default theme class'
    );

    assert.ok(
        noSizeClassByDefault,
        'No size class is applied by default'
    );
});

test( 'Class property is supported', function( assert ) {
    this.render( hbs`
        {{#sl-button class='testClass'}}
           Test Button
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'testClass' )
    );
});

test( 'Labels are correctly initialized', function( assert ) {
    const labelText = 'Test';

    this.set( 'label', labelText );
    this.render( hbs`
        {{#sl-button label=label}}
            Default Text
        {{/sl-button}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        labelText,
        'Expected label text is present'
    );
});

test( 'Correct size class is applied', function( assert ) {
    this.render( hbs`
        {{#sl-button size="large"}}
            Default Text
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'btn-lg' ),
        'Has expected class "btn-lg"'
    );
});

test( 'Theme class is applied correctly', function( assert ) {
    this.render( hbs`
        {{#sl-button theme="success"}}
            Default Text
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'btn-success' ),
        'Has expected class "btn-success"'
    );
});

test( 'Label is correct for pending state', function( assert ) {
    const pendingLabelText = 'Pending';
    const changedPendingLabelText = 'Changed pending label text';
    const staticText = 'Static';

    this.set( 'staticText', staticText );

    this.render( hbs`
        {{#sl-button}}
            {{staticText}}
        {{/sl-button}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        staticText,
        'Static text is set initially'
    );

    this.set( 'pendingLabel', pendingLabelText );

    this.render( hbs`
        {{#sl-button pendingLabel=pendingLabel pending=true}}
            Default Text
            {{staticText}}
        {{/sl-button}}
    ` );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        pendingLabelText,
        'Pending text is set while pending'
    );

    this.set( 'pendingLabel', changedPendingLabelText );

    assert.equal(
        this.$( '>:first-child' ).text().trim(),
        changedPendingLabelText,
        'Pending label text is set correctly when updated dynamically'
    );
});

test( 'Pending class is present when in pending state', function( assert ) {
    this.render( hbs`
        {{#sl-button pendingLabel='pending' pending=true}}
            Default Text
        {{/sl-button}}
    ` );

    assert.ok(
        this.$( '>:first-child' ).hasClass( 'pending' )
    );
});

test( 'Tooltip properties are set correctly when title parameter is set', function( assert ) {
    const title = 'test title';

    this.set( 'title', title );

    this.render( hbs`
        {{#sl-button title=title}}
            default text
        {{/sl-button}}
    ` );

    const element = this.$( '>:first-child' );
    const data = element.data();
    const tooltipData = data[ 'bs.tooltip' ];
    const options = tooltipData.getOptions();

    assert.equal(
        tooltipData.enabled,
        true,
        'tooltip is enabled'
    );

    assert.equal(
        tooltipData.getTitle(),
        title,
        'Title text is set correctly'
    );

    assert.equal(
        options.trigger,
        'hover focus',
        'Default trigger is "hover focus"'
    );
});

test( 'Popover properties are set correctly when popover parameter is set', function( assert ) {
    const title = 'test title';
    const popover = 'popover text';

    this.set( 'title', title );
    this.set( 'popover', popover );

    this.render( hbs`
        {{#sl-button title=title popover=popover}}
            default text
        {{/sl-button}}
    ` );

    const element = this.$( '>:first-child' );
    const data = element.data();
    const popoverData = data[ 'bs.popover' ];
    const options = popoverData.getOptions();

    assert.equal(
        popoverData.enabled,
        true,
        'Popover is enabled'
    );

    assert.equal(
        popoverData.getTitle(),
        title,
        'Popover title was set correctly'
    );

    assert.equal(
        popoverData.getContent(),
        popover,
        'Popover text is set correctly'
    );

    assert.equal(
        options.trigger,
        'click',
        'Default trigger is "click"'
    );
});
<|endoftext|>


<commit_before>describe("Label.textAlign", function(){
    var context, core, label;

    beforeEach(function(){
        enchant();
        core = new enchant.Core(320, 320);
        // dummy label for activate canvas layer
        var dummyLabel = new Label('.');
        dummyLabel.moveTo(320, 320);
        core.rootScene.addChild(dummyLabel);
        context = document.getElementsByTagName('canvas')[0].getContext('2d');
        // using multibyte char in tests causes problem when running on phantomjs
        label = new Label('=');
        label.color = "#f00";
        label.font = '10px mono monospace';
    });

    var verifyTextAt = function(textAlign){
        var x = 4, image;
        if(textAlign === 'center') {
            x = label.width / 2;
        } else if (textAlign === 'right') {
            x = label.width - 5;
        }
        // this code is trying to avoid problem about difference of font
        var max = 0;
        for (var y = 0; y < 10; y++) {
            image = context.getImageData(x, y, 1, 1).data;
            max = Math.max(image[0], max);
        }
        return max > 128;
    };

    it("should not be ok with no alignment setting", function(){
        expect(verifyTextAt('left')).to.not.be.ok;
        expect(verifyTextAt('center')).to.not.be.ok;
        expect(verifyTextAt('right')).to.not.be.ok;
    });

    it("should align left", function(){
        label.textAlign = "left";
        core.rootScene.addChild(label);
        expect(verifyTextAt('left')).to.be.ok;
        expect(verifyTextAt('center')).to.not.be.ok;
        expect(verifyTextAt('right')).to.not.be.ok;
    });

    it("should align center", function(){
        label.textAlign = "center";
        core.rootScene.addChild(label);
        expect(verifyTextAt('left')).to.not.be.ok;
        expect(verifyTextAt('center')).to.be.ok;
        expect(verifyTextAt('right')).to.not.be.ok;
    });

    it("should align right", function(){
        label.textAlign = "right";
        core.rootScene.addChild(label);
        expect(verifyTextAt('left')).to.not.be.ok;
        expect(verifyTextAt('center')).to.not.be.ok;
        expect(verifyTextAt('right')).to.be.ok;
    });

    it("should align left as default", function(){
        core.rootScene.addChild(label);
        expect(verifyTextAt('left')).to.be.ok;
        expect(verifyTextAt('center')).to.not.be.ok;
        expect(verifyTextAt('right')).to.not.be.ok;
    });
});
<commit_msg>add Label test<commit_after><|endoftext|>


<commit_before>/*
 * mobile checkboxradio unit tests
 */
(function($){
	module( 'jquery.mobile.forms.checkboxradio.js' );

	test( "widget can be disabled and enabled", function(){
		var input = $( "#checkbox-1" ),
			button = input.parent().find( ".ui-btn" );

		input.checkboxradio( "disable" );
		input.checkboxradio( "enable" );
		ok( !input.attr( "disabled" ), "start input as enabled" );
		ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" );
		ok( !input.attr( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( input.attr( "checked" ), "checked after click" );
		ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" );
		button.trigger( "click" );

		input.checkboxradio( "disable" );
		ok( input.attr( "disabled" ), "input disabled" );
		ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" );
		ok( !input.attr( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( !input.attr( "checked" ), "not checked after click" );
		ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" );
	});

	test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){
		var input1 = $("#checkbox-31");
		var button1 = input1.parent().find(".ui-btn");
		var input2 = $("#checkbox-32");
		var button2 = input2.parent().find(".ui-btn");

		ok(!input1.attr("checked"), "input1 not checked before click");
		ok(!input2.attr("checked"), "input2 not checked before click");

		button1.trigger("click");
		ok(input1.attr("checked"), "input1 checked after click on input1");
		ok(!input2.attr("checked"), "input2 not checked after click on input1");

		button2.trigger("click");
		ok(input1.attr("checked"), "input1 not changed after click on input2");
		ok(input2.attr("checked"), "input2 checked after click on input2");
	});

	asyncTest( "change events fired on checkbox for both check and uncheck", function(){
		var $checkbox = $( "#checkbox-2" ),
			$checkboxLabel = $checkbox.parent().find( ".ui-btn" );

		$checkbox.unbind( "change" );

		expect( 1 );

		$checkbox.one('change', function(){
			ok( true, "change fired on click to check the box" );
		});

		$checkboxLabel.trigger( "click" );

		//test above will be triggered twice, and the start here once
		$checkbox.one('change', function(){
			start();
		});

		$checkboxLabel.trigger( "click" );
	});

	asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){
		var $radioBtns = $( '#radio-active-btn-test input' ),
			singleActiveAndChecked = function(){
				deepEqual( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" );
				// Use the .checked property, not the checked attribute which is not dynamic
				var numChecked = 0;
				$( "#radio-active-btn-test input" ).each(function(i, e) {
					if( e.checked ) {
						numChecked++;
					}
				});
				deepEqual( numChecked, 1, "there should be only one checked" );
			};

		$.testHelper.sequence([
			function(){
				$radioBtns.last().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.last().prop( 'checked' ), "last input is checked" );
				ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is an active button" );

				ok( !$radioBtns.first().prop( 'checked' ), "first input label is not active" );
				ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is not active" );

				singleActiveAndChecked();

				$radioBtns.first().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.first().prop( 'checked' ));
				ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is an active button" );

				ok( !$radioBtns.last().prop( 'checked' ));
				ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is not active" );

				singleActiveAndChecked();

				start();
			}
		], 500);

	});

	test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){
		ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" );
		ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" );
	});

	$.mobile.page.prototype.options.keepNative = "input.should-be-native";

	// not testing the positive case here since's it's obviously tested elsewhere
	test( "checkboxradio elements in the keepNative set shouldn't be enhanced", function() {
		ok( !$("input.should-be-native").parent().is("div.ui-checkbox") );
	});

	test( "Elements with \u201cdata-mini='true'\u201d should have \u201cui-mini\u201d class attached to enhanced element.", function(){
		var full = document.getElementById("radio-full"),
			$fulllbl = $('[for="radio-full"]'),
			mini = document.getElementById("radio-mini"),
			$minilbl = $('[for="radio-mini"]'),
			minictrl = $("#mini-control");

		ok( !full.getAttribute('data-nstest-mini') && !$fulllbl.hasClass('ui-mini'), "Original element does not have data attribute, enhanced version does not recieve .ui-mini.");
		ok( mini.getAttribute('data-nstest-mini'), "Original element has data attribute, enhanced version recieves .ui-mini." );
	});

	asyncTest( "clicking the label triggers a click on the element", function() {
		var clicked = false;

		expect( 1 );

		$( "#checkbox-click-triggered" ).one('click', function() {
			clicked = true;
		});

		$.testHelper.sequence([
			function() {
				$( "[for='checkbox-click-triggered']" ).click();
			},

			function() {
				ok(clicked, "click was fired on input");
				start();
			}
		], 2000);
	});

	asyncTest( "clicking the label triggers a change on the element", function() {
		var changed = false;

		expect( 1 );

		$( "#checkbox-change-triggered" ).one('change', function() {
			changed = true;
		});

		$.testHelper.sequence([
			function() {
				$( "[for='checkbox-change-triggered']" ).click();
			},

			function() {
				ok(changed, "change was fired on input");
				start();
			}
		], 2000);
	});

	test( "theme should be inherited", function() {
		var $inherited = $( "#checkbox-inherit-theme" ),
			$explicit = $( "#checkbox-explicit-theme" );

		ok( $inherited.siblings("label").hasClass( "ui-btn-up-a" ), "should inherit from page" );
		ok( $explicit.siblings("label").hasClass( "ui-btn-up-b" ), "should not inherit" );
	});

	asyncTest( "form submission should include radio button values", function() {
		var $form = $( "#radio-form" ), $input = $form.find("input").first();

		$.testHelper.pageSequence([
			function() {
				$input.click();
				$form.submit();
			},

			function( timeout ){
				var check = location.hash || location.search;

				ok( check.indexOf("radio1=1") >= 0, "the radio was checked" );

				// if the changepage in the previous function failed don't go back
				if( !timeout ){
					window.history.back();
				}
			},

			function(){
				start();
			}
		]);
	});

	asyncTest( "form submission should include checkbox button values", function() {
		var $form = $( "#check-form" ), $inputs = $form.find("input");

		$.testHelper.pageSequence([
			function() {
				$inputs.click();
				$form.submit();
			},

			function( timeout ){
				var check = location.hash || location.search;

				ok( check.indexOf("checkbox-form=on") >= 0, "the first checkbox was checked" );
				ok( check.indexOf("checkbox-form-2=on") >= 0, "the second checkbox was checked" );
				// if the changepage in the previous function failed don't go back
				if( !timeout ){
					window.history.back();
				}
			},

			function(){
				start();
			}
		]);
	});

  test( "nested label checkbox still renders", function() {
    var $checkbox = $( "#checkbox-nested-label" );

    try {
      $checkbox.checkboxradio();
    } catch (e) {
      ok( false, "checkboxradio exception raised: " + e.toString());
    }

    ok( $checkbox.parent().hasClass("ui-checkbox"), "enhancement has occured");
  });

  test( "nested label (no [for]) checkbox still renders", function() {
    var $checkbox = $( "#checkbox-nested-label-no-for" );

    try {
      $checkbox.checkboxradio();
    } catch (e) {
      ok( false, "checkboxradio exception raised: " + e.toString());
    }

    ok( $checkbox.parent().hasClass("ui-checkbox"), "enhancement has occured");
  });

	test( "Icon positioning", function() {
		var bottomicon = $("[for='bottomicon']"),
			topicon = $("[for='topicon']");

		ok( bottomicon.hasClass("ui-btn-icon-bottom"), "Icon position set on label adds the appropriate class." );
		ok( topicon.hasClass("ui-btn-icon-top"), "Icon position set on input adds the appropriate class to the label." );
	});
})(jQuery);
<commit_msg>move checkbox radio property checks to jQuery.fn.prop<commit_after>/*
 * mobile checkboxradio unit tests
 */
(function($){
	module( 'jquery.mobile.forms.checkboxradio.js' );

	test( "widget can be disabled and enabled", function(){
		var input = $( "#checkbox-1" ),
			button = input.parent().find( ".ui-btn" );

		input.checkboxradio( "disable" );
		input.checkboxradio( "enable" );
		ok( !input.prop("disabled"), "start input as enabled" );
		ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" );
		ok( !input.prop("checked"), "not checked before click" );
		button.trigger( "click" );
		ok( input.prop("checked"), "checked after click" );
		ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" );
		button.trigger( "click" );

		input.checkboxradio( "disable" );
		ok( input.attr( "disabled" ), "input disabled" );
		ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" );
		ok( !input.prop( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( !input.prop( "checked" ), "not checked after click" );
		ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" );
	});

	test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){
		var input1 = $("#checkbox-31");
		var button1 = input1.parent().find(".ui-btn");
		var input2 = $("#checkbox-32");
		var button2 = input2.parent().find(".ui-btn");

		ok(!input1.prop("checked"), "input1 not checked before click");
		ok(!input2.prop("checked"), "input2 not checked before click");

		button1.trigger("click");
		ok(input1.prop("checked"), "input1 checked after click on input1");
		ok(!input2.prop("checked"), "input2 not checked after click on input1");

		button2.trigger("click");
		ok(input1.prop("checked"), "input1 not changed after click on input2");
		ok(input2.prop("checked"), "input2 checked after click on input2");
	});

	asyncTest( "change events fired on checkbox for both check and uncheck", function(){
		var $checkbox = $( "#checkbox-2" ),
			$checkboxLabel = $checkbox.parent().find( ".ui-btn" );

		$checkbox.unbind( "change" );

		expect( 1 );

		$checkbox.one('change', function(){
			ok( true, "change fired on click to check the box" );
		});

		$checkboxLabel.trigger( "click" );

		//test above will be triggered twice, and the start here once
		$checkbox.one('change', function(){
			start();
		});

		$checkboxLabel.trigger( "click" );
	});

	asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){
		var $radioBtns = $( '#radio-active-btn-test input' ),
			singleActiveAndChecked = function(){
				deepEqual( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" );
				// Use the .checked property, not the checked attribute which is not dynamic
				var numChecked = 0;
				$( "#radio-active-btn-test input" ).each(function(i, e) {
					if( e.checked ) {
						numChecked++;
					}
				});
				deepEqual( numChecked, 1, "there should be only one checked" );
			};

		$.testHelper.sequence([
			function(){
				$radioBtns.last().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.last().prop( 'checked' ), "last input is checked" );
				ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is an active button" );

				ok( !$radioBtns.first().prop( 'checked' ), "first input label is not active" );
				ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is not active" );

				singleActiveAndChecked();

				$radioBtns.first().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.first().prop( 'checked' ));
				ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is an active button" );

				ok( !$radioBtns.last().prop( 'checked' ));
				ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is not active" );

				singleActiveAndChecked();

				start();
			}
		], 500);

	});

	test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){
		ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" );
		ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" );
	});

	$.mobile.page.prototype.options.keepNative = "input.should-be-native";

	// not testing the positive case here since's it's obviously tested elsewhere
	test( "checkboxradio elements in the keepNative set shouldn't be enhanced", function() {
		ok( !$("input.should-be-native").parent().is("div.ui-checkbox") );
	});

	test( "Elements with \u201cdata-mini='true'\u201d should have \u201cui-mini\u201d class attached to enhanced element.", function(){
		var full = document.getElementById("radio-full"),
			$fulllbl = $('[for="radio-full"]'),
			mini = document.getElementById("radio-mini"),
			$minilbl = $('[for="radio-mini"]'),
			minictrl = $("#mini-control");

		ok( !full.getAttribute('data-nstest-mini') && !$fulllbl.hasClass('ui-mini'), "Original element does not have data attribute, enhanced version does not recieve .ui-mini.");
		ok( mini.getAttribute('data-nstest-mini'), "Original element has data attribute, enhanced version recieves .ui-mini." );
	});

	asyncTest( "clicking the label triggers a click on the element", function() {
		var clicked = false;

		expect( 1 );

		$( "#checkbox-click-triggered" ).one('click', function() {
			clicked = true;
		});

		$.testHelper.sequence([
			function() {
				$( "[for='checkbox-click-triggered']" ).click();
			},

			function() {
				ok(clicked, "click was fired on input");
				start();
			}
		], 2000);
	});

	asyncTest( "clicking the label triggers a change on the element", function() {
		var changed = false;

		expect( 1 );

		$( "#checkbox-change-triggered" ).one('change', function() {
			changed = true;
		});

		$.testHelper.sequence([
			function() {
				$( "[for='checkbox-change-triggered']" ).click();
			},

			function() {
				ok(changed, "change was fired on input");
				start();
			}
		], 2000);
	});

	test( "theme should be inherited", function() {
		var $inherited = $( "#checkbox-inherit-theme" ),
			$explicit = $( "#checkbox-explicit-theme" );

		ok( $inherited.siblings("label").hasClass( "ui-btn-up-a" ), "should inherit from page" );
		ok( $explicit.siblings("label").hasClass( "ui-btn-up-b" ), "should not inherit" );
	});

	asyncTest( "form submission should include radio button values", function() {
		var $form = $( "#radio-form" ), $input = $form.find("input").first();

		$.testHelper.pageSequence([
			function() {
				$input.click();
				$form.submit();
			},

			function( timeout ){
				var check = location.hash || location.search;

				ok( check.indexOf("radio1=1") >= 0, "the radio was checked" );

				// if the changepage in the previous function failed don't go back
				if( !timeout ){
					window.history.back();
				}
			},

			function(){
				start();
			}
		]);
	});

	asyncTest( "form submission should include checkbox button values", function() {
		var $form = $( "#check-form" ), $inputs = $form.find("input");

		$.testHelper.pageSequence([
			function() {
				$inputs.click();
				$form.submit();
			},

			function( timeout ){
				var check = location.hash || location.search;

				ok( check.indexOf("checkbox-form=on") >= 0, "the first checkbox was checked" );
				ok( check.indexOf("checkbox-form-2=on") >= 0, "the second checkbox was checked" );
				// if the changepage in the previous function failed don't go back
				if( !timeout ){
					window.history.back();
				}
			},

			function(){
				start();
			}
		]);
	});

  test( "nested label checkbox still renders", function() {
    var $checkbox = $( "#checkbox-nested-label" );

    try {
      $checkbox.checkboxradio();
    } catch (e) {
      ok( false, "checkboxradio exception raised: " + e.toString());
    }

    ok( $checkbox.parent().hasClass("ui-checkbox"), "enhancement has occured");
  });

  test( "nested label (no [for]) checkbox still renders", function() {
    var $checkbox = $( "#checkbox-nested-label-no-for" );

    try {
      $checkbox.checkboxradio();
    } catch (e) {
      ok( false, "checkboxradio exception raised: " + e.toString());
    }

    ok( $checkbox.parent().hasClass("ui-checkbox"), "enhancement has occured");
  });

	test( "Icon positioning", function() {
		var bottomicon = $("[for='bottomicon']"),
			topicon = $("[for='topicon']");

		ok( bottomicon.hasClass("ui-btn-icon-bottom"), "Icon position set on label adds the appropriate class." );
		ok( topicon.hasClass("ui-btn-icon-top"), "Icon position set on input adds the appropriate class to the label." );
	});
})(jQuery);
<|endoftext|>


<commit_before>'use strict';
var childProcessExecPromise = require('../utils.js').childProcessExecPromise;
var exec = require('child_process').exec;
var fs = require('fs-extra-promise');
var path = require("path");
var Promise = require('lie');
var xcode = require("xcode");

module.exports.addFramework = function(projectPath, thaliCoreFrameworkProjectFolder, includeTests) {
  // We need to build ThaliCore.framework before embedding it into the project
  var thaliFrameworkOutputFolder = path.join(thaliCoreFrameworkProjectFolder, "framework");
  return buildThaliCoreFramework(thaliCoreFrameworkProjectFolder, thaliFrameworkOutputFolder, includeTests)
    .then(function() {
      var pbxProjectPath = path.join(projectPath, "project.pbxproj");
      var xcodeProject = xcode.project(pbxProjectPath);

      return new Promise(function (resolve, reject) {

        xcodeProject.parse(function(err) {

            // If we couldn't parse the project, bail out.
            if (err) {
              reject(new Error("Cannot parse Xcode project: " + JSON.stringify(err)));
              return;
            }

            // Project should not have more that one target.
            var targetUUID = xcodeProject.getFirstTarget().uuid;

            // We need to tell to Xcode project that we use Swift in our framework
            // I believe that this line of code will be removed in the future
            console.log("Adding Build Properties");

            xcodeProject.removeBuildProperty('EMBEDDED_CONTENT_CONTAINS_SWIFT');
            xcodeProject.addBuildProperty('EMBEDDED_CONTENT_CONTAINS_SWIFT', 'YES');

            xcodeProject.removeBuildProperty('OTHER_SWIFT_FLAGS');
            xcodeProject.addBuildProperty('OTHER_SWIFT_FLAGS', '-DTEST');

            xcodeProject.removeBuildProperty('GCC_PREPROCESSOR_DEFINITIONS');
            xcodeProject.updateBuildProperty('GCC_PREPROCESSOR_DEFINITIONS', ['$(inherited)', 'TEST=1']);

            // First check to see if the Embed Framework node exists, if not, add it.
            // This is all we need to do as they are added to the embedded section by default.
            if (!xcodeProject.pbxEmbedFrameworksBuildPhaseObj(targetUUID)) {
                var buildPhaseResult = xcodeProject.addBuildPhase([], "PBXCopyFilesBuildPhase", "Embed Frameworks", targetUUID,  "framework");
                // No idea why, but "Framework" (value 10) is not available in node-xcode, set it here manually so libraries
                // embed correctly.  If we don't set it, the folder type defaults to "Shared Frameworks".
                buildPhaseResult.buildPhase.dstSubfolderSpec = 10;
                console.log("Adding Embedded Build Phase");
            } else {
                console.log("Embedded Build Phase already added");
            }

            // This is critical to include, otherwise the library loader cannot find the dynamic Braintree libs at runtime
            // on a device.
            xcodeProject.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", "Debug");
            xcodeProject.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", "Release");

            // Add the frameworks again.  This time they will have the code-sign option set so they get code signed when being deployed to devices.
            console.log("Adding ThaliCore.framework");
            xcodeProject.addFramework(path.join(thaliFrameworkOutputFolder, "ThaliCore.framework"), {customFramework: true, embed: true, link: true, sign: true});

            // Add the frameworks again. This time they will have the code-sign option set so they get code signed when being deployed to devices.
            if (includeTests) {
              console.log("Adding XCTest.framework");
              var xcTestFrameworkPath = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework";
              // var xcTestFrameworkPath = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework";
              xcodeProject.addFramework(xcTestFrameworkPath, {customFramework: true, embed: true, link: true, sign: true});
            }

            resolve(xcodeProject);
        });
      })
      .then(function(xcodeProject) {
        // Save the project file back to disk.
        return fs.writeFileAsync(pbxProjectPath, xcodeProject.writeSync(), "utf-8");
      });
    });
};

function buildThaliCoreFramework(projectFolder, outputFolder, includeTests) {
  var projectName = "ThaliCore";
  var projectScheme = "ThaliCore";
  if (includeTests) {
    projectScheme = "ThaliCoreCITests";
  }

  var projectConfiguration = "Release";
  var sdk = "iphoneos";
  var projectPath = path.join(projectFolder, projectName + ".xcodeproj");
  var buildDir = path.join(projectFolder, "build");

  var buildCmd = "set -o pipefail && " +
    "xcodebuild -project " +
    "\"" + projectPath + "\"" +
    " -scheme " + "\"" + projectScheme + "\"" +
    " -configuration " + projectConfiguration +
    " -sdk " + sdk +
    " ONLY_ACTIVE_ARCH=NO " +
    " BUILD_DIR=" + "\"" + buildDir + "\"" +
    " clean build" +
    " > /dev/null";

  console.log("Building ThaliCore.framework");

  return childProcessExecPromise(buildCmd, "")
    .then(function () {
      return childProcessExecPromise("mkdir -p " + "\"" + outputFolder + "\"", "");
    })
    .then(function () {
      var frameworkInputPath = path.join(buildDir, projectConfiguration + "-" + sdk, projectName + ".framework");
      var copyFrameworkCmd =
        "cp -R " +
        " \"" + frameworkInputPath + "\"" +
        " \"" + outputFolder + "\"" ;

      return childProcessExecPromise(copyFrameworkCmd, "");
    });
}
<commit_msg>fix prepareThaliCoreFramework.js<commit_after>'use strict';
var childProcessExecPromise = require('../utils.js').childProcessExecPromise;
var exec = require('child_process').exec;
var fs = require('fs-extra-promise');
var path = require("path");
var Promise = require('lie');
var xcode = require("xcode");

module.exports.addFramework = function(projectPath, thaliCoreFrameworkProjectFolder, includeTests) {
  // We need to build ThaliCore.framework before embedding it into the project
  var thaliFrameworkOutputFolder = path.join(thaliCoreFrameworkProjectFolder, "framework");
  return buildThaliCoreFramework(thaliCoreFrameworkProjectFolder, thaliFrameworkOutputFolder, includeTests)
    .then(function() {
      var pbxProjectPath = path.join(projectPath, "project.pbxproj");
      var xcodeProject = xcode.project(pbxProjectPath);

      return new Promise(function (resolve, reject) {

        xcodeProject.parse(function(err) {

            // If we couldn't parse the project, bail out.
            if (err) {
              reject(new Error("Cannot parse Xcode project: " + JSON.stringify(err)));
              return;
            }

            // Project should not have more that one target.
            var targetUUID = xcodeProject.getFirstTarget().uuid;

            // We need to tell to Xcode project that we use Swift in our framework
            // I believe that this line of code will be removed in the future
            console.log("Adding Build Properties");

            xcodeProject.removeBuildProperty('EMBEDDED_CONTENT_CONTAINS_SWIFT');
            xcodeProject.addBuildProperty('EMBEDDED_CONTENT_CONTAINS_SWIFT', 'YES');

            xcodeProject.removeBuildProperty('OTHER_SWIFT_FLAGS');
            xcodeProject.addBuildProperty('OTHER_SWIFT_FLAGS', '\"-DTEST\"');

            xcodeProject.removeBuildProperty('GCC_PREPROCESSOR_DEFINITIONS');
            xcodeProject.updateBuildProperty('GCC_PREPROCESSOR_DEFINITIONS', ['\"$(inherited)\"', '\"TEST=1\"']);

            // First check to see if the Embed Framework node exists, if not, add it.
            // This is all we need to do as they are added to the embedded section by default.
            if (!xcodeProject.pbxEmbedFrameworksBuildPhaseObj(targetUUID)) {
                var buildPhaseResult = xcodeProject.addBuildPhase([], "PBXCopyFilesBuildPhase", "Embed Frameworks", targetUUID,  "framework");
                // No idea why, but "Framework" (value 10) is not available in node-xcode, set it here manually so libraries
                // embed correctly.  If we don't set it, the folder type defaults to "Shared Frameworks".
                buildPhaseResult.buildPhase.dstSubfolderSpec = 10;
                console.log("Adding Embedded Build Phase");
            } else {
                console.log("Embedded Build Phase already added");
            }

            // This is critical to include, otherwise the library loader cannot find the dynamic Braintree libs at runtime
            // on a device.
            xcodeProject.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", "Debug");
            xcodeProject.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", "Release");

            // Add the frameworks again.  This time they will have the code-sign option set so they get code signed when being deployed to devices.
            console.log("Adding ThaliCore.framework");
            xcodeProject.addFramework(path.join(thaliFrameworkOutputFolder, "ThaliCore.framework"), {customFramework: true, embed: true, link: true, sign: true});

            // Add the frameworks again. This time they will have the code-sign option set so they get code signed when being deployed to devices.
            if (includeTests) {
              console.log("Adding XCTest.framework");
              var xcTestFrameworkPath = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework";
              // var xcTestFrameworkPath = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework";
              xcodeProject.addFramework(xcTestFrameworkPath, {customFramework: true, embed: true, link: true, sign: true});
            }

            resolve(xcodeProject);
        });
      })
      .then(function(xcodeProject) {
        // Save the project file back to disk.
        return fs.writeFileAsync(pbxProjectPath, xcodeProject.writeSync(), "utf-8");
      });
    });
};

function buildThaliCoreFramework(projectFolder, outputFolder, includeTests) {
  var projectName = "ThaliCore";
  var projectScheme = "ThaliCore";
  if (includeTests) {
    projectScheme = "ThaliCoreCITests";
  }

  var projectConfiguration = "Release";
  var sdk = "iphoneos";
  var projectPath = path.join(projectFolder, projectName + ".xcodeproj");
  var buildDir = path.join(projectFolder, "build");

  var buildCmd = "set -o pipefail && " +
    "xcodebuild -project " +
    "\"" + projectPath + "\"" +
    " -scheme " + "\"" + projectScheme + "\"" +
    " -configuration " + projectConfiguration +
    " -sdk " + sdk +
    " ONLY_ACTIVE_ARCH=NO " +
    " BUILD_DIR=" + "\"" + buildDir + "\"" +
    " clean build" +
    " > /dev/null";

  console.log("Building ThaliCore.framework");

  return childProcessExecPromise(buildCmd, "")
    .then(function () {
      return childProcessExecPromise("mkdir -p " + "\"" + outputFolder + "\"", "");
    })
    .then(function () {
      var frameworkInputPath = path.join(buildDir, projectConfiguration + "-" + sdk, projectName + ".framework");
      var copyFrameworkCmd =
        "cp -R " +
        " \"" + frameworkInputPath + "\"" +
        " \"" + outputFolder + "\"" ;

      return childProcessExecPromise(copyFrameworkCmd, "");
    });
}
<|endoftext|>


<commit_before>(function(){
/**
 * IX.Date is a set of utilities for Date to convert to or deconvert to data string. It includes: {
  	setDS(v) : set separator between YYYY MM DD, will affect all date utilities;
 	setTS(v) : set separator between hh mm ss, will affect all date utilities;
 	setUTC(bool) : set if using UTC
 	getDS() : get separator between YYYY MM DD
 	getTS() : get separator between hh mm ss
 	isUTC :return if using UTC

 	format(date) : return a string like "YYYY-MM-DD hh:mm:ss" for date;
	formatDate(date) : return a string  in "YYYY-MM-DD" for date
	formatTime(date) : return a string  in "hh:mm:ss" for date

 	formatStr(str) :  parse str first, next do similar as format
 	formatDateStr(str) : similar as formatDate
 	formatTimeStr(str) : similar as formatTime

	getDateText(oldTSinMS, curTSinMS) : show interval in simple mode,
 	isValid(dateStr, type) :  check if valid type format for dateStr which separated with TS/DS
 * }
 *
 * IX.IDate is a Class to deal with Date. It is supplement for Date:
 * 	@Params timeInSecond : the time ticks in second from 1970,1,1
 *	@Methods :{
		toText : similar to IX.Date.format
		toWeek : return the day in the week
		toDate(includeYear) : return [YYYY年]M月D日,
		toTime(ts) : return hh:mm
		toShort :return [[YYYY年]M月D日] hh:mm
		toInterval(tsInSec) : return simple interval or Today hh:mm or [[YYYY年]M月D日] hh:mm for tsInSec or now,
		toSimpleInterval : show interval in simple mode until now,
 *	};
 */

var Fields4Day = ["FullYear", "Month", "Date"];
var Fields4Time = ["Hours", "Minutes", "Seconds"],
	Fields4Week = ["Hours", "Minutes",, "Day"];

var FieldLimits4Day = [-1, 12, 31], FieldLimits4Time = [24, 60, 60];
var IntervalUnits = ["刚才", "秒钟前", "分钟前", "小时前", "天前", "周前", "个月前", "年前"];
var IntervalCounts = [0, 10, 60, 3600, 86400, 604800, 2592000, 31536000];
var DT_Weeks = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");
var DT_KeyWords = {
	Year : "年",
	Month : "月",
	Day : "日",
	Today : "今天"
};

var _isUTC = false;
var ds = "-", ts = ":";

function getFieldValues(dt, fields){
	var getPrefix = "get" + (_isUTC?"UTC":"");
	return IX.map(fields, function(f){
		var v  = dt[getPrefix + f]() - (f=="Month"?-1:0);
		var s = "00"+ v;
		return f=="FullYear" ? v : s.substring(s.length-2);
	});
}
function getText4Interval(olderTSInMS, tsInMS) {
	var interval = (tsInMS -olderTSInMS) / 1000 ;
	for (var i = IntervalCounts.length-1; i>=0; i--)
		if (interval >= IntervalCounts[i]){
			var nstr = i===0 ? "" : Math.round(interval / (i==1?1:IntervalCounts[i]));
			return nstr + IntervalUnits[i];
		}
}
function isValidDate(sps, isDate){ // sps: [2012,9, 3] or [13, 30, 0]...
	var limits = isDate ? FieldLimits4Day : FieldLimits4Time;
	return sps.length == 3 && IX.loop(sps, true, function(acc, item, idx){
		if (!acc || isNaN(item) || item.indexOf(".")>=0) return false; // invalid number;
		if (isDate && idx===0) return true; //  will not check year number;
		var n = item * 1 + (isDate ? 0 : 1);
		return n > 0 && n <= limits[idx];
	});
}

function _formatStr(str, sp) {
	if (IX.isEmpty(str))
		return "";
	str = str.split(sp, 3);
	return IX.map(sp==ds?[4,2,2]:[2,2,2], function(item, idx){
		var nstr = (str.length>idx?str[idx]:"");
		return ("0".multi(item) + nstr).substr(nstr.length, item);
	}).join(sp);
}
function _format(date, type) {
	var dateStr = type != "Time" ? getFieldValues(date, Fields4Day).join(ds) : "",
		timeStr = type != "Date" ? getFieldValues(date, Fields4Time).join(ts) : "";
	if (type == "Date") return dateStr;
	else if (type == "Time") return timeStr;
	else return dateStr + " " + timeStr;
}
function isValid(str, isDate){
	return isValidDate(str.split(isDate?ds :ts, 3), isDate);
}
IX.Date = {
	setDS : function(v){ds = v;},
	setTS : function(v){ts = v;},
	setUTC : function(isUTC){_isUTC= isUTC;},
	getDS : function(){return ds;},
	getTS : function(){return ts;},
	isUTC :function(){return _isUTC;},
	// return YYYY-MM-DD hh:mm:ss
	format : _format,
	// return YYYY-MM-DD
	formatDate : function(date) {return _format(date, "Date");},
	// return hh:mm:ss
	formatTime : function(date) {return _format(date, "Time");},

	// return YYYY-MM-DD hh:mm:ss
	formatStr:function(str) {
		str = (str + " ").split(" ");
		return _formatStr(str[0], ds) + " " + _formatStr(str[1], ts);
	},
	// return YYYY-MM-DD
	formatDateStr:function(str){return _formatStr(str, ds);},
	// return hh:mm:ss
	formatTimeStr:function(str){return _formatStr(str, ts);},
	getDateText : getText4Interval,

	formatBySec : function(tickInSec, withTime){
		return !tickInSec?"":_format(new Date(tickInSec*1000), withTime?"":"Date");
	},
	getTickInSec : function(str){
		var tickInMS = null;
		if (str && str instanceof Date)
			tickInMS =  str.getTime();
		else if (IX.isString(str) && !IX.isEmpty(str)) {
			var sp = str.replace(/[0-9|:|\ ]/g, '')[0];
			tickInMS = (new Date(str.replaceAll(sp, "/"))).getTime();
		}
		return isNaN(tickInMS) ? null : Math.ceil(tickInMS/1000);
	},

	// accept YYYY-MM-DD hh:mm:ss return true/false;
	isValid : function(dateStr, type) {
		var dt = dateStr.split(" ");
		if (type=="Date" ||type=="Time")
			return dt.length==1 && isValid(dt[0], type == "Date");
		return dt.length==2 && isValid(dt[0], true) && isValid(dt[1], false);
	}
};

IX.IDate = function(timeInSecond) {
	var timeInMS = timeInSecond*1000;
	var date = new Date(timeInMS);
	var dateStr = _format(date);
	var timeValues = getFieldValues(date, [].concat(Fields4Day, Fields4Week));

	function toDateStr(includeYear){
		var curTime = getFieldValues(new Date(), Fields4Day);
		includeYear = includeYear || (curTime[0]>timeValues[0]);
		return [includeYear?timeValues[0]:"", includeYear?DT_KeyWords.Year:"",timeValues[1], DT_KeyWords.Month, timeValues[2], DT_KeyWords.Day].join("");
	}
	function _toIntvText(_date, showToday){
		var curTime = getFieldValues(_date, [].concat(Fields4Day, Fields4Week));
		var strs = [];
		var shouldAppend = false;
		if (timeValues[0] != curTime[0]){
			shouldAppend = true;
			strs = strs.concat(timeValues[0], ds);
		}
		if (shouldAppend || timeValues[1] != curTime[1] || timeValues[2] != curTime[2])
			strs = strs.concat(timeValues[1], ds, timeValues[2], "");
		else if (showToday)
			strs = DT_KeyWords.Today +" ";

		strs = strs.concat(timeValues[3], ts, timeValues[4]);
		return strs.join("");
	}

	return {
		toText: function(){return dateStr;},
		toWeek : function() {return DT_Weeks[timeValues[5]];},
		toDate: toDateStr,
		toTime : function(ds){return [timeValues[3], timeValues[4]].join(ds || ":");},
		toShort : function(){ return _toIntvText(new Date(), false);},
		toInterval : function(tsInSec){
			var _date = tsInSec?(new Date(tsInSec*1000)) :(new Date());
			var _tsInMS = _date.getTime();
			if(_tsInMS- timeInMS<3600000) // inner one hour
				return getText4Interval(timeInMS, _tsInMS);
			return _toIntvText(_date, true);
		},
		toSimpleInterval : function(){return getText4Interval(timeInSecond * 1000, IX.getTimeInMS());}
	};
};
})();<commit_msg>fix bug<commit_after>(function(){
/**
 * IX.Date is a set of utilities for Date to convert to or deconvert to data string. It includes: {
  	setDS(v) : set separator between YYYY MM DD, will affect all date utilities;
 	setTS(v) : set separator between hh mm ss, will affect all date utilities;
 	setUTC(bool) : set if using UTC
 	getDS() : get separator between YYYY MM DD
 	getTS() : get separator between hh mm ss
 	isUTC :return if using UTC

 	format(date) : return a string like "YYYY-MM-DD hh:mm:ss" for date;
	formatDate(date) : return a string  in "YYYY-MM-DD" for date
	formatTime(date) : return a string  in "hh:mm:ss" for date

 	formatStr(str) :  parse str first, next do similar as format
 	formatDateStr(str) : similar as formatDate
 	formatTimeStr(str) : similar as formatTime

	getDateText(oldTSinMS, curTSinMS) : show interval in simple mode,
 	isValid(dateStr, type) :  check if valid type format for dateStr which separated with TS/DS
 * }
 *
 * IX.IDate is a Class to deal with Date. It is supplement for Date:
 * 	@Params timeInSecond : the time ticks in second from 1970,1,1
 *	@Methods :{
		toText : similar to IX.Date.format
		toWeek : return the day in the week
		toDate(includeYear) : return [YYYY年]M月D日,
		toTime(ts) : return hh:mm
		toShort :return [[YYYY年]M月D日] hh:mm
		toInterval(tsInSec) : return simple interval or Today hh:mm or [[YYYY年]M月D日] hh:mm for tsInSec or now,
		toSimpleInterval : show interval in simple mode until now,
 *	};
 */

var Fields4Day = ["FullYear", "Month", "Date"];
var Fields4Time = ["Hours", "Minutes", "Seconds"],
	Fields4Week = ["Hours", "Minutes", "Day"];

var FieldLimits4Day = [-1, 12, 31], FieldLimits4Time = [24, 60, 60];
var IntervalUnits = ["刚才", "秒钟前", "分钟前", "小时前", "天前", "周前", "个月前", "年前"];
var IntervalCounts = [0, 10, 60, 3600, 86400, 604800, 2592000, 31536000];
var DT_Weeks = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");
var DT_KeyWords = {
	Year : "年",
	Month : "月",
	Day : "日",
	Today : "今天"
};

var _isUTC = false;
var ds = "-", ts = ":";

function getFieldValues(dt, fields){
	var getPrefix = "get" + (_isUTC?"UTC":"");
	return IX.map(fields, function(f){
		var v  = dt[getPrefix + f]() - (f=="Month"?-1:0);
		var s = "00"+ v;
		return f=="FullYear" ? v : s.substring(s.length-2);
	});
}
function getText4Interval(olderTSInMS, tsInMS) {
	var interval = (tsInMS -olderTSInMS) / 1000 ;
	for (var i = IntervalCounts.length-1; i>=0; i--)
		if (interval >= IntervalCounts[i]){
			var nstr = i===0 ? "" : Math.round(interval / (i==1?1:IntervalCounts[i]));
			return nstr + IntervalUnits[i];
		}
}
function isValidDate(sps, isDate){ // sps: [2012,9, 3] or [13, 30, 0]...
	var limits = isDate ? FieldLimits4Day : FieldLimits4Time;
	return sps.length == 3 && IX.loop(sps, true, function(acc, item, idx){
		if (!acc || isNaN(item) || item.indexOf(".")>=0) return false; // invalid number;
		if (isDate && idx===0) return true; //  will not check year number;
		var n = item * 1 + (isDate ? 0 : 1);
		return n > 0 && n <= limits[idx];
	});
}

function _formatStr(str, sp) {
	if (IX.isEmpty(str))
		return "";
	str = str.split(sp, 3);
	return IX.map(sp==ds?[4,2,2]:[2,2,2], function(item, idx){
		var nstr = (str.length>idx?str[idx]:"");
		return ("0".multi(item) + nstr).substr(nstr.length, item);
	}).join(sp);
}
function _format(date, type) {
	var dateStr = type != "Time" ? getFieldValues(date, Fields4Day).join(ds) : "",
		timeStr = type != "Date" ? getFieldValues(date, Fields4Time).join(ts) : "";
	if (type == "Date") return dateStr;
	else if (type == "Time") return timeStr;
	else return dateStr + " " + timeStr;
}
function isValid(str, isDate){
	return isValidDate(str.split(isDate?ds :ts, 3), isDate);
}
IX.Date = {
	setDS : function(v){ds = v;},
	setTS : function(v){ts = v;},
	setUTC : function(isUTC){_isUTC= isUTC;},
	getDS : function(){return ds;},
	getTS : function(){return ts;},
	isUTC :function(){return _isUTC;},
	// return YYYY-MM-DD hh:mm:ss
	format : _format,
	// return YYYY-MM-DD
	formatDate : function(date) {return _format(date, "Date");},
	// return hh:mm:ss
	formatTime : function(date) {return _format(date, "Time");},

	// return YYYY-MM-DD hh:mm:ss
	formatStr:function(str) {
		str = (str + " ").split(" ");
		return _formatStr(str[0], ds) + " " + _formatStr(str[1], ts);
	},
	// return YYYY-MM-DD
	formatDateStr:function(str){return _formatStr(str, ds);},
	// return hh:mm:ss
	formatTimeStr:function(str){return _formatStr(str, ts);},
	getDateText : getText4Interval,

	formatBySec : function(tickInSec, withTime){
		return !tickInSec?"":_format(new Date(tickInSec*1000), withTime?"":"Date");
	},
	getTickInSec : function(str){
		var tickInMS = null;
		if (str && str instanceof Date)
			tickInMS =  str.getTime();
		else if (IX.isString(str) && !IX.isEmpty(str)) {
			var sp = str.replace(/[0-9|:|\ ]/g, '')[0];
			tickInMS = (new Date(str.replaceAll(sp, "/"))).getTime();
		}
		return isNaN(tickInMS) ? null : Math.ceil(tickInMS/1000);
	},

	// accept YYYY-MM-DD hh:mm:ss return true/false;
	isValid : function(dateStr, type) {
		var dt = dateStr.split(" ");
		if (type=="Date" ||type=="Time")
			return dt.length==1 && isValid(dt[0], type == "Date");
		return dt.length==2 && isValid(dt[0], true) && isValid(dt[1], false);
	}
};

IX.IDate = function(timeInSecond) {
	var timeInMS = timeInSecond*1000;
	var date = new Date(timeInMS);
	var dateStr = _format(date);
	var timeValues = getFieldValues(date, [].concat(Fields4Day, Fields4Week));

	function toDateStr(includeYear){
		var curTime = getFieldValues(new Date(), Fields4Day);
		includeYear = includeYear || (curTime[0]>timeValues[0]);
		return [includeYear?timeValues[0]:"", includeYear?DT_KeyWords.Year:"",timeValues[1], DT_KeyWords.Month, timeValues[2], DT_KeyWords.Day].join("");
	}
	function _toIntvText(_date, showToday){
		var curTime = getFieldValues(_date, [].concat(Fields4Day, Fields4Week));
		var strs = [];
		var shouldAppend = false;
		if (timeValues[0] != curTime[0]){
			shouldAppend = true;
			strs = strs.concat(timeValues[0], ds);
		}
		if (shouldAppend || timeValues[1] != curTime[1] || timeValues[2] != curTime[2])
			strs = strs.concat(timeValues[1], ds, timeValues[2], "");
		else if (showToday)
			strs = DT_KeyWords.Today +" ";

		strs = strs.concat(timeValues[3], ts, timeValues[4]);
		return strs.join("");
	}

	return {
		toText: function(){return dateStr;},
		toWeek : function() {return DT_Weeks[timeValues[5]-0];},
		toDate: toDateStr,
		toTime : function(ds){return [timeValues[3], timeValues[4]].join(ds || ":");},
		toShort : function(){ return _toIntvText(new Date(), false);},
		toInterval : function(tsInSec){
			var _date = tsInSec?(new Date(tsInSec*1000)) :(new Date());
			var _tsInMS = _date.getTime();
			if(_tsInMS- timeInMS<3600000) // inner one hour
				return getText4Interval(timeInMS, _tsInMS);
			return _toIntvText(_date, true);
		},
		toSimpleInterval : function(){return getText4Interval(timeInSecond * 1000, IX.getTimeInMS());}
	};
};
})();
<|endoftext|>


<commit_before><commit_msg>js refactor foreach through arrays<commit_after><|endoftext|>


<commit_before>// This file is used to make additional changes
// when building an app to run in node.js.
// Free to edit. You can break tests (cli test runner uses
// this to build itself - it is a node executable).
define("amber/Platform", ["amber_core/Platform-Node"], {});
define("amber/browser-compatibility", {});
define("jquery", {});
<commit_msg>config-node: map amber/c11y to amber/node-c11y<commit_after>// This file is used to make additional changes
// when building an app to run in node.js.
// Free to edit. You can break tests (cli test runner uses
// this to build itself - it is a node executable).
define("amber/Platform", ["amber_core/Platform-Node"], {});
define("amber/compatibility", ["amber/node-compatibility"], {});
define("jquery", {});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Alejandro Mantilla <@AlejoJamC>.
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the LICENSE
 * file in the root directory of this source tree or translated in the assets folder.
 */

var express     = require('express');
var base64      = require('../config/base64');
var crypto      = require('crypto');
var dashRoutes  = express.Router();
var fs          = require('fs');
var logger      = require('../config/logger').logger;
var multer      = require('multer');
var oracledb    = require('oracledb');
var path        = require('path');

// Upload and rename files
var storage = multer.diskStorage({
    destination: 'uploads/',
    filename: function (req, file, cb) {
        crypto.pseudoRandomBytes(16, function (err, raw) {
            if (err) return cb(err);

            cb(null, raw.toString('hex') + path.extname(file.originalname))
        })
    }
});
var upload = multer({ storage: storage });

/* GET Index page | Dashboard. */
dashRoutes.get('/dashboard', function (req, res) {
    // Basic error validator
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        res.redirect('/login');
    }

    res.render('dash/index', {
        title   : 'Analytics Website | Index',
        level   : '',
        layout  : 'dash'
    });
});

/* GET Images handler page | Dashboard. */
dashRoutes.get('/dashboard/images', function (req, res) {
    res.render('dash/image', {
        title   : 'Analytics Website | Images',
        level   : '../',
        layout  : 'dash'
    });
});

/* GET Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/capture',  function (req, res) {
    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        res.redirect('/dashboard/images?error=12');
    }

    logger.info(req.body);

    var encoded_image = req.body.finalimage;
    var binary_data = base64.decode(encoded_image);
    // Create the file inside uploads folder
    var fileresult = fs.writeFile('uploads/fototomada.jpg', binary_data, function (err) {
        logger.info('archivo creado');
    })

});

/* GET Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/input', upload.single('inputpicture'), function (req, res) {
    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        res.redirect('/login?error=12');
    }

    //logger.info(req.file);
    //logger.info(req.body);

    var personId = req.body.personid;

    var sql = "UPDATE ANALYTICS.\"NPersonas\" SET ANALYTICS.\"NPersonas\".\"Foto\" = '" +
        req.file.path + "' WHERE ANALYTICS.\"NPersonas\".\"idPersona\" =" + personId;

    logger.info(sql);

    // Save image route
    oracledb.autoCommit = true;
    oracledb.getConnection({
        user            : process.env.ORACLE_USERNAME,
        password        : process.env.ORACLE_PASSWORD,
        connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
        + '/' + process.env.ORACLE_SID
    }, function (err, connection) {
        if (err){
            logger.error(err.message);
            // error=0 trying to connect with database
            res.redirect('/dashboard/images?error=0');
        }

        connection.execute(
            sql,
            // The Callback function handles the SQL execution results
            function (err, result) {
                if (err) {
                    logger.error(err.message);
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                res.redirect('/dashboard/images?error=1');
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    // Error doing select statement
                    res.redirect('/dashboard/images?error=12');
                }

                logger.info(result);

                // UPDATE image capture success
                connection.close(
                    function(err) {
                        if (err) {
                            // error=1 trying to disconnect of database
                            logger.error(err.message);
                            res.redirect('/dashboard/images?error=1');
                        }
                        logger.info('Connection to Oracle closed successfully!');
                    });
                res.redirect('/dashboard/images?flag=success');
            }
        );

        // Image route
        //var imgroute =
    });

});

module.exports = dashRoutes;<commit_msg>avoid unnecesary logs<commit_after>/**
 * Copyright (c) 2016-present, Alejandro Mantilla <@AlejoJamC>.
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the LICENSE
 * file in the root directory of this source tree or translated in the assets folder.
 */

var express     = require('express');
var base64      = require('../config/base64');
var crypto      = require('crypto');
var dashRoutes  = express.Router();
var fs          = require('fs');
var logger      = require('../config/logger').logger;
var multer      = require('multer');
var oracledb    = require('oracledb');
var path        = require('path');

// Upload and rename files
var storage = multer.diskStorage({
    destination: 'uploads/',
    filename: function (req, file, cb) {
        crypto.pseudoRandomBytes(16, function (err, raw) {
            if (err) return cb(err);

            cb(null, raw.toString('hex') + path.extname(file.originalname))
        })
    }
});
var upload = multer({ storage: storage });

/* GET Index page | Dashboard. */
dashRoutes.get('/dashboard', function (req, res) {
    // Basic error validator
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        res.redirect('/login');
    }

    res.render('dash/index', {
        title   : 'Analytics Website | Index',
        level   : '',
        layout  : 'dash'
    });
});

/* GET Images handler page | Dashboard. */
dashRoutes.get('/dashboard/images', function (req, res) {
    res.render('dash/image', {
        title   : 'Analytics Website | Images',
        level   : '../',
        layout  : 'dash'
    });
});

/* GET Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/capture',  function (req, res) {
    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        res.redirect('/dashboard/images?error=12');
    }

    logger.info(req.body);

    var encoded_image = req.body.finalimage;
    var binary_data = base64.decode(encoded_image);
    // Create the file inside uploads folder
    var fileresult = fs.writeFile('uploads/fototomada.jpg', binary_data, function (err) {
        logger.info('archivo creado');
    })

});

/* GET Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/input', upload.single('inputpicture'), function (req, res) {
    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        res.redirect('/login?error=12');
    }

    //logger.info(req.file);
    //logger.info(req.body);

    var personId = req.body.personid;

    var sql = "UPDATE ANALYTICS.\"NPersonas\" SET ANALYTICS.\"NPersonas\".\"Foto\" = '" +
        req.file.path + "' WHERE ANALYTICS.\"NPersonas\".\"idPersona\" =" + personId;

    //logger.info(sql);

    // Save image route
    oracledb.autoCommit = true;
    oracledb.getConnection({
        user            : process.env.ORACLE_USERNAME,
        password        : process.env.ORACLE_PASSWORD,
        connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
        + '/' + process.env.ORACLE_SID
    }, function (err, connection) {
        if (err){
            logger.error(err.message);
            // error=0 trying to connect with database
            res.redirect('/dashboard/images?error=0');
        }

        connection.execute(
            sql,
            // The Callback function handles the SQL execution results
            function (err, result) {
                if (err) {
                    logger.error(err.message);
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                res.redirect('/dashboard/images?error=1');
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    // Error doing select statement
                    res.redirect('/dashboard/images?error=12');
                }

                logger.info(result);

                // UPDATE image capture success
                connection.close(
                    function(err) {
                        if (err) {
                            // error=1 trying to disconnect of database
                            logger.error(err.message);
                            res.redirect('/dashboard/images?error=1');
                        }
                        logger.info('Connection to Oracle closed successfully!');
                    });
                res.redirect('/dashboard/images?flag=success');
            }
        );
    });

});

module.exports = dashRoutes;<|endoftext|>