<commit_before>$.get(
    "/fetchDB",
    function(data) {
       //alert('page content: ' + data);
       console.log(data)
       var fetched_data = data;
       var holder = []

       $.each(fetched_data[0].total_positive_percentage_sum, function( index, value ) {
         //alert( index + ": " + value );
          holder.push(value/fetched_data[0].total_count[index]);
       });

       console.log("holder ", holder)

        var n = 3, // The number of series.
            m = 24; // The number of values per series.

        // The xz array has m elements, representing the x-values shared by all series.
        // The yz array has n elements, representing the y-values of each of the n series.
        // Each yz[i] is an array of m non-negative numbers representing a y-value for xz[i].
        // The y01z array has the same structure as yz, but with stacked [y₀, y₁] instead of y.
        var xz = d3.range(m),
            yz=[holder,fetched_data[1]]
            //yz = [[1,2],[3,4]]//d3.range(n).map(function() { return bumps(m); }),
            y01z = d3.stack().keys(d3.range(n))(d3.transpose(yz)),
            yMax = d3.max(yz, function(y) { return d3.max(y); }),
            y1Max = d3.max(y01z, function(y) { return d3.max(y, function(d) { return d[1]; }); });

        var svg = d3.select("#chart"),
            margin = {top: 40, right: 10, bottom: 20, left: 10},
            width = +svg.attr("width") - margin.left - margin.right,
            height = +svg.attr("height") - margin.top - margin.bottom,
            g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var x = d3.scaleBand()
            .domain(xz)
            .rangeRound([0, width])
            .padding(0.08);

        var y = d3.scaleLinear()
            .domain([0, y1Max])
            .range([height, 0]);

        var color = d3.scaleOrdinal()
            .domain(d3.range(n))
            .range(d3.schemeCategory20c);

        var series = g.selectAll(".series")
          .data(y01z)
          .enter().append("g")
            .attr("fill", function(d, i) { return color(i); });

        var rect = series.selectAll("rect")
          .data(function(d) { return d; })
          .enter().append("rect")
            .attr("x", function(d, i) { return x(i); })
            .attr("y", height)
            .attr("width", x.bandwidth())
            .attr("height", 0);

        rect.transition()
            .delay(function(d, i) { return i * 10; })
            .attr("y", function(d) { return y(d[1]); })
            .attr("height", function(d) { return y(d[0]) - y(d[1]); });

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x)
                .tickSize(0)
                .tickPadding(6));

        d3.selectAll("input")
            .on("change", changed);

        var timeout = d3.timeout(function() {
          d3.select("input[value=\"grouped\"]")
              .property("checked", true)
              .dispatch("change");
        }, 2000);

        function changed() {
          timeout.stop();
          if (this.value === "grouped") transitionGrouped();
          else transitionStacked();
        }

        function transitionGrouped() {
          y.domain([0, yMax]);

          rect.transition()
              .duration(500)
              .delay(function(d, i) { return i * 10; })
              .attr("x", function(d, i) { return x(i) + x.bandwidth() / n * this.parentNode.__data__.key; })
              .attr("width", x.bandwidth() / n)
            .transition()
              .attr("y", function(d) { return y(d[1] - d[0]); })
              .attr("height", function(d) { return y(0) - y(d[1] - d[0]); });
        }

        function transitionStacked() {
          y.domain([0, y1Max]);

          rect.transition()
              .duration(500)
              .delay(function(d, i) { return i * 10; })
              .attr("y", function(d) { return y(d[1]); })
              .attr("height", function(d) { return y(d[0]) - y(d[1]); })
            .transition()
              .attr("x", function(d, i) { return x(i); })
              .attr("width", x.bandwidth());
        }

        // Returns an array of m psuedorandom, smoothly-varying non-negative numbers.
        // Inspired by Lee Byron’s test data generator.
        // http://leebyron.com/streamgraph/
        function bumps(m) {
          var values = [], i, j, w, x, y, z;

          // Initialize with uniform random values in [0.1, 0.2).
          for (i = 0; i < m; ++i) {
            values[i] = 0.1 + 0.1 * Math.random();
          }

          // Add five random bumps.
          for (j = 0; j < 5; ++j) {
            x = 1 / (0.1 + Math.random());
            y = 2 * Math.random() - 0.5;
            z = 10 / (0.1 + Math.random());
            for (i = 0; i < m; i++) {
              w = (i / m - y) * z;
              values[i] += x * Math.exp(-w * w);
            }
          }

          // Ensure all values are positive.
          for (i = 0; i < m; ++i) {
            values[i] = Math.max(0, values[i]);
          }

          return values;
        }

    }
);

<commit_msg>tests<commit_after>$.get(
    "/fetchDB",
    function(data) {
       //alert('page content: ' + data);
       console.log(data)
       var fetched_data = data;
       var holder = []

       $.each(fetched_data[0].total_positive_percentage_sum, function( index, value ) {
         //alert( index + ": " + value );
          holder.push(value/fetched_data[0].total_count[index]);
       });

       console.log("holder ", holder)

        var n = 3, // The number of series.
            m = 24; // The number of values per series.

        // The xz array has m elements, representing the x-values shared by all series.
        // The yz array has n elements, representing the y-values of each of the n series.
        // Each yz[i] is an array of m non-negative numbers representing a y-value for xz[i].
        // The y01z array has the same structure as yz, but with stacked [y₀, y₁] instead of y.
        var xz = d3.range(m),
            yz=[holder]
            //yz = [[1,2],[3,4]]//d3.range(n).map(function() { return bumps(m); }),
            y01z = d3.stack().keys(d3.range(n))(d3.transpose(yz)),
            yMax = d3.max(yz, function(y) { return d3.max(y); }),
            y1Max = d3.max(y01z, function(y) { return d3.max(y, function(d) { return d[1]; }); });

        var svg = d3.select("#chart"),
            margin = {top: 40, right: 10, bottom: 20, left: 10},
            width = +svg.attr("width") - margin.left - margin.right,
            height = +svg.attr("height") - margin.top - margin.bottom,
            g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var x = d3.scaleBand()
            .domain(xz)
            .rangeRound([0, width])
            .padding(0.08);

        var y = d3.scaleLinear()
            .domain([0, y1Max])
            .range([height, 0]);

        var color = d3.scaleOrdinal()
            .domain(d3.range(n))
            .range(d3.schemeCategory20c);

        var series = g.selectAll(".series")
          .data(y01z)
          .enter().append("g")
            .attr("fill", function(d, i) { return color(i); });

        var rect = series.selectAll("rect")
          .data(function(d) { return d; })
          .enter().append("rect")
            .attr("x", function(d, i) { return x(i); })
            .attr("y", height)
            .attr("width", x.bandwidth())
            .attr("height", 0);

        rect.transition()
            .delay(function(d, i) { return i * 10; })
            .attr("y", function(d) { return y(d[1]); })
            .attr("height", function(d) { return y(d[0]) - y(d[1]); });

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x)
                .tickSize(0)
                .tickPadding(6));

        d3.selectAll("input")
            .on("change", changed);

        var timeout = d3.timeout(function() {
          d3.select("input[value=\"grouped\"]")
              .property("checked", true)
              .dispatch("change");
        }, 2000);

        function changed() {
          timeout.stop();
          if (this.value === "grouped") transitionGrouped();
          else transitionStacked();
        }

        function transitionGrouped() {
          y.domain([0, yMax]);

          rect.transition()
              .duration(500)
              .delay(function(d, i) { return i * 10; })
              .attr("x", function(d, i) { return x(i) + x.bandwidth() / n * this.parentNode.__data__.key; })
              .attr("width", x.bandwidth() / n)
            .transition()
              .attr("y", function(d) { return y(d[1] - d[0]); })
              .attr("height", function(d) { return y(0) - y(d[1] - d[0]); });
        }

        function transitionStacked() {
          y.domain([0, y1Max]);

          rect.transition()
              .duration(500)
              .delay(function(d, i) { return i * 10; })
              .attr("y", function(d) { return y(d[1]); })
              .attr("height", function(d) { return y(d[0]) - y(d[1]); })
            .transition()
              .attr("x", function(d, i) { return x(i); })
              .attr("width", x.bandwidth());
        }

        // Returns an array of m psuedorandom, smoothly-varying non-negative numbers.
        // Inspired by Lee Byron’s test data generator.
        // http://leebyron.com/streamgraph/
        function bumps(m) {
          var values = [], i, j, w, x, y, z;

          // Initialize with uniform random values in [0.1, 0.2).
          for (i = 0; i < m; ++i) {
            values[i] = 0.1 + 0.1 * Math.random();
          }

          // Add five random bumps.
          for (j = 0; j < 5; ++j) {
            x = 1 / (0.1 + Math.random());
            y = 2 * Math.random() - 0.5;
            z = 10 / (0.1 + Math.random());
            for (i = 0; i < m; i++) {
              w = (i / m - y) * z;
              values[i] += x * Math.exp(-w * w);
            }
          }

          // Ensure all values are positive.
          for (i = 0; i < m; ++i) {
            values[i] = Math.max(0, values[i]);
          }

          return values;
        }

    }
);

<|endoftext|>


<commit_before>var watch = require('node-watch');

function initConfig(config) {
    config.configFile = config.configFile ? config.configFile : 'package.json';
    config.tempFolder = config.tempFolder ? config.tempFolder : 'dist';
    config.browserify = config.browserify ? config.browserify : true;
    config.rootFile = config.rootFile ? config.rootFile : 'boot';
    config.dest = config.dest ? config.dest : 'script.js';
}

module.exports = function(config) {
    return {
        prodRun: function(config) {
            initConfig(config);

            config.exec('tsc --p ' + config.configFile, () => {
                var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                console.log(' [ ] ' + config.dest + ' updating from ' + srcFile);
                config.exec('browserify -s main ' + srcFile + ' -o ' + config.dest, () => {
                    console.log(' [o] ' + config.dest + ' updated');
                });
            });
        },
        devRun: function(config) {
            initConfig(config);

            config.exec('tsc --p ' + config.configFile + ' --watch');

            if(!config.browserify)
                return;

            var countOut = 0;
            config.watch(config.tempFolder, { recursive: true }, function(event, filename) {
                ++countOut;
                setTimeout(function() {
                    if(--countOut > 0)
                        return;
                    var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                    console.log(' [ ] ' + config.dest + ' updating from ' + srcFile);
                    config.exec('browserify -s main ' + srcFile + ' -o ' + config.dest, () => {
                        console.log(' [o] ' + config.dest + ' updated');
                    });
                }, 200);
            });
        },
        clean: (config) => {
            initConfig(config);
            config.rmdir(config.tempFolder);
        },
        configSample: {
            type: 'typescript',
            tempFolder: 'react/bin',
            rootFile: 'root',
            dest: 'public/react.js',
            browserify: true
        }
    }
}<commit_msg>Added more verbosity<commit_after>var watch = require('node-watch');

function initConfig(config) {
    config.configFile = config.configFile ? config.configFile : 'package.json';
    config.tempFolder = config.tempFolder ? config.tempFolder : 'dist';
    config.browserify = config.browserify ? config.browserify : true;
    config.rootFile = config.rootFile ? config.rootFile : 'boot';
    config.dest = config.dest ? config.dest : 'script.js';
}

module.exports = function(config) {
    return {
        prodRun: function(config) {
            initConfig(config);

            config.exec('tsc --p ' + config.configFile, () => {
                var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                console.log(' [ ] ' + config.dest + ' updating from ' + srcFile);
                config.exec('browserify -s main ' + srcFile + ' -o ' + config.dest, () => {
                    console.log(' [o] ' + config.dest + ' updated');
                });
            });
        },
        devRun: function(config) {
            initConfig(config);

            config.exec('tsc --p ' + config.configFile + ' --watch');

            if(!config.browserify)
                return;

            var countOut = 0;
            config.watch(config.tempFolder, { recursive: true }, function(event, filename) {
                ++countOut;
                setTimeout(function() {
                    if(--countOut > 0)
                        return;
                    var srcFile = config.tempFolder + '/' + config.rootFile + '.js';
                    console.log(' [o] ' + filename + ' updated');
                    console.log(' [ ] compiling ' + srcFile + ' to ' + config.dest);
                    config.exec('browserify -s main ' + srcFile + ' -o ' + config.dest, () => {
                        console.log(' [o] ' + config.dest + ' updated');
                    });
                }, 200);
            });
        },
        clean: (config) => {
            initConfig(config);
            config.rmdir(config.tempFolder);
        },
        configSample: {
            type: 'typescript',
            tempFolder: 'react/bin',
            rootFile: 'root',
            dest: 'public/react.js',
            browserify: true
        }
    }
}<|endoftext|>


<commit_before>var Path = require('path');
var Hapi = require('hapi');
var data = require('./data/fall_2014');
var _ = require('lodash');

var server = new Hapi.Server('localhost', 3000, { files: { relativeTo: Path.join(__dirname, './') } });

var course = function (info){
  return {
    //hash: md5(hash),
    status: info[0],
    capacity: info[1],
    avaliableSeats: info[2],
    prop: info[3],
    courseNum: info[4],
    crn: info[5],
    note: info[6],
    description: info[7],
    days: info[8],
    location: info[9],
    instructor: info[10],
    i_user: info[11],
    unknown1: info[12],
    unknown2: info[13],
    unknown3: info[14],
    unknown4: info[15],
    unknown5: info[16],
    unknown6: info[17],
    unknown7: info[18]
  };
};

// Serve static files from `static` dir.
server.route({
  method: 'GET',
  path: '/{path*}',
  handler: {
      directory: { path: './', listing: false, index: true }
  }
});

server.route({
    method: 'GET',
    path: '/data',
    handler: function (request, reply) {
      var courses = [];
      var klass;
      _.each(data.main, function(info){
        klass = course(info);
        if (klass.status === "shut"){
          courses.push(klass);
        }
      });
        reply(courses);
    }
});

server.route({
    method: 'POST',
    path: '/subscribe',
    handler: function (request, reply) {
      //twilio you are subscribed to --- blah
    }
});

// Start your Mullet Server
server.start(function () {
  console.log('Coursica is running on port: 3000');
});
<commit_msg>needed data cleanup :)<commit_after>var Path = require('path');
var Hapi = require('hapi');
var data = require('./data/fall_2014');
var _ = require('lodash');

var server = new Hapi.Server('localhost', 3000, { files: { relativeTo: Path.join(__dirname, './') } });

var course = function (info){
  return {
    //hash: md5(hash),
    status: info[0],
    capacity: info[1],
    avaliableSeats: info[2],
    prop: info[3],
    courseNum: info[4],
    crn: info[5],
    note: info[6],
    description: info[7],
    days: info[8],
    location: info[9],
    instructor: info[10],
    i_user: info[11],
    unknown1: info[12],
    unknown2: info[13],
    unknown3: info[14],
    unknown4: info[15],
    unknown5: info[16],
    unknown6: info[17],
    unknown7: info[18]
  };
};

// Serve static files from `static` dir.
server.route({
  method: 'GET',
  path: '/{path*}',
  handler: {
      directory: { path: './', listing: false, index: true }
  }
});

server.route({
    method: 'GET',
    path: '/data',
    handler: function (request, reply) {
      var courses = [];
      var klass;
      _.each(data.main, function(info){
        klass = course(info);
        if (klass.status === "shut"){
          klass.description = klass.description.substr(0,20);
          klass.courseNum = "CS"+klass.courseNum;
          courses.push(klass);
        }
      });
        reply(courses);
    }
});

server.route({
    method: 'POST',
    path: '/subscribe',
    handler: function (request, reply) {
      //twilio you are subscribed to --- blah
    }
});

// Start your Mullet Server
server.start(function () {
  console.log('Coursica is running on port: 3000');
});
<|endoftext|>


<commit_before>import Emitter from 'tiny-emitter';
import Grid from './grid.js';
import HumanPlayer from './human-player.js';
import OnlinePlayer from './online-player.js';
import AIPlayer from './ai-player.js';
import Chip from './chip.js';

// A game between two players; the same Game instance is re-used for successive
// rounds
class Game extends Emitter {

  constructor({ grid = new Grid({ columnCount: 7, rowCount: 6 }), players = [], debug = false } = {}) {
    super();
    // The two-dimensional array representing the entire game grid
    this.grid = grid;
    // The list of all players for this game
    this.players = players;
    // The type of the current game (e.g. '1P', '2P', or 'online'); this is
    // reset to null when the game ends
    this.type = null;
    // The type of the current/last game; unlike this.type, this does not reset
    // when the game ends
    this.lastType = null;
    // The current player is null when a game is not in progress
    this.currentPlayer = null;
    // Whether or not the game is in progress
    this.inProgress = false;
    // The chip above the grid that is about to be placed
    this.pendingChip = null;
    // The winning player of the game
    this.winner = null;
    // The player who requests to end the game or start a new one
    this.requestingPlayer = null;
    // Keep track of the columns where chips are placed in debug mode (extremely
    // useful for creating new unit tests from real games)
    if (debug) {
      this.debug = true;
      this.columnHistory = [];
    } else {
      this.debug = false;
    }
  }

  startGame({ startingPlayer } = {}) {
    if (startingPlayer) {
      this.currentPlayer = startingPlayer;
    } else {
      this.currentPlayer = this.players[0];
    }
    this.inProgress = true;
    this.emit('game:start');
    this.startTurn();
  }

  // End the game without resetting the grid
  endGame() {
    if (this.winner) {
      this.winner.score += 1;
    }
    this.inProgress = false;
    this.currentPlayer = null;
    this.pendingChip = null;
    this.emit('game:end');
    this.type = null;
    if (this.debug) {
      this.columnHistory.length = 0;
    }
  }

  // Reset the game and grid completely without starting a new game (endGame
  // should be called somewhere before this method is called)
  resetGame() {
    this.winner = null;
    this.grid.resetGrid();
  }

  // Initialize or change the current set of players based on the specified game
  // type;
  setPlayers({ gameType, players = [], localPlayer = null }) {
    // Instantiate new players as needed (if user is about to play the first game
    // or if the user is switching modes)
    if (this.players.length === 0) {
      if (gameType === '1P') {
        // If user chose 1-Player mode, the user will play against the AI
        this.players.push(new HumanPlayer({ name: 'Human', color: 'red' }));
        this.players.push(new AIPlayer({ name: 'Mr. A.I.', color: 'black' }));
      } else if (gameType === '2P') {
        // If user chooses 2-Player mode, the user will play against another
        // human
        this.players.push(new HumanPlayer({ name: 'Human 1', color: 'red' }));
        this.players.push(new HumanPlayer({ name: 'Human 2', color: 'blue' }));
      } else if (gameType === 'online' && players.length > 0 && localPlayer) {
        // If user chooses Online mode, the user will play against another human
        // on another machine
        this.players.push(...players.map((player) => {
          if (player.color === localPlayer.color) {
            return new HumanPlayer(player);
          } else {
            return new OnlinePlayer(player);
          }
        }));
      }
    } else if (gameType !== this.lastType) {
      // If user switches game type (e.g. from 1-Player to 2-Player mode),
      // recreate set of players
      this.players.length = 0;
      this.setPlayers({ gameType });
      return;
    }
    this.type = gameType;
    this.lastType = gameType;
  }

  // Retrieve the player that isn't the given player
  getOtherPlayer(basePlayer = this.currentPlayer) {
    return this.players.find((player) => player.color !== basePlayer.color);
  }

  // Start the turn of the current player
  startTurn() {
    this.pendingChip = new Chip({ player: this.currentPlayer });
    if (this.currentPlayer.getNextMove) {
      this.currentPlayer.getNextMove({ game: this }).then((nextMove) => {
        this.emit('async-player:get-next-move', {
          player: this.currentPlayer,
          nextMove
        });
      });
    }
  }

  // End the turn of the current player and switch to the next player
  endTurn() {
    if (this.inProgress) {
      // Switch to next player's turn
      this.currentPlayer = this.getOtherPlayer(this.currentPlayer);
      this.startTurn();
    }
  }

  // Insert the current pending chip into the columns array at the given index
  placePendingChip({ column }) {
    this.grid.placeChip({
      chip: this.pendingChip,
      column
    });
    this.emit('player:place-chip', this.grid.lastPlacedChip);
    if (this.debug) {
      this.columnHistory.push(column);
      // The column history will only be logged on non-production sites, so we
      // can safely disable the ESLint error
      // eslint-disable-next-line no-console
      console.log(this.columnHistory.join(', '));
    }
    this.pendingChip = null;
    // Check for winning connections (i.e. four in a row)
    this.checkForWin();
    // Check if the grid is completely full
    this.checkForTie();
    // If the above checks have not ended the game, continue to next player's
    // turn
    this.endTurn();
  }

  // Check if the game has tied, and end the game if it is
  checkForTie() {
    if (this.grid.checkIfFull()) {
      this.emit('game:declare-tie');
      this.endGame();
    }
  }

  // Determine if a player won the game with four chips in a row (horizontally,
  // vertically, or diagonally)
  checkForWin() {
  if (!this.grid.lastPlacedChip) {
      return;
    }
    const connections = this.grid.getConnections({
      baseChip: this.grid.lastPlacedChip,
      minConnectionSize: 4
    });
    if (connections.length > 0) {
      // Mark chips in only the first winning connection, and only mark the
      // first four chips of this connection (since only a connect-four is
      // needed to win
      connections[0].length = 4;
      connections[0].forEach((chip) => {
        chip.winning = true;
      });
      this.winner = this.grid.lastPlacedChip.player;
      this.emit('game:declare-winner', this.winner);
      this.endGame();
    }
  }

  // Apply the given server game JSON to the current game instance, taking into
  // account which player is the local (human) player and which player is the
  // online player
  restoreFromServer({ game, localPlayer = {} }) {
    this.inProgress = game.inProgress;
    this.players.length = 0;

    this.setPlayers({
      gameType: 'online',
      players: game.players,
      localPlayer
    });
    // Remove the event listener for any leftover (unresolved)
    // OnlinePlayer.getNextMove() promise
    this.off('online-player:receive-next-move');

    this.currentPlayer = this.players.find((player) => player.color === game.currentPlayer);
    this.requestingPlayer = this.players.find((player) => player.color === game.requestingPlayer);

    this.grid.restoreFromServer({
      grid: game.grid,
      players: this.players
    });
    // Restore the last position of the pending chip when the game state is
    // restored
    if (game.pendingChipColumn) {
      this.emit('grid:align-pending-chip-initially', { column: game.pendingChipColumn });
    }
    this.winner = null;

    if (this.inProgress && this.currentPlayer) {
      this.startTurn();
    }
    this.checkForWin();
    this.checkForTie();
  }

}

export default Game;
<commit_msg>Add Game.winningConnectionSize<commit_after>import Emitter from 'tiny-emitter';
import Grid from './grid.js';
import HumanPlayer from './human-player.js';
import OnlinePlayer from './online-player.js';
import AIPlayer from './ai-player.js';
import Chip from './chip.js';

// A game between two players; the same Game instance is re-used for successive
// rounds
class Game extends Emitter {

  constructor({ grid = new Grid({ columnCount: 7, rowCount: 6 }), players = [], debug = false } = {}) {
    super();
    // The two-dimensional array representing the entire game grid
    this.grid = grid;
    // The list of all players for this game
    this.players = players;
    // The type of the current game (e.g. '1P', '2P', or 'online'); this is
    // reset to null when the game ends
    this.type = null;
    // The type of the current/last game; unlike this.type, this does not reset
    // when the game ends
    this.lastType = null;
    // The current player is null when a game is not in progress
    this.currentPlayer = null;
    // Whether or not the game is in progress
    this.inProgress = false;
    // The chip above the grid that is about to be placed
    this.pendingChip = null;
    // The winning player of the game
    this.winner = null;
    // The player who requests to end the game or start a new one
    this.requestingPlayer = null;
    // Keep track of the columns where chips are placed in debug mode (extremely
    // useful for creating new unit tests from real games)
    if (debug) {
      this.debug = true;
      this.columnHistory = [];
    } else {
      this.debug = false;
    }
  }

  startGame({ startingPlayer } = {}) {
    if (startingPlayer) {
      this.currentPlayer = startingPlayer;
    } else {
      this.currentPlayer = this.players[0];
    }
    this.inProgress = true;
    this.emit('game:start');
    this.startTurn();
  }

  // End the game without resetting the grid
  endGame() {
    if (this.winner) {
      this.winner.score += 1;
    }
    this.inProgress = false;
    this.currentPlayer = null;
    this.pendingChip = null;
    this.emit('game:end');
    this.type = null;
    if (this.debug) {
      this.columnHistory.length = 0;
    }
  }

  // Reset the game and grid completely without starting a new game (endGame
  // should be called somewhere before this method is called)
  resetGame() {
    this.winner = null;
    this.grid.resetGrid();
  }

  // Initialize or change the current set of players based on the specified game
  // type;
  setPlayers({ gameType, players = [], localPlayer = null }) {
    // Instantiate new players as needed (if user is about to play the first game
    // or if the user is switching modes)
    if (this.players.length === 0) {
      if (gameType === '1P') {
        // If user chose 1-Player mode, the user will play against the AI
        this.players.push(new HumanPlayer({ name: 'Human', color: 'red' }));
        this.players.push(new AIPlayer({ name: 'Mr. A.I.', color: 'black' }));
      } else if (gameType === '2P') {
        // If user chooses 2-Player mode, the user will play against another
        // human
        this.players.push(new HumanPlayer({ name: 'Human 1', color: 'red' }));
        this.players.push(new HumanPlayer({ name: 'Human 2', color: 'blue' }));
      } else if (gameType === 'online' && players.length > 0 && localPlayer) {
        // If user chooses Online mode, the user will play against another human
        // on another machine
        this.players.push(...players.map((player) => {
          if (player.color === localPlayer.color) {
            return new HumanPlayer(player);
          } else {
            return new OnlinePlayer(player);
          }
        }));
      }
    } else if (gameType !== this.lastType) {
      // If user switches game type (e.g. from 1-Player to 2-Player mode),
      // recreate set of players
      this.players.length = 0;
      this.setPlayers({ gameType });
      return;
    }
    this.type = gameType;
    this.lastType = gameType;
  }

  // Retrieve the player that isn't the given player
  getOtherPlayer(basePlayer = this.currentPlayer) {
    return this.players.find((player) => player.color !== basePlayer.color);
  }

  // Start the turn of the current player
  startTurn() {
    this.pendingChip = new Chip({ player: this.currentPlayer });
    if (this.currentPlayer.getNextMove) {
      this.currentPlayer.getNextMove({ game: this }).then((nextMove) => {
        this.emit('async-player:get-next-move', {
          player: this.currentPlayer,
          nextMove
        });
      });
    }
  }

  // End the turn of the current player and switch to the next player
  endTurn() {
    if (this.inProgress) {
      // Switch to next player's turn
      this.currentPlayer = this.getOtherPlayer(this.currentPlayer);
      this.startTurn();
    }
  }

  // Insert the current pending chip into the columns array at the given index
  placePendingChip({ column }) {
    this.grid.placeChip({
      chip: this.pendingChip,
      column
    });
    this.emit('player:place-chip', this.grid.lastPlacedChip);
    if (this.debug) {
      this.columnHistory.push(column);
      // The column history will only be logged on non-production sites, so we
      // can safely disable the ESLint error
      // eslint-disable-next-line no-console
      console.log(this.columnHistory.join(', '));
    }
    this.pendingChip = null;
    // Check for winning connections (i.e. four in a row)
    this.checkForWin();
    // Check if the grid is completely full
    this.checkForTie();
    // If the above checks have not ended the game, continue to next player's
    // turn
    this.endTurn();
  }

  // Check if the game has tied, and end the game if it is
  checkForTie() {
    if (this.grid.checkIfFull()) {
      this.emit('game:declare-tie');
      this.endGame();
    }
  }

  // Determine if a player won the game with four chips in a row (horizontally,
  // vertically, or diagonally)
  checkForWin() {
  if (!this.grid.lastPlacedChip) {
      return;
    }
    const connections = this.grid.getConnections({
      baseChip: this.grid.lastPlacedChip,
      minConnectionSize: Game.winningConnectionSize
    });
    if (connections.length > 0) {
      // Mark chips in only the first winning connection, and only mark the
      // first four chips of this connection (since only a connect-four is
      // needed to win
      connections[0].length = Game.winningConnectionSize;
      connections[0].forEach((chip) => {
        chip.winning = true;
      });
      this.winner = this.grid.lastPlacedChip.player;
      this.emit('game:declare-winner', this.winner);
      this.endGame();
    }
  }

  // Apply the given server game JSON to the current game instance, taking into
  // account which player is the local (human) player and which player is the
  // online player
  restoreFromServer({ game, localPlayer = {} }) {
    this.inProgress = game.inProgress;
    this.players.length = 0;

    this.setPlayers({
      gameType: 'online',
      players: game.players,
      localPlayer
    });
    // Remove the event listener for any leftover (unresolved)
    // OnlinePlayer.getNextMove() promise
    this.off('online-player:receive-next-move');

    this.currentPlayer = this.players.find((player) => player.color === game.currentPlayer);
    this.requestingPlayer = this.players.find((player) => player.color === game.requestingPlayer);

    this.grid.restoreFromServer({
      grid: game.grid,
      players: this.players
    });
    // Restore the last position of the pending chip when the game state is
    // restored
    if (game.pendingChipColumn) {
      this.emit('grid:align-pending-chip-initially', { column: game.pendingChipColumn });
    }
    this.winner = null;

    if (this.inProgress && this.currentPlayer) {
      this.startTurn();
    }
    this.checkForWin();
    this.checkForTie();
  }

}

// The minimum number of chips a connection must have to win the game
Game.winningConnectionSize = 4;

export default Game;
<|endoftext|>


<commit_before>((typeof define === "function" && define.amd && function (m) {
    define("formatio", ["samsam"], m);
}) || (typeof module === "object" && function (m) {
    module.exports = m(require("samsam"));
}) || function (m) { this.formatio = m(this.samsam); }
)(function (samsam) {
    "use strict";

    var formatio = {
        excludeConstructors: ["Object", /^.$/],
        quoteStrings: true,
        limitChildrenCount: 0
    };

    var hasOwn = Object.prototype.hasOwnProperty;

    var specialObjects = [];
    if (typeof global !== "undefined") {
        specialObjects.push({ object: global, value: "[object global]" });
    }
    if (typeof document !== "undefined") {
        specialObjects.push({
            object: document,
            value: "[object HTMLDocument]"
        });
    }
    if (typeof window !== "undefined") {
        specialObjects.push({ object: window, value: "[object Window]" });
    }

    function functionName(func) {
        if (!func) { return ""; }
        if (func.displayName) { return func.displayName; }
        if (func.name) { return func.name; }
        var matches = func.toString().match(/function\s+([^\(]+)/m);
        return (matches && matches[1]) || "";
    }

    function constructorName(f, object) {
        var name = functionName(object && object.constructor);
        var excludes = f.excludeConstructors ||
                formatio.excludeConstructors || [];

        var i, l;
        for (i = 0, l = excludes.length; i < l; ++i) {
            if (typeof excludes[i] === "string" && excludes[i] === name) {
                return "";
            } else if (excludes[i].test && excludes[i].test(name)) {
                return "";
            }
        }

        return name;
    }

    function isCircular(object, objects) {
        if (typeof object !== "object") { return false; }
        var i, l;
        for (i = 0, l = objects.length; i < l; ++i) {
            if (objects[i] === object) { return true; }
        }
        return false;
    }

    function ascii(f, object, processed, indent) {
        if (typeof object === "string") {
            var qs = f.quoteStrings;
            var quote = typeof qs !== "boolean" || qs;
            return processed || quote ? '"' + object + '"' : object;
        }

        if (typeof object === "function" && !(object instanceof RegExp)) {
            return ascii.func(object);
        }

        processed = processed || [];

        if (isCircular(object, processed)) { return "[Circular]"; }

        if (Object.prototype.toString.call(object) === "[object Array]") {
            return ascii.array.call(f, object, processed);
        }

        if (!object) { return String((1/object) === -Infinity ? "-0" : object); }
        if (samsam.isElement(object)) { return ascii.element(object); }

        if (typeof object.toString === "function" &&
                object.toString !== Object.prototype.toString) {
            return object.toString();
        }

        var i, l;
        for (i = 0, l = specialObjects.length; i < l; i++) {
            if (object === specialObjects[i].object) {
                return specialObjects[i].value;
            }
        }

        return ascii.object.call(f, object, processed, indent);
    }

    ascii.func = function (func) {
        return "function " + functionName(func) + "() {}";
    };

    ascii.array = function (array, processed) {
        processed = processed || [];
        processed.push(array);
        var pieces = [];
        var i, l;
        l = (this.limitChildrenCount > 0) ?
            Math.min(this.limitChildrenCount, array.length) : array.length;

        for (i = 0; i < l; ++i) {
            pieces.push(ascii(this, array[i], processed));
        }

        if(l < array.length)
            pieces.push("[... " + (array.length - l) + " more elements]");

        return "[" + pieces.join(", ") + "]";
    };

    ascii.object = function (object, processed, indent) {
        processed = processed || [];
        processed.push(object);
        indent = indent || 0;
        var pieces = [], properties = samsam.keys(object).sort();
        var length = 3;
        var prop, str, obj, i, k, l;
        l = (this.limitChildrenCount > 0) ?
            Math.min(this.limitChildrenCount, properties.length) : properties.length;

        for (i = 0; i < l; ++i) {
            prop = properties[i];
            obj = object[prop];

            if (isCircular(obj, processed)) {
                str = "[Circular]";
            } else {
                str = ascii(this, obj, processed, indent + 2);
            }

            str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
            length += str.length;
            pieces.push(str);
        }

        var cons = constructorName(this, object);
        var prefix = cons ? "[" + cons + "] " : "";
        var is = "";
        for (i = 0, k = indent; i < k; ++i) { is += " "; }

        if(l < properties.length)
            pieces.push("[... " + (properties.length - l) + " more elements]");

        if (length + indent > 80) {
            return prefix + "{\n  " + is + pieces.join(",\n  " + is) + "\n" +
                is + "}";
        }
        return prefix + "{ " + pieces.join(", ") + " }";
    };

    ascii.element = function (element) {
        var tagName = element.tagName.toLowerCase();
        var attrs = element.attributes, attr, pairs = [], attrName, i, l, val;

        for (i = 0, l = attrs.length; i < l; ++i) {
            attr = attrs.item(i);
            attrName = attr.nodeName.toLowerCase().replace("html:", "");
            val = attr.nodeValue;
            if (attrName !== "contenteditable" || val !== "inherit") {
                if (!!val) { pairs.push(attrName + "=\"" + val + "\""); }
            }
        }

        var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
        var content = element.innerHTML;

        if (content.length > 20) {
            content = content.substr(0, 20) + "[...]";
        }

        var res = formatted + pairs.join(" ") + ">" + content +
                "</" + tagName + ">";

        return res.replace(/ contentEditable="inherit"/, "");
    };

    function Formatio(options) {
        for (var opt in options) {
            this[opt] = options[opt];
        }
    }

    Formatio.prototype = {
        functionName: functionName,

        configure: function (options) {
            return new Formatio(options);
        },

        constructorName: function (object) {
            return constructorName(this, object);
        },

        ascii: function (object, processed, indent) {
            return ascii(this, object, processed, indent);
        }
    };

    return Formatio.prototype;
});
<commit_msg>Safe-guard innerHTML which may be empty (SVG elements)<commit_after>((typeof define === "function" && define.amd && function (m) {
    define("formatio", ["samsam"], m);
}) || (typeof module === "object" && function (m) {
    module.exports = m(require("samsam"));
}) || function (m) { this.formatio = m(this.samsam); }
)(function (samsam) {
    "use strict";

    var formatio = {
        excludeConstructors: ["Object", /^.$/],
        quoteStrings: true,
        limitChildrenCount: 0
    };

    var hasOwn = Object.prototype.hasOwnProperty;

    var specialObjects = [];
    if (typeof global !== "undefined") {
        specialObjects.push({ object: global, value: "[object global]" });
    }
    if (typeof document !== "undefined") {
        specialObjects.push({
            object: document,
            value: "[object HTMLDocument]"
        });
    }
    if (typeof window !== "undefined") {
        specialObjects.push({ object: window, value: "[object Window]" });
    }

    function functionName(func) {
        if (!func) { return ""; }
        if (func.displayName) { return func.displayName; }
        if (func.name) { return func.name; }
        var matches = func.toString().match(/function\s+([^\(]+)/m);
        return (matches && matches[1]) || "";
    }

    function constructorName(f, object) {
        var name = functionName(object && object.constructor);
        var excludes = f.excludeConstructors ||
                formatio.excludeConstructors || [];

        var i, l;
        for (i = 0, l = excludes.length; i < l; ++i) {
            if (typeof excludes[i] === "string" && excludes[i] === name) {
                return "";
            } else if (excludes[i].test && excludes[i].test(name)) {
                return "";
            }
        }

        return name;
    }

    function isCircular(object, objects) {
        if (typeof object !== "object") { return false; }
        var i, l;
        for (i = 0, l = objects.length; i < l; ++i) {
            if (objects[i] === object) { return true; }
        }
        return false;
    }

    function ascii(f, object, processed, indent) {
        if (typeof object === "string") {
            var qs = f.quoteStrings;
            var quote = typeof qs !== "boolean" || qs;
            return processed || quote ? '"' + object + '"' : object;
        }

        if (typeof object === "function" && !(object instanceof RegExp)) {
            return ascii.func(object);
        }

        processed = processed || [];

        if (isCircular(object, processed)) { return "[Circular]"; }

        if (Object.prototype.toString.call(object) === "[object Array]") {
            return ascii.array.call(f, object, processed);
        }

        if (!object) { return String((1/object) === -Infinity ? "-0" : object); }
        if (samsam.isElement(object)) { return ascii.element(object); }

        if (typeof object.toString === "function" &&
                object.toString !== Object.prototype.toString) {
            return object.toString();
        }

        var i, l;
        for (i = 0, l = specialObjects.length; i < l; i++) {
            if (object === specialObjects[i].object) {
                return specialObjects[i].value;
            }
        }

        return ascii.object.call(f, object, processed, indent);
    }

    ascii.func = function (func) {
        return "function " + functionName(func) + "() {}";
    };

    ascii.array = function (array, processed) {
        processed = processed || [];
        processed.push(array);
        var pieces = [];
        var i, l;
        l = (this.limitChildrenCount > 0) ?
            Math.min(this.limitChildrenCount, array.length) : array.length;

        for (i = 0; i < l; ++i) {
            pieces.push(ascii(this, array[i], processed));
        }

        if(l < array.length)
            pieces.push("[... " + (array.length - l) + " more elements]");

        return "[" + pieces.join(", ") + "]";
    };

    ascii.object = function (object, processed, indent) {
        processed = processed || [];
        processed.push(object);
        indent = indent || 0;
        var pieces = [], properties = samsam.keys(object).sort();
        var length = 3;
        var prop, str, obj, i, k, l;
        l = (this.limitChildrenCount > 0) ?
            Math.min(this.limitChildrenCount, properties.length) : properties.length;

        for (i = 0; i < l; ++i) {
            prop = properties[i];
            obj = object[prop];

            if (isCircular(obj, processed)) {
                str = "[Circular]";
            } else {
                str = ascii(this, obj, processed, indent + 2);
            }

            str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
            length += str.length;
            pieces.push(str);
        }

        var cons = constructorName(this, object);
        var prefix = cons ? "[" + cons + "] " : "";
        var is = "";
        for (i = 0, k = indent; i < k; ++i) { is += " "; }

        if(l < properties.length)
            pieces.push("[... " + (properties.length - l) + " more elements]");

        if (length + indent > 80) {
            return prefix + "{\n  " + is + pieces.join(",\n  " + is) + "\n" +
                is + "}";
        }
        return prefix + "{ " + pieces.join(", ") + " }";
    };

    ascii.element = function (element) {
        var tagName = element.tagName.toLowerCase();
        var attrs = element.attributes, attr, pairs = [], attrName, i, l, val;

        for (i = 0, l = attrs.length; i < l; ++i) {
            attr = attrs.item(i);
            attrName = attr.nodeName.toLowerCase().replace("html:", "");
            val = attr.nodeValue;
            if (attrName !== "contenteditable" || val !== "inherit") {
                if (!!val) { pairs.push(attrName + "=\"" + val + "\""); }
            }
        }

        var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
        // SVG elements have undefined innerHTML
        var content = element.innerHTML || '';

        if (content.length > 20) {
            content = content.substr(0, 20) + "[...]";
        }

        var res = formatted + pairs.join(" ") + ">" + content +
                "</" + tagName + ">";

        return res.replace(/ contentEditable="inherit"/, "");
    };

    function Formatio(options) {
        for (var opt in options) {
            this[opt] = options[opt];
        }
    }

    Formatio.prototype = {
        functionName: functionName,

        configure: function (options) {
            return new Formatio(options);
        },

        constructorName: function (object) {
            return constructorName(this, object);
        },

        ascii: function (object, processed, indent) {
            return ascii(this, object, processed, indent);
        }
    };

    return Formatio.prototype;
});
<|endoftext|>


<commit_before>var childProcess = require('child_process');
var path = require('path');

var async = require('async');
var colorConvert = require('color-convert');
var giphy = require('giphy-api')();
var pixelGif = require('pixel-gif');
var shuffleArray = require('shuffle-array');
var supportsColor = require('supports-color');

childProcess.fork(path.join(__dirname, 'music.js'));

function updateFrame(frame, cb) {
	var covfefe = [];
	var skipped = false;
	for (var y = 0; y < frame.height; y += 2) {
		for (var x = 0; x < frame.width; x += 2) {
			var offset = ((y * frame.width) + x) * 4;
			if (frame.data[offset + 3] === 0) {
				skipped = true;
			} else {
				if (skipped) {
					skipped = false;
					covfefe.push('\x1b[' + (y / 2 + 1) + ';' + (x / 2 + 1) + 'H');
				}

				switch (supportsColor.level) {
				case 0: // lol we're still gonna' try
				case 1:
					var ansi16 = colorConvert.rgb.ansi16(
						frame.data[offset],
						frame.data[offset + 1],
						frame.data[offset + 2]) + 10;
					covfefe.push('\x1b[' + ansi16 + 'm ');
					break;
				case 2:
					var ansi256 = colorConvert.rgb.ansi256(
						frame.data[offset],
						frame.data[offset + 1],
						frame.data[offset + 2]);
					covfefe.push('\x1b[48;5;' + ansi256 + 'm ');
					break;
				case 3:
					var r = frame.data[offset];
					var r = frame.data[offset + 1];
					var r = frame.data[offset + 2];
					covfefe.push('\x1b[48;2;' + r + ';' + g + ';' + b + 'm ');
					break;
				}
			}
		}
		covfefe.push('\x1b[m\n');
	}
	var cx = Math.floor(Math.random() * 70);
	var cy = Math.floor(Math.random() * 30);
	covfefe.push('\x1b[' + cy + ';' + cx + 'H\x1b[0mCOVFEFE!');
	process.stdout.write(covfefe.join(''));
	setTimeout(cb, frame.delay);
}

giphy.search('trump', function (err, res) {
	if (err) {
		throw err;
	}

	var images = res.data
		.filter(function (img) { return img.type === 'gif'; })
		.map(function (img) { return img.images.fixed_height_small.url });

	shuffleArray(images);
	var imageData = {};

	async.forever(function (cb) {
		async.each(images,
			function (imgUrl, cb) {
				var getImageData = function (cb) {
					if (imgUrl in imageData) {
						cb(null, imageData[imgUrl]);
					} else {
						pixelGif.parse(imgUrl)
							.then(function (data) {
								imageData[imgUrl] = data;
								cb(null, data);
							})
							.catch(cb);
					}
				};

				getImageData(function (err, data) {
					if (err) {
						return cb(err);
					}

					process.stdout.write('\x1b[2J\x1b[H\x1b[f');
					async.each(data, updateFrame, cb);
				});
			},
			cb);
	}, function (err) {
		if (err) {
			throw err;
		}
	});
});

<commit_msg>fix aspect ratio of gifs<commit_after>var childProcess = require('child_process');
var path = require('path');

var async = require('async');
var colorConvert = require('color-convert');
var giphy = require('giphy-api')();
var pixelGif = require('pixel-gif');
var shuffleArray = require('shuffle-array');
var supportsColor = require('supports-color');

childProcess.fork(path.join(__dirname, 'music.js'));

function updateFrame(frame, cb) {
	var covfefe = [];
	var skipped = false;
	for (var y = 0; y < frame.height; y += 2) {
		for (var x = 0; x < frame.width; x += 1) {
			var offset = ((y * frame.width) + x) * 4;
			if (frame.data[offset + 3] === 0) {
				skipped = true;
			} else {
				if (skipped) {
					skipped = false;
					covfefe.push('\x1b[' + (y / 2 + 1) + ';' + (x + 1) + 'H');
				}

				switch (supportsColor.level) {
				case 0: // lol we're still gonna' try
				case 1:
					var ansi16 = colorConvert.rgb.ansi16(
						frame.data[offset],
						frame.data[offset + 1],
						frame.data[offset + 2]) + 10;
					covfefe.push('\x1b[' + ansi16 + 'm ');
					break;
				case 2:
					var ansi256 = colorConvert.rgb.ansi256(
						frame.data[offset],
						frame.data[offset + 1],
						frame.data[offset + 2]);
					covfefe.push('\x1b[48;5;' + ansi256 + 'm ');
					break;
				case 3:
					var r = frame.data[offset];
					var r = frame.data[offset + 1];
					var r = frame.data[offset + 2];
					covfefe.push('\x1b[48;2;' + r + ';' + g + ';' + b + 'm ');
					break;
				}
			}
		}
		covfefe.push('\x1b[m\n');
	}
	var cx = Math.floor(Math.random() * 70);
	var cy = Math.floor(Math.random() * 30);
	covfefe.push('\x1b[' + cy + ';' + cx + 'H\x1b[0mCOVFEFE!');
	process.stdout.write(covfefe.join(''));
	setTimeout(cb, frame.delay);
}

giphy.search('trump', function (err, res) {
	if (err) {
		throw err;
	}

	var images = res.data
		.filter(function (img) { return img.type === 'gif'; })
		.map(function (img) { return img.images.fixed_height_small.url });

	shuffleArray(images);
	var imageData = {};

	async.forever(function (cb) {
		async.each(images,
			function (imgUrl, cb) {
				var getImageData = function (cb) {
					if (imgUrl in imageData) {
						cb(null, imageData[imgUrl]);
					} else {
						pixelGif.parse(imgUrl)
							.then(function (data) {
								imageData[imgUrl] = data;
								cb(null, data);
							})
							.catch(cb);
					}
				};

				getImageData(function (err, data) {
					if (err) {
						return cb(err);
					}

					process.stdout.write('\x1b[2J\x1b[H\x1b[f');
					async.each(data, updateFrame, cb);
				});
			},
			cb);
	}, function (err) {
		if (err) {
			throw err;
		}
	});
});

<|endoftext|>


<commit_before>// Global Variables Declaration -- start

var svgNS = "http://www.w3.org/2000/svg";
var displayNow = 0;
var possibleDisplays = 2;

// Global Variables Declaration -- end

// Code used for start up -- start

function displayNone()
{

  document.getElementById("container1").style.display = "none";
  document.getElementById("container2").style.display = "none";

}

function setHenosisAtCentre()
{

  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosis").setAttribute('cx', windowWidth/2);
  document.getElementById("henosis").setAttribute('cy', windowHeight/2);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

}

function start()
{

  displayNone();
  setHenosisAtCentre();

}

start();

// Code used for start up -- end

// Code used for dragging -- start

$( function() {
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  $('#henosis').draggable({
    containment: [ 0, 0, windowWidth-40, windowHeight-40]
  })
  .bind('mousedown', function(event, ui){
    // bring target to front
    $(event.target.parentElement).append( event.target );
  }).bind('drag', function(event, ui){

    var ua = navigator.userAgent.toLowerCase();
    var isChromium = ua.indexOf("chromium") > -1; //&& ua.indexOf("mobile");

    if(isChromium)
    {

      var leftPosition = ui.position.left + 20;
      var topPosition = ui.position.top + 20;

    }
    else
    {

      var leftPosition = ui.position.left+(windowWidth/2);
      var topPosition = ui.position.top+(windowHeight/2);

    }

    // update coordinates manually, since top/left style props don't work on SVG
    event.target.setAttribute('cx', leftPosition);
    event.target.setAttribute('cy', topPosition);
    changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

  });
} );

// Code used for dragging -- end

// Code used for page refresh -- start
// Move to a better containment when possible.

// See: https://www.sitepoint.com/jquery-refresh-page-browser-resize/
//refresh page on browser resize
$(window).bind('resize', function(e)
{
  if (window.RT) clearTimeout(window.RT);
  window.RT = setTimeout(function()
  {
    this.location.reload(false); /* false to get page from cache */
  }, 200);
});

// Code used for page refresh -- end

// Code for scaleUpAct and for switching containers -- start

function createActCircle(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircle");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","white");
  myCircle.setAttributeNS(null,"stroke","none");
  myCircle.setAttributeNS(null,"style","opacity: 1;");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function createActCircleShadow(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircleShadow");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","grey");
  myCircle.setAttributeNS(null,"stroke","none");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function displayToggle()
{
  if(displayNow==0)
  {
    displayNow++;
    document.getElementById("container"+displayNow).style.display = "block";
  }
  else if(displayNow == possibleDisplays)
  {
    document.getElementById("container"+displayNow).style.display = "none";
    displayNow = 1;
    document.getElementById("container"+displayNow).style.display = "block";
  }
  else
  {
    document.getElementById("container"+displayNow).style.display = "none";
    displayNow++;
    document.getElementById("container"+displayNow).style.display = "block";
  }
}

function reduceOpacity()
{
  setTimeout(function () {
    var opacity = document.getElementById("actCircle").style.opacity;
    if(opacity>0)
    {
      document.getElementById("actCircle").style.opacity = (parseFloat(opacity)-parseFloat(0.1));
      reduceOpacity();
    }
    else
    {
      document.getElementById("actCircle").remove();
      if (document.getElementById("henosis").addEventListener)
      {
        // all browsers except IE before version 9
        document.getElementById("henosis").addEventListener("click", henosisScaleUpActStart, false);
      }
      else
      {
        if (document.getElementById("henosis").attachEvent)
        {
          // IE before version 9
          document.getElementById("henosis").attachEvent("click", henosisScaleUpActStart);
        }
      }
    }
  }, 100);
}

function scaleUpActComplete()
{
  document.getElementById("actCircleShadow").remove();
  displayToggle();
  reduceOpacity();
}

function henosisActCircleScaleUpAct(maxValue)
{
  setTimeout(function () {
    var radius = document.getElementById("actCircle").getAttribute('r');
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if(radius<maxValue)
    {
      document.getElementById("actCircle").setAttribute('r', parseFloat(radius)+parseFloat(maxValue/15));
      changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
      henosisActCircleScaleUpAct(maxValue);
    }
    else
    {
      scaleUpActComplete();
    }
  }, 10);
}

function henosisScaleUpActStart()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  var diagonalLength = Math.sqrt((windowWidth*windowWidth)+(windowHeight*windowHeight));
  var cx = document.getElementById("henosis").getAttribute('cx');
  var cy = document.getElementById("henosis").getAttribute('cy');
  createActCircleShadow(cx, cy);
  createActCircle(cx, cy);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
  henosisActCircleScaleUpAct(diagonalLength);
}

// Code for scaleUpAct and for switching containers -- end

// pageloading part -- start
var colors = new Array( "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red");
var colornow=1;
var loopStop=0;
function changeBackground(color) {
  document.getElementById("henosis").setAttribute('fill', color);
}

function incrementcolor() {
  if(colornow==6) {
    colornow=0;
  }
  else {
    colornow++;
  }
}

function loopLi() {
  setTimeout(function () {
    changeBackground(colors[colornow]);
    incrementcolor();
    if(loopStop==0)
    {
      loopLi();
    }
    else
    {
      document.getElementById("henosis").setAttribute('fill', "white");
      henosisScaleUpActStart();
    }
  }, 1000);
}

loopLi();
// pageloading part -- end

// pageloaded -- start
$(window).on('load', function()
{
  loopStop=1;
});
// pageloaded -- end
<commit_msg>bug fix<commit_after>// Global Variables Declaration -- start

var svgNS = "http://www.w3.org/2000/svg";
var displayNow = 0;
var possibleDisplays = 2;

// Global Variables Declaration -- end

// Code used for start up -- start

function displayNone()
{

  document.getElementById("container1").style.display = "none";
  document.getElementById("container2").style.display = "none";

}

function setHenosisAtCentre()
{

  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosis").setAttribute('cx', windowWidth/2);
  document.getElementById("henosis").setAttribute('cy', windowHeight/2);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

}

function start()
{

  displayNone();
  setHenosisAtCentre();

}

start();

// Code used for start up -- end

// Code used for dragging -- start

$( function() {
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  $('#henosis').draggable({
    containment: [ 0, 0, windowWidth-40, windowHeight-40]
  })
  // .bind('mousedown', function(event, ui){
  //   // bring target to front
  //   $(event.target.parentElement).append( event.target );
  // })
  .bind('drag', function(event, ui){

    var ua = navigator.userAgent.toLowerCase();
    var isChromium = ua.indexOf("chromium") > -1; //&& ua.indexOf("mobile");

    if(isChromium)
    {

      var leftPosition = ui.position.left + 20;
      var topPosition = ui.position.top + 20;

    }
    else
    {

      var leftPosition = ui.position.left+(windowWidth/2);
      var topPosition = ui.position.top+(windowHeight/2);

    }

    // update coordinates manually, since top/left style props don't work on SVG
    event.target.setAttribute('cx', leftPosition);
    event.target.setAttribute('cy', topPosition);
    changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

  });
} );

// Code used for dragging -- end

// Code used for page refresh -- start
// Move to a better containment when possible.

// See: https://www.sitepoint.com/jquery-refresh-page-browser-resize/
//refresh page on browser resize
$(window).bind('resize', function(e)
{
  if (window.RT) clearTimeout(window.RT);
  window.RT = setTimeout(function()
  {
    this.location.reload(false); /* false to get page from cache */
  }, 200);
});

// Code used for page refresh -- end

// Code for scaleUpAct and for switching containers -- start

function createActCircle(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircle");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","white");
  myCircle.setAttributeNS(null,"stroke","none");
  myCircle.setAttributeNS(null,"style","opacity: 1;");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function createActCircleShadow(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircleShadow");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","grey");
  myCircle.setAttributeNS(null,"stroke","none");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function displayToggle()
{
  if(displayNow==0)
  {
    displayNow++;
    document.getElementById("container"+displayNow).style.display = "block";
  }
  else if(displayNow == possibleDisplays)
  {
    document.getElementById("container"+displayNow).style.display = "none";
    displayNow = 1;
    document.getElementById("container"+displayNow).style.display = "block";
  }
  else
  {
    document.getElementById("container"+displayNow).style.display = "none";
    displayNow++;
    document.getElementById("container"+displayNow).style.display = "block";
  }
}

function reduceOpacity()
{
  setTimeout(function () {
    var opacity = document.getElementById("actCircle").style.opacity;
    if(opacity>0)
    {
      document.getElementById("actCircle").style.opacity = (parseFloat(opacity)-parseFloat(0.1));
      reduceOpacity();
    }
    else
    {
      document.getElementById("actCircle").remove();
      if (document.getElementById("henosis").addEventListener)
      {
        // all browsers except IE before version 9
        // $('#henosis').off('click');
        document.getElementById("henosis").addEventListener("click", henosisScaleUpActStart, true);
      }
      else
      {
        if (document.getElementById("henosis").attachEvent)
        {
          // IE before version 9
          document.getElementById("henosis").attachEvent("click", henosisScaleUpActStart);
        }
      }
    }
  }, 100);
}

function scaleUpActComplete()
{
  document.getElementById("actCircleShadow").remove();
  displayToggle();
  reduceOpacity();
}

function henosisActCircleScaleUpAct(maxValue)
{
  setTimeout(function () {
    var radius = document.getElementById("actCircle").getAttribute('r');
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if(radius<maxValue)
    {
      document.getElementById("actCircle").setAttribute('r', parseFloat(radius)+parseFloat(maxValue/15));
      changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
      henosisActCircleScaleUpAct(maxValue);
    }
    else
    {
      scaleUpActComplete();
    }
  }, 10);
}

function henosisScaleUpActStart()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  var diagonalLength = Math.sqrt((windowWidth*windowWidth)+(windowHeight*windowHeight));
  var cx = document.getElementById("henosis").getAttribute('cx');
  var cy = document.getElementById("henosis").getAttribute('cy');
  createActCircleShadow(cx, cy);
  createActCircle(cx, cy);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
  henosisActCircleScaleUpAct(diagonalLength);
}

// Code for scaleUpAct and for switching containers -- end

// pageloading part -- start
var colors = new Array( "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red");
var colornow=1;
var loopStop=0;
function changeBackground(color) {
  document.getElementById("henosis").setAttribute('fill', color);
}

function incrementcolor() {
  if(colornow==6) {
    colornow=0;
  }
  else {
    colornow++;
  }
}

function loopLi() {
  setTimeout(function () {
    changeBackground(colors[colornow]);
    incrementcolor();
    if(loopStop==0)
    {
      loopLi();
    }
    else
    {
      document.getElementById("henosis").setAttribute('fill', "white");
      henosisScaleUpActStart();
    }
  }, 1000);
}

loopLi();
// pageloading part -- end

// pageloaded -- start
$(window).on('load', function()
{
  loopStop=1;
});
// pageloaded -- end
<|endoftext|>


<commit_before>var express = require('express')

controllers = require('./lib/node-require-all')({
  dirname: __dirname + '/app/controllers',
  filter: /(.+)\.js(on)?$/
})

var app = express();

require('./config/initializers/middleware.js').configure(app)
require('./config/routes').configure(app, controllers)

app.listen()
console.log('Listening on port ', app.set('port'))

<commit_msg>Remove semicolon from server.js<commit_after>var express = require('express')

controllers = require('./lib/node-require-all')({
  dirname: __dirname + '/app/controllers',
  filter: /(.+)\.js(on)?$/
})

var app = express()

require('./config/initializers/middleware.js').configure(app)
require('./config/routes').configure(app, controllers)

app.listen()
console.log('Listening on port ', app.set('port'))

<|endoftext|>


<commit_before>import React, { Component } from "react";
import classNames from "classnames";
const helper = require("../middleware/helper.js");
import * as TYPES from "../middleware/constants.js";
import _ from "lodash";

export default class SingleRange extends Component {
	constructor(props, context) {
		super(props);
		this.state = {
			selected: null
		};
		this.type = "range";
		this.urlParams = helper.URLParams.get(this.props.componentId);
		this.handleChange = this.handleChange.bind(this);
		this.customQuery = this.customQuery.bind(this);
	}

	// Set query information
	componentWillMount() {
		this.previousQuery = null;	// initial value for onQueryChange
		this.setQueryInfo(this.props);
		this.checkDefault(this.props);
		this.listenFilter();
	}

	componentWillReceiveProps(nextProps) {
		if (this.props.defaultSelected !== nextProps.defaultSelected) {
			this.checkDefault(nextProps);
		}
		if (this.props.showFilter !== nextProps.showFilter || this.props.filterLabel !== nextProps.filterLabel) {
			this.setQueryInfo(nextProps);
			this.handleChange(this.state.selected);
		}
	}

	componentWillUnmount() {
		if(this.filterListener) {
			this.filterListener.remove();
		}
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if(data === this.props.componentId) {
				this.changeValue(null);
			}
		});
	}

	checkDefault(props) {
		this.urlParams = helper.URLParams.get(props.componentId);
		const defaultValue = this.urlParams !== null ? this.urlParams : props.defaultSelected;
		this.changeValue(defaultValue);
	}

	changeValue(defaultValue) {
		if (!_.isEqual(this.defaultSelected, defaultValue)) {
			this.defaultSelected = defaultValue;
			if(this.defaultSelected) {
				const records = this.props.data.filter(record => record.label === this.defaultSelected);
				if (records && records.length) {
					setTimeout(this.handleChange.bind(this, records[0]), 1000);
				}
			} else {
				this.handleChange(null);
			}
		}
	}

	// set the query type and input data
	setQueryInfo(props) {
		const getQuery = (value) => {
			const currentQuery = props.customQuery ? props.customQuery(value) : this.customQuery(value);
			if (this.props.onQueryChange && JSON.stringify(this.previousQuery) !== JSON.stringify(currentQuery)) {
				this.props.onQueryChange(this.previousQuery, currentQuery);
			}
			this.previousQuery = currentQuery;
			return currentQuery;
		};
		const obj = {
			key: props.componentId,
			value: {
				queryType: this.type,
				inputData: props.dataField,
				customQuery: getQuery,
				reactiveId: this.context.reactiveId,
				showFilter: props.showFilter,
				filterLabel: props.filterLabel ? props.filterLabel : props.componentId,
				component: "SingleRange",
				defaultSelected: this.urlParams !== null ? this.urlParams : props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	// build query for this sensor only
	customQuery(record) {
		if (record) {
			return {
				range: {
					[this.props.dataField]: {
						gte: record.start,
						lte: record.end,
						boost: 2.0
					}
				}
			};
		}
	}

	// handle the input change and pass the value inside sensor info
	handleChange(record) {
		this.setState({
			selected: record
		});
		const obj = {
			key: this.props.componentId,
			value: record
		};
		this.defaultSelected = record;

		const execQuery = () => {
			const isExecuteQuery = true;
			if (this.props.onValueChange) {
				this.props.onValueChange(obj.value);
			}
			helper.URLParams.update(this.props.componentId, record ? record.label : null, this.props.URLParams);
			helper.selectedSensor.set(obj, isExecuteQuery);
		};

		if (this.props.beforeValueChange) {
			this.props.beforeValueChange(obj.value)
			.then(() => {
				execQuery();
			})
			.catch((e) => {
				console.warn(`${this.props.componentId} - beforeValueChange rejected the promise with`, e);
			});
		} else {
			execQuery();
		}
	}

	renderButtons() {
		let buttons;
		const selectedText = this.state.selected && this.state.selected.label ? this.state.selected.label : "";
		if (this.props.data) {
			buttons = this.props.data.map((record, i) => {
				const cx = classNames({
					"rbc-radio-active": this.props.showRadio,
					"rbc-radio-inactive": !this.props.showRadio,
					"rbc-list-item-active": selectedText === record.label,
					"rbc-list-item-inactive": selectedText !== record.label
				});

				return (
					<div className={`rbc-list-item row ${cx}`} key={i} onClick={() => this.handleChange(record)}>
						<input
							type="radio"
							className="rbc-radio-item"
							checked={selectedText === record.label}
							value={record.label}
						/>
						{record.label}

				);
			});
		}
		return buttons;
	}

	// render
	render() {
		let title = null;
		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title,
			"rbc-radio-active": this.props.showRadio,
			"rbc-radio-inactive": !this.props.showRadio
		}, this.props.className);

		return (
			<div className={`rbc rbc-singlerange col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.style}>

					{title}

						{this.renderButtons()}

		);
	}
}

SingleRange.propTypes = {
	componentId: React.PropTypes.string.isRequired,
	dataField: React.PropTypes.string.isRequired,
	data: React.PropTypes.any.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	defaultSelected: React.PropTypes.string,
	customQuery: React.PropTypes.func,
	beforeValueChange: React.PropTypes.func,
	onValueChange: React.PropTypes.func,
	style: React.PropTypes.object,
	showFilter: React.PropTypes.bool,
	filterLabel: React.PropTypes.string,
	onQueryChange: React.PropTypes.func,
	showRadio: React.PropTypes.bool,
	className: React.PropTypes.string
};

// Default props value
SingleRange.defaultProps = {
	title: null,
	style: {},
	showFilter: true,
	showRadio: true
};

// context type
SingleRange.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired,
	reactiveId: React.PropTypes.number
};

SingleRange.types = {
	componentId: TYPES.STRING,
	dataField: TYPES.STRING,
	data: TYPES.OBJECT,
	dataFieldType: TYPES.NUMBER,
	title: TYPES.STRING,
	defaultSelected: TYPES.STRING,
	customQuery: TYPES.FUNCTION,
	style: TYPES.OBJECT,
	showFilter: TYPES.BOOLEAN,
	filterLabel: TYPES.STRING,
	onQueryChange: TYPES.FUNCTION,
	showRadio: TYPES.BOOLEAN,
	className: TYPES.STRING
};
<commit_msg>Update customQuery in SingleRange and fixes #222<commit_after>import React, { Component } from "react";
import classNames from "classnames";
const helper = require("../middleware/helper.js");
import * as TYPES from "../middleware/constants.js";
import _ from "lodash";

export default class SingleRange extends Component {
	constructor(props, context) {
		super(props);
		this.state = {
			selected: null
		};
		this.type = "range";
		this.urlParams = helper.URLParams.get(this.props.componentId);
		this.handleChange = this.handleChange.bind(this);
		this.customQuery = this.customQuery.bind(this);
	}

	// Set query information
	componentWillMount() {
		this.previousQuery = null;	// initial value for onQueryChange
		this.setQueryInfo(this.props);
		this.checkDefault(this.props);
		this.listenFilter();
	}

	componentWillReceiveProps(nextProps) {
		if (this.props.defaultSelected !== nextProps.defaultSelected) {
			this.checkDefault(nextProps);
		}
		if (this.props.showFilter !== nextProps.showFilter || this.props.filterLabel !== nextProps.filterLabel) {
			this.setQueryInfo(nextProps);
			this.handleChange(this.state.selected);
		}
	}

	componentWillUnmount() {
		if(this.filterListener) {
			this.filterListener.remove();
		}
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if(data === this.props.componentId) {
				this.changeValue(null);
			}
		});
	}

	checkDefault(props) {
		this.urlParams = helper.URLParams.get(props.componentId);
		const defaultValue = this.urlParams !== null ? this.urlParams : props.defaultSelected;
		this.changeValue(defaultValue);
	}

	changeValue(defaultValue) {
		if (!_.isEqual(this.defaultSelected, defaultValue)) {
			this.defaultSelected = defaultValue;
			if(this.defaultSelected) {
				const records = this.props.data.filter(record => record.label === this.defaultSelected);
				if (records && records.length) {
					setTimeout(this.handleChange.bind(this, records[0]), 1000);
				}
			} else {
				this.handleChange(null);
			}
		}
	}

	// set the query type and input data
	setQueryInfo(props) {
		const getQuery = (value) => {
			const currentQuery = props.customQuery ? props.customQuery(value) : this.customQuery(value);
			if (this.props.onQueryChange && JSON.stringify(this.previousQuery) !== JSON.stringify(currentQuery)) {
				this.props.onQueryChange(this.previousQuery, currentQuery);
			}
			this.previousQuery = currentQuery;
			return currentQuery;
		};
		const obj = {
			key: props.componentId,
			value: {
				queryType: this.type,
				inputData: props.dataField,
				customQuery: getQuery,
				reactiveId: this.context.reactiveId,
				showFilter: props.showFilter,
				filterLabel: props.filterLabel ? props.filterLabel : props.componentId,
				component: "SingleRange",
				defaultSelected: this.urlParams !== null ? this.urlParams : props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	// build query for this sensor only
	customQuery(record) {
		if (record) {
			return {
				range: {
					[this.props.dataField]: {
						gte: record.start,
						lte: record.end,
						boost: 2.0
					}
				}
			};
		}
		return null;
	}

	// handle the input change and pass the value inside sensor info
	handleChange(record) {
		this.setState({
			selected: record
		});
		const obj = {
			key: this.props.componentId,
			value: record
		};
		this.defaultSelected = record;

		const execQuery = () => {
			const isExecuteQuery = true;
			if (this.props.onValueChange) {
				this.props.onValueChange(obj.value);
			}
			helper.URLParams.update(this.props.componentId, record ? record.label : null, this.props.URLParams);
			helper.selectedSensor.set(obj, isExecuteQuery);
		};

		if (this.props.beforeValueChange) {
			this.props.beforeValueChange(obj.value)
			.then(() => {
				execQuery();
			})
			.catch((e) => {
				console.warn(`${this.props.componentId} - beforeValueChange rejected the promise with`, e);
			});
		} else {
			execQuery();
		}
	}

	renderButtons() {
		let buttons;
		const selectedText = this.state.selected && this.state.selected.label ? this.state.selected.label : "";
		if (this.props.data) {
			buttons = this.props.data.map((record, i) => {
				const cx = classNames({
					"rbc-radio-active": this.props.showRadio,
					"rbc-radio-inactive": !this.props.showRadio,
					"rbc-list-item-active": selectedText === record.label,
					"rbc-list-item-inactive": selectedText !== record.label
				});

				return (
					<div className={`rbc-list-item row ${cx}`} key={i} onClick={() => this.handleChange(record)}>
						<input
							type="radio"
							className="rbc-radio-item"
							checked={selectedText === record.label}
							value={record.label}
						/>
						{record.label}

				);
			});
		}
		return buttons;
	}

	// render
	render() {
		let title = null;
		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title,
			"rbc-radio-active": this.props.showRadio,
			"rbc-radio-inactive": !this.props.showRadio
		}, this.props.className);

		return (
			<div className={`rbc rbc-singlerange col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.style}>

					{title}

						{this.renderButtons()}

		);
	}
}

SingleRange.propTypes = {
	componentId: React.PropTypes.string.isRequired,
	dataField: React.PropTypes.string.isRequired,
	data: React.PropTypes.any.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	defaultSelected: React.PropTypes.string,
	customQuery: React.PropTypes.func,
	beforeValueChange: React.PropTypes.func,
	onValueChange: React.PropTypes.func,
	style: React.PropTypes.object,
	showFilter: React.PropTypes.bool,
	filterLabel: React.PropTypes.string,
	onQueryChange: React.PropTypes.func,
	showRadio: React.PropTypes.bool,
	className: React.PropTypes.string
};

// Default props value
SingleRange.defaultProps = {
	title: null,
	style: {},
	showFilter: true,
	showRadio: true
};

// context type
SingleRange.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired,
	reactiveId: React.PropTypes.number
};

SingleRange.types = {
	componentId: TYPES.STRING,
	dataField: TYPES.STRING,
	data: TYPES.OBJECT,
	dataFieldType: TYPES.NUMBER,
	title: TYPES.STRING,
	defaultSelected: TYPES.STRING,
	customQuery: TYPES.FUNCTION,
	style: TYPES.OBJECT,
	showFilter: TYPES.BOOLEAN,
	filterLabel: TYPES.STRING,
	onQueryChange: TYPES.FUNCTION,
	showRadio: TYPES.BOOLEAN,
	className: TYPES.STRING
};
<|endoftext|>


<commit_before>var Arkansas = require('./')
  , Model = require('./model')
  , utils = require('./utils')

var Fragment = module.exports = function(id, template, context) {
  this.id = id
  this.template = template
  this.context = context
  this.children = []
  this.parent = null
}

utils.eventify(Fragment)
require('./implode').register('Fragment', Fragment, ['id', 'template', 'context', 'events', 'parent', 'children'])

Fragment.prototype.observe = function(model, property) {
  if (this.silent) return
  var event = 'changed' + (property ? '.' + property : '')
  model.on(event, this, 'refresh')
  this.once('delete', model, 'off', model, event, this)
}

Fragment.prototype.render = function() {
  this.template.fn.fragment = this
  return this.template.fn(this.context)
}

Fragment.queue = []
Fragment.queue.push = function(fragment) {
  Array.prototype.push.call(Fragment.queue, fragment)
}
Fragment.refresh = function() {
  if (Fragment.queue.length === 0) return
  var fragment
  while ((fragment = Fragment.queue.shift()))
    fragment.refresh(true)
}

Fragment.prototype.refresh = function(force) {
  if (utils.isServer) return
  if (!force && Fragment.queue.indexOf(this) === -1) {
    Fragment.queue.push(this)
    setTimeout(Fragment.refresh)
    return
  }
  utils.debug('[Fragment] #%s refreshing', this.id)
  var that = this
  // delete Contents
  this.deleteContents()
  // initialize DOMFragment and an empty DIV
  var DOMFragment = document.createDocumentFragment()
    , tmp = document.createElement('div')
    , child
  // render the fragment into the DIV
  tmp.innerHTML = this.render()
  // to transfer its content to the DOMFragment afterwards
  while ((child = tmp.firstChild)) {
    DOMFragment.appendChild(child)
  }
  // traverse the Fragment to assign the start and end
  // comments to their corresponding fragments
  utils.aquireFragments(DOMFragment, window.app.fragments)
  // insert into the DOM
  this.endNode.parentNode.insertBefore(DOMFragment, this.endNode)
}

Fragment.prototype.remove = function(child) {
  var pos
  if ((pos = this.children.indexOf(child)) > -1) {
    this.children.splice(pos, 1)
  }
}

Fragment.prototype.insert = function(context, index) {
  var fragment = new Fragment(42, this.template, context)

  context.once('destroy', fragment, 'delete')
  fragment.once('delete', context, 'off', context, 'destroy', fragment)

  context.once('removed', fragment, 'delete')
  fragment.once('delete', context, 'off', context, 'removed', fragment)

  fragment.once('delete', this, 'remove', this, fragment)

  // context.on('moved', this, 'moveChild', this, fragment)
  // fragment.once('delete', context, 'off', context, 'moved', this)

  this.on('delete', fragment, 'dispose')
  fragment.once('delete', this, 'off', this, 'delete', fragment)

  this.on('deleteContents', fragment, 'dispose')
  fragment.once('delete', this, 'off', this, 'deleteContents', fragment)

  if (index === undefined)
    index = this.children.length

  var anchor
  if (utils.isBrowser) {
    if (index === 0 || index === this.children.length)
      anchor = this.endNode
    else
      anchor = this.children[index].startNode
  }

  this.children.splice(index, 0, fragment)

  if (!utils.isBrowser) return fragment

  fragment.startNode = document.createComment('-{')
  fragment.endNode = document.createComment('-}')

  anchor.parentNode.insertBefore(fragment.startNode, anchor)
  anchor.parentNode.insertBefore(fragment.endNode, anchor)

  fragment.refresh()

  return fragment
}

Fragment.prototype.deleteContents = function() {
  // emit delete event to get child fragments to delete themselfs
  this.emit('deleteContents')

  // remove DOMNodes between the fragments
  // start and end markers
  var node, next = this.startNode.nextSibling
  while ((node = next) !== this.endNode) {
    next = node.nextSibling
    node.parentNode.removeChild(node)
  }
}

Fragment.prototype.delete = function() {
  this.emit('delete')
  this.deleteContents()
  this.dispose()
}

Fragment.prototype.dispose = function() {
  this.emit('delete')

  this.removeAllListeners()

  // remove start and end markers
  this.startNode.parentNode.removeChild(this.startNode)
  this.endNode.parentNode.removeChild(this.endNode)

  // delete reference to removed nodes
  delete this.startNode
  delete this.endNode

  // remove from fragments registry
  var index
  if ((index = window.app.fragments.indexOf(this)) > -1) {
    window.app.fragments.splice(index, 1)
  }

  // remove from queue
  if ((index = Fragment.queue.indexOf(this)) > -1) {
    Fragment.queue.splice(index, 1)
  }
}<commit_msg>fix fragment#render to support tr and td fragments<commit_after>var Arkansas = require('./')
  , Model = require('./model')
  , utils = require('./utils')

var Fragment = module.exports = function(id, template, context) {
  this.id = id
  this.template = template
  this.context = context
  this.children = []
  this.parent = null
}

utils.eventify(Fragment)
require('./implode').register('Fragment', Fragment, ['id', 'template', 'context', 'events', 'parent', 'children'])

Fragment.prototype.observe = function(model, property) {
  if (this.silent) return
  var event = 'changed' + (property ? '.' + property : '')
  model.on(event, this, 'refresh')
  this.once('delete', model, 'off', model, event, this)
}

Fragment.prototype.render = function() {
  this.template.fn.fragment = this
  return this.template.fn(this.context)
}

Fragment.queue = []
Fragment.queue.push = function(fragment) {
  Array.prototype.push.call(Fragment.queue, fragment)
}
Fragment.refresh = function() {
  if (Fragment.queue.length === 0) return
  var fragment
  while ((fragment = Fragment.queue.shift()))
    fragment.refresh(true)
}

Fragment.prototype.refresh = function(force) {
  if (utils.isServer) return
  if (!force && Fragment.queue.indexOf(this) === -1) {
    Fragment.queue.push(this)
    setTimeout(Fragment.refresh)
    return
  }
  utils.debug('[Fragment] #%s refreshing', this.id)
  var that = this
  // delete Contents
  this.deleteContents()
  // initialize DOMFragment and an empty DIV
  var DOMFragment = document.createDocumentFragment()
  // render the fragment
  var rendered = this.render()
    , reg = rendered.match(/^[^<]*<([a-z]+)/i)
    , tmp, child
  switch (reg[1]) {
    case 'tr': tmp = document.createElement('tbody'); break
    case 'td': tmp = document.createElement('tr'); break
    default: tmp = document.createElement('div')
  }
  tmp.innerHTML = rendered
  // to transfer its content to the DOMFragment afterwards
  while ((child = tmp.firstChild)) {
    DOMFragment.appendChild(child)
  }
  // traverse the Fragment to assign the start and end
  // comments to their corresponding fragments
  utils.aquireFragments(DOMFragment, window.app.fragments)
  // insert into the DOM
  this.endNode.parentNode.insertBefore(DOMFragment, this.endNode)
}

Fragment.prototype.remove = function(child) {
  var pos
  if ((pos = this.children.indexOf(child)) > -1) {
    this.children.splice(pos, 1)
  }
}

Fragment.prototype.insert = function(context, index) {
  var fragment = new Fragment(42, this.template, context)

  context.once('destroy', fragment, 'delete')
  fragment.once('delete', context, 'off', context, 'destroy', fragment)

  context.once('removed', fragment, 'delete')
  fragment.once('delete', context, 'off', context, 'removed', fragment)

  fragment.once('delete', this, 'remove', this, fragment)

  // context.on('moved', this, 'moveChild', this, fragment)
  // fragment.once('delete', context, 'off', context, 'moved', this)

  this.on('delete', fragment, 'dispose')
  fragment.once('delete', this, 'off', this, 'delete', fragment)

  this.on('deleteContents', fragment, 'dispose')
  fragment.once('delete', this, 'off', this, 'deleteContents', fragment)

  if (index === undefined)
    index = this.children.length

  var anchor
  if (utils.isBrowser) {
    if (index === 0 || index === this.children.length)
      anchor = this.endNode
    else
      anchor = this.children[index].startNode
  }

  this.children.splice(index, 0, fragment)

  if (!utils.isBrowser) return fragment

  fragment.startNode = document.createComment('-{')
  fragment.endNode = document.createComment('-}')

  anchor.parentNode.insertBefore(fragment.startNode, anchor)
  anchor.parentNode.insertBefore(fragment.endNode, anchor)

  fragment.refresh()

  return fragment
}

Fragment.prototype.deleteContents = function() {
  // emit delete event to get child fragments to delete themselfs
  this.emit('deleteContents')

  // remove DOMNodes between the fragments
  // start and end markers
  var node, next = this.startNode.nextSibling
  while ((node = next) !== this.endNode) {
    next = node.nextSibling
    node.parentNode.removeChild(node)
  }
}

Fragment.prototype.delete = function() {
  this.emit('delete')
  this.deleteContents()
  this.dispose()
}

Fragment.prototype.dispose = function() {
  this.emit('delete')

  this.removeAllListeners()

  // remove start and end markers
  this.startNode.parentNode.removeChild(this.startNode)
  this.endNode.parentNode.removeChild(this.endNode)

  // delete reference to removed nodes
  delete this.startNode
  delete this.endNode

  // remove from fragments registry
  var index
  if ((index = window.app.fragments.indexOf(this)) > -1) {
    window.app.fragments.splice(index, 1)
  }

  // remove from queue
  if ((index = Fragment.queue.indexOf(this)) > -1) {
    Fragment.queue.splice(index, 1)
  }
}<|endoftext|>


<commit_before>import { connect } from 'react-redux'
import { increment, doubleAsync } from '../modules/counter'

/*  This is a container component. Notice it does not contain any JSX,
    nor does it import React. This component is **only** responsible for
    wiring in the actions and state necessary to render a presentational
    component - in this case, the counter:   */

import Counter from '../components/Counter'

/*  Object of action creators (can also be function that returns object).
    Keys will be passed as props to presentational components. Here we are
    implementing our wrapper around increment; the component doesn't care   */

const mapDispatchToProps = {
  increment: () => increment(1),
  doubleAsync,
}

const mapStateToProps = state => ({
  counter: state.counter,
})

/*  Note: mapStateToProps is where you should use `reselect` to create selectors, ie:

    import { createSelector } from 'reselect'
    const counter = (state) => state.counter
    const tripleCount = createSelector(counter, (count) => count * 3)
    const mapStateToProps = (state) => ({
      counter: tripleCount(state)
    })

    Selectors can compute derived data, allowing Redux to store the minimal possible state.
    Selectors are efficient. A selector is not recomputed unless one of its arguments change.
    Selectors are composable. They can be used as input to other selectors.
    https://github.com/reactjs/reselect    */

export default connect(mapStateToProps, mapDispatchToProps)(Counter)
<commit_msg>bugfix: mapStateToProps<commit_after>import { connect } from 'react-redux'
import { increment, doubleAsync } from '../modules/counter'

/*  This is a container component. Notice it does not contain any JSX,
    nor does it import React. This component is **only** responsible for
    wiring in the actions and state necessary to render a presentational
    component - in this case, the counter:   */

import Counter from '../components/Counter'

/*  Object of action creators (can also be function that returns object).
    Keys will be passed as props to presentational components. Here we are
    implementing our wrapper around increment; the component doesn't care   */

const mapDispatchToProps = {
  increment: () => increment(1),
  doubleAsync,
}

const mapStateToProps = state => ({
  counter: state.get('counter'),
})

/*  Note: mapStateToProps is where you should use `reselect` to create selectors, ie:

    import { createSelector } from 'reselect'
    const counter = (state) => state.counter
    const tripleCount = createSelector(counter, (count) => count * 3)
    const mapStateToProps = (state) => ({
      counter: tripleCount(state)
    })

    Selectors can compute derived data, allowing Redux to store the minimal possible state.
    Selectors are efficient. A selector is not recomputed unless one of its arguments change.
    Selectors are composable. They can be used as input to other selectors.
    https://github.com/reactjs/reselect    */

export default connect(mapStateToProps, mapDispatchToProps)(Counter)
<|endoftext|>