<commit_before>import { action, observable, computed } from "mobx";
import SortBy from "sort-array";
import TestCase from "../../models/TestCase";
import Suite from "../../models/Suite";

export default class ProjectStore {
  @observable modified = false;
  @observable name = "";
  @observable url = "";
  @observable _tests = [];
  @observable _suites = [];
  @observable _urls = [];

  constructor(name = "Untitled Project") {
    this.name = name;
    this.toJSON = this.toJSON.bind(this);
  }

  @computed get suites() {
    return SortBy(this._suites, "name");
  }

  @computed get tests() {
    return SortBy(this._tests, "name");
  }

  @computed get urls() {
    return this._urls.sort();
  }

  @action.bound setUrl(url) {
    this.url = url;
  }

  @action.bound addUrl(url) {
    this._urls.push(url);
  }

  @action.bound changeName(name) {
    this.name = name;
  }

  @action.bound setModified() {
    this.modified = true;
  }

  @action.bound createSuite(...argv) {
    const suite = new Suite(undefined, ...argv);
    this._suites.push(suite);

    return suite;
  }

  @action.bound deleteSuite(suite) {
    this._suites.remove(suite);
  }

  @action.bound createTestCase(...argv) {
    const test = new TestCase(undefined, ...argv);
    this.addTestCase(test);

    return test;
  }

  @action.bound addTestCase(test) {
    if (!test || test.constructor.name !== "TestCase") {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this._tests.push(test);
    }
  }

  @action.bound deleteTestCase(test) {
    if (!test || test.constructor.name !== "TestCase") {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this.suites.forEach(suite => {
        suite.removeTestCase(test);
      });
      this._tests.remove(test);
    }
  }

  toJSON() {
    return JSON.stringify({
      name: this.name,
      url: this.url,
      tests: this._tests,
      suites: this._suites.map(s => s.exportSuite()),
      urls: this._urls
    });
  }

  @action
  static fromJS = function(jsRep) {
    const project = new ProjectStore(jsRep.name);
    project.setUrl(jsRep.url);
    project._tests.replace(jsRep.tests.map(TestCase.fromJS));
    project._suites.replace(jsRep.suites.map((suite) => Suite.fromJS(suite, project.tests)));
    project._urls.replace(jsRep.urls);

    return project;
  }
}
<commit_msg>Add the id observable<commit_after>import { action, observable, computed } from "mobx";
import uuidv4 from "uuid/v4";
import SortBy from "sort-array";
import TestCase from "../../models/TestCase";
import Suite from "../../models/Suite";

export default class ProjectStore {
  @observable id = uuidv4();
  @observable modified = false;
  @observable name = "";
  @observable url = "";
  @observable _tests = [];
  @observable _suites = [];
  @observable _urls = [];

  constructor(name = "Untitled Project") {
    this.name = name;
    this.toJSON = this.toJSON.bind(this);
  }

  @computed get suites() {
    return SortBy(this._suites, "name");
  }

  @computed get tests() {
    return SortBy(this._tests, "name");
  }

  @computed get urls() {
    return this._urls.sort();
  }

  @action.bound setUrl(url) {
    this.url = url;
  }

  @action.bound addUrl(url) {
    this._urls.push(url);
  }

  @action.bound changeName(name) {
    this.name = name;
  }

  @action.bound setModified() {
    this.modified = true;
  }

  @action.bound createSuite(...argv) {
    const suite = new Suite(undefined, ...argv);
    this._suites.push(suite);

    return suite;
  }

  @action.bound deleteSuite(suite) {
    this._suites.remove(suite);
  }

  @action.bound createTestCase(...argv) {
    const test = new TestCase(undefined, ...argv);
    this.addTestCase(test);

    return test;
  }

  @action.bound addTestCase(test) {
    if (!test || test.constructor.name !== "TestCase") {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this._tests.push(test);
    }
  }

  @action.bound deleteTestCase(test) {
    if (!test || test.constructor.name !== "TestCase") {
      throw new Error(`Expected to receive TestCase instead received ${test ? test.constructor.name : test}`);
    } else {
      this.suites.forEach(suite => {
        suite.removeTestCase(test);
      });
      this._tests.remove(test);
    }
  }

  @action.bound fromJS(jsRep) {
    this.id = jsRep.id || uuidv4();
    this.name = jsRep.name;
    this.setUrl(jsRep.url);
    this._tests.replace(jsRep.tests.map(TestCase.fromJS));
    this._suites.replace(jsRep.suites.map((suite) => Suite.fromJS(suite, this.tests)));
    this._urls.replace(jsRep.urls);
    this.modified = false;
  }

  toJSON() {
    return JSON.stringify({
      name: this.name,
      url: this.url,
      tests: this._tests,
      suites: this._suites.map(s => s.exportSuite()),
      urls: this._urls
    });
  }
}
<|endoftext|>


<commit_before><commit_msg>Updated systemjs to support bundled umd files<commit_after><|endoftext|>


<commit_before>var exec = require('cordova/exec');
/**
 * Constructor
 */
function MyBeacon() {}

MyBeacon.prototype.getBeacons = function() {
  exec(function(result){
      // result handler
      alert('Beacon count is '+result);
    },
    function(error){
      // error handler
      alert("Error" + error);
    },
    "MyBeacon",
    "getBeacons",
    []
  );
}

var myBeacon = new MyBeacon();
module.exports = myBeacon;<commit_msg>modify MyBeacon.js to latest version<commit_after>cordova.define("org.doublenian.mybeacon.MyBeacon", function(require, exports, module) { var exec = require('cordova/exec');
/**
 * Constructor
 */
 function MyBeacon() {}

  MyBeacon.prototype.getBeacons = function(sucess,error) {
          exec(sucess,
                    error,
                    "MyBeacon",
                    "getBeacons",
                    []
                    );
           }

   var myBeacon = new MyBeacon();
   module.exports = myBeacon;
   });
<|endoftext|>


<commit_before>/*
 * Copyright 2014 XWiki SAS
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
require.config({
    'shim': {
        'bower/modalBox/modalBox-min': ['bower/jquery/dist/jquery.min'],
    }
});
define([
    'messages',
    'bower/modalBox/modalBox-min'
], function (Messages) {

    var STYLE = [
        ''
    ].join('');

    var CONTENT = [
        '

',
        '
',
        '

'
    ].join('');

    var ERROR_ADDITIONAL = [
        '

',
        '',
        '<textarea id="errorBox_detailsBox" class="errorData"></textarea>',
    ].join('');

    var showError = function (errorType, docHtml, moreInfo) {
        $('body').append('

');
        var $modalbox = $('.modalBox')
        $modalbox.append(CONTENT + STYLE);

        $modalbox.find('.errorType').text(Messages['errorBox_errorType_' + errorType]);
        $modalbox.find('.errorExplanation').text(Messages['errorBox_errorExplanation_' + errorType]);
        if (moreInfo) {
            $modalbox.append(ERROR_ADDITIONAL);
            $modalbox.find('.errorMoreExplanation').text(Messages.errorBox_moreExplanation);
            $modalbox.find('.errorData').text(Messages['errorBox_' + errorType]);
        }

        $modalbox.modalBox({
            onOpen: boxOpened,
            onClose: function () { $('.modalBox').remove(); }
        });
        $('.iw-modalOverlay').css({'z-index':10000});
    };

    return {
        show: showError
    };
});
<commit_msg>error when opening error message window D:<commit_after>/*
 * Copyright 2014 XWiki SAS
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
require.config({
    'shim': {
        'bower/modalBox/modalBox-min': ['bower/jquery/dist/jquery.min'],
    }
});
define([
    'messages',
    'bower/modalBox/modalBox-min'
], function (Messages) {

    var STYLE = [
        ''
    ].join('');

    var CONTENT = [
        '

',
        '
',
        '

'
    ].join('');

    var ERROR_ADDITIONAL = [
        '

',
        '',
        '<textarea id="errorBox_detailsBox" class="errorData"></textarea>',
    ].join('');

    var showError = function (errorType, docHtml, moreInfo) {
        $('body').append('

');
        var $modalbox = $('.modalBox')
        $modalbox.append(CONTENT + STYLE);

        $modalbox.find('.errorType').text(Messages['errorBox_errorType_' + errorType]);
        $modalbox.find('.errorExplanation').text(Messages['errorBox_errorExplanation_' + errorType]);
        if (moreInfo) {
            $modalbox.append(ERROR_ADDITIONAL);
            $modalbox.find('.errorMoreExplanation').text(Messages.errorBox_moreExplanation);
            $modalbox.find('.errorData').text(Messages['errorBox_' + errorType]);
        }

        $modalbox.modalBox({
            onClose: function () { $('.modalBox').remove(); }
        });
        $('.iw-modalOverlay').css({'z-index':10000});
    };

    return {
        show: showError
    };
});
<|endoftext|>


<commit_before>"use strict";

var fs      = require('fs');
var util    = require('util');

module.exports = FsyncWriteStream;

function FsyncWriteStream (path, options) {
    if (!(this instanceof FsyncWriteStream)) return new FsyncWriteStream(path, options);

    fs.WriteStream.call(this, path, options);
}

util.inherits(FsyncWriteStream, fs.WriteStream);

FsyncWriteStream.prototype.flush = function() {
  if (this.busy) return;
  var self = this;

  var args = this._queue.shift();
  if (!args) {
    if (this.drainable) { this.emit('drain'); }
    return;
  }

  this.busy = true;

  var method = args.shift(),
      cb = args.pop();

  args.push(function(err) {
    self.busy = false;

    if (err) {
      self.writable = false;
      if (cb) {
        cb(err);
      }
      self.emit('error', err);
      return;
    }

    if (method == fs.write) {
      self.bytesWritten += arguments[1];
      if (cb) {
        // write callback
        cb(null, arguments[1]);
      }

    } else if (method === self._open) {
      // save reference for file pointer
      self.fd = arguments[1];
      self.emit('open', self.fd);

    } else if (method === fs.close) {
      // stop flushing after close
      if (cb) {
        cb(null);
      }
      self.emit('close');
      return;
    } else if (method === fs.fsync) {
      // XXX: New code compared to WriteStream.flush
      // stop flushing after fsync
      if (cb) {
        cb(null);
      }
      return;
    }

    self.flush();
  });

  // Inject the file pointer
  if (method !== self._open) {
    args.unshift(this.fd);
  }

  method.apply(this, args);
};

FsyncWriteStream.prototype.end = function(data, encoding, cb) {
  if (typeof(data) === 'function') {
    cb = data;
  } else if (typeof(encoding) === 'function') {
    cb = encoding;
    this.write(data);
  } else if (arguments.length > 0) {
    this.write(data, encoding);
  }
  this.writable = false;
  // XXX: New code compared to WriteStream.flush
  var self = this;
  var fsync_cb = function (err) {
    if (err) return cb(err);
    self._queue.push([fs.close, cb]);
    self.flush();
  }
  this._queue.push([fs.fsync, fsync_cb]);
  this.flush();
};

// for v0.10+ compat
FsyncWriteStream.prototype.close = function(cb) {
  var self = this;
  if (cb)
    this.once('close', cb);
  if (this.closed || 'number' !== typeof this.fd) {
    if ('number' !== typeof this.fd) {
      this.once('open', close);
      return;
    }
    return process.nextTick(this.emit.bind(this, 'close'));
  }
  this.closed = true;
  close();

  function close(fd) {
    fs.fsync(fd || self.fd, function(er) {
      if (er)
        self.emit('error', er);
      else {
        fs.close(fd || self.fd, function(er) {
          if (er)
            self.emit('error', er);
          else
            self.emit('close');
        });
        self.fd = null;
      }
    })
  }
};

<commit_msg>Address v0.10 compatibility<commit_after>"use strict";

var fs      = require('fs');
var util    = require('util');

module.exports = FsyncWriteStream;

function FsyncWriteStream (path, options) {
    if (!(this instanceof FsyncWriteStream)) return new FsyncWriteStream(path, options);

    fs.WriteStream.call(this, path, options);
}

util.inherits(FsyncWriteStream, fs.WriteStream);

var versions   = process.version.split('.'),
    version    = Number(versions[0].substring(1)),
    subversion = Number(versions[1]);

if (version > 0 || subversion >= 10) {
    // for v0.10+ compat
    FsyncWriteStream.prototype.close = function(cb) {
        var self = this;
        if (cb)
            this.once('close', cb);
        if (this.closed || 'number' !== typeof this.fd) {
            if ('number' !== typeof this.fd) {
                this.once('open', close);
                return;
            }
            return process.nextTick(this.emit.bind(this, 'close'));
        }
        this.closed = true;
        close();

        function close(fd) {
            fs.fsync(fd || self.fd, function(er) {
                if (er)
                self.emit('error', er);
                else {
                    fs.close(fd || self.fd, function(er) {
                        if (er)
                        self.emit('error', er);
                        else
                        self.emit('close');
                    });
                    self.fd = null;
                }
            })
        }
    };
}
else {
    FsyncWriteStream.prototype.flush = function() {
        if (this.busy) return;
        var self = this;

        var args = this._queue.shift();
        if (!args) {
            if (this.drainable) { this.emit('drain'); }
            return;
        }

        this.busy = true;

        var method = args.shift(),
            cb = args.pop();

        args.push(function(err) {
            self.busy = false;

            if (err) {
                self.writable = false;
                if (cb) {
                    cb(err);
                }
                self.emit('error', err);
                return;
            }

            if (method == fs.write) {
                self.bytesWritten += arguments[1];
                if (cb) {
                    // write callback
                    cb(null, arguments[1]);
                }

            } else if (method === self._open) {
                // save reference for file pointer
                self.fd = arguments[1];
                self.emit('open', self.fd);

            } else if (method === fs.close) {
                // stop flushing after close
                if (cb) {
                    cb(null);
                }
                self.emit('close');
                return;
            } else if (method === fs.fsync) {
                // XXX: New code compared to WriteStream.flush
                // stop flushing after fsync
                if (cb) {
                    cb(null);
                }
                return;
            }

            self.flush();
        });

        // Inject the file pointer
        if (method !== self._open) {
            args.unshift(this.fd);
        }

        method.apply(this, args);
    };

    FsyncWriteStream.prototype.end = function(data, encoding, cb) {
        if (typeof(data) === 'function') {
            cb = data;
        } else if (typeof(encoding) === 'function') {
            cb = encoding;
            this.write(data);
        } else if (arguments.length > 0) {
            this.write(data, encoding);
        }
        this.writable = false;
        // XXX: New code compared to WriteStream.flush
        var self = this;
        var fsync_cb = function (err) {
            if (err) return cb(err);
            self._queue.push([fs.close, cb]);
            self.flush();
        }
        this._queue.push([fs.fsync, fsync_cb]);
        this.flush();
    };
}

<|endoftext|>


<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Number formatter
//-------------------------------------------------------------------

vizwhiz.utils.format_num = function(val, percent, sig_figs, abbrv) {

  // test if number is REALLY small
  if(Math.abs(val - 1e-16) < 1e-10){
    val = 0;
  }

  if(percent){
    val = d3.format("."+sig_figs+"p")(val)
  }
  else if(abbrv){
    var symbol = d3.formatPrefix(val).symbol
    symbol = symbol.replace("G", "B") // d3 uses G for giga

    // Format number to precision level using proper scale
    val = d3.formatPrefix(val).scale(val)
    val = parseFloat(d3.format("."+sig_figs+"g")(val))
    val = val + " " + symbol;
  }
  else {
    val = d3.format(",."+sig_figs+"f")(val)
  }

  return val;
};

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Random color generator (if no color is given)
//-------------------------------------------------------------------

vizwhiz.utils.color_scale = d3.scale.category20();
vizwhiz.utils.rand_color = function() {
  var rand_int = Math.floor(Math.random()*20)
  return vizwhiz.utils.color_scale(rand_int);
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Returns appropriate text color based off of a given color
//-------------------------------------------------------------------

vizwhiz.utils.text_color = function(color) {
  return d3.hsl(color).l >= 0.5 ? "#333333" : "#ffffff";
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Merge two objects to create a new one with the properties of both
//-------------------------------------------------------------------

vizwhiz.utils.merge = function(obj1, obj2) {
  var obj3 = {};
  for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
  for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
  return obj3;
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// recursive function to rename "values" to "children" and "key" to "id"
// src: https://groups.google.com/group/d3-js/tree/browse_frm/month/2011-11/a5dc689238c3a685
//-------------------------------------------------------------------

vizwhiz.utils.rename_key_value = function(obj) {
  if (obj.values && obj.values.length) {
    return {
      'name': obj.key,
      'id': obj.key,
      'children': obj.values.map(function(obj) {
        return vizwhiz.utils.rename_key_value(obj);
      })
    };
  }
  else if(obj.values) {
    return obj.values
  }
  else {
    return obj;
  }
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Merge two objects to create a new one with the properties of both
//-------------------------------------------------------------------

vizwhiz.utils.nest = function(flat_data, nesting, flatten, extra) {

  var flattened = [];
  var nested_data = d3.nest();

  nesting.forEach(function(nest_key, i){

    nested_data.key(function(d){
      return d[nest_key].name;
    })

    if(i == nesting.length-1){
      nested_data.rollup(function(leaves){
        if(leaves.length == 1){
          flattened.push(leaves[0]);
          return leaves[0]
        }
        // to_return = leaves[0]
        to_return = {
          "value": d3.sum(leaves, function(d){ return d.value; }),
          "name": leaves[0][nest_key].name,
          "id": leaves[0][nest_key].id,
          "num_children": leaves.length,
          "num_children_active": d3.sum(leaves, function(d){ return d.active; })
        }

        if(extra){
          extra.forEach(function(e){
            if(e.agg == "sum"){
              to_return[e.key] = d3.sum(leaves, function(d){ return d[e.key]; })
            }
            else if(e.agg == "avg"){
              to_return[e.key] = d3.mean(leaves, function(d){ return d[e.key]; })
            }
            else {
              to_return[e.key] = leaves[0][e.key];
            }
          })
        }

        if(flatten){
          nesting.forEach(function(nk){
            to_return[nk] = leaves[0][nk]
          })
          flattened.push(to_return);
        }

        return to_return
      })
    }

  })

  nested_data = nested_data
    .entries(flat_data)
    .map(vizwhiz.utils.rename_key_value);

  if(flatten){
    return flattened;
  }

  return {"name":"root", "children": nested_data};

}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// for SVGs word wrapping is not built in, so here we must creat this
// function ourselves
//-------------------------------------------------------------------

vizwhiz.utils.wordwrap = function(params) {

  var parent = params.parent,
      padding = params.padding ? params.padding : 10,
      width = params.width ? params.width-(padding*2) : 20000,
      height = params.height ? params.height : 20000,
      resize = params.resize,
      font_max = params.font_max ? params.font_max : 40,
      font_min = params.font_min ? params.font_min : 8;

  if (params.text instanceof Array) wrap(String(params.text.shift()).split(/[\s-]/))
  else wrap(String(params.text).split(/[\s-]/))

  function wrap(words) {

    if (resize) {

      // Start by trying the largest font size
      var size = font_max
      d3.select(parent).attr('font-size',size)

      // Add each word to it's own line (to test for longest word)
      d3.select(parent).selectAll('tspan').remove()
      for(var i=0; i<words.length; i++) {
        if (words.length == 1) var t = words[i]
        else var t = words[i]+"..."
        d3.select(parent).append('tspan').attr('x',0).text(t)
      }

      // If the longest word is too wide, make the text proportionately smaller
      if (parent.getBBox().width > width) size = size*(width/parent.getBBox().width)

      // If the new size is too small, return NOTHING
      if (size < font_min) {
        d3.select(parent).selectAll('tspan').remove();
        if (typeof params.text == "string" || params.text.length == 0) return;
        else wrap(params.text.shift().split(/[\s-]/))
        return;
      }

      // Use new text size
      d3.select(parent).attr('font-size',size);

      // Flow text into box
      flow();

      // If text doesn't fit height-wise, shrink it!
      if (parent.childNodes.length*parent.getBBox().height > height) {
        var temp_size = size*(height/(parent.childNodes.length*parent.getBBox().height))
        if (temp_size < font_min) size = font_min
        else size = temp_size
        d3.select(parent).attr('font-size',size)
      } else finish();

    }

    flow();
    truncate();
    finish();

    function flow() {

      d3.select(parent).selectAll('tspan').remove()

      var tspan = d3.select(parent).append('tspan')
        .attr('x',parent.getAttribute('x'))
        .text(words[0])

      for (var i=1; i < words.length; i++) {

        tspan.text(tspan.text()+" "+words[i])

        if (tspan.node().getComputedTextLength() > width) {

          tspan.text(tspan.text().substr(0,tspan.text().lastIndexOf(" ")))

          tspan = d3.select(parent).append('tspan')
            .attr('x',parent.getAttribute('x'))
            .text(words[i])

        }
      }

    }

    function truncate() {
      var cut = false
      while (parent.childNodes.length*parent.getBBox().height > height && parent.lastChild && !cut) {
        parent.removeChild(parent.lastChild)
        if (parent.childNodes.length*parent.getBBox().height < height && parent.lastChild) cut = true
      }
      if (cut) {
        tspan = parent.lastChild
        words = d3.select(tspan).text().split(/[\s-]/)

        var last_char = words[words.length-1].charAt(words[words.length-1].length-1)
        if (last_char == ',' || last_char == ';' || last_char == ':') words[words.length-1] = words[words.length-1].substr(0,words[words.length-1].length-1)

        d3.select(tspan).text(words.join(' ')+'...')

        if (tspan.getComputedTextLength() > width) {
          if (words.length > 1) words.pop(words.length-1)
          last_char = words[words.length-1].charAt(words[words.length-1].length-1)
          if (last_char == ',' || last_char == ';' || last_char == ':') words[words.length-1].substr(0,words[words.length-1].length-2)
          d3.select(tspan).text(words.join(' ')+'...')
        }
      }
    }
  }

  function finish() {
    d3.select(parent).selectAll('tspan').attr("dy", d3.select(parent).style('font-size'));
    return;
  }

}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Drop shadow function, adds the proper definition with th parameters
// used to the page
//-------------------------------------------------------------------

vizwhiz.utils.drop_shadow = function(defs) {

  // add filter to svg defs
  var drop_shadow_filter = defs.append('filter')
    .attr('id', 'dropShadow')
    .attr('filterUnits', "userSpaceOnUse")
    .attr('width', '100%')
    .attr('height', '100%');

  // shadow blue
  drop_shadow_filter.append('feGaussianBlur')
    .attr('in', 'SourceAlpha')
    .attr('stdDeviation', 2);

  // shadow offset
  drop_shadow_filter.append('feOffset')
    .attr('dx', 1)
    .attr('dy', 1)
    .attr('result', 'offsetblur');

  var feMerge = drop_shadow_filter.append('feMerge');
  feMerge.append('feMergeNode');

  // put original on top of shadow
  feMerge.append('feMergeNode')
    .attr('in', "SourceGraphic");

}

//===================================================================
<commit_msg>fixed wordwrap String cast<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Number formatter
//-------------------------------------------------------------------

vizwhiz.utils.format_num = function(val, percent, sig_figs, abbrv) {

  // test if number is REALLY small
  if(Math.abs(val - 1e-16) < 1e-10){
    val = 0;
  }

  if(percent){
    val = d3.format("."+sig_figs+"p")(val)
  }
  else if(abbrv){
    var symbol = d3.formatPrefix(val).symbol
    symbol = symbol.replace("G", "B") // d3 uses G for giga

    // Format number to precision level using proper scale
    val = d3.formatPrefix(val).scale(val)
    val = parseFloat(d3.format("."+sig_figs+"g")(val))
    val = val + " " + symbol;
  }
  else {
    val = d3.format(",."+sig_figs+"f")(val)
  }

  return val;
};

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Random color generator (if no color is given)
//-------------------------------------------------------------------

vizwhiz.utils.color_scale = d3.scale.category20();
vizwhiz.utils.rand_color = function() {
  var rand_int = Math.floor(Math.random()*20)
  return vizwhiz.utils.color_scale(rand_int);
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Returns appropriate text color based off of a given color
//-------------------------------------------------------------------

vizwhiz.utils.text_color = function(color) {
  return d3.hsl(color).l >= 0.5 ? "#333333" : "#ffffff";
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Merge two objects to create a new one with the properties of both
//-------------------------------------------------------------------

vizwhiz.utils.merge = function(obj1, obj2) {
  var obj3 = {};
  for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
  for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
  return obj3;
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// recursive function to rename "values" to "children" and "key" to "id"
// src: https://groups.google.com/group/d3-js/tree/browse_frm/month/2011-11/a5dc689238c3a685
//-------------------------------------------------------------------

vizwhiz.utils.rename_key_value = function(obj) {
  if (obj.values && obj.values.length) {
    return {
      'name': obj.key,
      'id': obj.key,
      'children': obj.values.map(function(obj) {
        return vizwhiz.utils.rename_key_value(obj);
      })
    };
  }
  else if(obj.values) {
    return obj.values
  }
  else {
    return obj;
  }
}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Merge two objects to create a new one with the properties of both
//-------------------------------------------------------------------

vizwhiz.utils.nest = function(flat_data, nesting, flatten, extra) {

  var flattened = [];
  var nested_data = d3.nest();

  nesting.forEach(function(nest_key, i){

    nested_data.key(function(d){
      return d[nest_key].name;
    })

    if(i == nesting.length-1){
      nested_data.rollup(function(leaves){
        if(leaves.length == 1){
          flattened.push(leaves[0]);
          return leaves[0]
        }
        // to_return = leaves[0]
        to_return = {
          "value": d3.sum(leaves, function(d){ return d.value; }),
          "name": leaves[0][nest_key].name,
          "id": leaves[0][nest_key].id,
          "num_children": leaves.length,
          "num_children_active": d3.sum(leaves, function(d){ return d.active; })
        }

        if(extra){
          extra.forEach(function(e){
            if(e.agg == "sum"){
              to_return[e.key] = d3.sum(leaves, function(d){ return d[e.key]; })
            }
            else if(e.agg == "avg"){
              to_return[e.key] = d3.mean(leaves, function(d){ return d[e.key]; })
            }
            else {
              to_return[e.key] = leaves[0][e.key];
            }
          })
        }

        if(flatten){
          nesting.forEach(function(nk){
            to_return[nk] = leaves[0][nk]
          })
          flattened.push(to_return);
        }

        return to_return
      })
    }

  })

  nested_data = nested_data
    .entries(flat_data)
    .map(vizwhiz.utils.rename_key_value);

  if(flatten){
    return flattened;
  }

  return {"name":"root", "children": nested_data};

}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// for SVGs word wrapping is not built in, so here we must creat this
// function ourselves
//-------------------------------------------------------------------

vizwhiz.utils.wordwrap = function(params) {

  var parent = params.parent,
      padding = params.padding ? params.padding : 10,
      width = params.width ? params.width-(padding*2) : 20000,
      height = params.height ? params.height : 20000,
      resize = params.resize,
      font_max = params.font_max ? params.font_max : 40,
      font_min = params.font_min ? params.font_min : 8;

  if (params.text instanceof Array) wrap(String(params.text.shift()).split(/[\s-]/))
  else wrap(String(params.text).split(/[\s-]/))

  function wrap(words) {

    if (resize) {

      // Start by trying the largest font size
      var size = font_max
      d3.select(parent).attr('font-size',size)

      // Add each word to it's own line (to test for longest word)
      d3.select(parent).selectAll('tspan').remove()
      for(var i=0; i<words.length; i++) {
        if (words.length == 1) var t = words[i]
        else var t = words[i]+"..."
        d3.select(parent).append('tspan').attr('x',0).text(t)
      }

      // If the longest word is too wide, make the text proportionately smaller
      if (parent.getBBox().width > width) size = size*(width/parent.getBBox().width)

      // If the new size is too small, return NOTHING
      if (size < font_min) {
        d3.select(parent).selectAll('tspan').remove();
        if (typeof params.text == "string" || params.text.length == 0) return;
        else wrap(String(params.text.shift()).split(/[\s-]/))
        return;
      }

      // Use new text size
      d3.select(parent).attr('font-size',size);

      // Flow text into box
      flow();

      // If text doesn't fit height-wise, shrink it!
      if (parent.childNodes.length*parent.getBBox().height > height) {
        var temp_size = size*(height/(parent.childNodes.length*parent.getBBox().height))
        if (temp_size < font_min) size = font_min
        else size = temp_size
        d3.select(parent).attr('font-size',size)
      } else finish();

    }

    flow();
    truncate();
    finish();

    function flow() {

      d3.select(parent).selectAll('tspan').remove()

      var tspan = d3.select(parent).append('tspan')
        .attr('x',parent.getAttribute('x'))
        .text(words[0])

      for (var i=1; i < words.length; i++) {

        tspan.text(tspan.text()+" "+words[i])

        if (tspan.node().getComputedTextLength() > width) {

          tspan.text(tspan.text().substr(0,tspan.text().lastIndexOf(" ")))

          tspan = d3.select(parent).append('tspan')
            .attr('x',parent.getAttribute('x'))
            .text(words[i])

        }
      }

    }

    function truncate() {
      var cut = false
      while (parent.childNodes.length*parent.getBBox().height > height && parent.lastChild && !cut) {
        parent.removeChild(parent.lastChild)
        if (parent.childNodes.length*parent.getBBox().height < height && parent.lastChild) cut = true
      }
      if (cut) {
        tspan = parent.lastChild
        words = d3.select(tspan).text().split(/[\s-]/)

        var last_char = words[words.length-1].charAt(words[words.length-1].length-1)
        if (last_char == ',' || last_char == ';' || last_char == ':') words[words.length-1] = words[words.length-1].substr(0,words[words.length-1].length-1)

        d3.select(tspan).text(words.join(' ')+'...')

        if (tspan.getComputedTextLength() > width) {
          if (words.length > 1) words.pop(words.length-1)
          last_char = words[words.length-1].charAt(words[words.length-1].length-1)
          if (last_char == ',' || last_char == ';' || last_char == ':') words[words.length-1].substr(0,words[words.length-1].length-2)
          d3.select(tspan).text(words.join(' ')+'...')
        }
      }
    }
  }

  function finish() {
    d3.select(parent).selectAll('tspan').attr("dy", d3.select(parent).style('font-size'));
    return;
  }

}

//===================================================================

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Drop shadow function, adds the proper definition with th parameters
// used to the page
//-------------------------------------------------------------------

vizwhiz.utils.drop_shadow = function(defs) {

  // add filter to svg defs
  var drop_shadow_filter = defs.append('filter')
    .attr('id', 'dropShadow')
    .attr('filterUnits', "userSpaceOnUse")
    .attr('width', '100%')
    .attr('height', '100%');

  // shadow blue
  drop_shadow_filter.append('feGaussianBlur')
    .attr('in', 'SourceAlpha')
    .attr('stdDeviation', 2);

  // shadow offset
  drop_shadow_filter.append('feOffset')
    .attr('dx', 1)
    .attr('dy', 1)
    .attr('result', 'offsetblur');

  var feMerge = drop_shadow_filter.append('feMerge');
  feMerge.append('feMergeNode');

  // put original on top of shadow
  feMerge.append('feMergeNode')
    .attr('in', "SourceGraphic");

}

//===================================================================
<|endoftext|>


<commit_before>WebFont.load({
	custom: {
		families: ['Gotham SSm:n4,n7'],
		urls: ['../font/GothamSSm.css']
	},
	timeout: 10000
});<commit_msg>Fix path for Gotham<commit_after>WebFont.load({
	custom: {
		families: ['Gotham SSm:n4,n7'],
		urls: ['font/GothamSSm.css']
	},
	timeout: 10000
});<|endoftext|>


<commit_before>app = {
  isDeviceReady: false,

  base_url: "https://myplaceonline.com",

  firstLoad: true,

  phonegapPath: "",

  phonegapHomepage: "",

  offline: false,

  static_ios: false, // See below

  // The basic flow is: JQM mobileinit calls this function. This function registers
  // a JQM pageloaded handler for the main built-in page. Once the built-in page loads,
  // we bind phonegap events. Once that finishes, we load the real homepage.
  // This is called after the myplaceonline.js load and mobileinit because that was bound first.
  mobileinit: function() {
    // We always set debug to true to capture the initial set of console logs in case there's a problem,
    // but in most cases when the homepage comes in, it will disable debug
    myplaceonline.setDebug(true);

    // Starting with iOS 11.3, the following security errors occur:
    // "SecurityError: Blocked attempt to use history.replaceState() to change session history URL
    // from [...]/myplaceonline.app/www/index.html#/?phonegap=true to
    // https://myplaceonline.com/?phonegap=true. Protocols, domains, ports, usernames, and passwords
    // must match."
    // The fix is to disable history on iOS:
    // https://stackoverflow.com/q/52236521/4135310
    // However, this early in loading, `device` isn't available, so
    // we can't call app.isiOS(), so we just have to comment/uncomment
    // for iOS vs. Android builds:
    myplaceonline.consoleLog("phonegap static_ios: " + app.static_ios);
    if (app.static_ios) {
      $.mobile.hashListeningEnabled = false;
      $.mobile.pushStateEnabled = false;
      $.mobile.changePage.defaults.changeHash = false;
    }

    myplaceonline.consoleLog("phonegap mobileinit");
    app.savePhonegapPath();
    window.CKEDITOR_BASEPATH = app.base_url + "/assets/ckeditor/";
    $.support.cors = true;
    $.mobile.allowCrossDomainPages = true;
    $.mobile.defaultPageTransition = "none";
    myplaceonline.setFocusAllowed(false);
    myplaceonline.setInPhonegap(true);
    $(document).on("pagecontainerchangefailed.phonegap", app.loadFailed);
    myplaceonline.pageloaded("phonegapmain", app.initialpageloaded);
  },

  savePhonegapPath: function() {
    app.phonegapHomepage = "" + window.location;
    var path = "" + window.location.pathname;
    app.phonegapPath = path.substring(0, path.lastIndexOf('/') + 1);
  },

  initialpageloaded: function() {
    myplaceonline.consoleLog("phonegap initialpageloaded");
    app.bindEvents();
  },

  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() {
    document.addEventListener("deviceready", app.onDeviceReady, false);
    document.addEventListener("backbutton", app.onBackButton, false);
    document.addEventListener("menubutton", app.onMenuButton, false);
  },

  onDeviceReady: function() {
    myplaceonline.consoleLog("phonegap onDeviceReady, splashscreen: " + navigator.splashscreen);

    // If the user click's on an http:// or https:// link, and that link
    // is not to myplaceonline, then open it in the phone's default external
    // browser
    $(document).on('click', 'a', function(ev) {
      try {
        var href = $(this).attr('href');
        if (href) {
          if ($(this).hasClass("externallink") || ((href.indexOf("http:") == 0 || href.indexOf("https:") == 0) && href.indexOf(app.base_url) != 0)) {
            myplaceonline.createSuccessNotification("Launching phone browser...");
            cordova.InAppBrowser.open(href, "_system");
            return false;
          }
        }
      } catch (clickE) {
        myplaceonline.criticalError("External Link Error. " + clickE);
      }
      return true;
    });
    app.isDeviceReady = true;
    // Hack: If we call splashcreen.hide immediately, there's a blank flash in between
    setTimeout(function() {
      navigator.splashscreen.hide();
      if (!app.offline) {
        app.loadHomepage();
      }
    }, 1000);
  },

  loadHomepage: function() {
    myplaceonline.consoleLog("phonegap loadHomepage " + app.base_url + "/" + "; current base href: " + $("base").attr("href"));
    $("base").attr("href", app.base_url + "/");
    var documentBaseUrl = $.mobile.path.parseUrl(app.base_url + "/");
    myplaceonline.consoleLog("phonegap new base href: " + $("base").attr("href") + "; setting documentBase: " + documentBaseUrl.href);
    $.mobile.path.documentBase = documentBaseUrl;
    app.navigate("/?phonegap=true");
  },

  navigate: function(url) {
    myplaceonline.consoleLog("phonegap navigate " + url);
    $.mobile.pageContainer.pagecontainer("change", url, {
      allowSamePageTransition: true,
      transition: 'none',
      reloadPage: true,
      changeHash: true
    });
  },

  onBackButton: function() {
    myplaceonline.consoleLog("phonegap onBackButton");

    if (!myplaceonline.isInitialPhonegapPage() || window.location.hash.indexOf("ui-state=dialog") != -1) {
      if (window.navigator && window.navigator.app && window.navigator.app.backHistory) {
        myplaceonline.consoleLog("phonegap window.navigator.app.backHistory");
        history.go(-1);
        navigator.app.backHistory();
        myplaceonline.consoleLog("phonegap tried to go back");
      } else {
        myplaceonline.consoleLog("phonegap window.history.back");
        window.history.back();
      }

      myplaceonline.consoleLog("phonegap history length: " + window.history.length + ", state:");
      myplaceonline.consoleDir(window.history.state);

    } else {
      app.close();
    }
  },

  onMenuButton: function() {
    myplaceonline.consoleLog("phonegap onMenuButton");
    var hmPopupSel = "#headerMenuPopup";
    var optPopupSel = "#menuPopup";
    var p = myplaceonline.getActivePage();
    if (p) {
      var uid = $(p).attr('data-uniqueid');
      if (uid) {
        // Close the popup if open and open it if closed
        if($(hmPopupSel).attr("aria-expanded") === "true"){
          $(optPopupSel + uid).popup("close");
        }
        else{
          $(optPopupSel + uid).popup("open", {"positionTo": hmPopupSel});
        }
      }
    }
  },

  loadFailed: function(event, ui) {
    myplaceonline.consoleLog("phonegap loadFailed " + event + "," + ui);
    myplaceonline.consoleDir(event);
    myplaceonline.consoleDir(ui);
    event.preventDefault();
    var activePage = myplaceonline.getActivePage();
    if (activePage) {
      if (activePage.id == "phonegapmain") {
        $("#pgextra").html("
Cannot connect to the server.

Retry
Show Diagnostics
");
        $("#refresh_button").click(function() {
          app.navigate("/?phonegap=true");
          return false;
        });
        $("#diagnostics_button").click(function() {
          myplaceonline.showDebugConsole();
        });
        var offlineData = myplaceonline.getMyplaceonlineSnapshot();
        if (offlineData) {
          $("#pgextra").append("
There is also an offline snapshot created at " + offlineData.time + "

Load Offline Snapshot
");
          $("#offline_button").click(function(e) {
            var offlineData = myplaceonline.getMyplaceonlineSnapshot();
            if (offlineData) {
              navigate(app.phonegapHomepage.replace("index.html", "offline.html"), true);
            }
            e.preventDefault();
            return false;
          });
        }
        myplaceonline.ensureStyledPage();
      } else {
        // This could have just been a network blip and JQM will show an error popup and then the user can
        // try again
        //activePage.empty();
        //activePage.html("
Cannot connect to the server.

Retry
");
      }
    } else {
      alert("Cannot connect to the server. Please reload the application.");
    }
    myplaceonline.hideLoading();
  },

  isAndroid: function() {
    return device.platform == 'android' || device.platform == 'Android';
  },

  isiOS: function() {
    return device.platform == 'iOS';
  },

  checkFirstLoad: function() {
    /*
    if (app.firstLoad) {
      app.firstLoad = false;

      setTimeout(function() {
        var activePage = myplaceonline.getActivePage();
        if (activePage) {
          if (activePage.id == "phonegapmain") {
            alert("We're very sorry, but you hit a known issue that we haven't figured out yet. Please click Send Details to help us figure it out, then terminate the app and restart. Sorry.");
            var extra = document.getElementById("pgextra");
            if (extra) {
              var button = document.createElement("button");
              button.innerHTML = "Send Details";
              button.onclick = function() {
                myplaceonline.sendDebug();
                window.setTimeout(function() {
                  alert("Thank you for providing details. Please re-open the app and try again.");
                  app.close();
                }, 10000);
              };
              extra.appendChild(button);
            }
          }
        }
      }, 5000);
    }
    */
  },

  // Attempt to close the application on non-iOS devices. This will probaby just send the app
  // to the background rather than terminating it.
  //
  // "Never quit an iOS app programmatically."
  // https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/MobileHIG.pdf
  close: function() {
    myplaceonline.consoleLog("app close called!");

    if (!app.isiOS()) {
      if (navigator.app) {
        navigator.app.exitApp();
      } else if (navigator.device) {
        navigator.device.exitApp();
      }
    }
  }
};
<commit_msg>Debug<commit_after>app = {
  isDeviceReady: false,

  base_url: "https://myplaceonline.com",

  firstLoad: true,

  phonegapPath: "",

  phonegapHomepage: "",

  offline: false,

  static_ios: false, // See below

  // The basic flow is: JQM mobileinit calls this function. This function registers
  // a JQM pageloaded handler for the main built-in page. Once the built-in page loads,
  // we bind phonegap events. Once that finishes, we load the real homepage.
  // This is called after the myplaceonline.js load and mobileinit because that was bound first.
  mobileinit: function() {
    // We always set debug to true to capture the initial set of console logs in case there's a problem,
    // but in most cases when the homepage comes in, it will disable debug
    myplaceonline.setDebug(true);

    // Starting with iOS 11.3, the following security errors occur:
    // "SecurityError: Blocked attempt to use history.replaceState() to change session history URL
    // from [...]/myplaceonline.app/www/index.html#/?phonegap=true to
    // https://myplaceonline.com/?phonegap=true. Protocols, domains, ports, usernames, and passwords
    // must match."
    // The fix is to disable history on iOS:
    // https://stackoverflow.com/q/52236521/4135310
    // However, this early in loading, `device` isn't available, so
    // we can't call app.isiOS(), so we just have to comment/uncomment
    // for iOS vs. Android builds:
    myplaceonline.consoleLog("phonegap static_ios: " + app.static_ios);
    if (app.static_ios) {
      $.mobile.hashListeningEnabled = false;
      $.mobile.pushStateEnabled = false;
      $.mobile.changePage.defaults.changeHash = false;
    }

    myplaceonline.consoleLog("phonegap mobileinit");
    app.savePhonegapPath();
    window.CKEDITOR_BASEPATH = app.base_url + "/assets/ckeditor/";
    $.support.cors = true;
    $.mobile.allowCrossDomainPages = true;
    $.mobile.defaultPageTransition = "none";
    myplaceonline.setFocusAllowed(false);
    myplaceonline.setInPhonegap(true);
    $(document).on("pagecontainerchangefailed.phonegap", app.loadFailed);
    myplaceonline.pageloaded("phonegapmain", app.initialpageloaded);
  },

  savePhonegapPath: function() {
    app.phonegapHomepage = "" + window.location;
    var path = "" + window.location.pathname;
    app.phonegapPath = path.substring(0, path.lastIndexOf('/') + 1);
  },

  initialpageloaded: function() {
    myplaceonline.consoleLog("phonegap initialpageloaded");
    app.bindEvents();
  },

  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() {
    document.addEventListener("deviceready", app.onDeviceReady, false);
    document.addEventListener("backbutton", app.onBackButton, false);
    document.addEventListener("menubutton", app.onMenuButton, false);
  },

  onDeviceReady: function() {
    myplaceonline.consoleLog("phonegap onDeviceReady, splashscreen: " + navigator.splashscreen);

    // If the user click's on an http:// or https:// link, and that link
    // is not to myplaceonline, then open it in the phone's default external
    // browser
    $(document).on('click', 'a', function(ev) {
      try {
        var href = $(this).attr('href');
        if (href) {
          if ($(this).hasClass("externallink") || ((href.indexOf("http:") == 0 || href.indexOf("https:") == 0) && href.indexOf(app.base_url) != 0)) {
            myplaceonline.createSuccessNotification("Launching phone browser...");
            cordova.InAppBrowser.open(href, "_system");
            return false;
          }
        }
      } catch (clickE) {
        myplaceonline.criticalError("External Link Error. " + clickE);
      }
      return true;
    });
    app.isDeviceReady = true;
    // Hack: If we call splashcreen.hide immediately, there's a blank flash in between
    setTimeout(function() {
      navigator.splashscreen.hide();
      if (!app.offline) {
        app.loadHomepage();
      }
    }, 1000);
  },

  loadHomepage: function() {
    myplaceonline.consoleLog("phonegap loadHomepage " + app.base_url + "/" + "; current base href: " + $("base").attr("href"));
    $("base").attr("href", app.base_url + "/");
    var documentBaseUrl = $.mobile.path.parseUrl(app.base_url + "/");
    myplaceonline.consoleLog("phonegap new base href: " + $("base").attr("href") + "; setting documentBase: " + documentBaseUrl.href);
    $.mobile.path.documentBase = documentBaseUrl;
    app.navigate("/?phonegap=true");
  },

  navigate: function(url) {
    myplaceonline.consoleLog("phonegap navigate " + url);
    $.mobile.pageContainer.pagecontainer("change", url, {
      allowSamePageTransition: true,
      transition: 'none',
      reloadPage: true,
      changeHash: true
    });
  },

  onBackButton: function() {
    myplaceonline.consoleLog("phonegap onBackButton");

    if (!myplaceonline.isInitialPhonegapPage() || window.location.hash.indexOf("ui-state=dialog") != -1) {
      if (window.navigator && window.navigator.app && window.navigator.app.backHistory) {
        myplaceonline.consoleLog("phonegap window.navigator.app.backHistory");

    window.history.back()

    navigator.app.backHistory();

    history.go(-1);

        myplaceonline.consoleLog("phonegap tried to go back");
      } else {
        myplaceonline.consoleLog("phonegap window.history.back");
        window.history.back();
      }

      myplaceonline.consoleLog("phonegap history length: " + window.history.length + ", state:");
      myplaceonline.consoleDir(window.history.state);

    } else {
      app.close();
    }
  },

  onMenuButton: function() {
    myplaceonline.consoleLog("phonegap onMenuButton");
    var hmPopupSel = "#headerMenuPopup";
    var optPopupSel = "#menuPopup";
    var p = myplaceonline.getActivePage();
    if (p) {
      var uid = $(p).attr('data-uniqueid');
      if (uid) {
        // Close the popup if open and open it if closed
        if($(hmPopupSel).attr("aria-expanded") === "true"){
          $(optPopupSel + uid).popup("close");
        }
        else{
          $(optPopupSel + uid).popup("open", {"positionTo": hmPopupSel});
        }
      }
    }
  },

  loadFailed: function(event, ui) {
    myplaceonline.consoleLog("phonegap loadFailed " + event + "," + ui);
    myplaceonline.consoleDir(event);
    myplaceonline.consoleDir(ui);
    event.preventDefault();
    var activePage = myplaceonline.getActivePage();
    if (activePage) {
      if (activePage.id == "phonegapmain") {
        $("#pgextra").html("
Cannot connect to the server.

Retry
Show Diagnostics
");
        $("#refresh_button").click(function() {
          app.navigate("/?phonegap=true");
          return false;
        });
        $("#diagnostics_button").click(function() {
          myplaceonline.showDebugConsole();
        });
        var offlineData = myplaceonline.getMyplaceonlineSnapshot();
        if (offlineData) {
          $("#pgextra").append("
There is also an offline snapshot created at " + offlineData.time + "

Load Offline Snapshot
");
          $("#offline_button").click(function(e) {
            var offlineData = myplaceonline.getMyplaceonlineSnapshot();
            if (offlineData) {
              navigate(app.phonegapHomepage.replace("index.html", "offline.html"), true);
            }
            e.preventDefault();
            return false;
          });
        }
        myplaceonline.ensureStyledPage();
      } else {
        // This could have just been a network blip and JQM will show an error popup and then the user can
        // try again
        //activePage.empty();
        //activePage.html("
Cannot connect to the server.

Retry
");
      }
    } else {
      alert("Cannot connect to the server. Please reload the application.");
    }
    myplaceonline.hideLoading();
  },

  isAndroid: function() {
    return device.platform == 'android' || device.platform == 'Android';
  },

  isiOS: function() {
    return device.platform == 'iOS';
  },

  checkFirstLoad: function() {
    /*
    if (app.firstLoad) {
      app.firstLoad = false;

      setTimeout(function() {
        var activePage = myplaceonline.getActivePage();
        if (activePage) {
          if (activePage.id == "phonegapmain") {
            alert("We're very sorry, but you hit a known issue that we haven't figured out yet. Please click Send Details to help us figure it out, then terminate the app and restart. Sorry.");
            var extra = document.getElementById("pgextra");
            if (extra) {
              var button = document.createElement("button");
              button.innerHTML = "Send Details";
              button.onclick = function() {
                myplaceonline.sendDebug();
                window.setTimeout(function() {
                  alert("Thank you for providing details. Please re-open the app and try again.");
                  app.close();
                }, 10000);
              };
              extra.appendChild(button);
            }
          }
        }
      }, 5000);
    }
    */
  },

  // Attempt to close the application on non-iOS devices. This will probaby just send the app
  // to the background rather than terminating it.
  //
  // "Never quit an iOS app programmatically."
  // https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/MobileHIG.pdf
  close: function() {
    myplaceonline.consoleLog("app close called!");

    if (!app.isiOS()) {
      if (navigator.app) {
        navigator.app.exitApp();
      } else if (navigator.device) {
        navigator.device.exitApp();
      }
    }
  }
};
<|endoftext|>


<commit_before>import constants from './constants';

let utils = {
  prefix: '_secure__ls__metadata',
  encryptionSecret: 's3cr3t@123',
  allKeys: [],
  is: function (key) {
    if (key) {
      return true;
    }
    return false;
  },
  warn: function (reason) {
    reason = reason ? reason : constants.DEFAULT_WARNING_TEXT;
    console.warn(constants.WarningTypes[reason]);
  },
  getAllKeys: function () {
    return this.allKeys;
  },
  isKeyPresent: function (key) {
    let isKeyAlreadyPresent;

    for (let i = 0; i < this.allKeys.length; i++) {
      if (String(this.allKeys[i]) === String(key)) {
        isKeyAlreadyPresent = true; // found
        break;
      }
    }

    return isKeyAlreadyPresent;
  },
  addToKeysList: function (key) {
    this.allKeys.push(key);
  },
  removeFromKeysList: function (key) {
    let index = this.allKeys.indexOf(key);

    if (index > -1) {
      this.allKeys.splice(index, 1);
    }
    return index;
  }
};

module.exports = utils;
<commit_msg>change structure of metadata - Array of Object instead of Array of just strings<commit_after>import constants from './constants';
import CryptoJSWordArray from './WordArray';
import PBKDF2 from 'crypto-js/pbkdf2';

let utils = {
  metaKey: '_secure__ls__metadata',
  encryptionSecret: '',
  secretPhrase: 's3cr3t$#@135^&*246',
  allKeys: [],
  is: function (key) {
    if (key) {
      return true;
    }
    return false;
  },
  warn: function (reason) {
    reason = reason ? reason : constants.WarningEnum.DEFAULT_TEXT;
    console.warn(constants.WarningTypes[reason]);
  },
  generateSecretKey: function () {
    let salt = CryptoJSWordArray.random(128 / 8);
    let key128Bits = PBKDF2(this.secretPhrase, salt, {keySize: 128 / 32 });

    return key128Bits && key128Bits.toString();
  },
  getObjectFromKey: function (data, key) {
    if (!data || !data.length) {
      return {};
    }

    let i, obj = {};

    for (i = 0; i < data.length; i++) {
      if (data[i].k === key) {
        obj = data[i];
        break;
      }
    }

    return obj;
  },
  extractKeyNames: function (data) {
    if (!data || !data.keys || !data.keys.length) {
      return [];
    }

    return data.keys.map(keyData => {
      return keyData.k;
    });
  },
  getAllKeys: function () {
    return this.allKeys;
  },
  isKeyPresent: function (key) {
    let isKeyAlreadyPresent = false;

    for (let i = 0; i < this.allKeys.length; i++) {
      if (String(this.allKeys[i].k) === String(key)) {
        isKeyAlreadyPresent = true; // found
        break;
      }
    }

    return isKeyAlreadyPresent;
  },
  addToKeysList: function (key) {
    this.allKeys.push({
      k: key,
      s: this.encryptionSecret
    });
  },
  removeFromKeysList: function (key) {
    let i, index = -1;

    for (i = 0; i < this.allKeys.length; i++) {
      if (this.allKeys[i].k === key) {
        index = i;
        break;
      }
    }
    if (index !== -1) {
      this.allKeys.splice(index, 1);
    }
    return index;
  }
};

module.exports = utils;
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var formData=JSON.parse('{"form":[["text",["This is text data, as a test element."]],["select","Name",["Option 1","Option 2"]],["MultipleChoice","MC",["The Option 1","The Option 2","The Option 3"]],["CheckBoxes","CB",["CB1","CB2","CB3"]]]}');
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
    $(document).ready(function(){
        $('#logi').on("tap",function(event){

            $.mobile.showPageLoadingMsg("a", "Logging In");
            $.mobile.changePage("#formSelect");
            $.mobile.hidePageLoadingMsg();
        });

        $('.formlink').on("tap",function(){
            //Populate the form page with proper content here.
            $('#formContent').html("
");
            console.log(this.id);
            $('#FormName').html($(this).html());
            for (var formPart = 0; formPart < formData["form"].length; formPart++) {
            switch(formData["form"][formPart][0]){
                case "text":
                    console.log("Text");
                    $('#formContent').append("
"+formData["form"][formPart][1]+"
");
                    break;
                case "select":
                    console.log("Select");
                    var options = "";
                    options += '
'+formData["form"][formPart][1]+"
";
                    options +='<select name="select'+formPart+'" id="select'+formPart+'">';
                    for (var i = 0; i < formData["form"][formPart][2].length; i++) {
                        options += '<option>'+formData["form"][formPart][2][i]+'</option>';
                    }
                    options += '</select>';
                    $('#formContent').append(options);
                    console.log($('#formContent').html());
                    break;
                case "MultipleChoice":
                    var options = "";
                    console.log("MC");
                    options += '<fieldset data-role="controlgroup"><legend>'+formData["form"][formPart][1]+"</legend>";
                     for (var i = 0; i < formData["form"][formPart][2].length; i++) {
                        options += '<input type="radio" name="rChoice-'+formPart+'" id="rChoice-'+formPart+'-'+i+'" value="'+formData["form"][formPart][2][i]+'" />'
                        options += ''+formData["form"][formPart][2][i]+'';
                    }
                    options += '</fieldset>'
                    console.log(options)
                    $('#formContent').append(options);
                    break;
                case "CheckBoxes":
                    var options = "";
                    console.log("MC");
                    options += '<fieldset data-role="controlgroup"><legend>'+formData["form"][formPart][1]+"</legend>";
                     for (var i = 0; i < formData["form"][formPart][2].length; i++) {
                        options += '<input type="checkbox" name="cChoice-'+formPart+'" id="cChoice-'+formPart+'-'+i+'" value="'+formData["form"][formPart][2][i]+'" />'
                        options += ''+formData["form"][formPart][2][i]+'';
                    }
                    options += '</fieldset>'
                    console.log(options)
                    $('#formContent').append(options);
                    break;
                case "ImageCapture":
                    break;
                case "VideoCapture":
                    break;
                case "AudioCapture":
                    break;
                case "Geolocation":
                    break;
                default:
                    console.log("Unknown... work to do");
                    break;
            }
            if(formPart+1 != formData["form"].length){
            $('#formContent').append("
");
        }
        }
        $('#formContent').append('Submit')
        });
    });
   app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {

    }
};
<commit_msg>Added basic barcode image scanner.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
 var formData=JSON.parse('{"form":[["text",["This is text data, as a test element."]],["select","Name",["Option 1","Option 2"]],["MultipleChoice","MC",["The Option 1","The Option 2","The Option 3"]],["CheckBoxes","CB",["CB1","CB2","CB3"]],["ImageCapture","CapIm"]]}');
 var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        $(document).ready(function(){
            $('#logi').on("tap",function(event){

                $.mobile.showPageLoadingMsg("a", "Logging In");
                $.mobile.changePage("#formSelect");
                $.mobile.hidePageLoadingMsg();
            });

            $('.formlink').on("tap",function(){
            //Populate the form page with proper content here.
            $('#formContent').html("
");
            console.log(this.id);
            $('#FormName').html($(this).html());
            for (var formPart = 0; formPart < formData["form"].length; formPart++) {
                switch(formData["form"][formPart][0]){
                    case "text":
                    console.log("Text");
                    $('#formContent').append("
"+formData["form"][formPart][1]+"
");
                    break;
                    case "select":
                    console.log("Select");
                    var options = "";
                    options += '
'+formData["form"][formPart][1]+"
";
                    options +='<select name="select'+formPart+'" id="select'+formPart+'">';
                    for (var i = 0; i < formData["form"][formPart][2].length; i++) {
                        options += '<option>'+formData["form"][formPart][2][i]+'</option>';
                    }
                    options += '</select>';
                    $('#formContent').append(options);
                    console.log($('#formContent').html());
                    break;
                    case "MultipleChoice":
                    var options = "";
                    console.log("MC");
                    options += '<fieldset data-role="controlgroup"><legend>'+formData["form"][formPart][1]+"</legend>";
                    for (var i = 0; i < formData["form"][formPart][2].length; i++) {
                        options += '<input type="radio" name="rChoice-'+formPart+'" id="rChoice-'+formPart+'-'+i+'" value="'+formData["form"][formPart][2][i]+'" />'
                        options += ''+formData["form"][formPart][2][i]+'';
                    }
                    options += '</fieldset>'
                    console.log(options)
                    $('#formContent').append(options);
                    break;
                    case "CheckBoxes":
                    var options = "";
                    console.log("MC");
                    options += '<fieldset data-role="controlgroup"><legend>'+formData["form"][formPart][1]+"</legend>";
                    for (var i = 0; i < formData["form"][formPart][2].length; i++) {
                        options += '<input type="checkbox" name="cChoice-'+formPart+'" id="cChoice-'+formPart+'-'+i+'" value="'+formData["form"][formPart][2][i]+'" />'
                        options += ''+formData["form"][formPart][2][i]+'';
                    }
                    options += '</fieldset>'
                    console.log(options)
                    $('#formContent').append(options);
                    break;
                    case "ImageCapture":
                    var options = "";
                    console.log("IC");
                    options += 'Capture Image'
                    $('#formContent').append(options);
                    $('#Cap-'+formPart).on("tap",function(){
                     var scanner = cordova.require("cordova/plugin/BarcodeScanner");
                     scanner.scan(
                      function (result) {
                          alert("We got a barcode\n" +
                            "Result: " + result.text + "\n");
                      },
                      function (error) {
                          alert("Scanning failed: " + error);
                      }
                      );
                 });
                    break;
                    case "VideoCapture":
                    break;
                    case "AudioCapture":
                    break;
                    case "Geolocation":
                    break;
                    default:
                    console.log("Unknown... work to do");
                    break;
                }
                if(formPart+1 != formData["form"].length){
                    $('#formContent').append("
");
                }
            }
            $('#formContent').append('Submit')
        });
});
app.receivedEvent('deviceready');
},
    // Update DOM on a Received Event
    receivedEvent: function(id) {

    }
};
<|endoftext|>


<commit_before>/* Code based on jQuery
 * (c)2010 John Resig
 * http://jquery.com/
 */
var	// Head node
	head = document.getElementsByTagName("head")[0] || document.documentElement,

	// References
	toString = {}.toString,
	slice = [].slice;

// noop
function noop() {}

// Utilities
function isArray( object ) {
	return toString.call( object ) === "[object Array]";
}

function isFunction( object ) {
	return toString.call( object ) === "[object Function]";
}

function isString( object ) {
	return typeof object === "string";
}

function loadScript( options , callback ) {

	var script = document.createElement("script"),
		url = options[ STR_URL ],
		readyState;

	// Opera doesn't re-execute scripts with same url
	script.src = url + ( options[ STR_CACHE ] === FALSE ? ( ( /\?/.test( url ) ? "&" : "?" ) + "_=" + (new Date()).getTime() ) : "" );

	if ( options[ STR_CHARSET ] ) {
		script[ STR_CHARSET ] = options[ STR_CHARSET ];
	}

	// Attach handlers for all browsers
	script[ STR_ON_LOAD ] = script[ STR_ON_READY_STATE_CHANGE ] = function() {

		if ( ! ( readyState  = script.readyState ) || readyState === "loaded" || readyState === STR_COMPLETE ) {

			// Handle memory leak in IE
			script[ STR_ON_LOAD ] = script[ STR_ON_READY_STATE_CHANGE ] = NULL;

			if ( head && script.parentNode ) {
				head.removeChild( script );
			}

			callback && callback();
		}
	};

	// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
	// This arises when a base node is used (jQuery #2709 and #4378).
	head.insertBefore( script, head.firstChild );
}

<commit_msg>Replaced constant by string value (constant didn't exist anymore)<commit_after>/* Code based on jQuery
 * (c)2010 John Resig
 * http://jquery.com/
 */
var	// Head node
	head = document.getElementsByTagName("head")[0] || document.documentElement,

	// References
	toString = {}.toString,
	slice = [].slice;

// noop
function noop() {}

// Utilities
function isArray( object ) {
	return toString.call( object ) === "[object Array]";
}

function isFunction( object ) {
	return toString.call( object ) === "[object Function]";
}

function isString( object ) {
	return typeof object === "string";
}

function loadScript( options , callback ) {

	var script = document.createElement("script"),
		url = options[ STR_URL ],
		readyState;

	// Opera doesn't re-execute scripts with same url
	script.src = url + ( options[ STR_CACHE ] === FALSE ? ( ( /\?/.test( url ) ? "&" : "?" ) + "_=" + (new Date()).getTime() ) : "" );

	if ( options[ STR_CHARSET ] ) {
		script[ STR_CHARSET ] = options[ STR_CHARSET ];
	}

	// Attach handlers for all browsers
	script[ STR_ON_LOAD ] = script[ STR_ON_READY_STATE_CHANGE ] = function() {

		if ( ! ( readyState  = script.readyState ) || readyState === "loaded" || readyState === "complete" ) {

			// Handle memory leak in IE
			script[ STR_ON_LOAD ] = script[ STR_ON_READY_STATE_CHANGE ] = NULL;

			if ( head && script.parentNode ) {
				head.removeChild( script );
			}

			callback && callback();
		}
	};

	// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
	// This arises when a base node is used (jQuery #2709 and #4378).
	head.insertBefore( script, head.firstChild );
}

<|endoftext|>


<commit_before>var curtemp = new TimeSeries();
var settemp = new TimeSeries();
var settempm = new TimeSeries();
var settempp = new TimeSeries();
var pterm = new TimeSeries();
var iterm = new TimeSeries();
var dterm = new TimeSeries();
var pidval = new TimeSeries();
var avgpid = new TimeSeries();
var lastreqdone = 1;
var timeout;

function refreshinputs() {
  $.getJSON({
    url: "/allstats",
    timeout: 500,
    success: function ( resp ) {
      $("#inputSetTemp").val( resp.settemp );
      $("#inputSnooze").val( resp.snooze );
    }
  });
}

function resettimer() {
  clearTimeout(timeout);
  timeout = setTimeout(refreshinputs, 30000);
}

function onresize() {
    var h;
    if ($(window).height()*.40 > 350 ) {
      h = 350;
    } else {
      h = $(window).height()*.40;
    }

    $("#chart").attr("width", $("#fullrow").width()-30);
    $("#chart").attr("height", h);
    $("#pidchart").attr("width", $("#fullrow").width()-30);
    $("#pidchart").attr("height", h);

    if ($(document).width() < 600) {
      $("#toggleadv").html("Adv Stats");
    } else {
      $("#toggleadv").html("Advanced Stats");
    }
}

$(document).ready(function(){
  resettimer();
  $(this).mousemove(resettimer);
  $(this).keypress(resettimer);

  onresize();
  $(window).resize(onresize);

  createTimeline();

  $(".adv").hide();
  $("#toggleadv").click(function(){
    $(".adv").toggle();
  });

  refreshinputs();

  $("#btnSetTemp").click(function(){
    $.post(
      "/settemp",
      { settemp: $("#inputSetTemp").val() }
    );
  });

  $("#btnSnooze").click(function(){
    $.post("/snooze",{ snooze: $("#inputSnooze").val() });
    $("#btnSnooze").hide();
    $("#btnSnoozeC").show();
  });

  $("#btnSnoozeC").click(function(){
    $.post("/resetsnooze");
    $("#btnSnooze").show();
    $("#btnSnoozeC").hide();
  });

});

setInterval(function() {
  if (lastreqdone == 1) {
    $.getJSON({
      url: "/allstats",
      timeout: 500,
      success: function ( resp ) {
        if (resp.snoozeon == true) {
          $("#btnSnooze").hide();
          $("#btnSnoozeC").show();
        } else {
          $("#btnSnooze").show();
          $("#btnSnoozeC").hide();
        }
        curtemp.append(new Date().getTime(), resp.tempf);
        settemp.append(new Date().getTime(), resp.settemp);
        settempm.append(new Date().getTime(), resp.settemp-4);
        settempp.append(new Date().getTime(), resp.settemp+4);
        pterm.append(new Date().getTime(), resp.pterm);
        iterm.append(new Date().getTime(), resp.iterm);
        dterm.append(new Date().getTime(), resp.dterm);
        pidval.append(new Date().getTime(), resp.pidval);
        avgpid.append(new Date().getTime(), resp.avgpid);
        $("#curtemp").html(resp.tempf.toFixed(2));
        $("#pterm").html(resp.pterm.toFixed(2));
        $("#iterm").html(resp.iterm.toFixed(2));
        $("#dterm").html(resp.dterm.toFixed(2));
        $("#pidval").html(resp.pidval.toFixed(2));
        $("#avgpid").html(resp.avgpid.toFixed(2));
      },
      complete: function () {
        lastreqdone = 1;
      }
    });
    lastreqdone = 0;
  }
}, 100);

function createTimeline() {
  var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  chart.addTimeSeries(settemp, {lineWidth:1,strokeStyle:'#ffff00'});
  chart.addTimeSeries(settempm, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(settempp, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(curtemp, {lineWidth:3,strokeStyle:'#ff0000'});
  chart.streamTo(document.getElementById("chart"), 500);

  var pidchart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  pidchart.addTimeSeries(pterm, {lineWidth:2,strokeStyle:'#ff0000'});
  pidchart.addTimeSeries(iterm, {lineWidth:2,strokeStyle:'#00ff00'});
  pidchart.addTimeSeries(dterm, {lineWidth:2,strokeStyle:'#0000ff'});
  pidchart.addTimeSeries(pidval, {lineWidth:2,strokeStyle:'#ffff00'});
  pidchart.addTimeSeries(avgpid, {lineWidth:2,strokeStyle:'#ff00ff'});
  pidchart.streamTo(document.getElementById("pidchart"), 500);
}
<commit_msg>increased graph height to 450px or 50%<commit_after>var curtemp = new TimeSeries();
var settemp = new TimeSeries();
var settempm = new TimeSeries();
var settempp = new TimeSeries();
var pterm = new TimeSeries();
var iterm = new TimeSeries();
var dterm = new TimeSeries();
var pidval = new TimeSeries();
var avgpid = new TimeSeries();
var lastreqdone = 1;
var timeout;

function refreshinputs() {
  $.getJSON({
    url: "/allstats",
    timeout: 500,
    success: function ( resp ) {
      $("#inputSetTemp").val( resp.settemp );
      $("#inputSnooze").val( resp.snooze );
    }
  });
}

function resettimer() {
  clearTimeout(timeout);
  timeout = setTimeout(refreshinputs, 30000);
}

function onresize() {
    var h;
    if ($(window).height()*.50 > 450 ) {
      h = 450;
    } else {
      h = $(window).height()*.50;
    }

    $("#chart").attr("width", $("#fullrow").width()-30);
    $("#chart").attr("height", h);
    $("#pidchart").attr("width", $("#fullrow").width()-30);
    $("#pidchart").attr("height", h);

    if ($(document).width() < 600) {
      $("#toggleadv").html("Adv Stats");
    } else {
      $("#toggleadv").html("Advanced Stats");
    }
}

$(document).ready(function(){
  resettimer();
  $(this).mousemove(resettimer);
  $(this).keypress(resettimer);

  onresize();
  $(window).resize(onresize);

  createTimeline();

  $(".adv").hide();
  $("#toggleadv").click(function(){
    $(".adv").toggle();
  });

  refreshinputs();

  $("#btnSetTemp").click(function(){
    $.post(
      "/settemp",
      { settemp: $("#inputSetTemp").val() }
    );
  });

  $("#btnSnooze").click(function(){
    $.post("/snooze",{ snooze: $("#inputSnooze").val() });
    $("#btnSnooze").hide();
    $("#btnSnoozeC").show();
  });

  $("#btnSnoozeC").click(function(){
    $.post("/resetsnooze");
    $("#btnSnooze").show();
    $("#btnSnoozeC").hide();
  });

});

setInterval(function() {
  if (lastreqdone == 1) {
    $.getJSON({
      url: "/allstats",
      timeout: 500,
      success: function ( resp ) {
        if (resp.snoozeon == true) {
          $("#btnSnooze").hide();
          $("#btnSnoozeC").show();
        } else {
          $("#btnSnooze").show();
          $("#btnSnoozeC").hide();
        }
        curtemp.append(new Date().getTime(), resp.tempf);
        settemp.append(new Date().getTime(), resp.settemp);
        settempm.append(new Date().getTime(), resp.settemp-4);
        settempp.append(new Date().getTime(), resp.settemp+4);
        pterm.append(new Date().getTime(), resp.pterm);
        iterm.append(new Date().getTime(), resp.iterm);
        dterm.append(new Date().getTime(), resp.dterm);
        pidval.append(new Date().getTime(), resp.pidval);
        avgpid.append(new Date().getTime(), resp.avgpid);
        $("#curtemp").html(resp.tempf.toFixed(2));
        $("#pterm").html(resp.pterm.toFixed(2));
        $("#iterm").html(resp.iterm.toFixed(2));
        $("#dterm").html(resp.dterm.toFixed(2));
        $("#pidval").html(resp.pidval.toFixed(2));
        $("#avgpid").html(resp.avgpid.toFixed(2));
      },
      complete: function () {
        lastreqdone = 1;
      }
    });
    lastreqdone = 0;
  }
}, 100);

function createTimeline() {
  var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  chart.addTimeSeries(settemp, {lineWidth:1,strokeStyle:'#ffff00'});
  chart.addTimeSeries(settempm, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(settempp, {lineWidth:1,strokeStyle:'#ffffff'});
  chart.addTimeSeries(curtemp, {lineWidth:3,strokeStyle:'#ff0000'});
  chart.streamTo(document.getElementById("chart"), 500);

  var pidchart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05});
  pidchart.addTimeSeries(pterm, {lineWidth:2,strokeStyle:'#ff0000'});
  pidchart.addTimeSeries(iterm, {lineWidth:2,strokeStyle:'#00ff00'});
  pidchart.addTimeSeries(dterm, {lineWidth:2,strokeStyle:'#0000ff'});
  pidchart.addTimeSeries(pidval, {lineWidth:2,strokeStyle:'#ffff00'});
  pidchart.addTimeSeries(avgpid, {lineWidth:2,strokeStyle:'#ff00ff'});
  pidchart.streamTo(document.getElementById("pidchart"), 500);
}
<|endoftext|>


<commit_before>function LoadUtils() {
    texty.utils.blockTagNames = ["ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "CANVAS", "DD", "DIV", "DL", "FIELDSET", "FIGCAPTION", "FIGURE", "H1", "H2", "H3", "H4", "H5", "H6", "FOOTER", "FORM", "HEADER", "HGROUP", "HR", "LI", "MAIN", "NAV", "NOSCRIPT", "OL", "OUTPUT", "P", "PRE", "SECTION", "TABLE", "TFOOT", "UL", "VIDEO"];
    texty.utils.filterBlockNodes = function (nodes) {
        return nodes.filter(function (node) {
            return texty.utils.blockTagNames.indexOf(node.nodeName) !== -1;
        });
    };
}<commit_msg>inline added<commit_after>function LoadUtils() {
    texty.utils.blockTagNames = ["ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "CANVAS", "DD", "DIV", "DL", "FIELDSET", "FIGCAPTION", "FIGURE", "H1", "H2", "H3", "H4", "H5", "H6", "FOOTER", "FORM", "HEADER", "HGROUP", "HR", "LI", "MAIN", "NAV", "NOSCRIPT", "OL", "OUTPUT", "P", "PRE", "SECTION",/* "TABLE", "TFOOT",*/ "UL", "VIDEO"];
    texty.utils.inLineTagNames = ["B", "BIG", "I", "SMALL", "TT", "ABBR", "ACRONYM", "CITE", "CODE", "DFN", "EM", "KBD", "STRONG", "SAMP", "TIME", "VAR", "A", "BDO", "BR", "IMG", "MAP", "OBJECT", "Q", "SCRIPT", "SPAN", "SUB", "SUP", "BUTTON", "INPUT", "LABEL", "SELECT", "TEXTAREA"];
    texty.utils.filterBlockNodes = function (nodes) {
        return nodes.filter(function (node) {
            return texty.utils.blockTagNames.indexOf(node.nodeName) !== -1;
        });
    };
    texty.utils.filterInLineNodes = function (nodes) {
        return nodes.filter(function (node) {
            return texty.utils.inLineTagNames.indexOf(node.nodeName) !== -1;
        });
    };
}<|endoftext|>


<commit_before>// This is a JavaScript file

// スワイプを検知したあとの処理
function swipeEvent(direction) {
  if (direction == 'right'){
    location.href = "./page/picSelect.html";
  } else if (direction == 'left'){
    location.href = "./page/camera.html";
  }
}

function loginCheck() {
    // localStorage.setItem(LOGIN_KEY, null);
  var loginKey = localStorage.getItem(LOGIN_KEY);
  if (loginKey == null) {
    $('#picList').hide();
    $('#login').show();
    $("#loading").fadeOut(3500);
  } else {
    var reqParam = {id : loginKey};
    $.ajax({
      type: 'post',
      url: API_DOMAIN + 'Login.php',
      data: JSON.stringify(reqParam),
      contentType: 'application/JSON',
      dataType : 'JSON',
      scriptCharset: 'utf-8'
    }).done(function(data) {
      // 検索成功時
      if (data.result == '0') {
        getPicList(loginKey).done(function(){
          $('#login').hide();
          $('#picList').show();
          $("#loading").fadeOut(3500);
          $("div.modal-body p").text(INDEX_001);
          $("#id-modal").modal();

        }).fail(function(){
          // 検索失敗時
          localStorage.setItem(LOGIN_KEY, null);
          $("div.modal-body p").text(INDEX_002);
          $("#id-modal").modal();
        });
      } else {
        // 検索失敗時
        localStorage.setItem(LOGIN_KEY, null);
        $('#picList').hide();
        $('#login').show();
        $("#loading").fadeOut(3000);
      }
    }).fail(function() {
      // 検索失敗時
      localStorage.setItem(LOGIN_KEY, null);
      $('#picList').hide();
      $('#login').show();
      $("#loading").fadeOut(3000);
    });
  }
}
function login() {
  var loginId = $('#formInputId').val();
  var loginPassword = $('#formInputPassword').val();
  var userId = CybozuLabs.MD5.calc(loginId + ":" + loginPassword);
  var reqParam = {id : userId};
  $.ajax({
    type: 'post',
    url: API_DOMAIN + 'Login.php',
    data: JSON.stringify(reqParam),
    contentType: 'application/JSON',
    dataType : 'JSON',
    scriptCharset: 'utf-8'
  }).done(function(data) {
    // 検索成功時
    if (data.result == '0') {
      localStorage.setItem(LOGIN_KEY, userId);
      getPicList(userId).done(function(){
        $('#login').hide();
        $('#picList').show();
        $("div.modal-body p").text(INDEX_001);
        $("#id-modal").modal();
      }).fail(function(){
        // 検索失敗時
        localStorage.setItem(LOGIN_KEY, null);
        $("div.modal-body p").text(INDEX_002);
        $("#id-modal").modal();
      });
    } else {
      // 検索失敗時
      localStorage.setItem(LOGIN_KEY, null);
      $("div.modal-body p").text(INDEX_002);
      $("#id-modal").modal();
    }
  }).fail(function(data) {
    // 検索失敗時
    localStorage.setItem(LOGIN_KEY, null);
    $("div.modal-body p").text(INDEX_002);
    $("#id-modal").modal();
  });
}

function getPicList(userId, page) {
  var reqParam = {userId : userId};
  if (page === undefined) {
    reqParam.page = page;
  }
  var d = new $.Deferred();
  $.ajax({
    type: 'post',
    url: API_DOMAIN + 'GetPhotoInfo.php',
    data: JSON.stringify(reqParam),
    contentType: 'application/JSON',
    dataType : 'JSON',
    scriptCharset: 'utf-8'
  }).done(function(data) {
    // 検索成功時
    if (data.result == '0') {
        var tagArray = [];
        for (var i=0;i < data.array.length; i++) {
          var imgSrc = "data:image/png;base64," + data.array[i].photoData;
          var tagIds =  data.array[i].tag1 + "-" +data.array[i].tag2
                      + "-" +data.array[i].tag3 + "-" +data.array[i].tag4
                      + "-" +data.array[i].tag5 + "-" +data.array[i].tag6
                      + "-" +data.array[i].tag7 + "-" +data.array[i].tag8
                      + "-" +data.array[i].tag9 + "-" +data.array[i].tag10;
          var imgTag = '';
          if (i == data.array.length - 1) {
            imgTag = '
';
          } else {
            imgTag = '
';
          }
          imgTag += '';
          imgTag += '';
          imgTag += '
';
          tagArray.push(imgTag);
        }
        $("div#picList div.row").append(tagArray.join(''));
        $('#login').hide();
        $('#picList').show();
        d.resolve();
    } else {
      // 検索失敗時
      localStorage.setItem(LOGIN_KEY, null);
      $("div.modal-body p").text(INDEX_002);
      $("#id-modal").modal();
    }
  })
  .fail(function() {
    // 検索失敗時
    localStorage.setItem(LOGIN_KEY, null);
    alert(INDEX_002);
    d.reject();
  });
  return d.promise();
}

function picTap(e) {
  var selectPic = {};
  selectPic.pic = e.getAttribute("data-pic");
  selectPic.tagName = e.getAttribute("data-tagName");
  selectPic.tagIds = e.getAttribute("data-tagIds");
  localStorage.setItem('selectPic', JSON.stringify(selectPic));
  location.href="./page/picDetail.html";
}

$(function(){
  localStorage.setItem('selectPic', null);
  $('#picList').hide();
  $('#login').hide();
  loginCheck();
  // 引き金となる要素を設定
  var triggerNode = $(".container-fluid .row #pageEnd");
  var ajaxLock = false;
  // 画面スクロール毎に判定を行う
  $(window).scroll(function(){
    // 引き金となる要素の位置を取得
    var triggerNodePosition = $(triggerNode).offset().top - $(window).height();
    console.log(triggerNodePosition);
    // 現在のスクロール位置が引き金要素の位置より下にあれば‥
    if ($(window).scrollTop() > triggerNodePosition) {
      // 写真情報取得APIを実行
      if (!ajaxLock) {
        ajaxLock = true;
        $("#loading").show();
        getPicList(localStorage.getItem(LOGIN_KEY)).done(function(){
          $("#loading").fadeOut(3000);
          ajaxLock = false;
        }).fail(function(){
          // 検索失敗時
        });
      }
    }
  });
});<commit_msg>localstrage保存部変更<commit_after>// This is a JavaScript file

// スワイプを検知したあとの処理
function swipeEvent(direction) {
  if (direction == 'right'){
    location.href = "./page/picSelect.html";
  } else if (direction == 'left'){
    location.href = "./page/camera.html";
  }
}

function loginCheck() {
    // localStorage.setItem(LOGIN_KEY, null);
  var loginKey = localStorage.getItem(LOGIN_KEY);
  if (loginKey == null) {
    $('#picList').hide();
    $('#login').show();
    $("#loading").fadeOut(3500);
  } else {
    var reqParam = {id : loginKey};
    $.ajax({
      type: 'post',
      url: API_DOMAIN + 'Login.php',
      data: JSON.stringify(reqParam),
      contentType: 'application/JSON',
      dataType : 'JSON',
      scriptCharset: 'utf-8'
    }).done(function(data) {
      // 検索成功時
      if (data.result == '0') {
        getPicList(loginKey).done(function(){
          $('#login').hide();
          $('#picList').show();
          $("#loading").fadeOut(3500);
          $("div.modal-body p").text(INDEX_001);
          $("#id-modal").modal();

        }).fail(function(){
          // 検索失敗時
          localStorage.setItem(LOGIN_KEY, null);
          $("div.modal-body p").text(INDEX_002);
          $("#id-modal").modal();
        });
      } else {
        // 検索失敗時
        localStorage.setItem(LOGIN_KEY, null);
        $('#picList').hide();
        $('#login').show();
        $("#loading").fadeOut(3000);
      }
    }).fail(function() {
      // 検索失敗時
      localStorage.setItem(LOGIN_KEY, null);
      $('#picList').hide();
      $('#login').show();
      $("#loading").fadeOut(3000);
    });
  }
}
function login() {
  var loginId = $('#formInputId').val();
  var loginPassword = $('#formInputPassword').val();
  var userId = CybozuLabs.MD5.calc(loginId + ":" + loginPassword);
  var reqParam = {id : userId};
  $.ajax({
    type: 'post',
    url: API_DOMAIN + 'Login.php',
    data: JSON.stringify(reqParam),
    contentType: 'application/JSON',
    dataType : 'JSON',
    scriptCharset: 'utf-8'
  }).done(function(data) {
    // 検索成功時
    if (data.result == '0') {
      localStorage.setItem(LOGIN_KEY, userId);
      getPicList(userId).done(function(){
        $('#login').hide();
        $('#picList').show();
        $("div.modal-body p").text(INDEX_001);
        $("#id-modal").modal();
      }).fail(function(){
        // 検索失敗時
        localStorage.setItem(LOGIN_KEY, null);
        $("div.modal-body p").text(INDEX_002);
        $("#id-modal").modal();
      });
    } else {
      // 検索失敗時
      localStorage.setItem(LOGIN_KEY, null);
      $("div.modal-body p").text(INDEX_002);
      $("#id-modal").modal();
    }
  }).fail(function(data) {
    // 検索失敗時
    localStorage.setItem(LOGIN_KEY, null);
    $("div.modal-body p").text(INDEX_002);
    $("#id-modal").modal();
  });
}

function getPicList(userId, page) {
  var reqParam = {userId : userId};
  if (page === undefined) {
    reqParam.page = page;
  }
  var d = new $.Deferred();
  $.ajax({
    type: 'post',
    url: API_DOMAIN + 'GetPhotoInfo.php',
    data: JSON.stringify(reqParam),
    contentType: 'application/JSON',
    dataType : 'JSON',
    scriptCharset: 'utf-8'
  }).done(function(data) {
    // 検索成功時
    if (data.result == '0') {
        var tagArray = [];
        for (var i=0;i < data.array.length; i++) {
          var photoId = data.array[i].photoId;
          var imgSrc = "data:image/png;base64," + data.array[i].photoData;
          var tagIds =  data.array[i].tag1 + "-" +data.array[i].tag2
                      + "-" +data.array[i].tag3 + "-" +data.array[i].tag4
                      + "-" +data.array[i].tag5 + "-" +data.array[i].tag6
                      + "-" +data.array[i].tag7 + "-" +data.array[i].tag8
                      + "-" +data.array[i].tag9 + "-" +data.array[i].tag10;
          var imgTag = '';
          if (i == data.array.length - 1) {
            imgTag = '
';
          } else {
            imgTag = '
';
          }
          imgTag += '';
          imgTag += '';
          imgTag += '
';
          tagArray.push(imgTag);
        }
        $("div#picList div.row").append(tagArray.join(''));
        $('#login').hide();
        $('#picList').show();
        d.resolve();
    } else {
      // 検索失敗時
      localStorage.setItem(LOGIN_KEY, null);
      $("div.modal-body p").text(INDEX_002);
      $("#id-modal").modal();
    }
  })
  .fail(function() {
    // 検索失敗時
    localStorage.setItem(LOGIN_KEY, null);
    alert(INDEX_002);
    d.reject();
  });
  return d.promise();
}

function picTap(e) {
  console.log(e.getAttribute("data-photoId"));
  //TODO picture_binari以外も定数化したい
  localStorage.setItem('selectPic', e.getAttribute("data-photoId"));
  localStorage.setItem('tagNames', e.getAttribute("data-tagName"));
  localStorage.setItem(PICTURE_BINARY, e.getAttribute("data-pic"));
  location.href="./page/picDetail.html";
}

$(function(){
  localStorage.setItem('selectPic', null);
  $('#picList').hide();
  $('#login').hide();
  loginCheck();
  // 引き金となる要素を設定
  var triggerNode = $(".container-fluid .row #pageEnd");
  var ajaxLock = false;
  // 画面スクロール毎に判定を行う
  $(window).scroll(function(){
    // 引き金となる要素の位置を取得
    var triggerNodePosition = $(triggerNode).offset().top - $(window).height();
    console.log(triggerNodePosition);
    // 現在のスクロール位置が引き金要素の位置より下にあれば‥
    if ($(window).scrollTop() > triggerNodePosition) {
      // 写真情報取得APIを実行
      if (!ajaxLock) {
        ajaxLock = true;
        $("#loading").show();
        getPicList(localStorage.getItem(LOGIN_KEY)).done(function(){
          $("#loading").fadeOut(3000);
          ajaxLock = false;
        }).fail(function(){
          // 検索失敗時
        });
      }
    }
  });
});<|endoftext|>