<commit_before>//IMPORTS
var Twit = require("twit");
var timer = require("timer");
var mongodb = require("mongodb");
var Geode =require('geode');
var conf = require('./config');
var util = require('util')
var io = require('socket.io').listen(conf.sockets.port-1); // temp for test

//TODO:
//-test socket
//-save noise to database
//-save number of tweets we can still send the next 15 min in database

//Variables
var numTweets=0;
var geo = new Geode('watchFire', {language: 'en', country : 'US'});

//Tweet class definition
function Tweet(user, text, coordinates) {
    this.user = user;
    this.text = text;
    this.coordinates = coordinates;
}

//Open socket for receiving data
io.configure(function(){
   io.set('resource','tweets');
});

io.sockets.on('connection', function (mysocket) {
	  mysocket.on('fire', function (data) {
		  console.log(data);
	  });
});

module.exports = function(con, bd, twit) {

	//Twitter credentials
   var T = new Twit(twit["watchFireZar"]);

   //City properties
   function City(area, coordinates, countryCode) {
      this.coordinates = coordinates
      this.noise = 0;
      this.area = area;
      this.tweets = [];
      this.countryCode=countryCode;
   }
   //Extract cities from hotspots
   function citiesFromHotspots(cities,hotspots){
	   var keys = Object.keys(hotspots);
	   var tasksToGo = keys.length;
	   if (tasksToGo === 0){
		   openTwitterStream(cities);
	   }else{
	   		keys.forEach(function(key){
	   			var p = hotspots[key];
	   			geo.findNearby({lat:p.coordinates.coordinates[1],lng:p.coordinates.coordinates[0]}, function(err, results){
	   	          	if (err) { console.log(err); return; }
	   		        var name = results.geonames[0].name;
	   		        console.log("City " + name +" "+results.geonames[0].countryCode+" " + " ["+p.coordinates.coordinates+"]...");
	   		        cities[name] = new City(round(p.coordinates.coordinates), p.coordinates, results.geonames[0].countryCode);
	   		        if(--tasksToGo === 0){
	   		           openTwitterStream(cities);
	   		        }
	   	        });
	   		});
	   }
   }
   //Open twitter stream
   function openTwitterStream(cities){
	   console.log("cities: "+Object.keys(cities).length);
       var watchSymbols="";
       var tweet;
       var wordsForFire=[];
       for (var city in cities) {
    	   	if (cities[city].countryCode in conf.keywords){//verify we know translations of fire for this country
    	   		wordsForFire = conf.keywords[cities[city].countryCode];
    	   	}else{//else use "fire"
    	   		wordsForFire = ["fire"];
    	   	}
       		for (var i = 0; i < wordsForFire.length; i++) {
       			symbol=wordsForFire[i]+" "+city
       			watchSymbols+=symbol+",";//',' as or ' ' as and
       			numTweets++;
       			if(numTweets<150){
       		       T.get('search/tweets', { q: symbol, count: 100 }, function(err, reply) {
       		    	   if (err) { console.log(err); return; }
       		    	   for (var j = 0; j < reply.statuses.length; j++) {
       		    		   if(reply.statuses[j].coordinates===null){//if the tweet doesn't come with coordinates, set city coordinates
       		    			   tweet = new Tweet(reply.statuses[j].user.screen_name,reply.statuses[j].text,cities[city].coordinates);
       		    		   }else{
       		    			   tweet = new Tweet(reply.statuses[j].user.screen_name,reply.statuses[j].text,reply.statuses[j].coordinates);
       		    		   }
       		    		   cities[city].tweets.push(tweet);
       		    		   io.sockets.emit('tweet', tweet);
       		    		   console.log(util.inspect(tweet));
       		    		   cities[city].noise++;
       		    	   }
       		       })
       			}
       		}
      }
       console.log("watchSymbols:"+watchSymbols);
       this.stream = T.stream("statuses/filter", {track: watchSymbols});
       this.stream.on("tweet", function(t) {
    	   console.log(t.text);
    	   for (var city in cities) {
   				if (t.text.toLowerCase().indexOf(city.toLowerCase()) !== -1) {
   					if(t.coordinates===null){//if the tweet doesn't come with coordinates, set city coordinates
		    			   tweet = new Tweet(t.user.screen_name,t.text,cities[city].coordinates);
		    		   }else{
		    			   tweet = new Tweet(t.user.screen_name,t.text,t.coordinates);
		    		   }
   					cities[city].tweets.push(tweet);
   					io.sockets.emit('tweet', tweet);
   					console.log(util.inspect(tweet));
   					cities[city].noise++; //noise in the city
   					break;
   				}
   			}
       });
   }

   //Update noise to database
   var notify = function(coord, noise) {
//	   FIXME:
//      new mongodb.Collection(con, bd.HOT_SPOTS).update({coordenadas:coord}, {$inc:{noise: noise}});
   }

   //Starts watching twitter
   //Checks noise
   var checkNoise = function(cities) {
//	  openTwitterStream(cities);
      console.log("  checking noise...")
      for (var i in cities) {
         if (cities[i].noise > 5) {
            console.log("  ALERT ["+cities[i].noise+"] on "+util.inspect(cities[i].coordinates));
            notify(cities[i].coordinates, cities[i].noise);
         }
      }
   }
   var resetNumTweets = function(){
	   numTweets=0;
   }
   //Create a surface from coordinates
   var round = function(coords) {
      var c = 0.5;
      return [Math.floor(coords[0]*10)/10-c, Math.floor(coords[1]*10)/10-c, Math.floor(coords[0]*10)/10+c, Math.floor(coords[0]*10)/10+c];
   }

   //Return object
   return {
      cities : {},
      init : function(hotspots) {
         console.log("init twitta");
         var that = this;
         this.destroy();
         citiesFromHotspots (that.cities,hotspots);
         this.checker = setInterval(checkNoise, 20000, that.cities);
         this.tweetLimiter = setInterval(resetNumTweets,15000);//Periodically reset number of tweets we can send
      },
      destroy : function() {
         //Clear structures
         clearInterval(this.checker);
         if (this.stream) this.stream.close();
      },
      checker : null,
      stream : null
   }

}
<commit_msg>forget to add<commit_after>//IMPORTS
var Twit = require("twit");
var timer = require("timer");
var mongodb = require("mongodb");
var Geode =require('geode');
var conf = require('./config');
var util = require('util')
var io = require('socket.io').listen(conf.sockets.port-1); // temp for test

//TODO:
//-test socket
//-save noise to database
//-save number of tweets we can still send the next 15 min in database

//Variables
var numTweets=0;
var geo = new Geode('watchFire', {language: 'en', country : 'US'});

//Tweet class definition
function Tweet(user, text, coordinates) {
    this.user = user;
    this.text = text;
    this.coordinates = coordinates;
}

//Open socket for receiving data
io.configure(function(){
   io.set('resource','/tweets');
});

io.on('connection', function (client) {
	  client.on('fire', function (data) {
		  console.log(data);
	  });
});

module.exports = function(con, bd, twit) {

	//Twitter credentials
   var T = new Twit(twit["watchFireZar"]);

   //City properties
   function City(area, coordinates, countryCode) {
      this.coordinates = coordinates
      this.noise = 0;
      this.area = area;
      this.tweets = [];
      this.countryCode=countryCode;
   }
   //Extract cities from hotspots
   function citiesFromHotspots(cities,hotspots){
	   var keys = Object.keys(hotspots);
	   var tasksToGo = keys.length;
	   if (tasksToGo === 0){
		   openTwitterStream(cities);
	   }else{
	   		keys.forEach(function(key){
	   			var p = hotspots[key];
	   			geo.findNearby({lat:p.coordinates.coordinates[1],lng:p.coordinates.coordinates[0]}, function(err, results){
	   	          	if (err) { console.log(err); return; }
	   		        var name = results.geonames[0].name;
	   		        console.log("City " + name +" "+results.geonames[0].countryCode+" " + " ["+p.coordinates.coordinates+"]...");
	   		        cities[name] = new City(round(p.coordinates.coordinates), p.coordinates, results.geonames[0].countryCode);
	   		        if(--tasksToGo === 0){
	   		           openTwitterStream(cities);
	   		        }
	   	        });
	   		});
	   }
   }
   //Open twitter stream
   function openTwitterStream(cities){
	   console.log("cities: "+Object.keys(cities).length);
       var watchSymbols="";
       var tweet;
       var wordsForFire=[];
       for (var city in cities) {
    	   	if (cities[city].countryCode in conf.keywords){//verify we know translations of fire for this country
    	   		wordsForFire = conf.keywords[cities[city].countryCode];
    	   	}else{//else use "fire"
    	   		wordsForFire = ["fire"];
    	   	}
       		for (var i = 0; i < wordsForFire.length; i++) {
       			symbol=wordsForFire[i]+" "+city
       			watchSymbols+=symbol+",";//',' as or ' ' as and
       			numTweets++;
       			if(numTweets<150){
       		       T.get('search/tweets', { q: symbol, count: 100 }, function(err, reply) {
       		    	   if (err) { console.log(err); return; }
       		    	   for (var j = 0; j < reply.statuses.length; j++) {
       		    		   if(reply.statuses[j].coordinates===null){//if the tweet doesn't come with coordinates, set city coordinates
       		    			   tweet = new Tweet(reply.statuses[j].user.screen_name,reply.statuses[j].text,cities[city].coordinates);
       		    		   }else{
       		    			   tweet = new Tweet(reply.statuses[j].user.screen_name,reply.statuses[j].text,reply.statuses[j].coordinates);
       		    		   }
       		    		   cities[city].tweets.push(tweet);
       		    		   io.sockets.emit('tweet', tweet);
       		    		   console.log(util.inspect(tweet));
       		    		   cities[city].noise++;
       		    	   }
       		       })
       			}
       		}
      }
       console.log("watchSymbols:"+watchSymbols);
       this.stream = T.stream("statuses/filter", {track: watchSymbols});
       this.stream.on("tweet", function(t) {
    	   console.log(t.text);
    	   for (var city in cities) {
   				if (t.text.toLowerCase().indexOf(city.toLowerCase()) !== -1) {
   					if(t.coordinates===null){//if the tweet doesn't come with coordinates, set city coordinates
		    			   tweet = new Tweet(t.user.screen_name,t.text,cities[city].coordinates);
		    		   }else{
		    			   tweet = new Tweet(t.user.screen_name,t.text,t.coordinates);
		    		   }
   					cities[city].tweets.push(tweet);
   					io.sockets.emit('tweet', tweet);
   					console.log(util.inspect(tweet));
   					cities[city].noise++; //noise in the city
   					break;
   				}
   			}
       });
   }

   //Update noise to database
   var notify = function(coord, noise) {
//	   FIXME:
//      new mongodb.Collection(con, bd.HOT_SPOTS).update({coordenadas:coord}, {$inc:{noise: noise}});
   }

   //Starts watching twitter
   //Checks noise
   var checkNoise = function(cities) {
//	  openTwitterStream(cities);
      console.log("  checking noise...")
      for (var i in cities) {
         if (cities[i].noise > 5) {
            console.log("  ALERT ["+cities[i].noise+"] on "+util.inspect(cities[i].coordinates));
            notify(cities[i].coordinates, cities[i].noise);
         }
      }
   }
   var resetNumTweets = function(){
	   numTweets=0;
   }
   //Create a surface from coordinates
   var round = function(coords) {
      var c = 0.5;
      return [Math.floor(coords[0]*10)/10-c, Math.floor(coords[1]*10)/10-c, Math.floor(coords[0]*10)/10+c, Math.floor(coords[0]*10)/10+c];
   }

   //Return object
   return {
      cities : {},
      init : function(hotspots) {
         console.log("init twitta");
         var that = this;
         this.destroy();
         citiesFromHotspots (that.cities,hotspots);
         this.checker = setInterval(checkNoise, 20000, that.cities);
         this.tweetLimiter = setInterval(resetNumTweets,15000);//Periodically reset number of tweets we can send
      },
      destroy : function() {
         //Clear structures
         clearInterval(this.checker);
         if (this.stream) this.stream.close();
      },
      checker : null,
      stream : null
   }

}
<|endoftext|>


<commit_before>/**
 * Created by suman on 08/05/16.
 */

var core = require('chanakya');
var _ = require('lodash');
var Q = require('q'),
  http = require('http');
var rp = require('request-promise');

core.response('fail', function (to) {
  return {
    text: `I am sorry ${to.first_name}, I am unable to understand what you mean. Please rephrase and send back.`
  };
});

core.response('balance', function (to) {

  console.log(to);

  var deferred = Q.defer();

  var options = {
    uri: `https://polar-atoll-33216.herokuapp.com/users/1`,
    headers: {
      'Authorization': 'Bearer LUPCP5OOAFQXURYOH7I7YVU4FGBGVAG3',
      'Accept': 'application/vnd.wit.20141022+json'
    },
    json: true // Automatically parses the JSON string in the response
  };

  rp(options)
    .then(function (res) {
      deferred.resolve({
        text: `Your balance is =${res.currency}${res.balance}`
      });
    })
    .catch(function (err) {
      console.error(err);
    });
  return deferred.promise;
}, 'statement');

core.response('creditcard', function (to) {
  return {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
          {
            "title":"NBA American Express Card",
            "image_url":"https://s3.amazonaws.com/facebookbot/NBA+American+Express+Card.png",
            "subtitle":"9.49% to 29.49% variable APR based on your creditworthiness",
            "buttons":[
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/customer-service/find-location.htm",
                "title":"Apply for this card"
              },
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm",
                "title":"View Details",
              },
              {
                "title":"View APR, Terms & Fees",
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm",
              }
            ]
          },
          {
            "title":"Clearpoints Credit Card",
            "image_url":"https://s3.amazonaws.com/facebookbot/Clearpoints+Credit+Card.png",
            "subtitle":"9.49% to 23.49% variable APR based on your creditworthiness",
            "buttons":[
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/customer-service/find-location.htm",
                "title":"Apply for this card"
              },
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm",
                "title":"View Details",
              },
              {
                "title":"View APR, Terms & Fees",
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm",
              }
            ]
          },
          {
            "title":"Select Credit Card",
            "image_url":"https://s3.amazonaws.com/facebookbot/Select+Credit+Card.png",
            "subtitle":"1.49% to 17.49% variable APR based on your creditworthiness",
            "buttons":[
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/customer-service/find-location.htm",
                "title":"Apply for this card"
              },
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm",
                "title":"View Details",
              },
              {
                "title":"View APR, Terms & Fees",
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm",
              }
            ]
          }
        ]
      }
    }
  };
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token:token},
    method: 'POST',
    json: {
      recipient: {id:sender},
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending message: ', error);
    } else if (response.body.error) {
      console.log('Error: ', response.body.error);
    }
  });
});
core.response('payment', function (to) {
  return {
      "attachment":{
        "type":"template",
        "payload":{
          "template_type":"generic",
          "elements":[
            {
              "title":"Please see your credit card statement below.",
              "image_url": "https://s3.amazonaws.com/facebookbot/creditcard.png",
              "buttons":[
                {
                  "type":"web_url",
                  "url":"https://www.billdesk.com/pgidsk/pgmerc/amexcard/amex_card.jsp",
                  "title":"Pay minimum payment due"
                },
                {
                  "type":"web_url",
                  "url":"https://www.billdesk.com/pgidsk/pgmerc/amexcard/amex_card.jsp",
                  "title":"Pay outstanding balance",
                },
                {
                  "title":"Increase credit limit",
                  "type":"web_url",
                  "url":"https://www.americanexpress.com/in/content/credit-know-how/credit-card-limits/",
                }
              ]
            }
          ]
        }
      }
    };
  });
<commit_msg>updated .gitignore<commit_after>/**
 * Created by suman on 08/05/16.
 */

var core = require('chanakya');
var _ = require('lodash');
var Q = require('q'),
  http = require('http');
var rp = require('request-promise');

core.response('fail', function (to) {
  return {
    text: `I am sorry ${to.first_name}, I am unable to understand what you meant. Please rephrase and send back.`
  };
});

core.response('balance', function (to) {

  console.log(to);

  var deferred = Q.defer();

  var options = {
    uri: `https://polar-atoll-33216.herokuapp.com/users/1`,
    headers: {
      'Authorization': 'Bearer LUPCP5OOAFQXURYOH7I7YVU4FGBGVAG3',
      'Accept': 'application/vnd.wit.20141022+json'
    },
    json: true // Automatically parses the JSON string in the response
  };

  rp(options)
    .then(function (res) {
      deferred.resolve({
        text: `Your balance is =${res.currency}${res.balance}`
      });
    })
    .catch(function (err) {
      console.error(err);
    });
  return deferred.promise;
}, 'statement');

core.response('creditcard', function (to) {
  return {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
          {
            "title":"NBA American Express Card",
            "image_url":"https://s3.amazonaws.com/facebookbot/NBA+American+Express+Card.png",
            "subtitle":"9.49% to 29.49% variable APR based on your creditworthiness",
            "buttons":[
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/customer-service/find-location.htm",
                "title":"Apply for this card"
              },
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm",
                "title":"View Details",
              },
              {
                "title":"View APR, Terms & Fees",
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm",
              }
            ]
          },
          {
            "title":"Clearpoints Credit Card",
            "image_url":"https://s3.amazonaws.com/facebookbot/Clearpoints+Credit+Card.png",
            "subtitle":"9.49% to 23.49% variable APR based on your creditworthiness",
            "buttons":[
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/customer-service/find-location.htm",
                "title":"Apply for this card"
              },
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm",
                "title":"View Details",
              },
              {
                "title":"View APR, Terms & Fees",
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm",
              }
            ]
          },
          {
            "title":"Select Credit Card",
            "image_url":"https://s3.amazonaws.com/facebookbot/Select+Credit+Card.png",
            "subtitle":"1.49% to 17.49% variable APR based on your creditworthiness",
            "buttons":[
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/customer-service/find-location.htm",
                "title":"Apply for this card"
              },
              {
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm",
                "title":"View Details",
              },
              {
                "title":"View APR, Terms & Fees",
                "type":"web_url",
                "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm",
              }
            ]
          }
        ]
      }
    }
  };
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token:token},
    method: 'POST',
    json: {
      recipient: {id:sender},
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending message: ', error);
    } else if (response.body.error) {
      console.log('Error: ', response.body.error);
    }
  });
});
core.response('payment', function (to) {
  return {
      "attachment":{
        "type":"template",
        "payload":{
          "template_type":"generic",
          "elements":[
            {
              "title":"Please see your credit card statement below.",
              "image_url": "https://s3.amazonaws.com/facebookbot/creditcard.png",
              "buttons":[
                {
                  "type":"web_url",
                  "url":"https://www.billdesk.com/pgidsk/pgmerc/amexcard/amex_card.jsp",
                  "title":"Pay minimum payment due"
                },
                {
                  "type":"web_url",
                  "url":"https://www.billdesk.com/pgidsk/pgmerc/amexcard/amex_card.jsp",
                  "title":"Pay outstanding balance",
                },
                {
                  "title":"Increase credit limit",
                  "type":"web_url",
                  "url":"https://www.americanexpress.com/in/content/credit-know-how/credit-card-limits/",
                }
              ]
            }
          ]
        }
      }
    };
  });
<|endoftext|>


<commit_before>/**
 * Battery API test
 *
 * @author Jeroen Desloovere <jeroen@siesqo.be>
 */
batteryAPITest =
{
	init: function()
	{
		if(jsFrontendBatteryAPI.isSupported())
		{
			// test some properties
			console.warn("Battery charging: ", jsFrontendBatteryAPI.isCharging()); // true
			console.warn("Battery level: ", jsFrontendBatteryAPI.getLevel()); // 0.58
			console.warn("Battery discharging time: ", jsFrontendBatteryAPI.getDischargingTime());

			// bind event for charging change
			battery.addEventListener("chargingchange", function(e)
			{
				console.warn("Battery charge change: ", jsFrontendBatteryAPI.isCharging());
			}, false);

			// bind event for charging time change
			battery.addEventListener("chargingtimechange", function(e)
			{
				console.warn("Battery charge time change: ", jsFrontendBatteryAPI.getChargingTime());
			}, false);

			// bind event for discharging time change
			battery.addEventListener("dischargingtimechange", function(e)
			{
				console.warn("Battery discharging time change: ", jsFrontendBatteryAPI.getDischargingTime());
			}, false);

			// bind event for battery level change
			battery.addEventListener("levelchange", function(e)
			{
				console.warn("Battery level change: ", jsFrontendBatteryAPI.getLevel());
			}, false);
		}
		else
		{
			console.warn('Can\'t use Battery API');
		}
	}
}

$(batteryAPITest.init);
<commit_msg>Renamed class in test<commit_after>/**
 * Battery API test
 *
 * @author Jeroen Desloovere <jeroen@siesqo.be>
 */
batteryAPITest =
{
	init: function()
	{
		if(batteryAPI.isSupported())
		{
			// test some properties
			console.warn("Battery charging: ", batteryAPI.isCharging()); // true
			console.warn("Battery level: ", batteryAPI.getLevel()); // 0.58
			console.warn("Battery discharging time: ", batteryAPI.getDischargingTime());

			// bind event for charging change
			battery.addEventListener("chargingchange", function(e)
			{
				console.warn("Battery charge change: ", batteryAPI.isCharging());
			}, false);

			// bind event for charging time change
			battery.addEventListener("chargingtimechange", function(e)
			{
				console.warn("Battery charge time change: ", batteryAPI.getChargingTime());
			}, false);

			// bind event for discharging time change
			battery.addEventListener("dischargingtimechange", function(e)
			{
				console.warn("Battery discharging time change: ", batteryAPI.getDischargingTime());
			}, false);

			// bind event for battery level change
			battery.addEventListener("levelchange", function(e)
			{
				console.warn("Battery level change: ", batteryAPI.getLevel());
			}, false);
		}
		else
		{
			console.warn('Can\'t use Battery API');
		}
	}
}

$(batteryAPITest.init);
<|endoftext|>


<commit_before>// http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

var rctk = rctk || {};

rctk.core = (function($) {
    /*
     * Private state
     */
    var not_defined = function(msg) { alert(msg); };
    var request_count = 0;
    var poll = false;
    var interval = 1000;
    var debug = false;
    var crashed = false;

    var handlers = {
        request: function(path, callback, sessionid, data) {
            not_defined("Request function not set -> " + path);
        },
        handle: function(task) {
            not_defined("Handle function not set -> " + task);
        },
        construct: function(class, parent, id) {
            not_defined("Construct function not set");
        },
        dump: function(data, debug) {
            // invoked to dump a debug stacktrace
            alert(data);
        },
        busy: function() {
            // invoked when we're waiting for data
            // add a delay XXX
            // setTimeout(function(if request_count...) {}, 1000);
            $("body").css("cursor", "progress");
        },
        idle: function() {
            // invoked when we're idle / not waiting for data
            $("body").css("cursor", "auto");
        }
    };

    var queue = [];
    var controls = {};
    var busy = [];

    return {
        sid: null,

        handlers: handlers,

        run: function(root) {
            controls[0] = root;
            handlers.request("start", rctk.util.proxy(this.start, this));
        },
        start: function(sessionid, data) {
            sid = sessionid;
            if(jQuery.isArray(data) && 'crash' in data[0] && data[0].crash) {
              // pass true for debug, since we've never actually received
              // a configuration
              handlers.dump(data[0], true);
              return;
            }
            if('config' in data) {
                var config = data.config;

                if('polling' in config) {
                    if(config.polling) {
                        poll = true;
                        interval = config.polling;
                        polltimer = setInterval(rctk.util.proxy(this.get_tasks, this), interval)
                    }
                    else {
                        poll = false;
                    }
                }
                if('debug' in config) {
                    debug = config.debug;
                }
                if('title' in config) {
                      // fails on IE8, argh!
                      //$("title").html(config.title);
                      document.title = config.title || '';
                }
            }
            this.get_tasks();
        },
        get_tasks: function() {
            request_count++;
            handlers.busy();
            handlers.request("pop",
                             rctk.util.proxy(this.handle_tasks, this), sid);
        },
        push: function(task) {
            queue.push(task);
        },
        flush: function() {
            if(queue.length > 0) {
                handlers.busy();
                handlers.request("task",
                                 rctk.util.proxy(this.handle_tasks, this),
                                 sid, "queue="+JSON.stringify(queue));
                queue = [];
            }
        },
        handle_tasks: function(sessionid, data) {
            request_count--;
            if(request_count == 0) {
                handlers.idle();
            }
            if(data) {
                for(var i=0; i < data.length; i++) {
                    this.handle_task(data[i]);
                }
            }
            // everything that was marked busy is no longer busy anymore
            for(var i in busy) {
                var c = busy[i];
                rctk.util.log("Control no longer busy", c);
                c.busy = false;
            }

            busy = [];
            this.flush();
        },
        handle_task: function(data) {
            var id = data.id;

            if(crashed) {
                return;
            }
            rctk.util.log("Action: " + data.action);
            rctk.util.log(data);
            switch(data.action) {
            case "append":
                var container = controls[id];
                var child = controls[data.child];
                container.append(child, data);
                break;
            case "remove":
                var container = controls[id];
                var child = controls[data.child];
                container.remove(child, data);
                break;
            case "create":
                var parent = controls[data.parentid];
                c = handlers.construct(data.control, parent, id);
                c.create(data);
                controls[id] = c;
                break;
            case "destroy":
                var control = controls[id];
                control.destroy();
                controls[id] = null;
                break;
            case "update":
                var control = controls[id];
                control.set_properties(data.update);
                break;
            case "call":
                var control = controls[id];
                var method = data.method;
                var args = data.args || [];
                control[method].apply(control, args);
                control.set_properties(data.update);
                break;
            case "handler":
                var control = controls[id];
                control["handle_"+data.type] = true;
                break;
            case "layout":
                var container = controls[id];
                container.setLayout(data.type, data.config);
                break;
            case "relayout":
                var container = controls[id];
                rctk.util.log("relayout", container);
                container.relayout(data.config);
                break;
            case "timer":
                rctk.util.log("Handling timer " + id + ", " + data.milliseconds);
                var self=this;
                setTimeout(
                  function() {
                      self.push({method:"event", type:"timer", id:id, data:{}});
                      self.flush();
                   }, data.milliseconds);
                break;

            }
        },
        get_control: function(id) {
            // used by, e.g., layout managers to lookup children
            return controls[id];
        },
        register_busy: function(control) {
            control.busy = true;
            busy.push(control);
        }
    };

})(jQuery);
<commit_msg>allow multiple instances to be constructed<commit_after>// http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

var rctk = rctk || {};

/*
 * We don't want a single, global monolithic object. In stead, create a
 * function that can be constructed multiple times using 'new', so we can
 * create multiple sessions in the same window. E.g. multiple applications
 * running in their own rctk space
 */
rctk.core = (function($) {
  // return a functions so we can create instances using new
  return function() {
    /*
     * Private state
     */
    var not_defined = function(msg) { alert(msg); };
    var request_count = 0;
    var poll = false;
    var interval = 1000;
    var debug = false;
    var crashed = false;

    var handlers = {
        request: function(path, callback, sessionid, data) {
            not_defined("Request function not set -> " + path);
        },
        handle: function(task) {
            not_defined("Handle function not set -> " + task);
        },
        construct: function(class, parent, id) {
            not_defined("Construct function not set");
        },
        dump: function(data, debug) {
            // invoked to dump a debug stacktrace
            alert(data);
        },
        busy: function() {
            // invoked when we're waiting for data
            // add a delay XXX
            // setTimeout(function(if request_count...) {}, 1000);
            $("body").css("cursor", "progress");
        },
        idle: function() {
            // invoked when we're idle / not waiting for data
            $("body").css("cursor", "auto");
        }
    };

    var queue = [];
    var controls = {};
    var busy = [];

    return {
        sid: null,

        handlers: handlers,

        run: function(root) {
            controls[0] = root;
            handlers.request("start", rctk.util.proxy(this.start, this));
        },
        start: function(sessionid, data) {
            sid = sessionid;
            if(jQuery.isArray(data) && 'crash' in data[0] && data[0].crash) {
              // pass true for debug, since we've never actually received
              // a configuration
              handlers.dump(data[0], true);
              return;
            }
            if('config' in data) {
                var config = data.config;

                if('polling' in config) {
                    if(config.polling) {
                        poll = true;
                        interval = config.polling;
                        polltimer = setInterval(rctk.util.proxy(this.get_tasks, this), interval)
                    }
                    else {
                        poll = false;
                    }
                }
                if('debug' in config) {
                    debug = config.debug;
                }
                if('title' in config) {
                      // fails on IE8, argh!
                      //$("title").html(config.title);
                      document.title = config.title || '';
                }
            }
            this.get_tasks();
        },
        get_tasks: function() {
            request_count++;
            handlers.busy();
            handlers.request("pop",
                             rctk.util.proxy(this.handle_tasks, this), sid);
        },
        push: function(task) {
            queue.push(task);
        },
        flush: function() {
            if(queue.length > 0) {
                handlers.busy();
                handlers.request("task",
                                 rctk.util.proxy(this.handle_tasks, this),
                                 sid, "queue="+JSON.stringify(queue));
                queue = [];
            }
        },
        handle_tasks: function(sessionid, data) {
            request_count--;
            if(request_count == 0) {
                handlers.idle();
            }
            if(data) {
                for(var i=0; i < data.length; i++) {
                    this.handle_task(data[i]);
                }
            }
            // everything that was marked busy is no longer busy anymore
            for(var i in busy) {
                var c = busy[i];
                rctk.util.log("Control no longer busy", c);
                c.busy = false;
            }

            busy = [];
            this.flush();
        },
        handle_task: function(data) {
            var id = data.id;

            if(crashed) {
                return;
            }
            rctk.util.log("Action: " + data.action);
            rctk.util.log(data);
            switch(data.action) {
            case "append":
                var container = controls[id];
                var child = controls[data.child];
                container.append(child, data);
                break;
            case "remove":
                var container = controls[id];
                var child = controls[data.child];
                container.remove(child, data);
                break;
            case "create":
                var parent = controls[data.parentid];
                c = handlers.construct(data.control, parent, id);
                c.create(data);
                controls[id] = c;
                break;
            case "destroy":
                var control = controls[id];
                control.destroy();
                controls[id] = null;
                break;
            case "update":
                var control = controls[id];
                control.set_properties(data.update);
                break;
            case "call":
                var control = controls[id];
                var method = data.method;
                var args = data.args || [];
                control[method].apply(control, args);
                control.set_properties(data.update);
                break;
            case "handler":
                var control = controls[id];
                control["handle_"+data.type] = true;
                break;
            case "layout":
                var container = controls[id];
                container.setLayout(data.type, data.config);
                break;
            case "relayout":
                var container = controls[id];
                rctk.util.log("relayout", container);
                container.relayout(data.config);
                break;
            case "timer":
                rctk.util.log("Handling timer " + id + ", " + data.milliseconds);
                var self=this;
                setTimeout(
                  function() {
                      self.push({method:"event", type:"timer", id:id, data:{}});
                      self.flush();
                   }, data.milliseconds);
                break;

            }
        },
        get_control: function(id) {
            // used by, e.g., layout managers to lookup children
            return controls[id];
        },
        register_busy: function(control) {
            control.busy = true;
            busy.push(control);
        }
    };
 }
})(jQuery);
<|endoftext|>


<commit_before>'use strict'

var app = app || {};

app.GameScreen = {

	init: function(stage){
		this.testButton = new app.Button(10, 10, 50, 50);
		//console.log(this.testButton);
		//stage.addChild(this.testButton);
		this.player = new app.Player();
		this.npc = new app.NPC();
		window.addEventListener("keydown", this.handleKeysDown.bind(this), true);
		window.addEventListener("keyup", this.handleKeysUp.bind(this), true);
                this.g = new PIXI.Rectangle(40,40,100,100);

	},

	update: function(){
		console.log("Game Screen: update");
		//this.npc.graphic.position.x++;
		//this.npc.move();
		this.movePlayer();
		this.npc.moveAI();
		//console.log("GameScreen: update");
                if(app.HitDetection.HIT(this.player.graphic , this.g))
                    console.log("hit");
                else
                    console.log("not hit");
	},

	exit: function(){
		console.log("GameScreen: exit");
	},

	movePlayer: function(){

		if(app.Game.keyboard["W"]){
			//console.log("AHHHHH");
			this.player.graphic.position.y -= this.player.speed;
		}else if(app.Game.keyboard["S"]){
			//console.log("brrrrrr");
			this.player.graphic.position.y += this.player.speed;
		}

		if(app.Game.keyboard["D"]){
			this.player.graphic.position.x += this.player.speed;
		}else if(app.Game.keyboard["A"]){
			this.player.graphic.position.x -= this.player.speed;
		}

		//player is in air
		if(this.player.isAir){

      		this.player.t2++;
			//this.player.graphic.scale.x = this.player.graphic.scale.y += this.player.v;
		}

		// Player is jumping!
		if(app.Game.keyboard["SPACE"]){

			if(!this.player.isAir){

				this.player.isAir = true;
				this.player.t1 = this.player.t2 = 0;
				console.log("JUMPING!");
			}
			this.player.graphic.scale.x = this.player.graphic.scale.y += ((this.player.t1-this.player.t2) + 40);
		}
	},

	handleKeysDown: function(e){
		//console.log(e.keyCode);
		if(e.keyCode === 87){
			app.Game.keyboard["W"] = true;
		}
		if(e.keyCode === 83){
			app.Game.keyboard["S"] = true;
		}
		if(e.keyCode === 68){
			app.Game.keyboard["D"] = true;
		}
		if(e.keyCode === 65){
			app.Game.keyboard["A"] = true;
		}
		if(e.keyCode === 32){
			app.Game.keyboard["SPACE"] = true;
		}
	},

	handleKeysUp: function(e){
		//console.log(e.keyCode);
		if(e.keyCode === 87){
			app.Game.keyboard["W"] = false;
		}
		if(e.keyCode === 83){
			app.Game.keyboard["S"] = false;
		}
		if(e.keyCode === 68){
			app.Game.keyboard["D"] = false;
		}
		if(e.keyCode === 65){
			app.Game.keyboard["A"] = false;
		}
		if(e.keyCode === 32){
			app.Game.keyboard["SPACE"] = false;
		}
	}
};<commit_msg>jumping<commit_after>'use strict'

var app = app || {};

app.GameScreen = {

	init: function(stage){
		this.testButton = new app.Button(10, 10, 50, 50);
		//console.log(this.testButton);
		//stage.addChild(this.testButton);
		this.player = new app.Player();
		this.npc = new app.NPC();
		window.addEventListener("keydown", this.handleKeysDown.bind(this), true);
		window.addEventListener("keyup", this.handleKeysUp.bind(this), true);
                this.g = new PIXI.Rectangle(40,40,100,100);

	},

	update: function(){
		console.log("Game Screen: update");
		//this.npc.graphic.position.x++;
		//this.npc.move();
		this.movePlayer();
		this.npc.moveAI();
		//console.log("GameScreen: update");
                if(app.HitDetection.HIT(this.player.graphic , this.g))
                    console.log("hit");
                else
                    console.log("not hit");
	},

	exit: function(){
		console.log("GameScreen: exit");
	},

	movePlayer: function(){

		if(app.Game.keyboard["W"]){
			//console.log("AHHHHH");
			this.player.graphic.position.y -= this.player.speed;
		}else if(app.Game.keyboard["S"]){
			//console.log("brrrrrr");
			this.player.graphic.position.y += this.player.speed;
		}

		if(app.Game.keyboard["D"]){
			this.player.graphic.position.x += this.player.speed;
		}else if(app.Game.keyboard["A"]){
			this.player.graphic.position.x -= this.player.speed;
		}

		//player is in air
		if(this.player.isAir){

      		this.player.t2++;
			//this.player.graphic.scale.x = this.player.graphic.scale.y += this.player.v;
		}

		// Player is jumping!
		if(app.Game.keyboard["SPACE"]){

			if(!this.player.isAir){

				this.player.isAir = true;
				this.player.t1 = this.player.t2 = 0;
				console.log("JUMPING!");
			}
			this.player.graphic.scale.x = this.player.graphic.scale.y += ((this.player.t1-this.player.t2) + 40)/1;
		}
	},

	handleKeysDown: function(e){
		//console.log(e.keyCode);
		if(e.keyCode === 87){
			app.Game.keyboard["W"] = true;
		}
		if(e.keyCode === 83){
			app.Game.keyboard["S"] = true;
		}
		if(e.keyCode === 68){
			app.Game.keyboard["D"] = true;
		}
		if(e.keyCode === 65){
			app.Game.keyboard["A"] = true;
		}
		if(e.keyCode === 32){
			app.Game.keyboard["SPACE"] = true;
		}
	},

	handleKeysUp: function(e){
		//console.log(e.keyCode);
		if(e.keyCode === 87){
			app.Game.keyboard["W"] = false;
		}
		if(e.keyCode === 83){
			app.Game.keyboard["S"] = false;
		}
		if(e.keyCode === 68){
			app.Game.keyboard["D"] = false;
		}
		if(e.keyCode === 65){
			app.Game.keyboard["A"] = false;
		}
		if(e.keyCode === 32){
			app.Game.keyboard["SPACE"] = false;
		}
	}
};<|endoftext|>


<commit_before>module.exports =  guild => {
    console.log(`I have stopped providing for ${guild.name} at ${new Date()}`);
};<commit_msg>Update guildDelete.js<commit_after>module.exports =  (guild) => {
    console.log(`I have stopped providing for ${guild.name} at ${new Date()}`);
};
<|endoftext|>


<commit_before>let Mixer = require('../../index')
let mixer = new Mixer('MIXER_TOKEN_HERE')

mixer.on('ready', async () => {

	console.log('mixer ready')

	let channel = await mixer.join()

	channel.on('ready', async () => {
		let msg = await channel.send('hello world!')
		console.log(mixer.user)
	})

	channel.on('message', msg => {
		console.log(msg.user.name, msg.content)
	})

	channel.on('message', msg => {
		if(msg.content.startsWith('!speak')) {
			msg.reply('hello there!', true)
		}

		if(msg.content.startsWith('!hello')) {
			msg.whisper('hello there!')
		}

		if(msg.content.startsWith('!giveaway')) {
			channel.send('ok starting giveaway!')
			channel.giveaway()
		}

		if(msg.content.startsWith('!vote')) {
			channel.send('ok starting a poll!')
			channel.startVote({
				name: 'Is this a great poll?',
				choices: ['Yes', 'No'],
				duration: 15
			})
		}
	})

	channel.on('vote', vote => {
		console.log('start', vote, channel.vote.remaining)

		vote.vote(vote.answers[0])

		vote.on('update', () => {
			console.log('update', channel.vote.responses, channel.vote.remaining)
		})

		vote.on('done', () => {
			console.log('done', channel.vote.responses, channel.vote.remaining)
		})
	})

	channel.on('delete', user => {
		console.log('delete', user)
	})

	channel.on('clear', user => {
		console.log('delete', user)
	})

	channel.on('update', user => {
		console.log('update', user)
	})

	channel.on('error', err => {
		console.log('error!', err)
	})

})

mixer.init()<commit_msg>feat(chat example): add environment token<commit_after>let Mixer = require('../../index')
let mixer = new Mixer(process.env.MIXER_TOKEN || 'MIXER_TOKEN_HERE')

mixer.on('ready', async () => {

	console.log('mixer ready')

	let channel = await mixer.join()

	channel.on('ready', async () => {
		let msg = await channel.send('hello world!')
		console.log(mixer.user)
	})

	channel.on('message', msg => {
		console.log(msg.user.name, msg.content)
	})

	channel.on('message', msg => {
		if(msg.content.startsWith('!speak')) {
			msg.reply('hello there!', true)
		}

		if(msg.content.startsWith('!hello')) {
			msg.whisper('hello there!')
		}

		if(msg.content.startsWith('!giveaway')) {
			channel.send('ok starting giveaway!')
			channel.giveaway()
		}

		if(msg.content.startsWith('!vote')) {
			channel.send('ok starting a poll!')
			channel.startVote({
				name: 'Is this a great poll?',
				choices: ['Yes', 'No'],
				duration: 15
			})
		}
	})

	channel.on('vote', vote => {
		console.log('start', vote, channel.vote.remaining)

		vote.vote(vote.answers[0])

		vote.on('update', () => {
			console.log('update', channel.vote.responses, channel.vote.remaining)
		})

		vote.on('done', () => {
			console.log('done', channel.vote.responses, channel.vote.remaining)
		})
	})

	channel.on('delete', user => {
		console.log('delete', user)
	})

	channel.on('clear', user => {
		console.log('delete', user)
	})

	channel.on('update', user => {
		console.log('update', user)
	})

	channel.on('error', err => {
		console.log('error!', err)
	})

})

mixer.init()<|endoftext|>


<commit_before>const Kafka = require('no-kafka');

(async () => {
  const consumer = new Kafka.GroupConsumer({
    groupId: '1234',
    clientId: 'abcd',
    connectionString: 'kafka://kafka:9092',
    codec: Kafka.COMPRESSION_GZIP,
    logger: {
      logLevel: 5,
    },
  });

  const producer = new Kafka.Producer({
    connectionString: 'kafka://kafka:9092',
    codec: Kafka.COMPRESSION_GZIP,
  });

  const receive = (messageSet, topic, partition) => {
    return Promise.all(messageSet.map(async (m) => {
      console.log('______RECEIEVE_____', m.message.value.toString('utf8'), topic, partition);
      await consumer.commitOffset({ topic, partition, offset: m.offset, metadata: 'optional' });
    }));
  };

  await producer.init();
  await consumer.init({ subscriptions: ['test-topic'], handler: receive });

  const sendParams = {
    retries: {
      attempts: 2,
      delay: {
        min: 100,
        max: 300,
      },
    },
  };

  const data = {
    timestamp: '651265412',
    topic: 'test-topic',
    message: { value: 'second' },
  };

  await producer.send(data, sendParams);
})();

<commit_msg>remove test kafka file<commit_after><|endoftext|>


<commit_before>var App = Ember.Application.create();

// Models

App.Store = DS.Store.extend({
  revision: 13,
  adapter: EmberCouchDBKit.DocumentAdapter.create({db: 'boards'})
});

App.Issue = DS.Model.extend({
  text: DS.attr('string'),
  type: DS.attr('string', {defaultValue: 'issue'}),
  board: DS.attr('string')
});

App.Position = DS.Model.extend({
  issues: DS.hasMany('App.Issue', {embeded: true}),
  type: DS.attr('string', {defaultValue: 'position'})
});

App.Boards = ['common', 'intermediate', 'advanced'];

// Routes

App.IndexRoute = Ember.Route.extend({

  setupController: function(controller, model) {
    this._feed();
    //this._setupPosition();
    self = this;
    App.Boards.forEach(function(type) {
      controller = self.controllerFor(type);
      controller.addObserver('content', controller, function(){

      });
    });
  },

  renderTemplate: function() {
    this.render();
    this.render('board',{outlet: 'common', into: 'index', controller: 'common'});
    this.render('board',{outlet: 'intermediate', into: 'index', controller: 'intermediate'});
    this.render('board',{outlet: 'advanced', into: 'index', controller: 'advanced'});
  },

  _setupPosition: function() {
    App.Boards.forEach(function(type) {
      doc = App.Position.find(type);
      if (!(doc.get('isLoaded'))){
        issue = App.Position.createRecord({ id: type });
        issue.get('store').commit();
      }
    });
  },

  _feed: function(){
    // create a CouchDB `/_change` feed listener
    feed = EmberCouchDBKit.ChangesFeed.create({ db: 'boards', content: {"include_docs": true, "timeout":1000}});
    // all upcoming changes are passed to `_handleChanges` callback through `longpool` strategy
    feed.longpoll(this._handleChanges, this);
  },

  _handleChanges: function(data){
    indexController = this.controllerFor("index");
    store = indexController.get('store')
    data.forEach(function(obj){
      if ((obj.doc.text)&&(obj.doc.type =='issue')&&(obj.doc.board)){
        App.Boards.forEach(function(type) {
          if (!(obj.doc._deleted)&&(indexController.get('controllers.%@'.fmt(type)).get('content').mapProperty('id').indexOf(obj.doc._id) >= 0)){
            App.Issue.find(obj.doc._id).reload();
          }else{
            store.adapterForType(App.Issue).load(store, App.Issue, obj.doc);
            if (obj.doc.board == type){
              issue = App.Issue.find(obj.doc._id);
              indexController.get('controllers.%@'.fmt(type)).get('content').pushObject(issue);
            }
          }
        });
      }
    }); // forEach
  } // _callback fuction
});

// Conttrollers

App.IndexController = Ember.ArrayController.extend({
  createIssue: function(fields) {
    issue = App.Issue.createRecord(fields);
    issue.get('store').commit();
    issue.on('didCreate', function() {
      position = App.Position.find(fields.board);
      position.get('issues').pushObject(issue);
      position.get('transaction').commit();
    });
  },
  saveMessage: function(model) {
    model.save();
  },
  needs: App.Boards
});

App.CommonController       = App.IndexController.extend({ name: 'common' });
App.IntermediateController = App.IndexController.extend({ name: 'intermediate' });
App.AdvancedController     = App.IndexController.extend({ name: 'advanced' });

//  Views

App.NewIssueView = Ember.View.extend({
  tagName: "form",
  create: false,
  _save:  function(event) {
    event.preventDefault();
    if (this.get('create')){
      this.get('controller').send("createIssue", {text: this.get("TextArea.value"), board: this.get('controller.name')} );
    }
    this.toggleProperty('create');
  },
  submit: function(event){
    this._save(event);
  },
  keyDown: function(event){
    if(event.keyCode == 13){
      this._save(event);
    }
  }
});

App.FocusedTextArea = Ember.TextArea.extend({
  attributeBindings: ['autofocus'],
  autofocus: 'autofocus'
});

App.CancelView = Ember.View.extend({
  tagName: "span",
  click: function(event){
    event.preventDefault();
    this.set('parentView.create',false);
  }
});

App.IssueView = Ember.View.extend({
  tagName: "form",
  edit: false,
  submit: function(event){
    event.preventDefault();
    if (this.get('edit')){
      this.get('controller').send('saveMessage', this.get("context"));
    }
    this.toggleProperty('edit');
  },
  attributeBindings: 'draggable',
  draggable: 'true',
  dragStart: function(event) {
    event.dataTransfer.setData('id', this.get('elementId'));
  },
  dragEnter: function(event) {
    event.preventDefault();
  },
  dragOver: function(event) {
    event.preventDefault();
  },
  drop: function(event) {
    var viewId = event.dataTransfer.getData('id');
    var view = Ember.View.views[viewId];
    var model = view.get('context');
    view.get('controller.content').removeObject(model);
    this.get('controller.content').addObject(model);
    model.set('board', this.get('controller.name'));
    this.get('controller').send('saveMessage', model);
    event.preventDefault();
  }
});
<commit_msg>Itergrated App.Position behavior<commit_after>var App = Ember.Application.create();

// Models

App.Store = DS.Store.extend({
  revision: 13,
  adapter: EmberCouchDBKit.DocumentAdapter.create({db: 'boards'})
});

App.Issue = DS.Model.extend({
  text: DS.attr('string'),
  type: DS.attr('string', {defaultValue: 'issue'}),
  board: DS.attr('string')
});

App.Position = DS.Model.extend({
  issues: DS.hasMany('App.Issue', {embeded: true}),
  type: DS.attr('string', {defaultValue: 'position'})
});

App.Boards = ['common', 'intermediate', 'advanced'];

// Routes

App.IndexRoute = Ember.Route.extend({

  setupController: function(controller, model) {
    this._feed();
    //this._setupPosition();
    self = this;
    App.Boards.forEach(function(type) {
      controller = self.controllerFor(type);

      controller.set('position', App.Position.find(type));
      //
      controller.addObserver('content', controller, function(){
        controller.get('position').set('issues', controller.get('content'));
        controller.get('position.store').commit();
      });
      //
      controller.get('position').one('didLoad', function() {
        controller.set('content', controller.get('position.issues'));
      });
    });
  },

  renderTemplate: function() {
    this.render();
    this.render('board',{outlet: 'common', into: 'index', controller: 'common'});
    this.render('board',{outlet: 'intermediate', into: 'index', controller: 'intermediate'});
    this.render('board',{outlet: 'advanced', into: 'index', controller: 'advanced'});
  },

  _setupPosition: function() {
    App.Boards.forEach(function(type) {
      doc = App.Position.find(type);
      if (!(doc.get('isLoaded'))){
        issue = App.Position.createRecord({ id: type });
        issue.get('store').commit();
      }
    });
  },

  _feed: function(){
    // create a CouchDB `/_change` feed listener
    feed = EmberCouchDBKit.ChangesFeed.create({ db: 'boards', content: {"include_docs": true, "timeout":1000}});
    // all upcoming changes are passed to `_handleChanges` callback through `longpool` strategy
    //feed.longpoll(this._handleChanges, this);
  },

  _handleChanges: function(data){
    indexController = this.controllerFor("index");
    store = indexController.get('store')
    data.forEach(function(obj){
      if ((obj.doc.text)&&(obj.doc.type =='issue')&&(obj.doc.board)){
        App.Boards.forEach(function(type) {
          if (!(obj.doc._deleted)&&(indexController.get('controllers.%@'.fmt(type)).get('content').mapProperty('id').indexOf(obj.doc._id) >= 0)){
            App.Issue.find(obj.doc._id).reload();
          }else{
            store.adapterForType(App.Issue).load(store, App.Issue, obj.doc);
            if (obj.doc.board == type){
              issue = App.Issue.find(obj.doc._id);
              indexController.get('controllers.%@'.fmt(type)).get('content').pushObject(issue);
            }
          }
        });
      }
    }); // forEach
  } // _callback fuction
});

// Conttrollers

App.IndexController = Ember.ArrayController.extend({
  createIssue: function(fields) {
    issue = App.Issue.createRecord(fields);
    issue.get('store').commit();
    issue.on('didCreate', function() {
      position = App.Position.find(fields.board);
      position.get('issues').pushObject(issue);
      position.get('transaction').commit();
    });
  },
  saveMessage: function(model) {
    model.save();
  },
  needs: App.Boards
});

App.CommonController       = App.IndexController.extend({ name: 'common' });
App.IntermediateController = App.IndexController.extend({ name: 'intermediate' });
App.AdvancedController     = App.IndexController.extend({ name: 'advanced' });

//  Views

App.NewIssueView = Ember.View.extend({
  tagName: "form",
  create: false,
  _save:  function(event) {
    event.preventDefault();
    if (this.get('create')){
      this.get('controller').send("createIssue", {text: this.get("TextArea.value"), board: this.get('controller.name')} );
    }
    this.toggleProperty('create');
  },
  submit: function(event){
    this._save(event);
  },
  keyDown: function(event){
    if(event.keyCode == 13){
      this._save(event);
    }
  }
});

App.FocusedTextArea = Ember.TextArea.extend({
  attributeBindings: ['autofocus'],
  autofocus: 'autofocus'
});

App.CancelView = Ember.View.extend({
  tagName: "span",
  click: function(event){
    event.preventDefault();
    this.set('parentView.create',false);
  }
});

App.IssueView = Ember.View.extend({
  tagName: "form",
  edit: false,
  submit: function(event){
    event.preventDefault();
    if (this.get('edit')){
      this.get('controller').send('saveMessage', this.get("context"));
    }
    this.toggleProperty('edit');
  },
  attributeBindings: 'draggable',
  draggable: 'true',
  dragStart: function(event) {
    event.dataTransfer.setData('id', this.get('elementId'));
  },
  dragEnter: function(event) {
    event.preventDefault();
  },
  dragOver: function(event) {
    event.preventDefault();
  },
  drop: function(event) {
    var viewId = event.dataTransfer.getData('id');
    var view = Ember.View.views[viewId];
    var model = view.get('context');
    view.get('controller.content').removeObject(model);
    this.get('controller.content').addObject(model);
    model.set('board', this.get('controller.name'));
    this.get('controller').send('saveMessage', model);
    event.preventDefault();
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import BigCalendar from 'react-big-calendar';
import { DragSource, DragDropContext, DropTarget } from 'react-dnd';
import { findDOMNode } from 'react-dom';
import HTML5Backend from 'react-dnd-html5-backend';
import events from '../events';

/* drag sources */

let eventSource = {
  beginDrag: function (props) {
    return props.event;
  }
}

function collectSource(connect) {
  return {
    connectDragSource: connect.dragSource()
  };
}

let DraggableEventWrapper = React.createClass({
  render() {
    let { connectDragSource, children, event } = this.props;
    let EventWrapper = BigCalendar.components.eventWrapper;

    return (<EventWrapper
      event={event}
      children={children}
      ref={instance => connectDragSource(findDOMNode(instance))}
    />);
  }
});

DraggableEventWrapper = DragSource('event', eventSource, collectSource)(DraggableEventWrapper);

/* drop targets */
const dropTarget = {
  drop(props, monitor) {
    const event = monitor.getItem();
    alert(`${event.title} was dropped`);
  }
};

function collectTarget(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget()
  };
}

class DroppableBackgroundWrapper extends React.Component {
  render() {
    const { connectDropTarget, children } = this.props;
    const BackgroundWrapper = BigCalendar.components.backgroundWrapper;

    return (<BackgroundWrapper
      children={children}
      ref={instance => connectDropTarget(findDOMNode(instance))}
    />);
  }
}

DroppableBackgroundWrapper = DropTarget(['event'], dropTarget, collectTarget)(DroppableBackgroundWrapper);

let Dnd = React.createClass({
  render(){
    return (
      <BigCalendar
        components={{
          eventWrapper: DraggableEventWrapper,
          backgroundWrapper: DroppableBackgroundWrapper
        }}
        events={events}
        defaultDate={new Date(2015, 3, 1)}
      />
    )
  }
})

export default DragDropContext(HTML5Backend)(Dnd);
<commit_msg>Change drop target style on isOver<commit_after>import React from 'react';
import BigCalendar from 'react-big-calendar';
import { DragSource, DragDropContext, DropTarget } from 'react-dnd';
import { findDOMNode } from 'react-dom';
import HTML5Backend from 'react-dnd-html5-backend';
import events from '../events';

/* drag sources */

let eventSource = {
  beginDrag: function (props) {
    return props.event;
  }
}

function collectSource(connect) {
  return {
    connectDragSource: connect.dragSource()
  };
}

let DraggableEventWrapper = React.createClass({
  render() {
    let { connectDragSource, children, event } = this.props;
    let EventWrapper = BigCalendar.components.eventWrapper;

    return (<EventWrapper
      event={event}
      children={children}
      ref={instance => connectDragSource(findDOMNode(instance))}
    />);
  }
});

DraggableEventWrapper = DragSource('event', eventSource, collectSource)(DraggableEventWrapper);

/* drop targets */
const dropTarget = {
  drop(props, monitor) {
    const event = monitor.getItem();
    alert(`${event.title} was dropped`);
  }
};

function collectTarget(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver()
  };
}

class DroppableBackgroundWrapper extends React.Component {
  render() {
    const { connectDropTarget, children, isOver } = this.props;
    const BackgroundWrapper = BigCalendar.components.backgroundWrapper;

    return (<BackgroundWrapper
      children={children}
      ref={instance => {
        const domNode = findDOMNode(instance);
        if(domNode) {
          domNode.style.backgroundColor = isOver ? '#dddddd' : '';
        }
        return connectDropTarget(domNode);
      }}
    />);
  }
}

DroppableBackgroundWrapper = DropTarget(['event'], dropTarget, collectTarget)(DroppableBackgroundWrapper);

let Dnd = React.createClass({
  render(){
    return (
      <BigCalendar
        components={{
          eventWrapper: DraggableEventWrapper,
          backgroundWrapper: DroppableBackgroundWrapper
        }}
        events={events}
        defaultDate={new Date(2015, 3, 1)}
      />
    )
  }
})

export default DragDropContext(HTML5Backend)(Dnd);
<|endoftext|>


<commit_before>/**
 * @author Slayvin / http://slayvin.net
 */

THREE.ShaderLib[ 'mirror' ] = {

	uniforms: {
		"mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
		"mirrorSampler": { value: null },
		"textureMatrix" : { value: new THREE.Matrix4() }
	},

	vertexShader: [

		"uniform mat4 textureMatrix;",

		"varying vec4 mirrorCoord;",

		"void main() {",

			"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
			"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
			"mirrorCoord = textureMatrix * worldPosition;",

			"gl_Position = projectionMatrix * mvPosition;",

		"}"

	].join( "\n" ),

	fragmentShader: [

		"uniform vec3 mirrorColor;",
		"uniform sampler2D mirrorSampler;",

		"varying vec4 mirrorCoord;",

		"float blendOverlay(float base, float blend) {",
			"return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
		"}",

		"void main() {",

			"vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
			"color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",

			"gl_FragColor = color;",

		"}"

	].join( "\n" )

};

THREE.Mirror = function ( renderer, camera, options ) {

	THREE.Object3D.call( this );

	this.name = 'mirror_' + this.id;

	options = options || {};

	this.matrixNeedsUpdate = true;

	var width = options.textureWidth !== undefined ? options.textureWidth : 512;
	var height = options.textureHeight !== undefined ? options.textureHeight : 512;

	this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;

	var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );

	this.renderer = renderer;
	this.mirrorPlane = new THREE.Plane();
	this.normal = new THREE.Vector3( 0, 0, 1 );
	this.mirrorWorldPosition = new THREE.Vector3();
	this.cameraWorldPosition = new THREE.Vector3();
	this.rotationMatrix = new THREE.Matrix4();
	this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
	this.clipPlane = new THREE.Vector4();

	// For debug only, show the normal and plane of the mirror
	var debugMode = options.debugMode !== undefined ? options.debugMode : false;

	if ( debugMode ) {

		var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
		var planeGeometry = new THREE.Geometry();
		planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
		planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
		planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
		planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
		planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
		var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );

		this.add( arrow );
		this.add( plane );

	}

	if ( camera instanceof THREE.PerspectiveCamera ) {

		this.camera = camera;

	} else {

		this.camera = new THREE.PerspectiveCamera();
		console.log( this.name + ': camera is not a Perspective Camera!' );

	}

	this.textureMatrix = new THREE.Matrix4();

	this.mirrorCamera = this.camera.clone();
	this.mirrorCamera.matrixAutoUpdate = true;

	var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };

	this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
	this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );

	var mirrorShader = THREE.ShaderLib[ "mirror" ];
	var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );

	this.material = new THREE.ShaderMaterial( {

		fragmentShader: mirrorShader.fragmentShader,
		vertexShader: mirrorShader.vertexShader,
		uniforms: mirrorUniforms

	} );

	this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
	this.material.uniforms.mirrorColor.value = mirrorColor;
	this.material.uniforms.textureMatrix.value = this.textureMatrix;

	if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {

		this.renderTarget.texture.generateMipmaps = false;
		this.renderTarget2.texture.generateMipmaps = false;

	}

	this.updateTextureMatrix();
	this.render();

};

THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
THREE.Mirror.prototype.constructor = THREE.Mirror;

THREE.Mirror.prototype.renderWithMirror = function ( otherMirror ) {

	// update the mirror matrix to mirror the current view
	this.updateTextureMatrix();
	this.matrixNeedsUpdate = false;

	// set the camera of the other mirror so the mirrored view is the reference view
	var tempCamera = otherMirror.camera;
	otherMirror.camera = this.mirrorCamera;

	// render the other mirror in temp texture
	otherMirror.renderTemp();
	otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;

	// render the current mirror
	this.render();
	this.matrixNeedsUpdate = true;

	// restore material and camera of other mirror
	otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
	otherMirror.camera = tempCamera;

	// restore texture matrix of other mirror
	otherMirror.updateTextureMatrix();

};

THREE.Mirror.prototype.updateTextureMatrix = function () {

	this.updateMatrixWorld();
	this.camera.updateMatrixWorld();

	this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
	this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );

	this.rotationMatrix.extractRotation( this.matrixWorld );

	this.normal.set( 0, 0, 1 );
	this.normal.applyMatrix4( this.rotationMatrix );

	var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
	view.reflect( this.normal ).negate();
	view.add( this.mirrorWorldPosition );

	this.rotationMatrix.extractRotation( this.camera.matrixWorld );

	this.lookAtPosition.set( 0, 0, - 1 );
	this.lookAtPosition.applyMatrix4( this.rotationMatrix );
	this.lookAtPosition.add( this.cameraWorldPosition );

	var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
	target.reflect( this.normal ).negate();
	target.add( this.mirrorWorldPosition );

	this.up.set( 0, - 1, 0 );
	this.up.applyMatrix4( this.rotationMatrix );
	this.up.reflect( this.normal ).negate();

	this.mirrorCamera.position.copy( view );
	this.mirrorCamera.up = this.up;
	this.mirrorCamera.lookAt( target );

	this.mirrorCamera.updateProjectionMatrix();
	this.mirrorCamera.updateMatrixWorld();
	this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );

	// Update the texture matrix
	this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
							0.0, 0.5, 0.0, 0.5,
							0.0, 0.0, 0.5, 0.5,
							0.0, 0.0, 0.0, 1.0 );
	this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
	this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );

	// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
	// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
	this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
	this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );

	this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );

	var q = new THREE.Vector4();
	var projectionMatrix = this.mirrorCamera.projectionMatrix;

	q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
	q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
	q.z = - 1.0;
	q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];

	// Calculate the scaled plane vector
	var c = new THREE.Vector4();
	c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );

	// Replacing the third row of the projection matrix
	projectionMatrix.elements[ 2 ] = c.x;
	projectionMatrix.elements[ 6 ] = c.y;
	projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
	projectionMatrix.elements[ 14 ] = c.w;

};

THREE.Mirror.prototype.render = function () {

	if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();

	this.matrixNeedsUpdate = true;

	// Render the mirrored view of the current scene into the target texture
	var scene = this;

	while ( scene.parent !== null ) {

		scene = scene.parent;

	}

	if ( scene !== undefined && scene instanceof THREE.Scene ) {

		// We can't render ourself to ourself
		var visible = this.material.visible;
		this.material.visible = false;

		this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );

		this.material.visible = visible;

	}

};

THREE.Mirror.prototype.renderTemp = function () {

	if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();

	this.matrixNeedsUpdate = true;

	// Render the mirrored view of the current scene into the target texture
	var scene = this;

	while ( scene.parent !== null ) {

		scene = scene.parent;

	}

	if ( scene !== undefined && scene instanceof THREE.Scene ) {

		this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );

	}

};
<commit_msg>remove UniformsUils.*<commit_after>/**
 * @author Slayvin / http://slayvin.net
 */

THREE.ShaderLib[ 'mirror' ] = {

	uniforms: {
		"mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
		"mirrorSampler": { value: null },
		"textureMatrix" : { value: new THREE.Matrix4() }
	},

	vertexShader: [

		"uniform mat4 textureMatrix;",

		"varying vec4 mirrorCoord;",

		"void main() {",

			"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
			"vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
			"mirrorCoord = textureMatrix * worldPosition;",

			"gl_Position = projectionMatrix * mvPosition;",

		"}"

	].join( "\n" ),

	fragmentShader: [

		"uniform vec3 mirrorColor;",
		"uniform sampler2D mirrorSampler;",

		"varying vec4 mirrorCoord;",

		"float blendOverlay(float base, float blend) {",
			"return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
		"}",

		"void main() {",

			"vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
			"color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",

			"gl_FragColor = color;",

		"}"

	].join( "\n" )

};

THREE.Mirror = function ( renderer, camera, options ) {

	THREE.Object3D.call( this );

	this.name = 'mirror_' + this.id;

	options = options || {};

	this.matrixNeedsUpdate = true;

	var width = options.textureWidth !== undefined ? options.textureWidth : 512;
	var height = options.textureHeight !== undefined ? options.textureHeight : 512;

	this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;

	var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );

	this.renderer = renderer;
	this.mirrorPlane = new THREE.Plane();
	this.normal = new THREE.Vector3( 0, 0, 1 );
	this.mirrorWorldPosition = new THREE.Vector3();
	this.cameraWorldPosition = new THREE.Vector3();
	this.rotationMatrix = new THREE.Matrix4();
	this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
	this.clipPlane = new THREE.Vector4();

	// For debug only, show the normal and plane of the mirror
	var debugMode = options.debugMode !== undefined ? options.debugMode : false;

	if ( debugMode ) {

		var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
		var planeGeometry = new THREE.Geometry();
		planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
		planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
		planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
		planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
		planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
		var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );

		this.add( arrow );
		this.add( plane );

	}

	if ( camera instanceof THREE.PerspectiveCamera ) {

		this.camera = camera;

	} else {

		this.camera = new THREE.PerspectiveCamera();
		console.log( this.name + ': camera is not a Perspective Camera!' );

	}

	this.textureMatrix = new THREE.Matrix4();

	this.mirrorCamera = this.camera.clone();
	this.mirrorCamera.matrixAutoUpdate = true;

	var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };

	this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
	this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );

	var mirrorShader = THREE.ShaderLib[ "mirror" ];
	var mirrorUniforms = Object.assign( {}, mirrorShader.uniforms );

	this.material = new THREE.ShaderMaterial( {

		fragmentShader: mirrorShader.fragmentShader,
		vertexShader: mirrorShader.vertexShader,
		uniforms: mirrorUniforms

	} );

	this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
	this.material.uniforms.mirrorColor.value = mirrorColor;
	this.material.uniforms.textureMatrix.value = this.textureMatrix;

	if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {

		this.renderTarget.texture.generateMipmaps = false;
		this.renderTarget2.texture.generateMipmaps = false;

	}

	this.updateTextureMatrix();
	this.render();

};

THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
THREE.Mirror.prototype.constructor = THREE.Mirror;

THREE.Mirror.prototype.renderWithMirror = function ( otherMirror ) {

	// update the mirror matrix to mirror the current view
	this.updateTextureMatrix();
	this.matrixNeedsUpdate = false;

	// set the camera of the other mirror so the mirrored view is the reference view
	var tempCamera = otherMirror.camera;
	otherMirror.camera = this.mirrorCamera;

	// render the other mirror in temp texture
	otherMirror.renderTemp();
	otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;

	// render the current mirror
	this.render();
	this.matrixNeedsUpdate = true;

	// restore material and camera of other mirror
	otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
	otherMirror.camera = tempCamera;

	// restore texture matrix of other mirror
	otherMirror.updateTextureMatrix();

};

THREE.Mirror.prototype.updateTextureMatrix = function () {

	this.updateMatrixWorld();
	this.camera.updateMatrixWorld();

	this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
	this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );

	this.rotationMatrix.extractRotation( this.matrixWorld );

	this.normal.set( 0, 0, 1 );
	this.normal.applyMatrix4( this.rotationMatrix );

	var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
	view.reflect( this.normal ).negate();
	view.add( this.mirrorWorldPosition );

	this.rotationMatrix.extractRotation( this.camera.matrixWorld );

	this.lookAtPosition.set( 0, 0, - 1 );
	this.lookAtPosition.applyMatrix4( this.rotationMatrix );
	this.lookAtPosition.add( this.cameraWorldPosition );

	var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
	target.reflect( this.normal ).negate();
	target.add( this.mirrorWorldPosition );

	this.up.set( 0, - 1, 0 );
	this.up.applyMatrix4( this.rotationMatrix );
	this.up.reflect( this.normal ).negate();

	this.mirrorCamera.position.copy( view );
	this.mirrorCamera.up = this.up;
	this.mirrorCamera.lookAt( target );

	this.mirrorCamera.updateProjectionMatrix();
	this.mirrorCamera.updateMatrixWorld();
	this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );

	// Update the texture matrix
	this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
							0.0, 0.5, 0.0, 0.5,
							0.0, 0.0, 0.5, 0.5,
							0.0, 0.0, 0.0, 1.0 );
	this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
	this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );

	// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
	// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
	this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
	this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );

	this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );

	var q = new THREE.Vector4();
	var projectionMatrix = this.mirrorCamera.projectionMatrix;

	q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
	q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
	q.z = - 1.0;
	q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];

	// Calculate the scaled plane vector
	var c = new THREE.Vector4();
	c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );

	// Replacing the third row of the projection matrix
	projectionMatrix.elements[ 2 ] = c.x;
	projectionMatrix.elements[ 6 ] = c.y;
	projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
	projectionMatrix.elements[ 14 ] = c.w;

};

THREE.Mirror.prototype.render = function () {

	if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();

	this.matrixNeedsUpdate = true;

	// Render the mirrored view of the current scene into the target texture
	var scene = this;

	while ( scene.parent !== null ) {

		scene = scene.parent;

	}

	if ( scene !== undefined && scene instanceof THREE.Scene ) {

		// We can't render ourself to ourself
		var visible = this.material.visible;
		this.material.visible = false;

		this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );

		this.material.visible = visible;

	}

};

THREE.Mirror.prototype.renderTemp = function () {

	if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();

	this.matrixNeedsUpdate = true;

	// Render the mirrored view of the current scene into the target texture
	var scene = this;

	while ( scene.parent !== null ) {

		scene = scene.parent;

	}

	if ( scene !== undefined && scene instanceof THREE.Scene ) {

		this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );

	}

};
<|endoftext|>