<commit_before>'use strict';

const smoochBot = require('smooch-bot');
const MemoryStore = smoochBot.MemoryStore;
const Bot = smoochBot.Bot;
const Script = smoochBot.Script;
const StateMachine = smoochBot.StateMachine;

class ConsoleBot extends Bot {
    constructor(options) {
        super(options);
    }

    say(text) {
        return new Promise((resolve) => {
            console.log(text);
            resolve();
        });
    }
}

const script = new Script({
    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name'),
        receive: (bot, message) => {
            const name = message.text.trim();
            bot.setProp('name', name);
            return bot.say(`I'll call you ${name}! Great!`)
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

const userId = 'testUserId';
const store = new MemoryStore();
const bot = new ConsoleBot({
    store,
    userId
});

const stateMachine = new StateMachine({
    script,
    bot,
    userId
});

process.stdin.on('data', function(data) {
    stateMachine.receiveMessage({
        text: data.toString().trim()
    })
        .catch((err) => {
            console.error(err);
            console.error(err.stack);
        });
});
<commit_msg>Fix console example<commit_after>'use strict';

const smoochBot = require('smooch-bot');
const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;
const Bot = smoochBot.Bot;
const Script = smoochBot.Script;
const StateMachine = smoochBot.StateMachine;

class ConsoleBot extends Bot {
    constructor(options) {
        super(options);
    }

    say(text) {
        return new Promise((resolve) => {
            console.log(text);
            resolve();
        });
    }
}

const script = new Script({
    start: {
        receive: (bot) => {
            return bot.say('Hi! I\'m Smooch Bot!')
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('What\'s your name'),
        receive: (bot, message) => {
            const name = message.text.trim();
            bot.setProp('name', name);
            return bot.say(`I'll call you ${name}! Great!`)
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});

const userId = 'testUserId';
const store = new MemoryStore();
const lock = new MemoryLock();
const bot = new ConsoleBot({
    store,
    lock,
    userId
});

const stateMachine = new StateMachine({
    script,
    bot,
    userId
});

process.stdin.on('data', function(data) {
    stateMachine.receiveMessage({
        text: data.toString().trim()
    })
        .catch((err) => {
            console.error(err);
            console.error(err.stack);
        });
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/ember-blockly-catalog';

export default Ember.Component.extend({
  layout,
  blockly: Ember.inject.service(),
  onlyCustom: true,
  showCode: true,
  current_block: '',

  cantidad: Ember.computed('blocks.length', function() {
    return this.get('blocks.length');
  }),

  blocks: Ember.computed('onlyCustom', function() {
    this.set('current_block', '');

    if (this.get('onlyCustom')) {
      return this.get('blockly').getCustomBlocksList();
    } else {
      return this.get('blockly').getBlocksList();
    }
  }),

  actions: {
    onSelect(item) {
      this.set('current_block', item);
    }
  }

});
<commit_msg>Haciendo que el bloque seleccionado se mantenga en ember-blockly-catalog a pesar del cambio de contexto en la lista.<commit_after>import Ember from 'ember';
import layout from '../templates/components/ember-blockly-catalog';

export default Ember.Component.extend({
  layout,
  blockly: Ember.inject.service(),
  onlyCustom: true,
  showCode: true,
  current_block: '',

  cantidad: Ember.computed('blocks.length', function() {
    return this.get('blocks.length');
  }),

  blocks: Ember.computed('onlyCustom', function() {
    if (this.get('onlyCustom')) {
      return this.get('blockly').getCustomBlocksList();
    } else {
      return this.get('blockly').getBlocksList();
    }
  }),

  actions: {
    onSelect(item) {
      this.set('current_block', item);
    }
  }

});
<|endoftext|>


<commit_before>/* jshint node:true */
var fs = require('fs');
var http = require('http');
var express = require('express');
var httpProxy = require('http-proxy');
var siteSearch = require('./siteSearch');

// Create server

var app = express();
var server = http.createServer(app);
var oneDay = 24*60*60*1000;

app.configure(function() {
  app.set('port', process.env.PORT || 2010, '127.0.0.1');

  app.use(express.logger('dev'));
  app.use(express.compress());

  app.configure('development', function() {
    console.log('use: connect-livereload');
    app.use(require('connect-livereload')());
  });

  app.use('/app', express.static(__dirname + '/app'));
  app.use('/favicon.png', express.static(__dirname + '/app/templates/favicon.png', { maxAge: oneDay }));
});

// Configure routes

var proxy = httpProxy.createProxyServer({});

app.get   ('/api/search', siteSearch.route);
app.get   ('/app/*'   , function(req, res) { res.send('404', 404); } );
app.get   ('/public/*', function(req, res) { res.send('404', 404); } );

var proxyFn = function(req, res) {
  proxy.web(req, res, {
    target: 'https://api.cbd.int',
    secure: false
  });
};
// app.get   ('/api/*', function(req, res) { res.send(502); } ); //emulate failure of backend api;
app.get   ('/api/*', proxyFn);
app.put   ('/api/*', proxyFn);
app.post  ('/api/*', proxyFn);
app.delete('/api/*', proxyFn);

// Configure index.html

app.get('/*', function(req, res) {
  fs.readFile(__dirname + '/app/templates/master.html', 'utf8', function (error, text) {
    res.send(text);
  });
});

// Start server

console.log('Server listening on port ' + app.get('port'));
server.listen(app.get('port'));<commit_msg>formatting<commit_after>/* jshint node:true */
var fs = require('fs');
var http = require('http');
var express = require('express');
var httpProxy = require('http-proxy');
var siteSearch = require('./siteSearch');

// Create server

var app = express();
var server = http.createServer(app);
var oneDay = 24*60*60*1000;

app.configure(function() {
  app.set('port', process.env.PORT || 2010, '127.0.0.1');

  app.use(express.logger('dev'));
  app.use(express.compress());

  app.configure('development', function() {
    console.log('use: connect-livereload');
    app.use(require('connect-livereload')());
  });

  app.use('/app', express.static(__dirname + '/app'));
  app.use('/favicon.png', express.static(__dirname + '/app/templates/favicon.png', { maxAge: oneDay }));
});

// Configure routes

var proxy = httpProxy.createProxyServer({});

app.get   ('/app/*'   , function(req, res) { res.send('404', 404); } );
app.get   ('/api/search', siteSearch.route);

// app.get   ('/api/*', function(req, res) { res.send(502); } ); //emulate failure of backend api;
app.all('/api/*', function(req, res) { proxy.web(req, res, { target: 'https://api.cbd.int', secure: false }); } );

app.get('/*', function(req, res) {
  fs.readFile(__dirname + '/app/templates/master.html', 'utf8', function (error, text) {
    res.send(text);
  });
});

// Start server

console.log('Server listening on port ' + app.get('port'));
server.listen(app.get('port'));<|endoftext|>


<commit_before>
var graphs = [];   // rickshaw objects
var datum = [];    // metric data
var urls = [];     // graphite urls
var aliases = [];  // alias strings

// minutes of data in the live feed
var period = (typeof period == 'undefined') ? 5 : period;

// construct a url
function constructUrl(index, period) {
  urls[index] = url + '/render/?target=' + encodeURI(metrics[index].target) + '&from=-' + period + 'minutes&format=json';
}

// build our graph objects
function constructGraphs() {
  for (var j=0; j<metrics.length; j++) {
    constructUrl(j, period);
    aliases[j] = metrics[j].alias || metrics[j].target;
    datum[j] = [{ x:0, y:0 }];
    graphs[j] = new Rickshaw.Graph({
      element: document.querySelector('.graph' + j),
      width: 350,
      height: 100,
      interpolation: 'step-after',
      series: [{
        name: aliases[j],
        color: '#afdab1',
        data: datum[j]
      }]
    });
    graphs[j].render();
  }
}

// refresh the graph
function refreshData(immediately) {

  for (var k=0; k<graphs.length; k++) {
    getData(function(n, values) {
      for (var x=0; x<values.length; x++) {
        datum[n][x] = values[x];
      }

      // check our thresholds and update color
      var lastValue = datum[n][datum[n].length - 1].y;
      var warning = metrics[n].warning;
      var critical = metrics[n].critical;
      if (critical > warning) {
        if (lastValue > critical) {
          graphs[n].series[0].color = '#d59295';
        } else if (lastValue > warning) {
          graphs[n].series[0].color = '#f5cb56';
        } else {
          graphs[n].series[0].color = '#afdab1';
        }
      } else {
        if (lastValue < critical) {
          graphs[n].series[0].color = '#d59295';
        } else if (lastValue < warning) {
          graphs[n].series[0].color = '#f5cb56';
        } else {
          graphs[n].series[0].color = '#afdab1';
        }
      }
      // we want to render immediately, i.e.
      // as soon as ajax completes
      // used for time period / pause view
      if (immediately) {
        updateGraphs(n);
      }
    }, k);
  }
  // we can wait until all data is gathered, i.e.
  // the live refresh should happen synchronously
  if (!immediately) {
    for (var q=0; q<graphs.length; q++) {
      updateGraphs(q);
    }
  }
}

// pull data from graphite
function getData(cb, n) {
  var myDatum = [];
  if (metrics[n].target !== false) {
    $.ajax({
      dataType: 'jsonp',
      jsonp: 'jsonp',
      error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
      url: urls[n]
    }).done(function(d) {
      if (d.length > 0) {
        myDatum[0] = {
          x: d[0].datapoints[0][1],
          y: d[0].datapoints[0][0] || graphs[n].lastKnownValue || 0
        };
        for (var m=1; m<d[0].datapoints.length; m++) {
          myDatum[m] = {
            x: d[0].datapoints[m][1],
            y: d[0].datapoints[m][0] || graphs[n].lastKnownValue
          };
          if (typeof d[0].datapoints[m][0] === "number") {
            graphs[n].lastKnownValue = d[0].datapoints[m][0];
          }
        }
        cb(n, myDatum);
      }
    });
  }
}

// perform the actual graph object and
// overlay name and number updates
function updateGraphs(m) {
  // update our graph
  graphs[m].update();
  if (metrics[m].target === false) {
    //continue;
  } else if (datum[m][datum[m].length - 1] !== undefined) {
    var lastValue = datum[m][datum[m].length - 1].y;
    var lastValueDisplay;
    if ((typeof lastValue == 'number') && lastValue < 2.0) {
      lastValueDisplay = Math.round(lastValue*1000)/1000;
    } else {
      lastValueDisplay = parseInt(lastValue)
    }
    $('.overlay-name' + m).text(aliases[m]);
    $('.overlay-number' + m).text(lastValueDisplay);
    if (metrics[m].unit) {
      $('.overlay-number' + m).append('' + metrics[m].unit + '');
    }
  } else {
    $('.overlay-name' + m).text(aliases[m])
    $('.overlay-number' + m).html('NF');
  }
}

// add our containers
for (var i=0; i<metrics.length; i++) {
  $('#main').append('

');
}

// build our graph objects
constructGraphs();

// set our last known value at invocation
Rickshaw.Graph.prototype.lastKnownValue = 0;

// set our theme
var myTheme = (typeof theme == 'undefined') ? 'default' : theme;
if (myTheme === "dark") { enableNightMode(); }

// initial load screen
refreshData();
for (var g=0; g<graphs.length; g++) {
  if (metrics[g].target === false) {
  } else if (myTheme === "dark") {
    $('.overlay-number' + g).html('');
  } else {
    $('.overlay-number' + g).html('');
  }
}

// define our refresh and start interval
var refreshInterval = (typeof refresh == 'undefined') ? 2000 : refresh;
var refreshId = setInterval(refreshData, refreshInterval);

// set our "live" interval hint
$('#toolbar ul li.timepanel a.play').text(period + 'min');

// activate night mode
function enableNightMode() {
  $('body').addClass('night');
  $('div#title h1').addClass('night');
  $('div#graph svg').css('opacity', '0.8');
  $('div#overlay-name').addClass('night');
  $('div#overlay-number').addClass('night');
  $('div#toolbar ul li.timepanel').addClass('night');
}

// deactivate night mode
function disableNightMode() {
  $('body').removeClass('night');
  $('div#title h1').removeClass('night');
  $('div#graph svg').css('opacity', '1.0');
  $('div#overlay-name').removeClass('night');
  $('div#overlay-number').removeClass('night');
  $('div#toolbar ul li.timepanel').removeClass('night');
}

// activate night mode by click
$('li.toggle-night a').click(function() {
  console.log(this);
  if ($('body').hasClass('night')) {
    disableNightMode();
  } else {
    enableNightMode();
  }
});

// toggle number display
$('li.toggle-nonum a').click(function() { $('div#overlay-number').toggleClass('nonum'); });

// time panel, pause live feed and show range
$('#toolbar ul li.timepanel a.range').click(function() {
  var period = $(this).attr("title");
  for (var n=0; n<metrics.length; n++) {
    constructUrl(n, period);
  }
  if (! $('#toolbar ul li.timepanel a.play').hasClass('pause')) {
    $('#toolbar ul li.timepanel a.play').addClass('pause');
  }
  $('#toolbar ul li.timepanel a.play').text('paused');
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  refreshData("now");
  clearInterval(refreshId);
});

// time panel, resume live feed
$('#toolbar ul li.timepanel a.play').click(function() {
  for (var p=0; p<metrics.length; p++) {
    constructUrl(p, 5);
  }
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  $(this).removeClass('pause');
  $('#toolbar ul li.timepanel a.play').text(period + 'min');
  refreshData("now");
  // explicitly clear the old Interval in case
  // someone "doubles up" on the live play button
  clearInterval(refreshId);
  // remove and recreate the original graphs[]
  // helps clear out any rendering artifacts
  $('#graph svg').remove();
  constructGraphs();
  // reapply our style settings if night mode is active
  if ($('body').hasClass('night')) { enableNightMode(); }
  // restart our refresh interval
  refreshId = setInterval(refreshData, refreshInterval);
});

<commit_msg>normalize our local iterators<commit_after>
var graphs = [];   // rickshaw objects
var datum = [];    // metric data
var urls = [];     // graphite urls
var aliases = [];  // alias strings

// minutes of data in the live feed
var period = (typeof period == 'undefined') ? 5 : period;

// construct a url
function constructUrl(index, period) {
  urls[index] = url + '/render/?target=' + encodeURI(metrics[index].target) + '&from=-' + period + 'minutes&format=json';
}

// build our graph objects
function constructGraphs() {
  for (var i=0; i<metrics.length; i++) {
    constructUrl(i, period);
    aliases[i] = metrics[i].alias || metrics[i].target;
    datum[i] = [{ x:0, y:0 }];
    graphs[i] = new Rickshaw.Graph({
      element: document.querySelector('.graph' + i),
      width: 350,
      height: 100,
      interpolation: 'step-after',
      series: [{
        name: aliases[i],
        color: '#afdab1',
        data: datum[i]
      }]
    });
    graphs[i].render();
  }
}

// refresh the graph
function refreshData(immediately) {

  for (var i=0; i<graphs.length; i++) {
    getData(function(j, values) {
      for (var k=0; k<values.length; k++) {
        datum[j][k] = values[k];
      }

      // check our thresholds and update color
      var lastValue = datum[j][datum[j].length - 1].y;
      var warning = metrics[j].warning;
      var critical = metrics[j].critical;
      if (critical > warning) {
        if (lastValue > critical) {
          graphs[j].series[0].color = '#d59295';
        } else if (lastValue > warning) {
          graphs[j].series[0].color = '#f5cb56';
        } else {
          graphs[j].series[0].color = '#afdab1';
        }
      } else {
        if (lastValue < critical) {
          graphs[j].series[0].color = '#d59295';
        } else if (lastValue < warning) {
          graphs[j].series[0].color = '#f5cb56';
        } else {
          graphs[j].series[0].color = '#afdab1';
        }
      }
      // we want to render immediately, i.e.
      // as soon as ajax completes
      // used for time period / pause view
      if (immediately) {
        updateGraphs(j);
      }
    }, i);
  }
  // we can wait until all data is gathered, i.e.
  // the live refresh should happen synchronously
  if (!immediately) {
    for (var i=0; i<graphs.length; i++) {
      updateGraphs(i);
    }
  }
}

// pull data from graphite
function getData(cb, i) {
  var myDatum = [];
  if (metrics[i].target !== false) {
    $.ajax({
      dataType: 'jsonp',
      jsonp: 'jsonp',
      error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
      url: urls[i]
    }).done(function(d) {
      if (d.length > 0) {
        myDatum[0] = {
          x: d[0].datapoints[0][1],
          y: d[0].datapoints[0][0] || graphs[i].lastKnownValue || 0
        };
        for (var j=1; j<d[0].datapoints.length; j++) {
          myDatum[j] = {
            x: d[0].datapoints[j][1],
            y: d[0].datapoints[j][0] || graphs[i].lastKnownValue
          };
          if (typeof d[0].datapoints[j][0] === "number") {
            graphs[i].lastKnownValue = d[0].datapoints[j][0];
          }
        }
        cb(i, myDatum);
      }
    });
  }
}

// perform the actual graph object and
// overlay name and number updates
function updateGraphs(i) {
  // update our graph
  graphs[i].update();
  if (metrics[i].target === false) {
    //continue;
  } else if (datum[i][datum[i].length - 1] !== undefined) {
    var lastValue = datum[i][datum[i].length - 1].y;
    var lastValueDisplay;
    if ((typeof lastValue == 'number') && lastValue < 2.0) {
      lastValueDisplay = Math.round(lastValue*1000)/1000;
    } else {
      lastValueDisplay = parseInt(lastValue)
    }
    $('.overlay-name' + i).text(aliases[i]);
    $('.overlay-number' + i).text(lastValueDisplay);
    if (metrics[i].unit) {
      $('.overlay-number' + i).append('' + metrics[i].unit + '');
    }
  } else {
    $('.overlay-name' + i).text(aliases[i])
    $('.overlay-number' + i).html('NF');
  }
}

// add our containers
for (var i=0; i<metrics.length; i++) {
  $('#main').append('

');
}

// build our graph objects
constructGraphs();

// set our last known value at invocation
Rickshaw.Graph.prototype.lastKnownValue = 0;

// set our theme
var myTheme = (typeof theme == 'undefined') ? 'default' : theme;
if (myTheme === "dark") { enableNightMode(); }

// initial load screen
refreshData();
for (var i=0; i<graphs.length; i++) {
  if (metrics[i].target === false) {
  } else if (myTheme === "dark") {
    $('.overlay-number' + i).html('');
  } else {
    $('.overlay-number' + i).html('');
  }
}

// define our refresh and start interval
var refreshInterval = (typeof refresh == 'undefined') ? 2000 : refresh;
var refreshId = setInterval(refreshData, refreshInterval);

// set our "live" interval hint
$('#toolbar ul li.timepanel a.play').text(period + 'min');

// activate night mode
function enableNightMode() {
  $('body').addClass('night');
  $('div#title h1').addClass('night');
  $('div#graph svg').css('opacity', '0.8');
  $('div#overlay-name').addClass('night');
  $('div#overlay-number').addClass('night');
  $('div#toolbar ul li.timepanel').addClass('night');
}

// deactivate night mode
function disableNightMode() {
  $('body').removeClass('night');
  $('div#title h1').removeClass('night');
  $('div#graph svg').css('opacity', '1.0');
  $('div#overlay-name').removeClass('night');
  $('div#overlay-number').removeClass('night');
  $('div#toolbar ul li.timepanel').removeClass('night');
}

// activate night mode by click
$('li.toggle-night a').click(function() {
  console.log(this);
  if ($('body').hasClass('night')) {
    disableNightMode();
  } else {
    enableNightMode();
  }
});

// toggle number display
$('li.toggle-nonum a').click(function() { $('div#overlay-number').toggleClass('nonum'); });

// time panel, pause live feed and show range
$('#toolbar ul li.timepanel a.range').click(function() {
  var period = $(this).attr("title");
  for (var n=0; n<metrics.length; n++) {
    constructUrl(n, period);
  }
  if (! $('#toolbar ul li.timepanel a.play').hasClass('pause')) {
    $('#toolbar ul li.timepanel a.play').addClass('pause');
  }
  $('#toolbar ul li.timepanel a.play').text('paused');
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  refreshData("now");
  clearInterval(refreshId);
});

// time panel, resume live feed
$('#toolbar ul li.timepanel a.play').click(function() {
  for (var p=0; p<metrics.length; p++) {
    constructUrl(p, 5);
  }
  $(this).parent('li').parent('ul').find('li').removeClass('selected');
  $(this).parent('li').addClass('selected');
  $(this).removeClass('pause');
  $('#toolbar ul li.timepanel a.play').text(period + 'min');
  refreshData("now");
  // explicitly clear the old Interval in case
  // someone "doubles up" on the live play button
  clearInterval(refreshId);
  // remove and recreate the original graphs[]
  // helps clear out any rendering artifacts
  $('#graph svg').remove();
  constructGraphs();
  // reapply our style settings if night mode is active
  if ($('body').hasClass('night')) { enableNightMode(); }
  // restart our refresh interval
  refreshId = setInterval(refreshData, refreshInterval);
});

<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: 'spectrum-color-picker',

  tagName: 'input',

  color: null,

  flatMode: false,

  allowEmpty: false,

  disabled: false,

  showInput: false,

  showAlpha: false,

  showInitial: false,

  showButtons: true,

  showPalette: false,

  showPaletteOnly: false,

  palette: [],

  togglePaletteOnly: false,

  showSelectionPalette: false,

  hideAfterPaletteSelect: false,

  preferredFormat: null,

  moveFiresChange: false,

  clickoutFiresChange: false,

  chooseText: 'Choose',

  cancelText: 'Cancel',

  togglePaletteMoreText: 'More',

  togglePaletteLessText: 'Less',

  appendTo: 'body',

  localStorageKey: 'spectrum-color-picker',

  updatePicker: Ember.observer('color', function () {
    this.$().spectrum('set', this.get('color'));
  }),

  updateDisabled: Ember.observer('disabled', function () {
    this.$().spectrum(this.get('disabled') ? 'disable' : 'enable');
  }),

  didInsertElement() {
    let palette = this.get('palette');
    let opts = {
      color: this.get('color'),
      flat: this.get('flatMode'),
      allowEmpty: this.get('allowEmpty'),
      disabled: this.get('disabled'),
      showInput: this.get('showInput'),
      showAlpha: this.get('showAlpha'),
      showInitial: this.get('showInitial'),
      showButtons: this.get('showButtons'),
      showPalette: this.get('showPalette'),
      showPaletteOnly: this.get('showPaletteOnly'),
      palette: (typeof(palette) === 'string') ? JSON.parse(palette) : palette,
      togglePaletteOnly: this.get('togglePaletteOnly'),
      showSelectionPalette: this.get('showSelectionPalette'),
      hideAfterPaletteSelect: this.get('hideAfterPaletteSelect'),
      preferredFormat: this.get('preferredFormat'),
      clickoutFiresChange: this.get('clickoutFiresChange'),
      chooseText: this.get('chooseText'),
      cancelText: this.get('cancelText'),
      togglePaletteMoreText: this.get('togglePaletteMoreText'),
      togglePaletteLessText: this.get('togglePaletteLessText'),
      appendTo: this.get('appendTo'),
      localStorageKey: this.get('localStorageKey')
    };
    let self = this;
    let updateFunction = function (newColor) {
      let color = newColor ? newColor.toString() : null;
      let onChange = self.get('onChange');

      self.set('color', color);

      if (onChange) {
        onChange(color);
      }
    };

    opts.change = updateFunction;

    if (this.get('moveFiresChange')) {
      opts.move = updateFunction;
    }

    // Move Event
    let onMove = self.get('onMove');
    if (onMove) {
        opts.move = function (newColor) {
          onMove(newColor ? newColor.toString() : null);
        };
    }

    // Hide Event
    let onHide = self.get('onHide');
    if (onHide) {
        opts.hide = function (newColor) {
          onHide(newColor ? newColor.toString() : null);
        };
    }

    // Show Event
    let onShow = self.get('onShow');
    if (onShow) {
        opts.show = function (newColor) {
          onShow(newColor ? newColor.toString() : null);
        };
    }

    this.$().spectrum(opts);
  },

  willDestroyElement: function() {
    this.$().spectrum('destroy');
  }
});
<commit_msg>avoid calling set on destroyed objects<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: 'spectrum-color-picker',

  tagName: 'input',

  color: null,

  flatMode: false,

  allowEmpty: false,

  disabled: false,

  showInput: false,

  showAlpha: false,

  showInitial: false,

  showButtons: true,

  showPalette: false,

  showPaletteOnly: false,

  palette: [],

  togglePaletteOnly: false,

  showSelectionPalette: false,

  hideAfterPaletteSelect: false,

  preferredFormat: null,

  moveFiresChange: false,

  clickoutFiresChange: false,

  chooseText: 'Choose',

  cancelText: 'Cancel',

  togglePaletteMoreText: 'More',

  togglePaletteLessText: 'Less',

  appendTo: 'body',

  localStorageKey: 'spectrum-color-picker',

  updatePicker: Ember.observer('color', function () {
    this.$().spectrum('set', this.get('color'));
  }),

  updateDisabled: Ember.observer('disabled', function () {
    this.$().spectrum(this.get('disabled') ? 'disable' : 'enable');
  }),

  didInsertElement() {
    let palette = this.get('palette');
    let opts = {
      color: this.get('color'),
      flat: this.get('flatMode'),
      allowEmpty: this.get('allowEmpty'),
      disabled: this.get('disabled'),
      showInput: this.get('showInput'),
      showAlpha: this.get('showAlpha'),
      showInitial: this.get('showInitial'),
      showButtons: this.get('showButtons'),
      showPalette: this.get('showPalette'),
      showPaletteOnly: this.get('showPaletteOnly'),
      palette: (typeof(palette) === 'string') ? JSON.parse(palette) : palette,
      togglePaletteOnly: this.get('togglePaletteOnly'),
      showSelectionPalette: this.get('showSelectionPalette'),
      hideAfterPaletteSelect: this.get('hideAfterPaletteSelect'),
      preferredFormat: this.get('preferredFormat'),
      clickoutFiresChange: this.get('clickoutFiresChange'),
      chooseText: this.get('chooseText'),
      cancelText: this.get('cancelText'),
      togglePaletteMoreText: this.get('togglePaletteMoreText'),
      togglePaletteLessText: this.get('togglePaletteLessText'),
      appendTo: this.get('appendTo'),
      localStorageKey: this.get('localStorageKey')
    };
    let self = this;
    let updateFunction = function (newColor) {
      let color = newColor ? newColor.toString() : null;
      let onChange = self.get('onChange');

      if (!self.isDestroyed) {
        self.set('color', color);
      }

      if (onChange) {
        onChange(color);
      }
    };

    opts.change = updateFunction;

    if (this.get('moveFiresChange')) {
      opts.move = updateFunction;
    }

    // Move Event
    let onMove = self.get('onMove');
    if (onMove) {
        opts.move = function (newColor) {
          onMove(newColor ? newColor.toString() : null);
        };
    }

    // Hide Event
    let onHide = self.get('onHide');
    if (onHide) {
        opts.hide = function (newColor) {
          onHide(newColor ? newColor.toString() : null);
        };
    }

    // Show Event
    let onShow = self.get('onShow');
    if (onShow) {
        opts.show = function (newColor) {
          onShow(newColor ? newColor.toString() : null);
        };
    }

    this.$().spectrum(opts);
  },

  willDestroyElement: function() {
    this.$().spectrum('destroy');
  }
});
<|endoftext|>


<commit_before>var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var WebSocketServer = require('ws').Server
var http = require('http');

var count = 0;
var clients = {};

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
	response.writeHead(200, {'Content-Type': 'text/plain'});
	  response.write("Welcome to Node.js on OpenShift!\n\n");
	  response.end("Thanks for visiting us! \n");
});

server.listen( port, ipaddress, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wss = new WebSocketServer({
    server: server,
    autoAcceptConnections: false
});
wss.on('connection', function(ws) {
  // Specific id for this client & increment count
  var id = count++;
  ws.send('you are client ' + id);
  // Store the connection method so we can loop through & contact all clients
  clients[id] = ws;
  console.log("New connection");
  // ON SEND
  ws.on('message', function(message) {
    console.log(message);
    broadcast((new Date()) + " client " + id + " > " + message);
  });
  // DISCONNECT
  ws.on('close', function(reasonCode, description) {
    delete clients[id];
    console.log((new Date()) + ' Client ' + id + ' disconnected.');
  });

  ws.send('Welcome!');
});

wss.broadcast = function broadcast(data) {
  for(var i in clients){
      // Send a message to the client with the message
      clients[i].send(data);
  }
};

console.log("Listening to " + ipaddress + ":" + port + "...");
<commit_msg>fuck this bullshit<commit_after>var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var WebSocketServer = require('ws').Server
var http = require('http');

var count = 0;
var clients = {};

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
	response.writeHead(200, {'Content-Type': 'text/plain'});
	  response.write("Welcome to Node.js on OpenShift!\n\n");
	  response.end("Thanks for visiting us! \n");
});

server.listen( port, ipaddress, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wss = new WebSocketServer({
    server: server,
    autoAcceptConnections: false
});
wss.on('connection', function(ws) {
  // Specific id for this client & increment count
  var id = count++;
  ws.send('you are client ' + id);
  // Store the connection method so we can loop through & contact all clients
  clients[id] = ws;
  console.log("New connection");
  // ON SEND
  ws.on('message', function(message) {
    console.log(message);
    broadcast((new Date()) + " client " + id + " > " + message);
  });
  // DISCONNECT
  ws.on('close', function(reasonCode, description) {
    delete clients[id];
    console.log((new Date()) + ' Client ' + id + ' disconnected.');
  });

  ws.send('Welcome!');
});

function broadcast(data) {
  for(var i in clients){
      // Send a message to the client with the message
      clients[i].send(data);
  }
};

console.log("Listening to " + ipaddress + ":" + port + "...");
<|endoftext|>


<commit_before>$(document).ready(function(){function t(){var t=$(".main-container").width();t>=840?($(".about_title").css("margin","0").css("text-align","left"),$(".about_brief").css("width","45.25%").css("margin","0").css("text-align","left"),$(".about_img").css("width","400px").css("margin","0")):($(".about_title").css("margin","0 auto").css("text-align","center"),$(".about_brief").css("width","80%").css("margin","0 auto").css("text-align","center"),$(".about_img").css("width","480px").css("margin","48px auto 0 auto"))}function i(t){return function(){$(".about_img img").hide(),$("#about_"+t).fadeIn("slow");var i=$(".main-container").width();840>i&&$("body, html").animate({scrollTop:480},500)}}t(),$(window).resize(function(){t()});for(var a=1;12>a;a++)$("#about_link_"+a).click(i(a))});
<commit_msg>update<commit_after>$(document).ready(function(){function t(){var t=$(".main-container").width();t>=840?($(".about_title").css("margin","0").css("text-align","left"),$(".about_brief").css("width","50%").css("margin","0").css("text-align","left"),$(".about_img").css("width","400px").css("margin","0")):($(".about_title").css("margin","0 auto").css("text-align","center"),$(".about_brief").css("width","80%").css("margin","0 auto").css("text-align","center"),$(".about_img").css("width","480px").css("margin","48px auto 0 auto"))}function i(t){return function(){$(".about_img img").hide(),$("#about_"+t).fadeIn("slow");var i=$(".main-container").width();840>i&&$("body, html").animate({scrollTop:480},500)}}t(),$(window).resize(function(){t()});for(var a=1;12>a;a++)$("#about_link_"+a).click(i(a))});
<|endoftext|>


<commit_before>import Ember from 'ember';
import Error from '../util/error';

const {
  merge,
  RSVP: { resolve, reject }
} = Ember;

export default Ember.Mixin.create({

  _suspendChanges() {
    return () => {};
  },

  _invokeInternalWillSaveCallbacks(internal) {
    let model = internal.model;
    if(!model) {
      return resolve();
    }

    return resolve().then(() => {
      let isNew = internal.state.isNew;
      if(isNew) {
        return model.willCreate();
      }
    }).then(() => {
      return model.willSave();
    });
  },

  _isInternalModelUnique(internal) {
    let docId = internal.docId;
    if(docId) {
      let existing = this._internalModelWithDocId(docId);
      if(existing && existing !== internal) {
        return false;
      }
    }
    return true;
  },

  _validateInternalModelUniquiness(internal) {
    if(this._isInternalModelUnique(internal)) {
      return resolve();
    }
    return reject(new Error({
      error: 'conflict',
      reason: 'Document update conflict'
    }));
  },

  _onInternalModelWillSave(internal) {
    return resolve().then(() => {
      return this._invokeInternalWillSaveCallbacks(internal);
    }).then(() => {
      return this._validateInternalModelUniquiness(internal);
    });
  },

  _onInternalModelSaving(internal) {
    internal.withPropertyChanges(changed => {
      internal.onSaving(changed);
    }, true);
  },

  _onInternalModelSavedOrUpdated(internal, json) {
    internal.withPropertyChanges(changed => {
      this._deserializeInternalModelSave(internal, json, changed);
    }, true);
  },

  _onInternalModelSaveFailed(internal, err) {
    internal.withPropertyChanges(changed => {
      internal.onError(err, changed);
    }, true);
  },

  _reloadInternalModelAttachments(internal, json) {
    console.log('TODO: database-model-operations._reloadInternalModelAttachments', internal, json);
    return resolve();
  },

  _saveInternalModel(internal, opts) {
    opts = merge({}, opts);

    let force = !!opts.force;

    let isNew = internal.state.isNew;
    let isDeleted = internal.state.isDeleted;
    let isDirty = internal.state.isDirty;

    if(!force && !isDirty && !isNew && !isDeleted) {
      return resolve(internal);
    }

    let documents = this.get('documents');
    let resume;

    return resolve().then(() => {
      return this._onInternalModelWillSave(internal);
    }).then(() => {
      let doc = this._serializeInternalModelToDocument(internal, false);
      this._onInternalModelSaving(internal);
      resume = this._suspendChanges();
      return documents.save(doc);
    }).then(json => {
      this._onInternalModelSavedOrUpdated(internal, json);
      if(json.reload) {
        return this._reloadInternalModelAttachments(internal, json);
      }
    }).then(() => {
      resume();
      return internal;
    }, err => {
      this._onInternalModelSaveFailed(internal, err);
      if(resume) {
        resume();
      }
      return reject(err);
    });
  },

  _onInternalModelLoading(internal) {
    internal.withPropertyChanges(changed => {
      internal.onLoading(changed);
    }, true);
  },

  _isNotFoundDeleted(err) {
    return err.error === 'not_found' && err.reason === 'deleted';
  },

  _isNotFoundMissing(err) {
    return err.error === 'not_found' && err.reason === 'missing';
  },

  _isNotFoundMissingOrDeleted(err) {
    return this._isNotFoundMissing(err) || this._isNotFoundDeleted(err);
  },

  _onInternalModelLoadFailed(internal, err) {
    internal.withPropertyChanges(changed => {
      if(this._isNotFoundMissingOrDeleted(err)) {
        this._deserializeInternalModelDelete(internal, null, changed);
      }
      internal.onError(err, changed);
    }, true);
  },

  _onInternalModelLoaded(internal, doc) {
    let definition = internal.definition;
    this._assertDefinitionMatchesDocument(definition, doc);
    this._deserializeDocument(internal, doc);
    return internal;
  },

  _reloadInternalModel(internal) {
    if(internal.state.isNew) {
      return reject(new Error({ error: 'not_saved', reason: 'Model is not saved yet' }));
    }

    let docId = internal.docId;
    let documents = this.get('documents');

    return resolve().then(() => {
      this._onInternalModelLoading(internal);
      return documents.load(docId);
    }).then(doc => {
      return this._onInternalModelLoaded(internal, doc);
    }, err => {
      this._onInternalModelLoadFailed(internal, err);
      return reject(err);
    });
  },

  _loadInternalModel(internal, opts) {
    opts = merge({}, opts);
    if(internal.state.isLoaded && !opts.force) {
      return resolve(internal);
    }
    if(internal.state.isNew) {
      return resolve(internal);
    }
    return this._reloadInternalModel(internal);
  },

  _loadInternalModelForDocId(docId, opts) {
    let internal = this._internalModelWithDocId(docId);
    if(internal) {
      return this._loadInternalModel(internal, opts);
    }

    return this.get('documents').load(docId).then(doc => {
      return this._deserializeSavedDocumentToInternalModel(doc, null, false);
    });
  },

  _loadInternalModelForModelName(modelName, modelId, opts) {
    let modelClass = this.modelClassForName(modelName);
    let internal = this._existingInternalModelForModelClass(modelClass, modelId, { deleted: true });
    if(internal) {
      return this._loadInternalModel(internal, opts);
    }

    let definition = this._definitionForModelClass(modelClass);
    let docId = definition.docId(modelId);

    return this.get('documents').load(docId).then(doc => {
      internal = this._createExistingInternalModel(modelClass, modelId);
      return this._onInternalModelLoaded(internal, doc);
    });
  },

  _onInternalModelDeleted(internal, json) {
    internal.withPropertyChanges(changed => {
      this._deserializeInternalModelDelete(internal, json, changed);
    }, true);
  },

  _onInternalModelDeleteFailed(internal, err) {
    if(this._isNotFoundDeleted(err)) {
      internal.withPropertyChanges(changed => {
        this._deserializeInternalModelDelete(internal, null, changed);
        internal.onError(err, changed);
      });
      return resolve(internal);
    }
    internal.withPropertyChanges(changed => {
      internal.onError(err, changed);
    });
    return reject(err);
  },

  _invokeInternalWillDeleteCallbacks(internal) {
    let model = internal.model;
    if(!model) {
      return resolve();
    }

    return resolve().then(() => {
      return model.willDelete();
    });
  },

  _onInternalModelWillDelete(internal) {
    return resolve().then(() => {
      return this._invokeInternalWillDeleteCallbacks(internal);
    });
  },

  _onInternalModelDeleting(internal) {
    internal.withPropertyChanges(changed => {
      internal.onDeleting(changed);
    }, true);
  },

  _deleteInternalModel(internal) {
    if(internal.state.isNew) {
      return reject(new Error({ error: 'not_saved', reason: 'Model is not saved yet' }));
    }

    if(internal.state.isDeleted) {
      return reject(new Error({ error: 'deleted', reason: 'Model is already deleted' }));
    }

    let docId = internal.docId;
    let rev = internal.rev;
    let documents = this.get('documents');

    return resolve().then(() => {
      return this._onInternalModelWillDelete(internal);
    }).then(() => {
      this._onInternalModelDeleting(internal);
      return documents.delete(docId, rev);
    }).then(json => {
      this._onInternalModelDeleted(internal, json);
      return internal;
    }, err => {
      return this._onInternalModelDeleteFailed(internal, err);
    });
  },

  _deserializeDocuments(docs, expectedModelClass, optional) {
    return Ember.A(Ember.A(docs.map(doc => {
      if(!doc) {
        // on high load it is possible that view returns row with already deleted document's key, value but w/o doc
        // see: https://issues.apache.org/jira/browse/COUCHDB-1797
        return;
      }
      return this._deserializeDocumentToInternalModel(doc, expectedModelClass, optional);
    })).compact());
  },

  _expectedModelClassFromOpts(opts) {
    let model = opts.model;
    if(model) {
      delete opts.model;
      return this.modelClassForName(model);
    }
  },

  _optionalFromOpts(opts) {
    let optional = opts.optional;
    delete opts.optional;
    return !!optional;
  },

  _internalModelView(opts) {
    opts = merge({ include_docs: true }, opts);

    let ddoc = opts.ddoc;
    delete opts.ddoc;

    let view = opts.view;
    delete opts.view;

    let expectedModelClass = this._expectedModelClassFromOpts(opts);
    let optional = this._optionalFromOpts(opts);

    let documents = this.get('documents');
    return documents.view(ddoc, view, opts).then(json => {
      return this._deserializeDocuments(Ember.A(json.rows).map(row => row.doc), expectedModelClass, optional);
    });
  },

  _internalModelMango(opts) {
    opts = merge({}, opts);

    let expectedModelClass = this._expectedModelClassFromOpts(opts);
    let optional = this._optionalFromOpts(opts);

    if(expectedModelClass) {
      let definition = this._definitionForModelClass(expectedModelClass);
      let type = definition.type;
      if(!opts.selector[type.key]) {
        opts.selector[type.key] = type.value;
      }
    }

    let documents = this.get('documents');
    return documents.mango(opts).then(json => {
      return this._deserializeDocuments(json.docs, expectedModelClass, optional);
    });
  },

  _internalModelAll(opts) {
    opts = merge({ include_docs: true }, opts);

    let expectedModelClass = this._expectedModelClassFromOpts(opts);
    let optional = this._optionalFromOpts(opts);

    let documents = this.get('documents');
    return documents.all(opts).then(json => {
      return this._deserializeDocuments(Ember.A(json.rows).map(row => row.doc), expectedModelClass, optional);
    });
  },

  //
  // { id }
  // { id, model }
  // { all: true, model, key, startkey, endkey, ... }
  // { ddoc, view, model, key, ... }
  // { selector, sort, fields, ... }
  //
  // result: { result, type }
  _internalModelFind(opts) {
    opts = merge({}, opts);

    let all = opts.all;
    let id = opts.id;
    let model = opts.model;
    let ddoc = opts.ddoc;
    let selector = opts.selector;

    let result = (type) => {
      return (result) => {
        return { result, type };
      };
    };

    if(id) {
      delete opts.id;
      if(model) {
        delete opts.model;
        return this._loadInternalModelForModelName(model, id, opts).then(result('single'));
      } else {
        return this._loadInternalModelForDocId(id, opts).then(result('single'));
      }
    } else if(all) {
      delete opts.all;
      return this._internalModelAll(opts).then(result('array'));
    } else if(ddoc) {
      return this._internalModelView(opts).then(result('array'));
    } else if(selector) {
      return this._internalModelMango(opts).then(result('array'));
    }

    return reject(new Error({
      error: 'invalid_query',
      reason: 'opts must include either id, ddoc or selector'
    }));
  },

  _internalModelFirst(opts) {
    opts = merge({ limit: 1 }, opts);
    return this._internalModelFind(opts).then(({ result, type }) => {
      if(type === 'single') {
        return result;
      }
      return result[0];
    });
  }

});
<commit_msg>_onInternalModelLoaded stuff might throw error. handle that and set it as a internal.state.error<commit_after>import Ember from 'ember';
import Error from '../util/error';

const {
  merge,
  RSVP: { resolve, reject }
} = Ember;

export default Ember.Mixin.create({

  _suspendChanges() {
    return () => {};
  },

  _invokeInternalWillSaveCallbacks(internal) {
    let model = internal.model;
    if(!model) {
      return resolve();
    }

    return resolve().then(() => {
      let isNew = internal.state.isNew;
      if(isNew) {
        return model.willCreate();
      }
    }).then(() => {
      return model.willSave();
    });
  },

  _isInternalModelUnique(internal) {
    let docId = internal.docId;
    if(docId) {
      let existing = this._internalModelWithDocId(docId);
      if(existing && existing !== internal) {
        return false;
      }
    }
    return true;
  },

  _validateInternalModelUniquiness(internal) {
    if(this._isInternalModelUnique(internal)) {
      return resolve();
    }
    return reject(new Error({
      error: 'conflict',
      reason: 'Document update conflict'
    }));
  },

  _onInternalModelWillSave(internal) {
    return resolve().then(() => {
      return this._invokeInternalWillSaveCallbacks(internal);
    }).then(() => {
      return this._validateInternalModelUniquiness(internal);
    });
  },

  _onInternalModelSaving(internal) {
    internal.withPropertyChanges(changed => {
      internal.onSaving(changed);
    }, true);
  },

  _onInternalModelSavedOrUpdated(internal, json) {
    internal.withPropertyChanges(changed => {
      this._deserializeInternalModelSave(internal, json, changed);
    }, true);
  },

  _onInternalModelSaveFailed(internal, err) {
    internal.withPropertyChanges(changed => {
      internal.onError(err, changed);
    }, true);
  },

  _reloadInternalModelAttachments(internal, json) {
    console.log('TODO: database-model-operations._reloadInternalModelAttachments', internal, json);
    return resolve();
  },

  _saveInternalModel(internal, opts) {
    opts = merge({}, opts);

    let force = !!opts.force;

    let isNew = internal.state.isNew;
    let isDeleted = internal.state.isDeleted;
    let isDirty = internal.state.isDirty;

    if(!force && !isDirty && !isNew && !isDeleted) {
      return resolve(internal);
    }

    let documents = this.get('documents');
    let resume;

    return resolve().then(() => {
      return this._onInternalModelWillSave(internal);
    }).then(() => {
      let doc = this._serializeInternalModelToDocument(internal, false);
      this._onInternalModelSaving(internal);
      resume = this._suspendChanges();
      return documents.save(doc);
    }).then(json => {
      this._onInternalModelSavedOrUpdated(internal, json);
      if(json.reload) {
        return this._reloadInternalModelAttachments(internal, json);
      }
    }).then(() => {
      resume();
      return internal;
    }, err => {
      this._onInternalModelSaveFailed(internal, err);
      if(resume) {
        resume();
      }
      return reject(err);
    });
  },

  _onInternalModelLoading(internal) {
    internal.withPropertyChanges(changed => {
      internal.onLoading(changed);
    }, true);
  },

  _isNotFoundDeleted(err) {
    return err.error === 'not_found' && err.reason === 'deleted';
  },

  _isNotFoundMissing(err) {
    return err.error === 'not_found' && err.reason === 'missing';
  },

  _isNotFoundMissingOrDeleted(err) {
    return this._isNotFoundMissing(err) || this._isNotFoundDeleted(err);
  },

  _onInternalModelError(internal, err) {
    internal.withPropertyChanges(changed => {
      internal.onError(err, changed);
    }, true);
  },

  _onInternalModelLoadFailed(internal, err) {
    internal.withPropertyChanges(changed => {
      if(this._isNotFoundMissingOrDeleted(err)) {
        this._deserializeInternalModelDelete(internal, null, changed);
      }
      internal.onError(err, changed);
    }, true);
  },

  _onInternalModelLoaded(internal, doc) {
    return resolve().then(() => {
      let definition = internal.definition;
      this._assertDefinitionMatchesDocument(definition, doc);
      this._deserializeDocument(internal, doc);
    }).then(() => internal, err => {
      this._onInternalModelError(internal, err);
      return reject(err);
    });
  },

  _reloadInternalModel(internal) {
    if(internal.state.isNew) {
      return reject(new Error({ error: 'not_saved', reason: 'Model is not saved yet' }));
    }

    let docId = internal.docId;
    let documents = this.get('documents');

    return resolve().then(() => {
      this._onInternalModelLoading(internal);
      return documents.load(docId);
    }).then(doc => {
      return this._onInternalModelLoaded(internal, doc);
    }, err => {
      this._onInternalModelLoadFailed(internal, err);
      return reject(err);
    });
  },

  _loadInternalModel(internal, opts) {
    opts = merge({}, opts);
    if(internal.state.isLoaded && !opts.force) {
      return resolve(internal);
    }
    if(internal.state.isNew) {
      return resolve(internal);
    }
    return this._reloadInternalModel(internal);
  },

  _loadInternalModelForDocId(docId, opts) {
    let internal = this._internalModelWithDocId(docId);
    if(internal) {
      return this._loadInternalModel(internal, opts);
    }

    return this.get('documents').load(docId).then(doc => {
      return this._deserializeSavedDocumentToInternalModel(doc, null, false);
    });
  },

  _loadInternalModelForModelName(modelName, modelId, opts) {
    let modelClass = this.modelClassForName(modelName);
    let internal = this._existingInternalModelForModelClass(modelClass, modelId, { deleted: true });
    if(internal) {
      return this._loadInternalModel(internal, opts);
    }

    let definition = this._definitionForModelClass(modelClass);
    let docId = definition.docId(modelId);

    return this.get('documents').load(docId).then(doc => {
      internal = this._createExistingInternalModel(modelClass, modelId);
      return this._onInternalModelLoaded(internal, doc);
    });
  },

  _onInternalModelDeleted(internal, json) {
    internal.withPropertyChanges(changed => {
      this._deserializeInternalModelDelete(internal, json, changed);
    }, true);
  },

  _onInternalModelDeleteFailed(internal, err) {
    if(this._isNotFoundDeleted(err)) {
      internal.withPropertyChanges(changed => {
        this._deserializeInternalModelDelete(internal, null, changed);
        internal.onError(err, changed);
      });
      return resolve(internal);
    }
    internal.withPropertyChanges(changed => {
      internal.onError(err, changed);
    });
    return reject(err);
  },

  _invokeInternalWillDeleteCallbacks(internal) {
    let model = internal.model;
    if(!model) {
      return resolve();
    }

    return resolve().then(() => {
      return model.willDelete();
    });
  },

  _onInternalModelWillDelete(internal) {
    return resolve().then(() => {
      return this._invokeInternalWillDeleteCallbacks(internal);
    });
  },

  _onInternalModelDeleting(internal) {
    internal.withPropertyChanges(changed => {
      internal.onDeleting(changed);
    }, true);
  },

  _deleteInternalModel(internal) {
    if(internal.state.isNew) {
      return reject(new Error({ error: 'not_saved', reason: 'Model is not saved yet' }));
    }

    if(internal.state.isDeleted) {
      return reject(new Error({ error: 'deleted', reason: 'Model is already deleted' }));
    }

    let docId = internal.docId;
    let rev = internal.rev;
    let documents = this.get('documents');

    return resolve().then(() => {
      return this._onInternalModelWillDelete(internal);
    }).then(() => {
      this._onInternalModelDeleting(internal);
      return documents.delete(docId, rev);
    }).then(json => {
      this._onInternalModelDeleted(internal, json);
      return internal;
    }, err => {
      return this._onInternalModelDeleteFailed(internal, err);
    });
  },

  _deserializeDocuments(docs, expectedModelClass, optional) {
    return Ember.A(Ember.A(docs.map(doc => {
      if(!doc) {
        // on high load it is possible that view returns row with already deleted document's key, value but w/o doc
        // see: https://issues.apache.org/jira/browse/COUCHDB-1797
        return;
      }
      return this._deserializeDocumentToInternalModel(doc, expectedModelClass, optional);
    })).compact());
  },

  _expectedModelClassFromOpts(opts) {
    let model = opts.model;
    if(model) {
      delete opts.model;
      return this.modelClassForName(model);
    }
  },

  _optionalFromOpts(opts) {
    let optional = opts.optional;
    delete opts.optional;
    return !!optional;
  },

  _internalModelView(opts) {
    opts = merge({ include_docs: true }, opts);

    let ddoc = opts.ddoc;
    delete opts.ddoc;

    let view = opts.view;
    delete opts.view;

    let expectedModelClass = this._expectedModelClassFromOpts(opts);
    let optional = this._optionalFromOpts(opts);

    let documents = this.get('documents');
    return documents.view(ddoc, view, opts).then(json => {
      return this._deserializeDocuments(Ember.A(json.rows).map(row => row.doc), expectedModelClass, optional);
    });
  },

  _internalModelMango(opts) {
    opts = merge({}, opts);

    let expectedModelClass = this._expectedModelClassFromOpts(opts);
    let optional = this._optionalFromOpts(opts);

    if(expectedModelClass) {
      let definition = this._definitionForModelClass(expectedModelClass);
      let type = definition.type;
      if(!opts.selector[type.key]) {
        opts.selector[type.key] = type.value;
      }
    }

    let documents = this.get('documents');
    return documents.mango(opts).then(json => {
      return this._deserializeDocuments(json.docs, expectedModelClass, optional);
    });
  },

  _internalModelAll(opts) {
    opts = merge({ include_docs: true }, opts);

    let expectedModelClass = this._expectedModelClassFromOpts(opts);
    let optional = this._optionalFromOpts(opts);

    let documents = this.get('documents');
    return documents.all(opts).then(json => {
      return this._deserializeDocuments(Ember.A(json.rows).map(row => row.doc), expectedModelClass, optional);
    });
  },

  //
  // { id }
  // { id, model }
  // { all: true, model, key, startkey, endkey, ... }
  // { ddoc, view, model, key, ... }
  // { selector, sort, fields, ... }
  //
  // result: { result, type }
  _internalModelFind(opts) {
    opts = merge({}, opts);

    let all = opts.all;
    let id = opts.id;
    let model = opts.model;
    let ddoc = opts.ddoc;
    let selector = opts.selector;

    let result = (type) => {
      return (result) => {
        return { result, type };
      };
    };

    if(id) {
      delete opts.id;
      if(model) {
        delete opts.model;
        return this._loadInternalModelForModelName(model, id, opts).then(result('single'));
      } else {
        return this._loadInternalModelForDocId(id, opts).then(result('single'));
      }
    } else if(all) {
      delete opts.all;
      return this._internalModelAll(opts).then(result('array'));
    } else if(ddoc) {
      return this._internalModelView(opts).then(result('array'));
    } else if(selector) {
      return this._internalModelMango(opts).then(result('array'));
    }

    return reject(new Error({
      error: 'invalid_query',
      reason: 'opts must include either id, ddoc or selector'
    }));
  },

  _internalModelFirst(opts) {
    opts = merge({ limit: 1 }, opts);
    return this._internalModelFind(opts).then(({ result, type }) => {
      if(type === 'single') {
        return result;
      }
      return result[0];
    });
  }

});
<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');

// 404!
function send404(response) {
	response.writeHead(404, {"Content-Type": "text/plane"});
	response.write("Yap, that's an 404...")
	response.end();
}

function onRequest(request, response) {
	if(request.method == 'GET' && request.url == '/' ){
		response.writeHead(200, {"Content-Type": "text/html"})
		fs.createReadStream("./index.html").pipe(response);
	} else {
		try {
			response.writeHead(200, {"Content-Type": "text/html"})
			file = fs.createReadStream("." + request.url);
			file.on('error', send404());
			file.pipe(response);
		}
		catch(err) {
			send404();
		}
	}
}

http.createServer(onRequest).listen(80, "0.0.0.0");
console.log("Server created");
<commit_msg>Fixed not sending correct parameter and orgenizing layers<commit_after>var http = require('http');
var fs = require('fs');

// 404!
function send404(response) {
	response.writeHead(404, {"Content-Type": "text/plane"});
	response.write("Yap, that's an 404...")
	response.end();
}

function onRequest(request, response) {
	if(request.method == 'GET' && request.url == '/' ){
		response.writeHead(200, {"Content-Type": "text/html"})
		fs.createReadStream("./index.html").pipe(response);
	} else {
		try {
			file = fs.createReadStream("." + request.url);
			file.on('error', send404(response));
			response.writeHead(200, {"Content-Type": "text/html"})
			file.pipe(response);
		}
		catch(err) {
			send404();
		}
	}
}

http.createServer(onRequest).listen(80, "0.0.0.0");
console.log("Server created");
<|endoftext|>


<commit_before>var events = new Events();

var AudioHandler = function() {

	var waveData = []; //waveform - from 0 - 1 . no sound is 0.5. Array [binCount]
	var levelsData = []; //levels of each frequecy - from 0 - 1 . no sound is 0. Array [levelsCount]
	var level = 0; // averaged normalized level from 0 - 1
	var bpmTime = 0; // bpmTime ranges from 0 to 1. 0 = on beat. Based on tap bpm
	var ratedBPMTime = 550;//time between beats (msec) multiplied by BPMRate
	var levelHistory = []; //last 256 ave norm levels
	var bpmStart;

	var BEAT_HOLD_TIME = 40; //num of frames to hold a beat
	var BEAT_DECAY_RATE = 0.88;
	var BEAT_MIN = 0.15; //a volume less than this is no beat

	//BPM STUFF
	var count = 0;
	var msecsFirst = 0;
	var msecsPrevious = 0;
	var msecsAvg = 633; //time between beats (msec)

	var timer;
	var gotBeat = false;
	var beatCutOff = 0;
	var beatTime = 0;
	var scl = 0;

	var freqByteData; //bars - bar data is from 0 - 256 in 512 bins. no sound is 0;
	var timeByteData; //waveform - waveform data is from 0-256 for 512 bins. no sound is 128.
	var levelsCount = 16; //should be factor of 512

	var binCount; //512
	var levelBins;

	var isPlayingAudio = false;

	var source;
	var buffer;
	var audioBuffer;
	var dropArea;
	var audioContext;
	var analyser;

	function init() {
		//EVENT HANDLERS
		events.on("update", update);

		//Get an Audio Context
		try {
			window.AudioContext = window.AudioContext || window.webkitAudioContext;
			audioContext = new window.AudioContext();
		} catch(e) {
			//Web Audio API is not supported in this browser
			$('#info').append('Sorry!
This browser does not support the Web Audio API. Please use Chrome, Safari or Firefox.');
			$('#controls').hide();
			return;
		}

		analyser = audioContext.createAnalyser();
		analyser.smoothingTimeConstant = 0.8; //0<->1. 0 is no time smoothing
		analyser.fftSize = 1024;
		analyser.connect(audioContext.destination);
		binCount = analyser.frequencyBinCount; // = 512

		levelBins = Math.floor(binCount / levelsCount); //number of bins in each level

		freqByteData = new Uint8Array(binCount);
		timeByteData = new Uint8Array(binCount);

		var length = 256;
		for(var i = 0; i < length; i++) {
		    levelHistory.push(0);
		}

		getMicInput();
		setInterval(update, 5);

		onBMPBeat();
		msecsAvg = 640;
		timer = setInterval(onBMPBeat,msecsAvg);
	}

	function getMicInput() {
		//x-browser
		navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

		if (navigator.getUserMedia ) {
			navigator.getUserMedia(
				{audio: true},

				function(stream) {
					//reinit here or get an echo on the mic
					source = audioContext.createBufferSource();
					analyser = audioContext.createAnalyser();
					analyser.fftSize = 1024;
					analyser.smoothingTimeConstant = 0.3;

					microphone = audioContext.createMediaStreamSource(stream);
					microphone.connect(analyser);
					isPlayingAudio = true;
				},

				// errorCallback
				function(err) {
					alert("The following error occured: " + err);
				}
			);

		}else{
			alert("Could not getUserMedia");
		}
	}

	function onBMPBeat(){
		//console.log("onBMPBeat");
		bpmStart = new Date().getTime();

		//only fire bpm beat if there was an on onBeat in last timeframe
		//experimental combined beat + bpm mode
		//if (gotBeat){
			gotBeat = false;
		//}

	}

	//called every frame
	//update published viz data
	function update(){

		if (!isPlayingAudio) return;

		//GET DATA
		analyser.getByteFrequencyData(freqByteData); //<-- bar chart
		analyser.getByteTimeDomainData(timeByteData); // <-- waveform

		//normalize waveform data
		for(var i = 0; i < binCount; i++) {
			waveData[i] = ((timeByteData[i] - 128) / 128);
		}
		//TODO - cap levels at 1 and -1 ?

		//normalize levelsData from freqByteData
		for(var i = 0; i < levelsCount; i++) {
			var sum = 0;
			for(var j = 0; j < levelBins; j++) {
				sum += freqByteData[(i * levelBins) + j];
			}
			levelsData[i] = sum / levelBins / 256; //freqData maxs at 256

			//adjust for the fact that lower levels are percieved more quietly
			//make lower levels smaller
			levelsData[i] *=  1 + (i / levelsCount) / 2;
		}
		//TODO - cap levels at 1?

		//GET AVG LEVEL
		var sum = 0;
		for(var j = 0; j < levelsCount; j++) {
			sum += levelsData[j];
		}

		level = sum / levelsCount;

		levelHistory.push(level);
		levelHistory.shift(1);

		//BEAT DETECTION
		if (level  > beatCutOff && level > BEAT_MIN){
			getLastFreq();
			beatCutOff = level * 1.1;
			beatTime = 0;
		} else{
			if (beatTime <= BEAT_HOLD_TIME){
				beatTime ++;
			}else{
				beatCutOff *= BEAT_DECAY_RATE;
				beatCutOff = Math.max(beatCutOff,BEAT_MIN);
			}
		}

		bpmTime = (new Date().getTime() - bpmStart) / msecsAvg;
		//trace(bpmStart);
	}

	function getLastFreq() {
		const level = levelHistory.length ? levelHistory[levelHistory.length - 1] : 0;
		var gotoScale = level * 1.2 + 0.1;
		scl += (gotoScale - scl) / 3;

		var color = hexToRgb('#'+Math.random().toString(16).substr(-6));
		if (bpmTime <= 0.3) {
			return;
		}

		$.ajax({
			headers : {
				'Accept' : 'application/json',
				'Content-Type' : 'application/json'
			},
			url : `${document.URL}254e381abc4b4d5cb3612817acba6345`,
			type : 'PATCH',
			data : JSON.stringify({
				"red": color.r,
				"green": color.g,
				"blue": color.b,
				"brightness": 100,
				"saturation": 100
			}),
			success : function(response, textStatus, jqXhr) {
					console.log("Successfully Patched!");
			},
			error : function(jqXHR, textStatus, errorThrown) {
					// log the error to the console
					console.log("The following error occured: " + textStatus, errorThrown);
			}
		});

		init();
	}

	function onBeat(){
		gotBeat = true;
	}

	function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

	return {
		update:update,
		init:init,
		getMicInput:getMicInput,
	};

}();
<commit_msg>Trying to select brighter/contrasting but random colors<commit_after>var events = new Events();

var AudioHandler = function() {

	var waveData = []; //waveform - from 0 - 1 . no sound is 0.5. Array [binCount]
	var levelsData = []; //levels of each frequecy - from 0 - 1 . no sound is 0. Array [levelsCount]
	var level = 0; // averaged normalized level from 0 - 1
	var bpmTime = 0; // bpmTime ranges from 0 to 1. 0 = on beat. Based on tap bpm
	var ratedBPMTime = 550;//time between beats (msec) multiplied by BPMRate
	var levelHistory = []; //last 256 ave norm levels
	var colorHistory = []; //last 256 ave norm levels
	var bpmStart;

	var BEAT_HOLD_TIME = 40; //num of frames to hold a beat
	var BEAT_DECAY_RATE = 0.88;
	var BEAT_MIN = 0.15; //a volume less than this is no beat

	//BPM STUFF
	var count = 0;
	var msecsFirst = 0;
	var msecsPrevious = 0;
	var msecsAvg = 633; //time between beats (msec)

	var timer;
	var gotBeat = false;
	var beatCutOff = 0;
	var beatTime = 0;
	var scl = 0;

	var freqByteData; //bars - bar data is from 0 - 256 in 512 bins. no sound is 0;
	var timeByteData; //waveform - waveform data is from 0-256 for 512 bins. no sound is 128.
	var levelsCount = 16; //should be factor of 512

	var binCount; //512
	var levelBins;

	var isPlayingAudio = false;

	var source;
	var buffer;
	var audioBuffer;
	var dropArea;
	var audioContext;
	var analyser;

	// Seed to get repeatable colors
	var seed = null;

	// Shared color dictionary
	var colorDictionary = {};

	function init() {
		//EVENT HANDLERS
		events.on("update", update);

		//Get an Audio Context
		try {
			window.AudioContext = window.AudioContext || window.webkitAudioContext;
			audioContext = new window.AudioContext();
		} catch(e) {
			//Web Audio API is not supported in this browser
			$('#info').append('Sorry!
This browser does not support the Web Audio API. Please use Chrome, Safari or Firefox.');
			$('#controls').hide();
			return;
		}

		analyser = audioContext.createAnalyser();
		analyser.smoothingTimeConstant = 0.8; //0<->1. 0 is no time smoothing
		analyser.fftSize = 1024;
		analyser.connect(audioContext.destination);
		binCount = analyser.frequencyBinCount; // = 512

		levelBins = Math.floor(binCount / levelsCount); //number of bins in each level

		freqByteData = new Uint8Array(binCount);
		timeByteData = new Uint8Array(binCount);

		var length = 256;
		for(var i = 0; i < length; i++) {
		    levelHistory.push(0);
		}

		getMicInput();
		setInterval(update, 5);

		onBMPBeat();
		msecsAvg = 640;
		timer = setInterval(onBMPBeat,msecsAvg);

		// Populate the color dictionary
		loadColorBounds();
	}

	function getMicInput() {
		//x-browser
		navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

		if (navigator.getUserMedia ) {
			navigator.getUserMedia(
				{audio: true},

				function(stream) {
					//reinit here or get an echo on the mic
					source = audioContext.createBufferSource();
					analyser = audioContext.createAnalyser();
					analyser.fftSize = 1024;
					analyser.smoothingTimeConstant = 0.3;

					microphone = audioContext.createMediaStreamSource(stream);
					microphone.connect(analyser);
					isPlayingAudio = true;
				},

				// errorCallback
				function(err) {
					alert("The following error occured: " + err);
				}
			);

		}else{
			alert("Could not getUserMedia");
		}
	}

	function onBMPBeat(){
		//console.log("onBMPBeat");
		bpmStart = new Date().getTime();

		//only fire bpm beat if there was an on onBeat in last timeframe
		//experimental combined beat + bpm mode
		//if (gotBeat){
			gotBeat = false;
		//}

	}

	//called every frame
	//update published viz data
	function update(){

		if (!isPlayingAudio) return;

		//GET DATA
		analyser.getByteFrequencyData(freqByteData); //<-- bar chart
		analyser.getByteTimeDomainData(timeByteData); // <-- waveform

		//normalize waveform data
		for(var i = 0; i < binCount; i++) {
			waveData[i] = ((timeByteData[i] - 128) / 128);
		}
		//TODO - cap levels at 1 and -1 ?

		//normalize levelsData from freqByteData
		for(var i = 0; i < levelsCount; i++) {
			var sum = 0;
			for(var j = 0; j < levelBins; j++) {
				sum += freqByteData[(i * levelBins) + j];
			}
			levelsData[i] = sum / levelBins / 256; //freqData maxs at 256

			//adjust for the fact that lower levels are percieved more quietly
			//make lower levels smaller
			levelsData[i] *=  1 + (i / levelsCount) / 2;
		}
		//TODO - cap levels at 1?

		//GET AVG LEVEL
		var sum = 0;
		for(var j = 0; j < levelsCount; j++) {
			sum += levelsData[j];
		}

		level = sum / levelsCount;

		levelHistory.push(level);
		levelHistory.shift(1);

		//BEAT DETECTION
		if (level  > beatCutOff && level > BEAT_MIN){
			getLastFreq();
			beatCutOff = level * 1.1;
			beatTime = 0;
		} else{
			if (beatTime <= BEAT_HOLD_TIME){
				beatTime ++;
			}else{
				beatCutOff *= BEAT_DECAY_RATE;
				beatCutOff = Math.max(beatCutOff,BEAT_MIN);
			}
		}

		bpmTime = (new Date().getTime() - bpmStart) / msecsAvg;
		//trace(bpmStart);
	}

	function invertColor(lastColor) {
		return {
			r: (255 - lastColor.r),
			g: (255 - lastColor.g),
			b: (255 - lastColor.b)
		};
	}

	function randomizeColor(options) {
	  options = options || {};

	  // Check if there is a seed and ensure it's an
	  // integer. Otherwise, reset the seed value.
	  if (options.seed !== undefined && options.seed !== null && options.seed === parseInt(options.seed, 10)) {
	    seed = options.seed;

	  // A string was passed as a seed
	  } else if (typeof options.seed === 'string') {
	    seed = stringToInteger(options.seed);

	  // Something was passed as a seed but it wasn't an integer or string
	  } else if (options.seed !== undefined && options.seed !== null) {
	    throw new TypeError('The seed value must be an integer or string');

	  // No seed, reset the value outside.
	  } else {
	    seed = null;
	  }

	  var H,S,B;

	  // Check if we need to generate multiple colors
	  if (options.count !== null && options.count !== undefined) {

	    var totalColors = options.count,
	        colors = [];

	    options.count = null;

	    while (totalColors > colors.length) {

	      // Since we're generating multiple colors,
	      // incremement the seed. Otherwise we'd just
	      // generate the same color each time...
	      if (seed && options.seed) options.seed += 1;

	      colors.push(randomColor(options));
	    }

	    options.count = totalColors;

	    return colors;
	  }

	  // First we pick a hue (H)
	  H = pickHue(options);

	  // Then use H to determine saturation (S)
	  S = pickSaturation(H, options);

	  // Then use S and H to determine brightness (B).
	  B = pickBrightness(H, S, options);

	  // Then we return the HSB color in the desired format
	  var rgbArray = setFormat([H,S,B], options);
		return {
			r: rgbArray[0],
			g: rgbArray[1],
			b: rgbArray[2]
		};
	}

	function getLastFreq() {
		const level = levelHistory.length ? levelHistory[levelHistory.length - 1] : 0;
		var gotoScale = level * 1.2 + 0.1;
		scl += (gotoScale - scl) / 3;

		if (bpmTime <= 0.25 && level < 0.7) {
			// console.log('not enough');
			return;
		}

		var color = 0;
		if (colorHistory.length % 2) {
			color = invertColor(colorHistory[colorHistory.length - 1]);
		} else {
			color = randomizeColor({
			   luminosity: 'bright',
			   format: 'rgbArray',
				 hue: 'random'
			});
		}
		colorHistory.push(color);
		console.log(color);

		$.ajax({
			headers : {
				'Accept' : 'application/json',
				'Content-Type' : 'application/json'
			},
			url : `${document.URL}254e381abc4b4d5cb3612817acba6345`,
			type : 'PATCH',
			data : JSON.stringify({
				"red": color.r,
				"green": color.g,
				"blue": color.b,
				"brightness": 100,
				"saturation": 100
			}),
			success : function(response, textStatus, jqXhr) {
					console.log("Successfully Patched!");
			},
			error : function(jqXHR, textStatus, errorThrown) {
					// log the error to the console
					console.log("The following error occured: " + textStatus, errorThrown);
			}
		});

		init();
	}

	function onBeat(){
		gotBeat = true;
	}

	function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function pickHue (options) {

  var hueRange = getHueRange(options.hue),
      hue = randomWithin(hueRange);

  // Instead of storing red as two seperate ranges,
  // we group them, using negative numbers
  if (hue < 0) {hue = 360 + hue;}

  return hue;

}

function pickSaturation (hue, options) {

  if (options.hue === 'monochrome') {
    return 0;
  }

  if (options.luminosity === 'random') {
    return randomWithin([0,100]);
  }

  var saturationRange = getSaturationRange(hue);

  var sMin = saturationRange[0],
      sMax = saturationRange[1];

  switch (options.luminosity) {

    case 'bright':
      sMin = 55;
      break;

    case 'dark':
      sMin = sMax - 10;
      break;

    case 'light':
      sMax = 55;
      break;
 }

  return randomWithin([sMin, sMax]);

}

function pickBrightness (H, S, options) {

  var bMin = getMinimumBrightness(H, S),
      bMax = 100;

  switch (options.luminosity) {

    case 'dark':
      bMax = bMin + 20;
      break;

    case 'light':
      bMin = (bMax + bMin)/2;
      break;

    case 'random':
      bMin = 0;
      bMax = 100;
      break;
  }

  return randomWithin([bMin, bMax]);
}

function setFormat (hsv, options) {

  switch (options.format) {

    case 'hsvArray':
      return hsv;

    case 'hslArray':
      return HSVtoHSL(hsv);

    case 'hsl':
      var hsl = HSVtoHSL(hsv);
      return 'hsl('+hsl[0]+', '+hsl[1]+'%, '+hsl[2]+'%)';

    case 'hsla':
      var hslColor = HSVtoHSL(hsv);
      var alpha = options.alpha || Math.random();
      return 'hsla('+hslColor[0]+', '+hslColor[1]+'%, '+hslColor[2]+'%, ' + alpha + ')';

    case 'rgbArray':
      return HSVtoRGB(hsv);

    case 'rgb':
      var rgb = HSVtoRGB(hsv);
      return 'rgb(' + rgb.join(', ') + ')';

    case 'rgba':
      var rgbColor = HSVtoRGB(hsv);
      var alpha = options.alpha || Math.random();
      return 'rgba(' + rgbColor.join(', ') + ', ' + alpha + ')';

    default:
      return HSVtoHex(hsv);
  }

}

function getMinimumBrightness(H, S) {

  var lowerBounds = getColorInfo(H).lowerBounds;

  for (var i = 0; i < lowerBounds.length - 1; i++) {

    var s1 = lowerBounds[i][0],
        v1 = lowerBounds[i][1];

    var s2 = lowerBounds[i+1][0],
        v2 = lowerBounds[i+1][1];

    if (S >= s1 && S <= s2) {

       var m = (v2 - v1)/(s2 - s1),
           b = v1 - m*s1;

       return m*S + b;
    }

  }

  return 0;
}

function getHueRange (colorInput) {

  if (typeof parseInt(colorInput) === 'number') {

    var number = parseInt(colorInput);

    if (number < 360 && number > 0) {
      return [number, number];
    }

  }

  if (typeof colorInput === 'string') {

    if (colorDictionary[colorInput]) {
      var color = colorDictionary[colorInput];
      if (color.hueRange) {return color.hueRange;}
    } else if (colorInput.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)) {
      const hue = HexToHSB(colorInput)[0];
      return [ hue, hue ];
    }
  }

  return [0,360];

}

function getSaturationRange (hue) {
  return getColorInfo(hue).saturationRange;
}

function getColorInfo (hue) {

  // Maps red colors to make picking hue easier
  if (hue >= 334 && hue <= 360) {
    hue-= 360;
  }

  for (var colorName in colorDictionary) {
     var color = colorDictionary[colorName];
     if (color.hueRange &&
         hue >= color.hueRange[0] &&
         hue <= color.hueRange[1]) {
        return colorDictionary[colorName];
     }
  } return 'Color not found';
}

function randomWithin (range) {
  if (seed === null) {
    return Math.floor(range[0] + Math.random()*(range[1] + 1 - range[0]));
  } else {
    //Seeded random algorithm from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
    var max = range[1] || 1;
    var min = range[0] || 0;
    seed = (seed * 9301 + 49297) % 233280;
    var rnd = seed / 233280.0;
    return Math.floor(min + rnd * (max - min));
  }
}

function HSVtoHex (hsv){

  var rgb = HSVtoRGB(hsv);

  function componentToHex(c) {
      var hex = c.toString(16);
      return hex.length == 1 ? '0' + hex : hex;
  }

  var hex = '#' + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);

  return hex;

}

function defineColor (name, hueRange, lowerBounds) {

  var sMin = lowerBounds[0][0],
      sMax = lowerBounds[lowerBounds.length - 1][0],

      bMin = lowerBounds[lowerBounds.length - 1][1],
      bMax = lowerBounds[0][1];

  colorDictionary[name] = {
    hueRange: hueRange,
    lowerBounds: lowerBounds,
    saturationRange: [sMin, sMax],
    brightnessRange: [bMin, bMax]
  };

}

function loadColorBounds () {

  defineColor(
    'monochrome',
    null,
    [[0,0],[100,0]]
  );

  defineColor(
    'red',
    [-26,18],
    [[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]
  );

  defineColor(
    'orange',
    [19,46],
    [[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]
  );

  defineColor(
    'yellow',
    [47,62],
    [[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]
  );

  defineColor(
    'green',
    [63,178],
    [[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]
  );

  defineColor(
    'blue',
    [179, 257],
    [[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]
  );

  defineColor(
    'purple',
    [258, 282],
    [[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]
  );

  defineColor(
    'pink',
    [283, 334],
    [[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]]
  );

}

function HSVtoRGB (hsv) {

  // this doesn't work for the values of 0 and 360
  // here's the hacky fix
  var h = hsv[0];
  if (h === 0) {h = 1;}
  if (h === 360) {h = 359;}

  // Rebase the h,s,v values
  h = h/360;
  var s = hsv[1]/100,
      v = hsv[2]/100;

  var h_i = Math.floor(h*6),
    f = h * 6 - h_i,
    p = v * (1 - s),
    q = v * (1 - f*s),
    t = v * (1 - (1 - f)*s),
    r = 256,
    g = 256,
    b = 256;

  switch(h_i) {
    case 0: r = v; g = t; b = p;  break;
    case 1: r = q; g = v; b = p;  break;
    case 2: r = p; g = v; b = t;  break;
    case 3: r = p; g = q; b = v;  break;
    case 4: r = t; g = p; b = v;  break;
    case 5: r = v; g = p; b = q;  break;
  }

  var result = [Math.floor(r*255), Math.floor(g*255), Math.floor(b*255)];
  return result;
}

function HexToHSB (hex) {
  hex = hex.replace(/^#/, '');
  hex = hex.length === 3 ? hex.replace(/(.)/g, '$1$1') : hex;

  const red = parseInt(hex.substr(0, 2), 16) / 255,
        green = parseInt(hex.substr(2, 2), 16) / 255,
        blue = parseInt(hex.substr(4, 2), 16) / 255;

  const cMax = Math.max(red, green, blue),
        delta = cMax - Math.min(red, green, blue),
        saturation = cMax ? (delta / cMax) : 0;

  switch (cMax) {
    case red: return [ 60 * (((green - blue) / delta) % 6) || 0, saturation, cMax ];
    case green: return [ 60 * (((blue - red) / delta) + 2) || 0, saturation, cMax ];
    case blue: return [ 60 * (((red - green) / delta) + 4) || 0, saturation, cMax ];
  }
}

function HSVtoHSL (hsv) {
  var h = hsv[0],
    s = hsv[1]/100,
    v = hsv[2]/100,
    k = (2-s)*v;

  return [
    h,
    Math.round(s*v / (k<1 ? k : 2-k) * 10000) / 100,
    k/2 * 100
  ];
}

function stringToInteger (string) {
  var total = 0
  for (var i = 0; i !== string.length; i++) {
    if (total >= Number.MAX_SAFE_INTEGER) break;
    total += string.charCodeAt(i)
  }
  return total
}

	return {
		update:update,
		init:init,
		getMicInput:getMicInput,
	};

}();
<|endoftext|>


<commit_before>var Board = function( attributes ){
  this.humanoid;
  this.score = 0;
  this.dx = 0;
  this.dy = 0;
  this.humanoids = attributes.humanoids || [];
  this.width = attributes.width  || '600px';
  this.height = attributes.height || '400px';
}

Board.prototype = {
  isPositionEqual: function( position1, position2 ){
    return position1.x === position2.x && position1.y === position2.y
  },

  isValidDestination: function( target_position ){
    var result = true
    for(var i= 0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , target_position ) ){
        result = false
      }
    }
    return result
  },

  nearestHumanoid: function( humanoidType ){
    var similarHumanoids = this.findSimilarHumanoids( humanoidType )
    var closestPos = this.findClosestPos( similarHumanoids )
    var closestHumanoid = this.findClosestHumanoid( closestPos, similarHumanoids )
    return closestHumanoid
  },

  isAnyHumanRemaining: function(){
    var result = false
    for( var i=0; i < this.humanoids.length; i++ ){
      if(this.humanoids[i].humanType == "human"  || this.humanoids[i].humanType == "player") { result = true; break };
    }
    return result
  },

  nextTurn: function(){
    for( var i=0; i< this.humanoids.length; i++ ){
      this.humanoid = this.humanoids[i]
      if( this.humanoid.humanType == "infectedHuman" ){
          this.humanoid.incrementTimeSinceInfection()
          continue
      }
      if( this.humanoid.humanType == "player" ){
        var targetLoc = { x: this.humanoid.position.x + this.dx*this.humanoid.speed,  y: this.humanoid.position.y + this.dy*this.humanoid.speed }
        var coords = ( Pathfinder.moveTowards(this.humanoid.position, targetLoc, this.humanoid.speed) )
        coords.x = ( (coords.x + this.width) % this.width )
        coords.y = ( (coords.y + this.height) % this.height )
        this.humanoid.position = coords
        continue
      }
      var nearestZombie = this.nearestHumanoid( "zombie" )
      var nearestHuman = this.nearestHumanoid( "human" )
      var player = this.nearestHumanoid( 'player' )
      var destination = this.setDestination( nearestHuman, nearestZombie, player )
      destination.x = ( (destination.x + this.width) % this.width )
      destination.y = ( (destination.y + this.height) % this.height )

      if ( this.humanoid.isAbleToBite( player ) ){
        this.humanoid.bite( player )
      }

      if ( this.humanoid.isAbleToBite( nearestHuman ) ){
        this.humanoid.bite( nearestHuman )
      }

      if( this.isValidDestination( destination ) ){
        this.humanoid.position = destination
      }
    };
    this.incrementStore(player);
  },

  incrementStore: function(player){
    if (player && player.humanType === 'player'){ this.score += 10 }
  },

  setDestination: function( nearestHuman, nearestZombie, player ){
    if( this.humanoid.humanType == "zombie" ){ return this.setZombieDestination( nearestHuman, nearestZombie, player ) }
    else if( this.humanoid.humanType == "human" ){ return this.setHumanDestination( nearestHuman, nearestZombie, player ) }
    else { return this.humanoid.position }
  },

  setZombieDestination: function( nearestHuman, nearestZombie, player ){
    var playerDistance = Number.POSITIVE_INFINITY;
    var humanDistance = Number.POSITIVE_INFINITY;
    var zombieDistance = Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) * gameSettings.zombieSpread
    if (player){ playerDistance = Pathfinder.distanceTo( player.position, this.humanoid.position ) }
    if (nearestHuman){ humanDistance = Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) }

    if ( playerDistance < humanDistance ){
      if ( playerDistance < zombieDistance ){
        return this.humanoid.moveNearest( player )
      } else {
        return this.humanoid.moveNearest( nearestZombie )
      }
    } else if ( humanDistance < zombieDistance ){
      return this.humanoid.moveNearest( nearestHuman )
    } else {
      return this.humanoid.moveNearest( nearestZombie )
    }
  },

  setHumanDestination: function( nearestHuman, nearestZombie, player ){
    var playerDistance = Number.POSITIVE_INFINITY;
    var humanDistance = Number.POSITIVE_INFINITY;
    var zombieDistance = Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position )
    if (player){ playerDistance = Pathfinder.distanceTo( player.position, this.humanoid.position ) }
    if (nearestHuman){ humanDistance = Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) }

    if ( zombieDistance < gameSettings.humanFearRange || ( !player && !nearestHuman ) ){
      return this.humanoid.moveNearest( nearestZombie )
    } else if ( playerDistance < humanDistance ){
      return this.humanoid.moveNearest( player )
    } else {
      return this.humanoid.moveNearest( nearestHuman )
    }
  },

  deleteSelfHumanoid: function(){
    var otherHumanoids = []
    for( var i=0; i < this.humanoids.length; i++){otherHumanoids.push(this.humanoids[i])}

    for( var i=0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , this.humanoid.position ) ){
        otherHumanoids.splice( i, 1 )
        break
      }
    }
    return otherHumanoids
  },
  findSimilarHumanoids: function( humanoidType ){
    var otherHumanoids = this.deleteSelfHumanoid()
    var similar = [];
    for( var i=0; i< otherHumanoids.length; i++ ){
      if( otherHumanoids[i].humanType === humanoidType ){ similar.push(otherHumanoids[i])}
    }
    return similar
  },
  findClosestPos: function( otherHumanoids ){
    var closestPos = []
    for( var i=0; i< otherHumanoids.length; i++ ){
      var dist = Pathfinder.distanceTo( otherHumanoids[i].position, this.humanoid.position )
      closestPos.push( dist );
    }
    return closestPos
  },
  findClosestHumanoid: function( closestPos, otherHumanoids ){
    var closestHumanoidValue = Math.min.apply( null, closestPos )
    for( var i=0; i < closestPos.length; i++ ){
      if( closestPos[i] == closestHumanoidValue ){ var closestHumanoid = otherHumanoids[i]}
    }
   return closestHumanoid
  }
}
<commit_msg>create functions to determine if player is alive and if any human/player is alive<commit_after>var Board = function( attributes ){
  this.humanoid;
  this.score = 0;
  this.dx = 0;
  this.dy = 0;
  this.humanoids = attributes.humanoids || [];
  this.width = attributes.width  || '600px';
  this.height = attributes.height || '400px';
}

Board.prototype = {
  isGameActive: function(){
    var activeStatus = false;
    for (var i = 0; i < this.humanoids.length; i++){
      if (this.humanoids[i].humanType === 'human' || this.humanoids[i].humanType === 'player'){
        activeStatus = true;
      }
    }
    return activeStatus;
  },

  isPlayerAlive: function(){
    var activeStatus = false;
    for (var i = 0; i < this.humanoids.length; i++){
      if (this.humanoids[i].humanType === 'player'){
        activeStatus = true;
      }
    }
    return activeStatus;
  },

  isPositionEqual: function( position1, position2 ){
    return position1.x === position2.x && position1.y === position2.y
  },

  isValidDestination: function( target_position ){
    var result = true
    for(var i= 0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , target_position ) ){
        result = false
      }
    }
    return result
  },

  nearestHumanoid: function( humanoidType ){
    var similarHumanoids = this.findSimilarHumanoids( humanoidType )
    var closestPos = this.findClosestPos( similarHumanoids )
    var closestHumanoid = this.findClosestHumanoid( closestPos, similarHumanoids )
    return closestHumanoid
  },

  isAnyHumanRemaining: function(){
    var result = false
    for( var i=0; i < this.humanoids.length; i++ ){
      if(this.humanoids[i].humanType == "human"  || this.humanoids[i].humanType == "player") { result = true; break };
    }
    return result
  },

  nextTurn: function(){
    for( var i=0; i< this.humanoids.length; i++ ){
      this.humanoid = this.humanoids[i]
      if( this.humanoid.humanType == "infectedHuman" ){
          this.humanoid.incrementTimeSinceInfection()
          continue
      }
      if( this.humanoid.humanType == "player" ){
        var targetLoc = { x: this.humanoid.position.x + this.dx*this.humanoid.speed,  y: this.humanoid.position.y + this.dy*this.humanoid.speed }
        var coords = ( Pathfinder.moveTowards(this.humanoid.position, targetLoc, this.humanoid.speed) )
        coords.x = ( (coords.x + this.width) % this.width )
        coords.y = ( (coords.y + this.height) % this.height )
        this.humanoid.position = coords
        continue
      }
      var nearestZombie = this.nearestHumanoid( "zombie" )
      var nearestHuman = this.nearestHumanoid( "human" )
      var player = this.nearestHumanoid( 'player' )
      var destination = this.setDestination( nearestHuman, nearestZombie, player )
      destination.x = ( (destination.x + this.width) % this.width )
      destination.y = ( (destination.y + this.height) % this.height )

      if ( this.humanoid.isAbleToBite( player ) ){
        this.humanoid.bite( player )
      }

      if ( this.humanoid.isAbleToBite( nearestHuman ) ){
        this.humanoid.bite( nearestHuman )
      }

      if( this.isValidDestination( destination ) ){
        this.humanoid.position = destination
      }
    };
    this.incrementStore(player);
  },

  incrementStore: function(player){
    if (player && player.humanType === 'player'){ this.score += 10 }
  },

  setDestination: function( nearestHuman, nearestZombie, player ){
    if( this.humanoid.humanType == "zombie" ){ return this.setZombieDestination( nearestHuman, nearestZombie, player ) }
    else if( this.humanoid.humanType == "human" ){ return this.setHumanDestination( nearestHuman, nearestZombie, player ) }
    else { return this.humanoid.position }
  },

  setZombieDestination: function( nearestHuman, nearestZombie, player ){
    var playerDistance = Number.POSITIVE_INFINITY;
    var humanDistance = Number.POSITIVE_INFINITY;
    var zombieDistance = Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position ) * gameSettings.zombieSpread
    if (player){ playerDistance = Pathfinder.distanceTo( player.position, this.humanoid.position ) }
    if (nearestHuman){ humanDistance = Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) }

    if ( playerDistance < humanDistance ){
      if ( playerDistance < zombieDistance ){
        return this.humanoid.moveNearest( player )
      } else {
        return this.humanoid.moveNearest( nearestZombie )
      }
    } else if ( humanDistance < zombieDistance ){
      return this.humanoid.moveNearest( nearestHuman )
    } else {
      return this.humanoid.moveNearest( nearestZombie )
    }
  },

  setHumanDestination: function( nearestHuman, nearestZombie, player ){
    var playerDistance = Number.POSITIVE_INFINITY;
    var humanDistance = Number.POSITIVE_INFINITY;
    var zombieDistance = Pathfinder.distanceTo( nearestZombie.position, this.humanoid.position )
    if (player){ playerDistance = Pathfinder.distanceTo( player.position, this.humanoid.position ) }
    if (nearestHuman){ humanDistance = Pathfinder.distanceTo( nearestHuman.position, this.humanoid.position ) }

    if ( zombieDistance < gameSettings.humanFearRange || ( !player && !nearestHuman ) ){
      return this.humanoid.moveNearest( nearestZombie )
    } else if ( playerDistance < humanDistance ){
      return this.humanoid.moveNearest( player )
    } else {
      return this.humanoid.moveNearest( nearestHuman )
    }
  },

  deleteSelfHumanoid: function(){
    var otherHumanoids = []
    for( var i=0; i < this.humanoids.length; i++){otherHumanoids.push(this.humanoids[i])}

    for( var i=0; i < this.humanoids.length; i++ ){
      if( this.isPositionEqual( this.humanoids[i].position , this.humanoid.position ) ){
        otherHumanoids.splice( i, 1 )
        break
      }
    }
    return otherHumanoids
  },
  findSimilarHumanoids: function( humanoidType ){
    var otherHumanoids = this.deleteSelfHumanoid()
    var similar = [];
    for( var i=0; i< otherHumanoids.length; i++ ){
      if( otherHumanoids[i].humanType === humanoidType ){ similar.push(otherHumanoids[i])}
    }
    return similar
  },
  findClosestPos: function( otherHumanoids ){
    var closestPos = []
    for( var i=0; i< otherHumanoids.length; i++ ){
      var dist = Pathfinder.distanceTo( otherHumanoids[i].position, this.humanoid.position )
      closestPos.push( dist );
    }
    return closestPos
  },
  findClosestHumanoid: function( closestPos, otherHumanoids ){
    var closestHumanoidValue = Math.min.apply( null, closestPos )
    for( var i=0; i < closestPos.length; i++ ){
      if( closestPos[i] == closestHumanoidValue ){ var closestHumanoid = otherHumanoids[i]}
    }
   return closestHumanoid
  }
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.8.0
(function() {
  var Duplex, argv, backend, browserChannel, connect, serveStatic, livedb, livedbMongo, numClients, port, share, sharejs, webserver;

  Duplex = require('stream').Duplex;

  browserChannel = require('browserchannel').server;

  connect = require('connect');

  serveStatic = require('serve-static');

  argv = require('optimist').argv;

  livedb = require('livedb');

  livedbMongo = require('livedb-mongo');

  try {
    require('heapdump');
  } catch (_error) {}

  sharejs = require('share');

  webserver = connect(serveStatic("" + __dirname + "/public"), serveStatic(sharejs.scriptsDir));

  backend = livedb.client(livedbMongo('mongodb://localhost:27017/test?auto_reconnect', {
    safe: false
  }));

  backend.addProjection('_users', 'users', 'json0', {
    x: true
  });

  share = sharejs.server.createClient({
    backend: backend
  });

  /*
  share.use 'validate', (req, callback) ->
    err = 'noooo' if req.snapshot.data?.match /x/
    callback err

  share.use 'connect', (req, callback) ->
    console.log req.agent
    callback()
   */

  numClients = 0;

  webserver.use(browserChannel({
    webserver: webserver,
    sessionTimeoutInterval: 5000
  }, function(client) {
    var stream;
    numClients++;
    stream = new Duplex({
      objectMode: true
    });
    stream._write = function(chunk, encoding, callback) {
      console.log('s->c ', JSON.stringify(chunk));
      if (client.state !== 'closed') {
        client.send(chunk);
      }
      return callback();
    };
    stream._read = function() {};
    stream.headers = client.headers;
    stream.remoteAddress = stream.address;
    client.on('message', function(data) {
      console.log('c->s ', JSON.stringify(data));
      return stream.push(data);
    });
    stream.on('error', function(msg) {
      return client.stop();
    });
    client.on('close', function(reason) {
      stream.push(null);
      stream.emit('close');
      numClients--;
      return console.log('client went away', numClients);
    });
    stream.on('end', function() {
      return client.close();
    });
    return share.listen(stream);
  }));

  webserver.use('/doc', share.rest());
  webserver.use('/docs', function (req, res, next) {
    try {
      var col = backend.snapshotDb.mongo.collection('gantt');
      col.find({},{_id:1}).toArray(function(err, data){
        var docs = [];
        data.forEach(function(doc){
          docs.push(doc._id);
        });
        res.end(JSON.stringify(docs.sort()));
      });
    } catch (e) {
      res.end('[]');
    }
  });

  port = argv.p || 7007;

  webserver.listen(port);

  console.log("Listening on http://localhost:" + port + "/");

}).call(this);
<commit_msg>serve static files<commit_after>// Generated by CoffeeScript 1.8.0
(function() {
  var Duplex, argv, backend, browserChannel, connect, serveStatic, livedb, livedbMongo, numClients, port, share, sharejs, webserver;

  Duplex = require('stream').Duplex;

  browserChannel = require('browserchannel').server;

  connect = require('connect');

  serveStatic = require('serve-static');

  argv = require('optimist').argv;

  livedb = require('livedb');

  livedbMongo = require('livedb-mongo');

  try {
    require('heapdump');
  } catch (_error) {}

  sharejs = require('share');

  webserver = connect();
  webserver.use(serveStatic("" + __dirname + "/public"));
  webserver.use(serveStatic(sharejs.scriptsDir));

  backend = livedb.client(livedbMongo('mongodb://localhost:27017/gantt?auto_reconnect', {
    safe: false
  }));

  backend.addProjection('_users', 'users', 'json0', {
    x: true
  });

  share = sharejs.server.createClient({
    backend: backend
  });

  /*
  share.use 'validate', (req, callback) ->
    err = 'noooo' if req.snapshot.data?.match /x/
    callback err

  share.use 'connect', (req, callback) ->
    console.log req.agent
    callback()
   */

  numClients = 0;

  webserver.use(browserChannel({
    webserver: webserver,
    sessionTimeoutInterval: 5000
  }, function(client) {
    var stream;
    numClients++;
    stream = new Duplex({
      objectMode: true
    });
    stream._write = function(chunk, encoding, callback) {
      console.log('s->c ', JSON.stringify(chunk));
      if (client.state !== 'closed') {
        client.send(chunk);
      }
      return callback();
    };
    stream._read = function() {};
    stream.headers = client.headers;
    stream.remoteAddress = stream.address;
    client.on('message', function(data) {
      console.log('c->s ', JSON.stringify(data));
      return stream.push(data);
    });
    stream.on('error', function(msg) {
      return client.stop();
    });
    client.on('close', function(reason) {
      stream.push(null);
      stream.emit('close');
      numClients--;
      return console.log('client went away', numClients);
    });
    stream.on('end', function() {
      return client.close();
    });
    return share.listen(stream);
  }));

  webserver.use('/doc', share.rest());
  webserver.use('/docs', function (req, res, next) {
    try {
      var col = backend.snapshotDb.mongo.collection('gantt');
      col.find({},{_id:1}).toArray(function(err, data){
        var docs = [];
        data.forEach(function(doc){
          docs.push(doc._id);
        });
        res.end(JSON.stringify(docs.sort()));
      });
    } catch (e) {
      res.end('[]');
    }
  });

  port = argv.p || 7007;

  webserver.listen(port);

  console.log("Listening on http://localhost:" + port + "/");

}).call(this);
<|endoftext|>