<commit_before>/**
 *
 */

cls.ResourceManagerService = function(view, data)
{
  if (cls.ResourceManagerService.instance)
  {
    return cls.ResourceManagerService.instance;
  }
  cls.ResourceManagerService.instance = this;

  this._current_context = null;

  this._enable_content_tracking = function()
  {
    this._res_service.requestSetResponseMode(null, [[3, 1]]);
  }

  this._on_abouttoloaddocument_bound = function(msg)
  {
    var data = new cls.DocumentManager["1.0"].AboutToLoadDocument(msg);
    // if not a top resource, just ignore. This usually means it's an iframe
    if (data.parentDocumentID) { return; }
    this._current_context = new cls.ResourceContext();
  }.bind(this);

  this._on_urlload_bound = function(msg)
  {
    if (!this._current_context) { return; }
    var data = new cls.ResourceManager["1.0"].UrlLoad(msg);

    //bail if we get dupes. Why do we get dupes? fixme
    //if (data.resourceID in this._current_document.resourcemap) { return }
    this._current_context.update("urlload", data);
  }.bind(this);

  this._on_urlredirect_bound = function(msg)
  {
    if (!this._current_context) { return; }

    var data = new cls.ResourceManager["1.0"].UrlRedirect(msg);
    // a bit of cheating since further down we use .resouceID to determine
    // what resource the event applies to:
    data.resourceID = data.fromResourceID;
    this._current_context.update("urlredirect", data);
  }.bind(this);

  this._on_urlfinished_bound = function(msg)
  {
    if (!this._current_context) { return; }
    var data = new cls.ResourceManager["1.0"].UrlFinished(msg);
    this._current_context.update("urlfinished", data);
  }.bind(this);

  this._on_response_bound = function(msg)
  {
    if (!this._current_context) { return; }
    var data = new cls.ResourceManager["1.0"].Response(msg);
    this._current_context.update("response", data);
  }.bind(this);

  this.init = function()
  {
    this._res_service = window.services['resource-manager'];
    this._res_service.addListener("urlload", this._on_urlload_bound);
    this._res_service.addListener("response", this._on_response_bound);
    this._res_service.addListener("urlredirect", this._on_urlredirect_bound);
    this._res_service.addListener("urlfinished", this._on_urlfinished_bound);
    this._doc_service = window.services['document-manager'];
    this._doc_service.addListener("abouttoloaddocument", this._on_abouttoloaddocument_bound);
  };

  this.get_resource_context = function()
  {
    return this._current_context;
  };

  /**
   * Returns an array of resource objects. The internal representation is to
   * keep separate lists of seen resources and a map of id/resource.
   */
  this.get_resource_list = function()
  {
    if (! this._current_context) { return []; }
    return this._current_context.resources;
  };

  this.get_resource_for_id = function(id)
  {
    if (this._current_document && id in this._current_document.resourcemap)
    {
      return this._current_document.resourcemap[id];
    }
    return null;
  };

  this.get_resource_for_url = function(url)
  {
    if (this._current_document) {
      for (var key in this._current_document.resourcemap) {
        if (this._current_document.resourcemap[key].urlload.url == url)
        {
          return this._current_document.resourcemap[key];
        }
      }
    }
    return null;
  };

  this.fetch_resource_data = function(callback, rid, type)
  {
    var typecode = {datauri: 3, string: 1}[type] || 1;
    var tag = window.tagManager.set_callback(null, callback);
    this._res_service.requestGetResource(tag, [rid, [typecode, 1]]);
  }

  this.init();
};

cls.ResourceContext = function()
{
  this.resources = [];

  this.update = function(eventname, event)
  {
    var res = this.get_resource(event.resourceID);

    if (!res && eventname == "urlload")
    {
      res = new cls.Resource(event.resourceID)
      if (this.resources.length == 0) { this.topresource = event.resourceID; }
      this.resources.push(res);
    }
    else if (!res)
    {
      // ignoring. Never saw an urlload, or it's allready invalidated
      return
    }

    res.update(eventname, event);
    if (res.invalid)
    {
      this.resources.splice(this.resources.indexOf(res), 1);
    }
  }

  this.get_resource = function(id)
  {
    return this.resources.filter(function(e) { return e.id == id; })[0];
  };

  this.get_resources_for_types = function()
  {
    var types = Array.prototype.slice.call(arguments, 0);
    var filterfun = function(e) { return types.indexOf(e.type) > -1;};
    return this.resources.filter(filterfun);
  };

  this.get_resources_for_mimes = function()
  {
    var mimes = Array.prototype.slice.call(arguments, 0);
    var filterfun = function(e) { return mimes.indexOf(e.mime) > -1; };
    return this.resources.filter(filterfun);
  };

  this.get_resource_groups = function()
  {
    var imgs = this.get_resources_for_type("image");
    var stylesheets = this.get_resources_for_mime("text/css");
    var markup = this.get_resources_for_mime("text/html",
                                             "application/xhtml+xml");
    var scripts = this.get_resources_for_mime("application/javascript",
                                              "text/javascript");

    var known = [].concat(imgs, stylesheets, markup, scripts);
    var other = this.resources.filter(function(e) {
      return known.indexOf(e) == -1;
    });
    return {
      images: imgs, stylesheets: stylesheets, markup: markup,
      scripts: scripts, other: other
    }
  }
}

cls.Resource = function(id)
{
  this.id = id;
  this.finished = false;
  this.url = null;
  this.result = null;
  this.mime = null;
  this.encoding = null;
  this.size = null;
  this.type = null;
  this.invalid = false;

  this.update = function(eventname, eventdata)
  {
    if (eventname == "urlload")
    {
      this.url = eventdata.url;
    }
    else if (eventname == "urlfinished")
    {
      this.result = eventdata.result;
      this.mime = eventdata.mimeType;
      this.encoding = eventdata.characterEncoding;
      this.size = eventdata.contentLength;
      this.finished = true;
      this._guess_type();
    }
    else if (eventname == "response")
    {
      if (eventdata.responseCode <= 100 || eventdata.responseCode >= 300)
      {
        this.invalid = true;
      }
    }
    else if (eventname == "urlredirect")
    {
      this.invalid = true;
    }
    else
    {
      opera.postError("got unknown event: " + eventname);
    }
  }

  this.get_source = function()
  {
    // cache, file, http, https ..
  }

  this._guess_type = function()
  {
    if (!this.finished)
    {
      this.type = undefined;
    }
    else if (this.mime.toLowerCase() == "application/octet-stream")
    {
      this.type = cls.ResourceUtil.path_to_type(this.url);
    }
    else
    {
      this.type = cls.ResourceUtil.mime_to_type(this.mime);
    }
  }
}<commit_msg>Fixed get_resource and get_resource_for_url in resource service<commit_after>/**
 *
 */

cls.ResourceManagerService = function(view, data)
{
  if (cls.ResourceManagerService.instance)
  {
    return cls.ResourceManagerService.instance;
  }
  cls.ResourceManagerService.instance = this;

  this._current_context = null;

  this._enable_content_tracking = function()
  {
    this._res_service.requestSetResponseMode(null, [[3, 1]]);
  }

  this._on_abouttoloaddocument_bound = function(msg)
  {
    var data = new cls.DocumentManager["1.0"].AboutToLoadDocument(msg);
    // if not a top resource, just ignore. This usually means it's an iframe
    if (data.parentDocumentID) { return; }
    this._current_context = new cls.ResourceContext();
  }.bind(this);

  this._on_urlload_bound = function(msg)
  {
    if (!this._current_context) { return; }
    var data = new cls.ResourceManager["1.0"].UrlLoad(msg);

    //bail if we get dupes. Why do we get dupes? fixme
    //if (data.resourceID in this._current_document.resourcemap) { return }
    this._current_context.update("urlload", data);
  }.bind(this);

  this._on_urlredirect_bound = function(msg)
  {
    if (!this._current_context) { return; }

    var data = new cls.ResourceManager["1.0"].UrlRedirect(msg);
    // a bit of cheating since further down we use .resouceID to determine
    // what resource the event applies to:
    data.resourceID = data.fromResourceID;
    this._current_context.update("urlredirect", data);
  }.bind(this);

  this._on_urlfinished_bound = function(msg)
  {
    if (!this._current_context) { return; }
    var data = new cls.ResourceManager["1.0"].UrlFinished(msg);
    this._current_context.update("urlfinished", data);
  }.bind(this);

  this._on_response_bound = function(msg)
  {
    if (!this._current_context) { return; }
    var data = new cls.ResourceManager["1.0"].Response(msg);
    this._current_context.update("response", data);
  }.bind(this);

  this.init = function()
  {
    this._res_service = window.services['resource-manager'];
    this._res_service.addListener("urlload", this._on_urlload_bound);
    this._res_service.addListener("response", this._on_response_bound);
    this._res_service.addListener("urlredirect", this._on_urlredirect_bound);
    this._res_service.addListener("urlfinished", this._on_urlfinished_bound);
    this._doc_service = window.services['document-manager'];
    this._doc_service.addListener("abouttoloaddocument", this._on_abouttoloaddocument_bound);
  };

  this.get_resource_context = function()
  {
    return this._current_context;
  };

  /**
   * Returns an array of resource objects. The internal representation is to
   * keep separate lists of seen resources and a map of id/resource.
   */
  this.get_resource_list = function()
  {
    if (! this._current_context) { return []; }
    return this._current_context.resources;
  };

  this.get_resource_for_id = function(id)
  {
    if (this._current_context)
    {
      return this._current_context.get_resource(id);
    }
    return null;
  };

  this.get_resource_for_url = function(url)
  {
    if (this._current_context) {
      var filterfun = function(res) { return res.url == url };
      return this._current_context.resources.filter(filterfun).pop();
    }
    return null;
  };

  this.fetch_resource_data = function(callback, rid, type)
  {
    var typecode = {datauri: 3, string: 1}[type] || 1;
    var tag = window.tagManager.set_callback(null, callback);
    this._res_service.requestGetResource(tag, [rid, [typecode, 1]]);
  }

  this.init();
};

cls.ResourceContext = function()
{
  this.resources = [];

  this.update = function(eventname, event)
  {
    var res = this.get_resource(event.resourceID);

    if (!res && eventname == "urlload")
    {
      res = new cls.Resource(event.resourceID)
      if (this.resources.length == 0) { this.topresource = event.resourceID; }
      this.resources.push(res);
    }
    else if (!res)
    {
      // ignoring. Never saw an urlload, or it's allready invalidated
      return
    }

    res.update(eventname, event);
    if (res.invalid)
    {
      this.resources.splice(this.resources.indexOf(res), 1);
    }
  }

  this.get_resource = function(id)
  {
    return this.resources.filter(function(e) { return e.id == id; })[0];
  };

  this.get_resources_for_types = function()
  {
    var types = Array.prototype.slice.call(arguments, 0);
    var filterfun = function(e) { return types.indexOf(e.type) > -1;};
    return this.resources.filter(filterfun);
  };

  this.get_resources_for_mimes = function()
  {
    var mimes = Array.prototype.slice.call(arguments, 0);
    var filterfun = function(e) { return mimes.indexOf(e.mime) > -1; };
    return this.resources.filter(filterfun);
  };

  this.get_resource_groups = function()
  {
    var imgs = this.get_resources_for_type("image");
    var stylesheets = this.get_resources_for_mime("text/css");
    var markup = this.get_resources_for_mime("text/html",
                                             "application/xhtml+xml");
    var scripts = this.get_resources_for_mime("application/javascript",
                                              "text/javascript");

    var known = [].concat(imgs, stylesheets, markup, scripts);
    var other = this.resources.filter(function(e) {
      return known.indexOf(e) == -1;
    });
    return {
      images: imgs, stylesheets: stylesheets, markup: markup,
      scripts: scripts, other: other
    }
  }
}

cls.Resource = function(id)
{
  this.id = id;
  this.finished = false;
  this.url = null;
  this.result = null;
  this.mime = null;
  this.encoding = null;
  this.size = null;
  this.type = null;
  this.invalid = false;

  this.update = function(eventname, eventdata)
  {
    if (eventname == "urlload")
    {
      this.url = eventdata.url;
    }
    else if (eventname == "urlfinished")
    {
      this.result = eventdata.result;
      this.mime = eventdata.mimeType;
      this.encoding = eventdata.characterEncoding;
      this.size = eventdata.contentLength;
      this.finished = true;
      this._guess_type();
    }
    else if (eventname == "response")
    {
      if (eventdata.responseCode <= 100 || eventdata.responseCode >= 300)
      {
        this.invalid = true;
      }
    }
    else if (eventname == "urlredirect")
    {
      this.invalid = true;
    }
    else
    {
      opera.postError("got unknown event: " + eventname);
    }
  }

  this.get_source = function()
  {
    // cache, file, http, https ..
  }

  this._guess_type = function()
  {
    if (!this.finished)
    {
      this.type = undefined;
    }
    else if (this.mime.toLowerCase() == "application/octet-stream")
    {
      this.type = cls.ResourceUtil.path_to_type(this.url);
    }
    else
    {
      this.type = cls.ResourceUtil.mime_to_type(this.mime);
    }
  }
}<|endoftext|>


<commit_before>var fs = require('fs');
var natural = require('natural');
var tokenizer = new natural.WordTokenizer();
var twitter = require('./twitterAPI');
var mongoose = require('mongoose');
var Tweet = require('./models/tweet.js');
//var async = require('async');
exports.sayHello = function(req, res){
	// return function(req, res){
		console.log("HELLO");
	// }
}

var words = [];
var scores = [];

exports.getSentiment = function(req, res){

		console.log("calling function to get sentiment");

		// Create dictionary
		fs.readFile(__dirname + '/nlp-dict.txt', 'utf-8' ,function (err, data) {
			if (err) throw err;
			var lines = data.split('\n');

			for (var i = 0; i < lines.length; i++) {
				var definition = lines[i].split('\t');
				// console.log("word: " + definition[0] + " score: " + definition[1]);
				words.push(definition[0]);
				scores.push(definition[1]);
			};
		// End of creating dictionary

			var tweetsArray;
			twitter.getTweets(function(data) {
				tweetsArrayFunction(data);
			});

			tweetsArrayFunction = function(tweetsArray) {

				console.log("THIS MATTERS");
				console.log(tweetsArray);

				// Tokenize tweet
				var tokenizeTweet = function(tweet){
					var tokenizedTweet = tokenizer.tokenize(tweet);
					return tokenizedTweet;
				}

				// Finds if a word is in array words[]
				var positionInDictionary = function(word){
					for (var i = 0; i < words.length; i++) {
						if (word == words[i]){
							return i;
						}
					}
					return -1;
				}

				var computeScore = function(tweet){
					var totalScore = 0;

					for (var i = 0; i < tweet.length; i++) {
						var token = tweet[i];
						var position = positionInDictionary(token);
						var parsedScore = parseInt(scores[position]);
						if(!isNaN(parsedScore)){
							totalScore += parsedScore;
						}
					}
					return totalScore;
				}

				// var totalSentiment = 0;

				for (var i = 0; i < tweetsArray.length; i++) {
					var text = tweetsArray[i].text;
					var tokenizedTweet = tokenizeTweet(text);
					var twitterScore = computeScore(tokenizedTweet);
					console.log("TWITTER SCORE");
					console.log(twitterScore);
					// totalSentiment += twitterScore;

					tweetsArray[i].sentiment = twitterScore;
				};

				res.json(tweetsArray);
				console.log(tweetsArray);

				for (var i = 0; i < tweetsArray.length; i++) {
					var newTweet = new Tweet(tweetsArray[i]);
					newTweet.save();
					console.log("tweet added: " + req.body);
  					res.json(req.body);
				};
			}
			//end of fs.readFile(...)
		});
}

exports.saveTweets = function(req, res){
	// var newTweet = new Tweet(req.body);
 //  	newTweet.save();
 //  	console.log("tweet added: " + req.body);
 //  	res.json(req.body);
}<commit_msg>saving tweets to db works<commit_after>var fs = require('fs');
var natural = require('natural');
var tokenizer = new natural.WordTokenizer();
var twitter = require('./twitterAPI');
var mongoose = require('mongoose');
var Tweet = require('./models/tweet.js');
//var async = require('async');
exports.sayHello = function(req, res){
	// return function(req, res){
		console.log("HELLO");
	// }
}

var words = [];
var scores = [];

exports.getSentiment = function(req, res){

		console.log("calling function to get sentiment");

		// Create dictionary
		fs.readFile(__dirname + '/nlp-dict.txt', 'utf-8' ,function (err, data) {
			if (err) throw err;
			var lines = data.split('\n');

			for (var i = 0; i < lines.length; i++) {
				var definition = lines[i].split('\t');
				// console.log("word: " + definition[0] + " score: " + definition[1]);
				words.push(definition[0]);
				scores.push(definition[1]);
			};
		// End of creating dictionary

			var tweetsArray;
			twitter.getTweets(function(data) {
				tweetsArrayFunction(data);
			});

			tweetsArrayFunction = function(tweetsArray) {

				console.log("THIS MATTERS");
				console.log(tweetsArray);

				// Tokenize tweet
				var tokenizeTweet = function(tweet){
					var tokenizedTweet = tokenizer.tokenize(tweet);
					return tokenizedTweet;
				}

				// Finds if a word is in array words[]
				var positionInDictionary = function(word){
					for (var i = 0; i < words.length; i++) {
						if (word == words[i]){
							return i;
						}
					}
					return -1;
				}

				var computeScore = function(tweet){
					var totalScore = 0;

					for (var i = 0; i < tweet.length; i++) {
						var token = tweet[i];
						var position = positionInDictionary(token);
						var parsedScore = parseInt(scores[position]);
						if(!isNaN(parsedScore)){
							totalScore += parsedScore;
						}
					}
					return totalScore;
				}

				// var totalSentiment = 0;

				for (var i = 0; i < tweetsArray.length; i++) {
					var text = tweetsArray[i].text;
					var tokenizedTweet = tokenizeTweet(text);
					var twitterScore = computeScore(tokenizedTweet);
					console.log("TWITTER SCORE");
					console.log(twitterScore);
					// totalSentiment += twitterScore;

					tweetsArray[i].sentiment = twitterScore;
				};

				res.json(tweetsArray);
				console.log(tweetsArray);

				for (var i = 0; i < tweetsArray.length; i++) {
					var newTweet = new Tweet(tweetsArray[i]);
					newTweet.save();
					console.log("tweet added");
				};
			}
			//end of fs.readFile(...)
		});
}
<|endoftext|>


<commit_before>"use strict";

var express = require('express');
var api = require('./modules/projectController.js');
var errorHandler = require('./modules/errorHandler.js');
var mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

var app = express();

// Configuration
app.use('/v1', api);
app.use(errorHandler);

// Routes
app.get('/', function (req, res) {
  res.send('Regard website api running');
});

module.exports = app;<commit_msg>Make sure user is authenticated when calling api<commit_after>"use strict";

var express = require('express');
var api = require('./modules/projectController.js');
var errorHandler = require('./modules/errorHandler.js');
var mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

var app = express();

app.all('*', function (req, res, next) {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.send(401);
  }
});

app.use('/v1', api);
app.use(errorHandler);

// Routes
app.get('/', function (req, res) {
  res.send('Regard website api running');
});

module.exports = app;<|endoftext|>


<commit_before>import Viewport from '../graphics/viewport.js'
import InputHandler from './input.js'
import Sound from '../media/sound.js'
import Sfx from '../media/sfx.js'
import SongSystem from '../song/songsystem.js'
import LoadingController from './controller/1-loading.js'
import MenuController from './controller/2-menu.js'
import SongLoadController from './controller/3-song-load.js'
import SongController from './controller/4-song.js'
import ResultController from './controller/5-result.js'
import VolumeController from './controller/9-volume.js'
import LoadingScreen from '../screen/1-loading.js'
import MenuScreen from '../screen/2-menu.js'
import SongScreen from '../screen/4-song.js'
import ResultScreen from '../screen/5-result.js'
import SongInfoScreen from '../screen/8-songinfo.js'
import BackgroundScreen from '../screen/9-background.js'

export default class TypingMania {
  constructor (config) {
    this.config = Object.assign({}, {
      assets_url: 'assets/assets.dat',
      songs_url: 'data/songs.json',
    }, config)

    this.viewport = new Viewport(1920, 1080)
    this.input = new InputHandler()
    this.sound = new Sound()
    this.sfx = new Sfx(this.sound)
    this.songs = new SongSystem(this.sound)

    // Will be set in song-load because they're not global
    this.typing = null
    this.score = null
    this.media = null

    this.background_screen = new BackgroundScreen(this.viewport, '1.0.0')
    this.songinfo_screen = new SongInfoScreen(this.viewport)
    this.loading_screen = new LoadingScreen(this.viewport)
    this.menu_screen = new MenuScreen(this.viewport)
    this.song_screen = new SongScreen(this.viewport)
    this.result_screen = new ResultScreen(this.viewport)

    this.loading_controller = new LoadingController(this)
    this.menu_controller = new MenuController(this)
    this.song_load_controller = new SongLoadController(this)
    this.song_controller = new SongController(this)
    this.result_controller = new ResultController(this)

    this.volume_controller = new VolumeController(this)
  }

  reset () {
    // Reset all song-dependant system
    this.media.pause()
    this.media.destroy()
    this.typing = null
    this.score = null
    this.media = null
  }

  // Main game/input loop
  async run () {
    let runner = this.loading_controller

    while (true) {
      runner = await runner.run()
      if (!runner) {
        break
      }
    }
  }
}
<commit_msg>Prepare for 1.0.1<commit_after>import Viewport from '../graphics/viewport.js'
import InputHandler from './input.js'
import Sound from '../media/sound.js'
import Sfx from '../media/sfx.js'
import SongSystem from '../song/songsystem.js'
import LoadingController from './controller/1-loading.js'
import MenuController from './controller/2-menu.js'
import SongLoadController from './controller/3-song-load.js'
import SongController from './controller/4-song.js'
import ResultController from './controller/5-result.js'
import VolumeController from './controller/9-volume.js'
import LoadingScreen from '../screen/1-loading.js'
import MenuScreen from '../screen/2-menu.js'
import SongScreen from '../screen/4-song.js'
import ResultScreen from '../screen/5-result.js'
import SongInfoScreen from '../screen/8-songinfo.js'
import BackgroundScreen from '../screen/9-background.js'

export default class TypingMania {
  constructor (config) {
    this.config = Object.assign({}, {
      assets_url: 'assets/assets.dat',
      songs_url: 'data/songs.json',
    }, config)

    this.viewport = new Viewport(1920, 1080)
    this.input = new InputHandler()
    this.sound = new Sound()
    this.sfx = new Sfx(this.sound)
    this.songs = new SongSystem(this.sound)

    // Will be set in song-load because they're not global
    this.typing = null
    this.score = null
    this.media = null

    this.background_screen = new BackgroundScreen(this.viewport, '1.0.1')
    this.songinfo_screen = new SongInfoScreen(this.viewport)
    this.loading_screen = new LoadingScreen(this.viewport)
    this.menu_screen = new MenuScreen(this.viewport)
    this.song_screen = new SongScreen(this.viewport)
    this.result_screen = new ResultScreen(this.viewport)

    this.loading_controller = new LoadingController(this)
    this.menu_controller = new MenuController(this)
    this.song_load_controller = new SongLoadController(this)
    this.song_controller = new SongController(this)
    this.result_controller = new ResultController(this)

    this.volume_controller = new VolumeController(this)
  }

  reset () {
    // Reset all song-dependant system
    this.media.pause()
    this.media.destroy()
    this.typing = null
    this.score = null
    this.media = null
  }

  // Main game/input loop
  async run () {
    let runner = this.loading_controller

    while (true) {
      runner = await runner.run()
      if (!runner) {
        break
      }
    }
  }
}
<|endoftext|>


<commit_before>var sys = require('pex-sys');
var glu = require('pex-glu');
var materials = require('pex-materials');
var color = require('pex-color');
var gen = require('pex-gen');
var geom = require('pex-geom');
var helpers = require('pex-helpers');

var OctreeHelper = helpers.OctreeHelper;

var Cube = gen.Cube;
var Vec3 = geom.Vec3;
var Mesh = glu.Mesh;
var ShowNormals = materials.ShowNormals;
var SolidColor = materials.SolidColor;
var PerspectiveCamera = glu.PerspectiveCamera;
var Arcball = glu.Arcball;
var Color = color.Color;
var Platform = sys.Platform;
var Time = sys.Time;

sys.Window.create({
  settings: {
    width: 1280,
    height: 720,
    type: '3d',
    fullscreen: Platform.isBrowser ? true : false
  },
  init: function() {
    this.pointMesh = new Mesh(new Cube(0.05), new SolidColor({ color: Color.Red }));

    this.camera = new PerspectiveCamera(60, this.width / this.height);
    this.arcball = new Arcball(this, this.camera, 5);
    this.arcball.setTarget(new Vec3(1, 1, 0))
    this.arcball.setPosition(new Vec3(1, 1, 3))

    this.octree = new Octree(new Vec3(0, 0, 0), new Vec3(2, 2, 2));
    this.points = [];

    //this.testRandom(this.octree);
    this.testNearest(this.octree);

    this.pointInstances = this.points.map(function(p) {
      return { position: p, uniforms: { color: Color.Red } };
    })

    this.octreeHelper0 = new OctreeHelper(this.octree, Color.Green, 0);
    this.octreeHelper0.z = -0.01;
    this.octreeHelper1 = new OctreeHelper(this.octree, Color.Blue, 1);
    this.octreeHelper1.x = -0.01;
    this.octreeHelper2 = new OctreeHelper(this.octree, Color.Red, 2);
    this.octreeHelper2.x = 0.01;
    this.octreeHelper3 = new OctreeHelper(this.octree, Color.White, 3);

    this.on('mouseMoved', function(e){
      var ray = this.camera.getWorldRay(e.x, e.y, this.width, this.height);
      var hit = ray.hitTestPlane(new Vec3(0, 0, 1), new Vec3(0, 0, -1));
      if (hit.length > 0) {
        this.targetPoint = hit[0];
      }
      else {
        console.log('bla')
      }
    }.bind(this))
  },
  testRandom: function(octree) {
    var n = 10;

    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      this.points.push(p);
      octree.add(p);
    }
  },
  testNearest: function(octree) {
    var n = 100;

    geom.randomSeed(1);
    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      p.z = 1; //for easier debugging
      this.points.push(p);
    }

    //this.points.push(new Vec3(0, 0, 0));
    //this.points.push(new Vec3(1, 0, 0));
    //this.points.push(new Vec3(0, 1, 0));
    //this.points.push(new Vec3(0, 0, 1));
    //this.points.push(new Vec3(1, 0, 1));
    //this.points.push(new Vec3(1, 1, 0));
    //this.points.push(new Vec3(0, 1, 1));
    //this.points.push(new Vec3(1, 1, 1));
    //this.points.push(new Vec3(0.5, 0.5, 0.5));
    //this.points.push(new Vec3(0.75, 0.75, 0.75));

    this.points.forEach(function(p) {
      octree.add(p);
    })

    console.log('this.nearestPoint', this.nearestPoint)
  },
  draw: function() {
    glu.clearColorAndDepth(Color.Black);
    glu.enableDepthReadAndWrite(true);
    this.octreeHelper0.draw(this.camera);
    this.octreeHelper1.draw(this.camera);
    this.octreeHelper2.draw(this.camera);
    this.octreeHelper3.draw(this.camera);
    this.pointMesh.drawInstances(this.camera, this.pointInstances);

    if (!this.once) {
      //this.targetPoint = new Vec3(
      //  1 + 0.9 * Math.cos(1 * Time.seconds),
      //  1, //1 + 0.9 * Math.sin(1 * Time.seconds*1.5), //for easier debugging
      //  1 - 0.9 * Math.cos(1 * Time.seconds*0.2)
      //);
      this.targetPoint = new Vec3(1-0.51, 1, 1 + 0.49); //tricky edge case
      this.once = true;
    }

    this.nearestPoint = this.octree.findNearestPoint(this.targetPoint);

    if (this.targetPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.targetPoint, uniforms: { color: Color.Yellow } }]);
    if (this.nearestPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.nearestPoint, uniforms: { color: Color.Green }, scale: new Vec3(1.1, 1.1, 1.1) }]);
  }
});
<commit_msg>Added missing import to Octree example<commit_after>var sys = require('pex-sys');
var glu = require('pex-glu');
var materials = require('pex-materials');
var color = require('pex-color');
var gen = require('pex-gen');
var geom = require('pex-geom');
var helpers = require('pex-helpers');

var Octree = geom.Octree;
var OctreeHelper = helpers.OctreeHelper;
var Cube = gen.Cube;
var Vec3 = geom.Vec3;
var Mesh = glu.Mesh;
var ShowNormals = materials.ShowNormals;
var SolidColor = materials.SolidColor;
var PerspectiveCamera = glu.PerspectiveCamera;
var Arcball = glu.Arcball;
var Color = color.Color;
var Platform = sys.Platform;
var Time = sys.Time;

sys.Window.create({
  settings: {
    width: 1280,
    height: 720,
    type: '3d',
    fullscreen: Platform.isBrowser ? true : false
  },
  init: function() {
    this.pointMesh = new Mesh(new Cube(0.05), new SolidColor({ color: Color.Red }));

    this.camera = new PerspectiveCamera(60, this.width / this.height);
    this.arcball = new Arcball(this, this.camera, 5);
    this.arcball.setTarget(new Vec3(1, 1, 0));
    this.arcball.setPosition(new Vec3(1, 1, 4));

    this.octree = new Octree(new Vec3(0, 0, 0), new Vec3(2, 2, 2));
    this.points = [];

    //this.testRandom(this.octree);
    this.testNearest(this.octree);

    this.pointInstances = this.points.map(function(p) {
      return { position: p, uniforms: { color: Color.Red } };
    })

    this.octreeHelper0 = new OctreeHelper(this.octree, Color.Green, 0);
    this.octreeHelper0.z = -0.01;
    this.octreeHelper1 = new OctreeHelper(this.octree, Color.Blue, 1);
    this.octreeHelper1.x = -0.01;
    this.octreeHelper2 = new OctreeHelper(this.octree, Color.Red, 2);
    this.octreeHelper2.x = 0.01;
    this.octreeHelper3 = new OctreeHelper(this.octree, Color.White, 3);

    this.on('mouseMoved', function(e){
      var ray = this.camera.getWorldRay(e.x, e.y, this.width, this.height);
      var hit = ray.hitTestPlane(new Vec3(0, 0, 1), new Vec3(0, 0, -1));
      if (hit.length > 0) {
        this.targetPoint = hit[0];
      }
      else {
        console.log('bla')
      }
    }.bind(this))
  },
  testRandom: function(octree) {
    var n = 10;

    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      this.points.push(p);
      octree.add(p);
    }
  },
  testNearest: function(octree) {
    var n = 100;

    geom.randomSeed(1);
    for(var i=0; i<n; i++) {
      var p = geom.randomVec3(1).add(new Vec3(1, 1, 1)); //move the points to (0,0,0),(2,2,2) box
      p.z = 1; //for easier debugging
      this.points.push(p);
    }

    //this.points.push(new Vec3(0, 0, 0));
    //this.points.push(new Vec3(1, 0, 0));
    //this.points.push(new Vec3(0, 1, 0));
    //this.points.push(new Vec3(0, 0, 1));
    //this.points.push(new Vec3(1, 0, 1));
    //this.points.push(new Vec3(1, 1, 0));
    //this.points.push(new Vec3(0, 1, 1));
    //this.points.push(new Vec3(1, 1, 1));
    //this.points.push(new Vec3(0.5, 0.5, 0.5));
    //this.points.push(new Vec3(0.75, 0.75, 0.75));

    this.points.forEach(function(p) {
      octree.add(p);
    })

    console.log('this.nearestPoint', this.nearestPoint)
  },
  draw: function() {
    glu.clearColorAndDepth(Color.Black);
    glu.enableDepthReadAndWrite(true);
    this.octreeHelper0.draw(this.camera);
    this.octreeHelper1.draw(this.camera);
    this.octreeHelper2.draw(this.camera);
    this.octreeHelper3.draw(this.camera);
    this.pointMesh.drawInstances(this.camera, this.pointInstances);

    if (!this.once) {
      //this.targetPoint = new Vec3(
      //  1 + 0.9 * Math.cos(1 * Time.seconds),
      //  1, //1 + 0.9 * Math.sin(1 * Time.seconds*1.5), //for easier debugging
      //  1 - 0.9 * Math.cos(1 * Time.seconds*0.2)
      //);
      this.targetPoint = new Vec3(1-0.51, 1, 1 + 0.49); //tricky edge case
      this.once = true;
    }

    this.nearestPoint = this.octree.findNearestPoint(this.targetPoint);

    if (this.targetPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.targetPoint, uniforms: { color: Color.Yellow } }]);
    if (this.nearestPoint) this.pointMesh.drawInstances(this.camera, [ { position: this.nearestPoint, uniforms: { color: Color.Green }, scale: new Vec3(1.1, 1.1, 1.1) }]);
  }
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React, {Suspense, useCallback, useEffect, useRef, useState} from 'react'
import {arrayOf, bool, func, instanceOf, number, oneOfType, shape, string} from 'prop-types'
import formatMessage from 'format-message'

import {Billboard} from '@instructure/ui-billboard'
import {Button} from '@instructure/ui-buttons'
import {Checkbox} from '@instructure/ui-checkbox'
import {FileDrop} from '@instructure/ui-file-drop'
import {Flex} from '@instructure/ui-flex'
import {View} from '@instructure/ui-view'
import {IconTrashLine, IconVideoLine} from '@instructure/ui-icons'
import {ScreenReaderContent} from '@instructure/ui-a11y-content'
import {Text} from '@instructure/ui-text'
import {px} from '@instructure/ui-utils'
import {MediaPlayer} from '@instructure/ui-media-player'
import {TextInput} from '@instructure/ui-text-input'

import LoadingIndicator from './shared/LoadingIndicator'
import RocketSVG from './RocketSVG'
import translationShape from './translationShape'
import useComputerPanelFocus from './useComputerPanelFocus'
import {isAudio, isVideo, isPreviewable, sizeMediaPlayer} from './shared/utils'

const ClosedCaptionPanel = React.lazy(() => import('./ClosedCaptionCreator'))

export default function ComputerPanel({
  accept,
  hasUploadedFile,
  label,
  languages,
  liveRegion,
  setFile,
  setHasUploadedFile,
  theFile,
  uploadMediaTranslations,
  updateSubtitles,
  bounds
}) {
  const {
    ADD_CLOSED_CAPTIONS_OR_SUBTITLES,
    LOADING_MEDIA
  } = uploadMediaTranslations.UploadMediaStrings
  const [messages, setMessages] = useState([])
  const [mediaTracksCheckbox, setMediaTracksCheckbox] = useState(false)
  const [previewURL, setPreviewURL] = useState(null)
  const height = 0.8 * (bounds?.height - 38 - px('1.5rem')) // the trashcan is 38px tall and the 1.5rem margin-bottom
  const width = 0.8 * bounds?.width

  const previewPanelRef = useRef(null)
  const clearButtonRef = useRef(null)
  const panelRef = useRef(null)
  useComputerPanelFocus(theFile, panelRef, clearButtonRef)

  useEffect(() => {
    return () => URL?.revokeObjectURL?.(previewURL)
  }, [previewURL])

  useEffect(() => {
    if (previewPanelRef.current && mediaTracksCheckbox) {
      previewPanelRef.current.scrollIntoView(false)
    }
  }, [mediaTracksCheckbox])

  const handlePlayerSize = useCallback(
    _event => {
      const player = previewPanelRef.current.querySelector('video')
      let boundingBox = {width, height}
      if (document.fullscreenElement || document.webkitFullscreenElement) {
        boundingBox = {
          width: window.innerWidth,
          height: window.innerHeight
        }
      }
      const sz = sizeMediaPlayer(player, theFile.type, boundingBox)
      player.style.width = sz.width
      player.style.height = sz.height
      player.style.margin = '0 auto'
      // from this sub-package, I don't have a URL to use as the
      // audio player's poster image. We can give it a background image though
      player.classList.add(isAudio(theFile.type) ? 'audio-player' : 'video-player')
    },
    [theFile, width, height]
  )

  const handleLoadedMetadata = useCallback(
    _event => {
      handlePlayerSize()
    },
    [handlePlayerSize]
  )

  useEffect(() => {
    window.addEventListener('resize', handlePlayerSize)
    return () => {
      window.removeEventListener('resize', handlePlayerSize)
    }
  }, [handlePlayerSize])

  if (hasUploadedFile) {
    return (

        <Flex direction="row-reverse" margin="none none medium">
          <Flex.Item>
            <Button
              elementRef={el => {
                clearButtonRef.current = el
              }}
              onClick={() => {
                setFile(null)
                setHasUploadedFile(false)
                setPreviewURL(null)
              }}
              renderIcon={IconTrashLine}
            >
              <ScreenReaderContent>
                {uploadMediaTranslations.UploadMediaStrings.CLEAR_FILE_TEXT}
              </ScreenReaderContent>
            </Button>
          </Flex.Item>
        </Flex>
        <View as="div" textAlign="center" margin="0 auto">
          {/* avi, wma, and wmv files won't load from a blob URL */}
          {!(isPreviewable(theFile.type) && previewURL) ? (
            <>
              <IconVideoLine size="medium" data-testid="preview-video-icon" />
              <Text as="p" weight="normal">
                {formatMessage('No preview is available for this file.')}
              </Text>
            </>
          ) : (
            <MediaPlayer
              sources={[{label: theFile.name, src: previewURL, type: theFile.type}]}
              hideFullScreen={!(document.fullscreenEnabled || document.webkitFullscreenEnabled)}
              onLoadedMetadata={handleLoadedMetadata}
            />
          )}
        </View>
        <View display="block" padding="medium 0 0">
          <TextInput
            placeholder={formatMessage('File name')}
            value={theFile.title}
            onChange={(e, val) => {
              theFile.title = val
              setFile(theFile)
            }}
          />
        </View>
        {isVideo(theFile.type) && (
          <>
            <View display="block" padding="medium medium medium 0">
              <Checkbox
                onChange={event => setMediaTracksCheckbox(event.target.checked)}
                checked={mediaTracksCheckbox}
                label={ADD_CLOSED_CAPTIONS_OR_SUBTITLES}
                value="mediaTracks"
              />
            </View>
            {mediaTracksCheckbox && (
              <Suspense fallback={LoadingIndicator(LOADING_MEDIA)}>
                <ClosedCaptionPanel
                  languages={languages}
                  liveRegion={liveRegion}
                  uploadMediaTranslations={uploadMediaTranslations}
                  updateSubtitles={updateSubtitles}
                />
              </Suspense>
            )}
          </>
        )}

    )
  }

  return (

      <FileDrop
        accept={accept}
        onDropAccepted={([file]) => {
          if (messages.length) {
            setMessages([])
          }
          file.title = file.name
          setFile(file)
          setHasUploadedFile(true)
          setPreviewURL(URL.createObjectURL(file))
        }}
        onDropRejected={() => {
          setMessages(msgs =>
            msgs.concat({
              text: uploadMediaTranslations.UploadMediaStrings.INVALID_FILE_TEXT,
              type: 'error'
            })
          )
        }}
        messages={messages}
        renderLabel={
          <Billboard
            heading={label}
            hero={<RocketSVG width="3em" height="3em" />}
            message={uploadMediaTranslations.UploadMediaStrings.DRAG_DROP_CLICK_TO_BROWSE}
          />
        }
      />

  )
}

ComputerPanel.propTypes = {
  accept: oneOfType([string, arrayOf(string)]),
  hasUploadedFile: bool,
  label: string.isRequired,
  languages: arrayOf(
    shape({
      id: string,
      label: string
    })
  ),
  liveRegion: func,
  setFile: func.isRequired,
  setHasUploadedFile: func.isRequired,
  theFile: instanceOf(File),
  uploadMediaTranslations: translationShape,
  updateSubtitles: func.isRequired,
  bounds: shape({
    width: number.isRequired,
    height: number.isRequired
  })
}
<commit_msg>Add label to input after uploading file<commit_after>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React, {Suspense, useCallback, useEffect, useRef, useState} from 'react'
import {arrayOf, bool, func, instanceOf, number, oneOfType, shape, string} from 'prop-types'
import formatMessage from 'format-message'

import {Billboard} from '@instructure/ui-billboard'
import {Button} from '@instructure/ui-buttons'
import {Checkbox} from '@instructure/ui-checkbox'
import {FileDrop} from '@instructure/ui-file-drop'
import {Flex} from '@instructure/ui-flex'
import {View} from '@instructure/ui-view'
import {IconTrashLine, IconVideoLine} from '@instructure/ui-icons'
import {ScreenReaderContent} from '@instructure/ui-a11y-content'
import {Text} from '@instructure/ui-text'
import {px} from '@instructure/ui-utils'
import {MediaPlayer} from '@instructure/ui-media-player'
import {TextInput} from '@instructure/ui-text-input'

import LoadingIndicator from './shared/LoadingIndicator'
import RocketSVG from './RocketSVG'
import translationShape from './translationShape'
import useComputerPanelFocus from './useComputerPanelFocus'
import {isAudio, isVideo, isPreviewable, sizeMediaPlayer} from './shared/utils'

const ClosedCaptionPanel = React.lazy(() => import('./ClosedCaptionCreator'))

export default function ComputerPanel({
  accept,
  hasUploadedFile,
  label,
  languages,
  liveRegion,
  setFile,
  setHasUploadedFile,
  theFile,
  uploadMediaTranslations,
  updateSubtitles,
  bounds
}) {
  const {
    ADD_CLOSED_CAPTIONS_OR_SUBTITLES,
    LOADING_MEDIA
  } = uploadMediaTranslations.UploadMediaStrings
  const [messages, setMessages] = useState([])
  const [mediaTracksCheckbox, setMediaTracksCheckbox] = useState(false)
  const [previewURL, setPreviewURL] = useState(null)
  const height = 0.8 * (bounds?.height - 38 - px('1.5rem')) // the trashcan is 38px tall and the 1.5rem margin-bottom
  const width = 0.8 * bounds?.width

  const previewPanelRef = useRef(null)
  const clearButtonRef = useRef(null)
  const panelRef = useRef(null)
  useComputerPanelFocus(theFile, panelRef, clearButtonRef)

  useEffect(() => {
    return () => URL?.revokeObjectURL?.(previewURL)
  }, [previewURL])

  useEffect(() => {
    if (previewPanelRef.current && mediaTracksCheckbox) {
      previewPanelRef.current.scrollIntoView(false)
    }
  }, [mediaTracksCheckbox])

  const handlePlayerSize = useCallback(
    _event => {
      const player = previewPanelRef.current.querySelector('video')
      let boundingBox = {width, height}
      if (document.fullscreenElement || document.webkitFullscreenElement) {
        boundingBox = {
          width: window.innerWidth,
          height: window.innerHeight
        }
      }
      const sz = sizeMediaPlayer(player, theFile.type, boundingBox)
      player.style.width = sz.width
      player.style.height = sz.height
      player.style.margin = '0 auto'
      // from this sub-package, I don't have a URL to use as the
      // audio player's poster image. We can give it a background image though
      player.classList.add(isAudio(theFile.type) ? 'audio-player' : 'video-player')
    },
    [theFile, width, height]
  )

  const handleLoadedMetadata = useCallback(
    _event => {
      handlePlayerSize()
    },
    [handlePlayerSize]
  )

  useEffect(() => {
    window.addEventListener('resize', handlePlayerSize)
    return () => {
      window.removeEventListener('resize', handlePlayerSize)
    }
  }, [handlePlayerSize])

  if (hasUploadedFile) {
    return (

        <Flex direction="row-reverse" margin="none none medium">
          <Flex.Item>
            <Button
              elementRef={el => {
                clearButtonRef.current = el
              }}
              onClick={() => {
                setFile(null)
                setHasUploadedFile(false)
                setPreviewURL(null)
              }}
              renderIcon={IconTrashLine}
            >
              <ScreenReaderContent>
                {uploadMediaTranslations.UploadMediaStrings.CLEAR_FILE_TEXT}
              </ScreenReaderContent>
            </Button>
          </Flex.Item>
        </Flex>
        <View as="div" textAlign="center" margin="0 auto">
          {/* avi, wma, and wmv files won't load from a blob URL */}
          {!(isPreviewable(theFile.type) && previewURL) ? (
            <>
              <IconVideoLine size="medium" data-testid="preview-video-icon" />
              <Text as="p" weight="normal">
                {formatMessage('No preview is available for this file.')}
              </Text>
            </>
          ) : (
            <MediaPlayer
              sources={[{label: theFile.name, src: previewURL, type: theFile.type}]}
              hideFullScreen={!(document.fullscreenEnabled || document.webkitFullscreenEnabled)}
              onLoadedMetadata={handleLoadedMetadata}
            />
          )}
        </View>
        <View display="block" padding="medium 0 0">
          <TextInput
            renderLabel={formatMessage('File name')}
            placeholder={formatMessage('File name')}
            value={theFile.title}
            onChange={(e, val) => {
              theFile.title = val
              setFile(theFile)
            }}
          />
        </View>
        {isVideo(theFile.type) && (
          <>
            <View display="block" padding="medium medium medium 0">
              <Checkbox
                onChange={event => setMediaTracksCheckbox(event.target.checked)}
                checked={mediaTracksCheckbox}
                label={ADD_CLOSED_CAPTIONS_OR_SUBTITLES}
                value="mediaTracks"
              />
            </View>
            {mediaTracksCheckbox && (
              <Suspense fallback={LoadingIndicator(LOADING_MEDIA)}>
                <ClosedCaptionPanel
                  languages={languages}
                  liveRegion={liveRegion}
                  uploadMediaTranslations={uploadMediaTranslations}
                  updateSubtitles={updateSubtitles}
                />
              </Suspense>
            )}
          </>
        )}

    )
  }

  return (

      <FileDrop
        accept={accept}
        onDropAccepted={([file]) => {
          if (messages.length) {
            setMessages([])
          }
          file.title = file.name
          setFile(file)
          setHasUploadedFile(true)
          setPreviewURL(URL.createObjectURL(file))
        }}
        onDropRejected={() => {
          setMessages(msgs =>
            msgs.concat({
              text: uploadMediaTranslations.UploadMediaStrings.INVALID_FILE_TEXT,
              type: 'error'
            })
          )
        }}
        messages={messages}
        renderLabel={
          <Billboard
            heading={label}
            hero={<RocketSVG width="3em" height="3em" />}
            message={uploadMediaTranslations.UploadMediaStrings.DRAG_DROP_CLICK_TO_BROWSE}
          />
        }
      />

  )
}

ComputerPanel.propTypes = {
  accept: oneOfType([string, arrayOf(string)]),
  hasUploadedFile: bool,
  label: string.isRequired,
  languages: arrayOf(
    shape({
      id: string,
      label: string
    })
  ),
  liveRegion: func,
  setFile: func.isRequired,
  setHasUploadedFile: func.isRequired,
  theFile: instanceOf(File),
  uploadMediaTranslations: translationShape,
  updateSubtitles: func.isRequired,
  bounds: shape({
    width: number.isRequired,
    height: number.isRequired
  })
}
<|endoftext|>


<commit_before>const path = require("path");
const fs = require('fs');
const spawn  = require('cross-spawn');

function _parserPath(path){
  return [process.cwd(), destination].join(path.sep)
}
module.exports = function copy(root,destination){
  const destinationPath = _parserPath(destination)
  //TODO Move this method to validate in another function to throw a error and prompt another name
  if(fs.existsSync(destinationPath)){
    if(fs.readdirSync(destinationPath).length > 0) return Promise.reject(`directory ${destinationPath} exist and not empty`);
  }
  return spawn.sync('cp', ['-r', root, destinationPath]);
}

<commit_msg>[refactor] [m]: split fun to validate and parser path<commit_after>const path = require("path");
const fs = require('fs');
const spawn  = require('cross-spawn');

function _parserPath(projectPath){
  return [process.cwd(), projectPath].join(path.sep)
}

function copy(root,destination){
  const destinationPath = _parserPath(destination)
  return spawn.sync('cp', ['-r', root, destinationPath]);
}

function isPathInUse(projectPath){
  const fullPath = _parserPath(projectPath)
  const isPathExists = fs.existsSync(fullPath)
  if(isPathExists) {
    return fs.readdirSync(fullPath).length
  }
  return isPathExists
}

module.exports = { copy, isPathInUse }<|endoftext|>


<commit_before>const ReplManager = require("./repl");
const Command = require("./command");
const provision = require("@truffle/provisioner");
const { Web3Shim } = require("@truffle/interface-adapter");
const contract = require("@truffle/contract");
const vm = require("vm");
const expect = require("@truffle/expect");
const TruffleError = require("@truffle/error");
const fse = require("fs-extra");
const path = require("path");
const EventEmitter = require("events");

const processInput = input => {
  const inputComponents = input.trim().split(" ");
  if (inputComponents.length === 0) return input;

  if (inputComponents[0] === "truffle") {
    return inputComponents.slice(1).join(" ");
  }
  return input.trim();
};

class Console extends EventEmitter {
  constructor(tasks, options) {
    super();
    EventEmitter.call(this);

    expect.options(options, [
      "working_directory",
      "contracts_directory",
      "contracts_build_directory",
      "migrations_directory",
      "networks",
      "network",
      "network_id",
      "provider",
      "resolver",
      "build_directory"
    ]);

    this.options = options;

    this.repl = options.repl || new ReplManager(options);
    this.command = new Command(tasks);

    this.web3 = new Web3Shim({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });

    // Bubble the ReplManager's exit event
    this.repl.on("exit", () => this.emit("exit"));
  }

  start(callback) {
    if (!this.repl) this.repl = new Repl(this.options);

    // TODO: This should probalby be elsewhere.
    // It's here to ensure the repl manager instance gets
    // passed down to commands.
    this.options.repl = this.repl;

    try {
      this.web3.eth.getAccounts().then(fetchedAccounts => {
        const abstractions = this.provision();

        this.repl.start({
          prompt: "truffle(" + this.options.network + ")> ",
          context: {
            web3: this.web3,
            accounts: fetchedAccounts
          },
          interpreter: this.interpret.bind(this),
          done: callback
        });

        this.resetContractsInConsoleContext(abstractions);
      });
    } catch (error) {
      this.options.logger.log(
        "Unexpected error: Cannot provision contracts while instantiating the console."
      );
      this.options.logger.log(error.stack || error.message || error);
    }
  }

  provision() {
    let files;
    try {
      files = fse.readdirSync(this.options.contracts_build_directory);
    } catch (error) {
      // Error reading the build directory? Must mean it doesn't exist or we don't have access to it.
      // Couldn't provision the contracts if we wanted. It's possible we're hiding very rare FS
      // errors, but that's better than showing the user error messages that will be "build folder
      // doesn't exist" 99.9% of the time.
    }

    let jsonBlobs = [];
    files = files || [];

    files.forEach(file => {
      try {
        const body = fse.readFileSync(
          path.join(this.options.contracts_build_directory, file),
          "utf8"
        );
        jsonBlobs.push(JSON.parse(body));
      } catch (error) {
        throw new Error(`Error parsing or reading ${file}: ${error.message}`);
      }
    });

    const abstractions = jsonBlobs.map(json => {
      const abstraction = contract(json);
      provision(abstraction, this.options);
      return abstraction;
    });

    this.resetContractsInConsoleContext(abstractions);

    return abstractions;
  }

  resetContractsInConsoleContext(abstractions) {
    abstractions = abstractions || [];

    const contextVars = {};

    abstractions.forEach(abstraction => {
      contextVars[abstraction.contract_name] = abstraction;
    });

    this.repl.setContextVars(contextVars);
  }

  interpret(input, context, filename, callback) {
    const processedInput = processInput(input);
    if (
      this.command.getCommand(processedInput, this.options.noAliases) != null
    ) {
      return this.command.run(processedInput, this.options, error => {
        if (error) {
          // Perform error handling ourselves.
          if (error instanceof TruffleError) {
            console.log(error.message);
          } else {
            // Bubble up all other unexpected errors.
            console.log(error.stack || error.toString());
          }
          return callback();
        }

        // Reprovision after each command as it may change contracts.
        try {
          this.provision();
          callback();
        } catch (error) {
          // Don't pass abstractions to the callback if they're there or else
          // they'll get printed in the repl.
          callback(error);
        }
      });
    }

    // Much of the following code is from here, though spruced up:
    // https://github.com/nfcampos/await-outside

    /*
    - allow whitespace before everything else
    - optionally capture `var|let|const <varname> = `
      - varname only matches if it starts with a-Z or _ or $
        and if contains only those chars or numbers
      - this is overly restrictive but is easier to maintain
    - capture `await <anything that follows it>`
    */
    let includesAwait = /^\s*((?:(?:var|const|let)\s+)?[a-zA-Z_$][0-9a-zA-Z_$]*\s*=\s*)?(\(?\s*await[\s\S]*)/;

    const match = processedInput.match(includesAwait);
    let source = processedInput;
    let assignment = null;

    // If our code includes an await, add special processing to ensure it's evaluated properly.
    if (match) {
      let assign = match[1];
      const expression = match[2];

      const RESULT = "__await_outside_result";

      // Wrap the await inside an async function.
      // Strange indentation keeps column offset correct in stack traces
      source = `(async function() { try { ${
        assign ? `global.${RESULT} =` : "return"
      } (
  ${expression.trim()}
  ); } catch(e) { global.ERROR = e; throw e; } }())`;

      assignment = assign
        ? `${assign.trim()} global.${RESULT}; void delete global.${RESULT};`
        : null;
    }

    const runScript = script => {
      const options = {
        displayErrors: true,
        breakOnSigint: true,
        filename: filename
      };
      return script.runInContext(context, options);
    };

    let script;
    try {
      const options = { displayErrors: true, lineOffset: -1 };
      script = vm.createScript(source, options);
    } catch (error) {
      // If syntax error, or similar, bail.
      return callback(error);
    }

    // Ensure our script returns a promise whether we're using an
    // async function or not. If our script is an async function,
    // this will ensure the console waits until that await is finished.
    Promise.resolve(runScript(script))
      .then(value => {
        // If there's an assignment to run, run that.
        if (assignment) return runScript(vm.createScript(assignment));
        return value;
      })
      .then(value => {
        // All good? Return the value (e.g., eval'd script or assignment)
        callback(null, value);
      })
      .catch(callback);
  }
}

module.exports = Console;
<commit_msg>fix: filter console reading of contracts_build_directory for json files only<commit_after>const ReplManager = require("./repl");
const Command = require("./command");
const provision = require("@truffle/provisioner");
const { Web3Shim } = require("@truffle/interface-adapter");
const contract = require("@truffle/contract");
const vm = require("vm");
const expect = require("@truffle/expect");
const TruffleError = require("@truffle/error");
const fse = require("fs-extra");
const path = require("path");
const EventEmitter = require("events");

const processInput = input => {
  const inputComponents = input.trim().split(" ");
  if (inputComponents.length === 0) return input;

  if (inputComponents[0] === "truffle") {
    return inputComponents.slice(1).join(" ");
  }
  return input.trim();
};

class Console extends EventEmitter {
  constructor(tasks, options) {
    super();
    EventEmitter.call(this);

    expect.options(options, [
      "working_directory",
      "contracts_directory",
      "contracts_build_directory",
      "migrations_directory",
      "networks",
      "network",
      "network_id",
      "provider",
      "resolver",
      "build_directory"
    ]);

    this.options = options;

    this.repl = options.repl || new ReplManager(options);
    this.command = new Command(tasks);

    this.web3 = new Web3Shim({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });

    // Bubble the ReplManager's exit event
    this.repl.on("exit", () => this.emit("exit"));
  }

  start(callback) {
    if (!this.repl) this.repl = new Repl(this.options);

    // TODO: This should probalby be elsewhere.
    // It's here to ensure the repl manager instance gets
    // passed down to commands.
    this.options.repl = this.repl;

    try {
      this.web3.eth.getAccounts().then(fetchedAccounts => {
        const abstractions = this.provision();

        this.repl.start({
          prompt: "truffle(" + this.options.network + ")> ",
          context: {
            web3: this.web3,
            accounts: fetchedAccounts
          },
          interpreter: this.interpret.bind(this),
          done: callback
        });

        this.resetContractsInConsoleContext(abstractions);
      });
    } catch (error) {
      this.options.logger.log(
        "Unexpected error: Cannot provision contracts while instantiating the console."
      );
      this.options.logger.log(error.stack || error.message || error);
    }
  }

  provision() {
    let files;
    try {
      const unfilteredFiles = fse.readdirSync(
        this.options.contracts_build_directory
      );
      files = unfilteredFiles.filter(file => file.match(".json") !== null);
    } catch (error) {
      // Error reading the build directory? Must mean it doesn't exist or we don't have access to it.
      // Couldn't provision the contracts if we wanted. It's possible we're hiding very rare FS
      // errors, but that's better than showing the user error messages that will be "build folder
      // doesn't exist" 99.9% of the time.
    }

    let jsonBlobs = [];
    files = files || [];

    files.forEach(file => {
      try {
        const body = fse.readFileSync(
          path.join(this.options.contracts_build_directory, file),
          "utf8"
        );
        jsonBlobs.push(JSON.parse(body));
      } catch (error) {
        throw new Error(`Error parsing or reading ${file}: ${error.message}`);
      }
    });

    const abstractions = jsonBlobs.map(json => {
      const abstraction = contract(json);
      provision(abstraction, this.options);
      return abstraction;
    });

    this.resetContractsInConsoleContext(abstractions);

    return abstractions;
  }

  resetContractsInConsoleContext(abstractions) {
    abstractions = abstractions || [];

    const contextVars = {};

    abstractions.forEach(abstraction => {
      contextVars[abstraction.contract_name] = abstraction;
    });

    this.repl.setContextVars(contextVars);
  }

  interpret(input, context, filename, callback) {
    const processedInput = processInput(input);
    if (
      this.command.getCommand(processedInput, this.options.noAliases) != null
    ) {
      return this.command.run(processedInput, this.options, error => {
        if (error) {
          // Perform error handling ourselves.
          if (error instanceof TruffleError) {
            console.log(error.message);
          } else {
            // Bubble up all other unexpected errors.
            console.log(error.stack || error.toString());
          }
          return callback();
        }

        // Reprovision after each command as it may change contracts.
        try {
          this.provision();
          callback();
        } catch (error) {
          // Don't pass abstractions to the callback if they're there or else
          // they'll get printed in the repl.
          callback(error);
        }
      });
    }

    // Much of the following code is from here, though spruced up:
    // https://github.com/nfcampos/await-outside

    /*
    - allow whitespace before everything else
    - optionally capture `var|let|const <varname> = `
      - varname only matches if it starts with a-Z or _ or $
        and if contains only those chars or numbers
      - this is overly restrictive but is easier to maintain
    - capture `await <anything that follows it>`
    */
    let includesAwait = /^\s*((?:(?:var|const|let)\s+)?[a-zA-Z_$][0-9a-zA-Z_$]*\s*=\s*)?(\(?\s*await[\s\S]*)/;

    const match = processedInput.match(includesAwait);
    let source = processedInput;
    let assignment = null;

    // If our code includes an await, add special processing to ensure it's evaluated properly.
    if (match) {
      let assign = match[1];
      const expression = match[2];

      const RESULT = "__await_outside_result";

      // Wrap the await inside an async function.
      // Strange indentation keeps column offset correct in stack traces
      source = `(async function() { try { ${
        assign ? `global.${RESULT} =` : "return"
      } (
  ${expression.trim()}
  ); } catch(e) { global.ERROR = e; throw e; } }())`;

      assignment = assign
        ? `${assign.trim()} global.${RESULT}; void delete global.${RESULT};`
        : null;
    }

    const runScript = script => {
      const options = {
        displayErrors: true,
        breakOnSigint: true,
        filename: filename
      };
      return script.runInContext(context, options);
    };

    let script;
    try {
      const options = { displayErrors: true, lineOffset: -1 };
      script = vm.createScript(source, options);
    } catch (error) {
      // If syntax error, or similar, bail.
      return callback(error);
    }

    // Ensure our script returns a promise whether we're using an
    // async function or not. If our script is an async function,
    // this will ensure the console waits until that await is finished.
    Promise.resolve(runScript(script))
      .then(value => {
        // If there's an assignment to run, run that.
        if (assignment) return runScript(vm.createScript(assignment));
        return value;
      })
      .then(value => {
        // All good? Return the value (e.g., eval'd script or assignment)
        callback(null, value);
      })
      .catch(callback);
  }
}

module.exports = Console;
<|endoftext|>


<commit_before>import { join } from 'path';
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

let getCommonConfig = {
  getLoders: function (args) {
    let name = args.hash ? '[name].[hash:8].[ext]' : '[name].[ext]';
    const babelQuery = {
      presets: ['stage-0', 'es2015', 'react']
    };
    const loaders = [
      { test: /\.js$/, loader: 'babel', query: babelQuery, exclude: /node_modules/ },
      { test: /\.json$/, loader: 'json' },
      { test: /\.(png|jpg|gif)$/, loader: 'url?limit=2048', name: `images/${name}` },
      { test: /\.woff$/, loader: 'url?limit=100&minetype=application/font-woff', name: `fonts/${name}` },
      { test: /\.woff2$/, loader: 'url?limit=100&minetype=application/font-woff2', name: `fonts/${name}` },
      { test: /\.ttf$/, loader: 'url?limit=100&minetype=application/octet-stream', name: `fonts/${name}` },
      { test: /\.eot$/, loader: 'url?limit=100', name: `fonts/${name}` },
      { test: /\.svg$/, loader: 'url?limit=10000&minetype=image/svg+xml', name: `fonts/${name}` }
    ];
    return loaders.concat(this.getCssLoaders(args))
  },
  getCssLoaders: function (args) {
    let cssLoaderLocal = 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss?pack=default';
    let cssLoaderGlobal = 'css!postcss?pack=default';
    let lessLoader = 'css?importLoaders=1!less!postcss?pack=default'
    if (args.extractCss) {
      cssLoaderLocal = ExtractTextPlugin.extract('style', cssLoaderLocal);
      cssLoaderGlobal = ExtractTextPlugin.extract('style', cssLoaderGlobal);
      lessLoader = ExtractTextPlugin.extract('style', lessLoader);
    } else {
      cssLoaderLocal = 'style!' + cssLoaderLocal;
      cssLoaderGlobal = 'style!' + cssLoaderGlobal;
      lessLoader = 'style!' + lessLoader;
    }
    if (args.cssModules) {
      return [
        { test: /\.css$/, loader: cssLoaderLocal, exclude: /node_modules/ },
        { test: /\.css$/, loader: cssLoaderGlobal, include: /node_modules/ },
        { test: /\.less$/, loader: lessLoader, include: /node_modules/ }
      ];
    } else {
      return [
        { test: /\.css$/, loader: cssLoaderGlobal },
        { test: /\.less$/, loader: lessLoader }
      ]
    }
  },
  getPluigns: function (args) {
    const vendorJsName = args.hash ? 'vendor.[chunkhash:8].js' : 'vendor.js';
    const cssName = args.hash ? '[name].[chunkhash:8].js' : '[name].js';
    let plugins = [
      new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(args.env) }),
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: vendorJsName, minChunks: Infinity }),
      new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: false })
    ]
    if (args.extractCss) {
      return plugins.concat([
        new ExtractTextPlugin(cssName, { allChunks: true })
      ])
    }
  }
}

/** args {Object}
  * args = {
  *   ...
  *   cwd {String} process.cwd
  *   devtool {String} choost webpack devtool, `false` recommended
  *   publicPath {String} could be a cdn prefix, default `/static/`
  *   hash {Boolean} determine to hash js/css or not, default `true`
  *   extractCss {Boolean} determine to extract css file or not, default `true`
  *   cssModules {Boolean} determine to make css(exclude /node_modules/) modular or not, default `true`
  *   ...
  * }
**/

export default function getDefaultConfig (args) {
  let pkg = require(join(args.cwd, 'package.json'));

  const jsName = args.hash ? '[name].[chunkhash:8].js' : '[name].js';

  return {
    devtool: args.devtool || false,
    entry: pkg.entry,
    output: {
      path: join(args.cwd, 'build'),
      filename: jsName,
      publicPath: args.publicPath || '/static/'
    },
    module: {
      loaders: getCommonConfig.getLoders(args)
    },
    resolve: {
      extensions: ['', '.js']
    },
    plugins: getCommonConfig.getPluigns(args),
    postcss: function () {
      return {
        default: [ require('autoprefixer')({ browsers: ['last 2 versions'] }) ]
      }
    }
  }
}
<commit_msg>fix loader query part<commit_after>import { join } from 'path';
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

let getCommonConfig = {
  getLoders: function (args) {
    let name = args.hash ? '[name].[hash:8].[ext]' : '[name].[ext]';
    const babelQuery = {
      presets: ['stage-0', 'es2015', 'react']
    };
    const loaders = [
      { test: /\.js$/, loader: 'babel', query: babelQuery, exclude: /node_modules/ },
      { test: /\.json$/, loader: 'json' },
      { test: /\.(png|jpg|gif)$/, loader: 'url', query: { limit: 2048, name: `images/${name}` } },
      { test: /\.woff$/, loader: 'url', query: { limit: 100, minetype: 'application/font-woff', name: `fonts/${name}` } },
      { test: /\.woff2$/, loader: 'url', query: { limit: 100, minetype: 'application/font-woff2', name: `fonts/${name}` } },
      { test: /\.ttf$/, loader: 'url', query: { limit: 100, minetype: 'application/octet-stream', name: `fonts/${name}` } },
      { test: /\.eot$/, loader: 'url', query: { limit: 100, name: `fonts/${name}` } },
      { test: /\.svg$/, loader: 'url', query: { limit: 10000, minetype: 'image/svg+xml', name: `fonts/${name}` } }
    ];
    return loaders.concat(this.getCssLoaders(args))
  },
  getCssLoaders: function (args) {
    let cssLoaderLocal = 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss?pack=default';
    let cssLoaderGlobal = 'css!postcss?pack=default';
    let lessLoader = 'css?importLoaders=1!less!postcss?pack=default'
    if (args.extractCss) {
      cssLoaderLocal = ExtractTextPlugin.extract('style', cssLoaderLocal);
      cssLoaderGlobal = ExtractTextPlugin.extract('style', cssLoaderGlobal);
      lessLoader = ExtractTextPlugin.extract('style', lessLoader);
    } else {
      cssLoaderLocal = 'style!' + cssLoaderLocal;
      cssLoaderGlobal = 'style!' + cssLoaderGlobal;
      lessLoader = 'style!' + lessLoader;
    }
    if (args.cssModules) {
      return [
        { test: /\.css$/, loader: cssLoaderLocal, exclude: /node_modules/ },
        { test: /\.css$/, loader: cssLoaderGlobal, include: /node_modules/ },
        { test: /\.less$/, loader: lessLoader, include: /node_modules/ }
      ];
    } else {
      return [
        { test: /\.css$/, loader: cssLoaderGlobal },
        { test: /\.less$/, loader: lessLoader }
      ]
    }
  },
  getPluigns: function (args) {
    const vendorJsName = args.hash ? 'vendor.[chunkhash:8].js' : 'vendor.js';
    const cssName = args.hash ? '[name].[chunkhash:8].js' : '[name].js';
    let plugins = [
      new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(args.env) }),
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: vendorJsName, minChunks: Infinity }),
      new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: false })
    ]
    if (args.extractCss) {
      return plugins.concat([
        new ExtractTextPlugin(cssName, { allChunks: true })
      ])
    }
  }
}

/** args {Object}
  * args = {
  *   ...
  *   cwd {String} process.cwd
  *   devtool {String} choost webpack devtool, `false` recommended
  *   publicPath {String} could be a cdn prefix, default `/static/`
  *   hash {Boolean} determine to hash js/css or not, default `true`
  *   extractCss {Boolean} determine to extract css file or not, default `true`
  *   cssModules {Boolean} determine to make css(exclude /node_modules/) modular or not, default `true`
  *   ...
  * }
**/

export default function getDefaultConfig (args) {
  let pkg = require(join(args.cwd, 'package.json'));

  const jsName = args.hash ? '[name].[chunkhash:8].js' : '[name].js';

  return {
    devtool: args.devtool || false,
    entry: pkg.entry,
    output: {
      path: join(args.cwd, 'build'),
      filename: jsName,
      publicPath: args.publicPath || '/static/'
    },
    module: {
      loaders: getCommonConfig.getLoders(args)
    },
    resolve: {
      extensions: ['', '.js']
    },
    plugins: getCommonConfig.getPluigns(args),
    postcss: function () {
      return {
        default: [ require('autoprefixer')({ browsers: ['last 2 versions'] }) ]
      }
    }
  }
}
<|endoftext|>


<commit_before>import React, { useRef, useCallback, useEffect } from 'react';
import './chart.css';
import * as d3 from 'd3'
import * as fc from 'd3fc';

let firstRun = true;

const Chart = ({ chartData }) => {

  useEffect(() => {
    if (chartData != null) {
      makeChart(chartData)
    } else {
      makeChart(fc.randomFinancial()(100))
    }
  }, [chartData]);

  const showcaseContainer = useRef(null);
  const navigationContainer = useRef(null);

  function makeChart(data) {

    var yExtent = fc.extentLinear().accessors([function (d) { return d.high; },
    function (d) { return d.low }]).pad([0.1, 0.1])

    var xExtent = fc.extentDate()
      .accessors([function (d) { return d.date; }]);

    var x = d3.scaleTime()
      .domain(xExtent(data));
    var y = d3.scaleLinear()
      .domain(yExtent(data));

    var chartData = {
      series: data,
      brushedRange: [0.75, 1]
    };

    var area = fc.seriesSvgLine()
      .crossValue(function (d) { return d.date; })
      .mainValue(function (d) { return d.close; })

    var candlestick = fc.seriesSvgCandlestick();

    var brush = fc.brushX()
      .on('brush', function (evt) {
        // if the brush has zero height there is no selection
        if (evt.selection) {
          chartData.brushedRange = evt.selection;
          mainChart.xDomain(evt.xDomain);
          render();
        }
      });

    var multi = fc.seriesSvgMulti()
      .series([area, brush])
      .mapping((data, index, series) => {
        switch (series[index]) {
          case area:
            return data.series;
          case brush:
            return data.brushedRange;
        }
      });

    var mainChart = fc.chartCartesian(x, y)
      .svgPlotArea(area);

    var navigatorChart = fc.chartCartesian(x.copy(), y.copy())
      .svgPlotArea(multi);

    var scale = d3.scaleTime().domain(x.domain());
    mainChart.xDomain(chartData.brushedRange.map(scale.invert));

    const render = () => {
      d3.select('#showcase-container')
        .datum(chartData.series)
        .call(mainChart);

      d3.select('#navigation-container')
        .datum(chartData)
        .call(navigatorChart);
    };

    render()
  }

  return

};

export default Chart;
<commit_msg>Basic chart with ability to toggle candlestick/line<commit_after>import React, { useRef, useCallback, useEffect } from 'react';
import './chart.css';
import * as d3 from 'd3'
import * as fc from 'd3fc';

let firstRun = true;

const Chart = ({ chartData, chartType }) => {

  useEffect(() => {
    if (chartData != null) {
      makeChart(chartData)
    } else {
      makeChart(fc.randomFinancial()(100))
    }
  }, [chartData, chartType]);

  const showcaseContainer = useRef(null);
  const navigationContainer = useRef(null);

  function makeChart(data) {

    var yExtent = fc.extentLinear().accessors([function (d) { return d.high; },
    function (d) { return d.low }]).pad([0.1, 0.1])

    var xExtent = fc.extentDate()
      .accessors([function (d) { return d.date; }]);

    var x = d3.scaleTime()
      .domain(xExtent(data));
    var y = d3.scaleLinear()
      .domain(yExtent(data));

    var chartData = {
      series: data,
      brushedRange: [0.75, 1]
    };

    var gridlines = fc.annotationSvgGridline().yTicks(10).xTicks(0)

    var area = fc.seriesSvgLine()
      .crossValue(function (d) { return d.date; })
      .mainValue(function (d) { return d.close; })
    var candlestick = fc.seriesSvgCandlestick()
    var brush = fc.brushX()
      .on('brush', function (evt) {
        // if the brush has zero height there is no selection
        if (evt.selection) {
          chartData.brushedRange = evt.selection;
          mainChart.xDomain(evt.xDomain);
          render();
        }
      });

    var multi = fc.seriesSvgMulti()
      .series([area, brush])
      .mapping((data, index, series) => {
        switch (series[index]) {
          case area:
            return data.series;
          case brush:
            return data.brushedRange;
        }
      });

    if (chartType === true) {
      var mainChart = fc.chartCartesian(x, y)
        .svgPlotArea(area)
    } else {
      var mainChart = fc.chartCartesian(x, y)
        .svgPlotArea(candlestick)
    }

    var navigatorChart = fc.chartCartesian(x.copy(), y.copy())
      .svgPlotArea(multi);

    var scale = d3.scaleTime().domain(x.domain());
    mainChart.xDomain(chartData.brushedRange.map(scale.invert));

    const render = () => {
      d3.selectAll("#showcase-container > *").remove();
      d3.select('#showcase-container')
        .datum(chartData.series)
        .call(mainChart);

      d3.select('#navigation-container')
        .datum(chartData)
        .call(navigatorChart);
    };

    render()
  }

  return

};

export default Chart;
<|endoftext|>


<commit_before>import { Swal, SwalWithoutAnimation, TIMEOUT } from '../../utils'

describe('inputValue', () => {
  it('inputValue number', () => {
    Swal.fire({ input: 'text', inputValue: 333 })
    expect(Swal.getInput().value).to.equal('333')
  })

  it('inputValue with object containing toPromise', (done) => {
    Swal.fire({
      input: 'text',
      inputValue: {
        toPromise: () => 'test'
      },
      onOpen: () => {
        expect(Swal.getInput().value).to.equal('test')
        done()
      }
    })
  })

  it('inputValue as a Promise', (done) => {
    const spy = cy.spy(console, 'warn')
    const inputTypes = ['text', 'email', 'number', 'tel', 'textarea']
    const value = '1.1 input value'
    const inputValue = new Promise((resolve) => {
      resolve('1.1 input value')
    })

    function showPopupWithInput () {
      const input = inputTypes.pop()
      SwalWithoutAnimation.fire({
        input,
        inputValue,
        onOpen: () => {
          setTimeout(() => {
            expect(Swal.getInput().value).to.equal(input === 'number' ? parseFloat(value).toString() : value)
            if (inputTypes.length) {
              showPopupWithInput()
            } else {
              done()
            }
          }, TIMEOUT)
        }
      })
    }
    showPopupWithInput()
    expect(spy.notCalled).to.be.true
  })

  it('should throw console error when inputValue as a Promise rejects', (done) => {
    const spy = cy.spy(console, 'error')
    SwalWithoutAnimation.fire({
      input: 'text',
      inputValue: new Promise((resolve, reject) => {
        reject(new Error('input promise rejected'))
      }),
      onOpen: () => {
        setTimeout(() => {
          expect(spy.calledWith('SweetAlert2: Error in inputValue promise: Error: input promise rejected')).to.be.true
          done()
        }, TIMEOUT)
      }
    })
  })

  it('should throw console warning about unexpected type of inputValue', () => {
    const spy = cy.spy(console, 'warn')
    Swal.fire({ input: 'text', inputValue: undefined })
    expect(spy.calledWith('SweetAlert2: Unexpected type of inputValue! Expected "string", "number" or "Promise", got "undefined"')).to.be.true
  })
})
<commit_msg>test: fix a inputValue integration test (#2000)<commit_after>import { Swal, SwalWithoutAnimation, TIMEOUT } from '../../utils'

describe('inputValue', () => {
  it('inputValue number', () => {
    Swal.fire({ input: 'text', inputValue: 333 })
    expect(Swal.getInput().value).to.equal('333')
  })

  it('inputValue with object containing toPromise', (done) => {
    Swal.fire({
      input: 'text',
      inputValue: {
        toPromise: () => Promise.resolve('test')
      },
      onOpen: () => {
        expect(Swal.getInput().value).to.equal('test')
        done()
      }
    })
  })

  it('inputValue as a Promise', (done) => {
    const spy = cy.spy(console, 'warn')
    const inputTypes = ['text', 'email', 'number', 'tel', 'textarea']
    const value = '1.1 input value'
    const inputValue = new Promise((resolve) => {
      resolve('1.1 input value')
    })

    function showPopupWithInput () {
      const input = inputTypes.pop()
      SwalWithoutAnimation.fire({
        input,
        inputValue,
        onOpen: () => {
          setTimeout(() => {
            expect(Swal.getInput().value).to.equal(input === 'number' ? parseFloat(value).toString() : value)
            if (inputTypes.length) {
              showPopupWithInput()
            } else {
              done()
            }
          }, TIMEOUT)
        }
      })
    }
    showPopupWithInput()
    expect(spy.notCalled).to.be.true
  })

  it('should throw console error when inputValue as a Promise rejects', (done) => {
    const spy = cy.spy(console, 'error')
    SwalWithoutAnimation.fire({
      input: 'text',
      inputValue: new Promise((resolve, reject) => {
        reject(new Error('input promise rejected'))
      }),
      onOpen: () => {
        setTimeout(() => {
          expect(spy.calledWith('SweetAlert2: Error in inputValue promise: Error: input promise rejected')).to.be.true
          done()
        }, TIMEOUT)
      }
    })
  })

  it('should throw console warning about unexpected type of inputValue', () => {
    const spy = cy.spy(console, 'warn')
    Swal.fire({ input: 'text', inputValue: undefined })
    expect(spy.calledWith('SweetAlert2: Unexpected type of inputValue! Expected "string", "number" or "Promise", got "undefined"')).to.be.true
  })
})
<|endoftext|>


<commit_before>/**
 * Created by Shadowgun on 24.02.2015.
 */
Imcms.Language = {};
Imcms.Language.Loader = function () {
    this.init();
};
Imcms.Language.Loader.prototype = {
    _api: {},
    init: function () {
        this._api = new Imcms.Language.API();
    },
    read: function (callback) {
        this._api.read({}, callback);
    }
};

Imcms.Language.API = function () {

};
Imcms.Language.API.prototype = {
    read: function (request, response) {
        $.ajax({
            url: Imcms.Linker.get("language"),
            type: "GET",
            data: request,
            success: response
        });
    }
};
<commit_msg>IMCMS-150 - Rewrite js hell in imCMS and use AMD mechanism: - Refactored Language API as module.<commit_after>/**
 * Created by Shadowgun on 24.02.2015.
 *
 * Refactored by Serhii Maksymchuk, 2017
 */
(function (Imcms) {
    var languageUrl = Imcms.Linker.get("language"),
        api = {};

    Imcms.Language = {};
    Imcms.Language.Loader = function () {
        this.init();
    };
    Imcms.Language.Loader.prototype = {
        init: function () {
            api = new Imcms.REST.API();
        },
        read: function (callback) {
            api.get({}, callback);
        }
    };

    return Imcms;
})(Imcms);
<|endoftext|>


<commit_before>/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

(function () {
    'use strict';

    function postMessage(txt) {
        Ext.Ajax.request({
            method: 'POST',
            url: window.ux.ROOT_URL + 'rest/messages',
            params: {
                message: txt
            },
            success: function () {
                window.console.log('message sent', txt);
            }
        });
    }

    function setNameAndPost(txt) {
        Ext.Msg.prompt(springchat.i18n.get('name'), springchat.i18n.get('enter.name'), function (buttonText, rawName) {
            var name = Ext.util.Format.trim(rawName);
            if (Ext.isEmpty(name)) {
                setNameAndPost(txt);
            } else {
                Ext.Ajax.request({
                    method: 'POST',
                    url: window.ux.ROOT_URL + 'rest/auth',
                    params: {
                        user: name
                    },
                    success: function (response) {
                        var json = Ext.decode(response.responseText);
                        if (json.success) {
                            window.ux.authenticated = true;
                            postMessage(txt);
                        } else {
                            Ext.Msg.alert('login.exception', json.info, function () {
                                setNameAndPost(txt);
                            });
                        }
                    },
                    failure: function () {
                        Ext.Msg.alert('error', 'error.connection', Ext.emptyFn);
                    }
                });
            }
        });
    }

    Ext.define('springchat.controller.Message', {
        extend: 'Ext.app.Controller',
        requires: [
            'Ext.util.Format',
            'Ext.MessageBox'
        ],
        config: {
            refs: {
                mainPanel: 'jschat-messages-panel',
                list: 'jschat-messages-panel dataview',
                sendMessageBtn: 'jschat-messages-panel button[action=sendMessage]',
                messageTxt: 'jschat-messages-panel textfield'
            },

            control: {
                mainPanel: {
                    show: function () {
                        var me = this;
                        var store = Ext.StoreManager.get('Message');
                        store.on('load', function () {
                            me.scroll();
                        });
                        store.on('addrecords', function () {
                            me.scroll();
                        });
                    }
                },
                sendMessageBtn: {
                    tap: 'onSendMessage'
                }
            }
        },

        scroll: function () {
            var me = this;
            var list = me.getList()
            var msg = list.el.query('.x-dataview-item:last-child');
            if(!Ext.isEmpty(msg)) {
                msg[0].scrollIntoView(list);
            }
        },

        init: function () {
            var me = this;
            me.getApplication().on('websocket-event-text', function (data) {
                var store = Ext.StoreManager.get('Message');
                store.add(data);
            });
        },

        getTextToSend: function () {
            var me = this;
            var txtField = me.getMessageTxt();
            var message = txtField.getValue();
            txtField.reset();
            return Ext.util.Format.trim(message);
        },

        onSendMessage: function () {
            var me = this;
            var txt = me.getTextToSend();
            if (txt === '') {
                return; // nothing to do.
            }
            if (window.ux.authenticated) {
                postMessage(txt);
            } else {
                setNameAndPost(txt);
            }
        }
    });

}());<commit_msg>fix scrolling and update tomee version<commit_after>/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

(function () {
    'use strict';

    function postMessage(txt) {
        Ext.Ajax.request({
            method: 'POST',
            url: window.ux.ROOT_URL + 'rest/messages',
            params: {
                message: txt
            },
            success: function () {
                window.console.log('message sent', txt);
            }
        });
    }

    function setNameAndPost(txt) {
        Ext.Msg.prompt(springchat.i18n.get('name'), springchat.i18n.get('enter.name'), function (buttonText, rawName) {
            var name = Ext.util.Format.trim(rawName);
            if (Ext.isEmpty(name)) {
                setNameAndPost(txt);
            } else {
                Ext.Ajax.request({
                    method: 'POST',
                    url: window.ux.ROOT_URL + 'rest/auth',
                    params: {
                        user: name
                    },
                    success: function (response) {
                        var json = Ext.decode(response.responseText);
                        if (json.success) {
                            window.ux.authenticated = true;
                            postMessage(txt);
                        } else {
                            Ext.Msg.alert('login.exception', json.info, function () {
                                setNameAndPost(txt);
                            });
                        }
                    },
                    failure: function () {
                        Ext.Msg.alert('error', 'error.connection', Ext.emptyFn);
                    }
                });
            }
        });
    }

    Ext.define('springchat.controller.Message', {
        extend: 'Ext.app.Controller',
        requires: [
            'Ext.util.Format',
            'Ext.MessageBox'
        ],
        config: {
            refs: {
                mainPanel: 'jschat-messages-panel',
                list: 'jschat-messages-panel dataview',
                sendMessageBtn: 'jschat-messages-panel button[action=sendMessage]',
                messageTxt: 'jschat-messages-panel textfield'
            },

            control: {
                mainPanel: {
                    show: function () {
                        var me = this;
                        var store = Ext.StoreManager.get('Message');
                        store.on('load', function () {
                            me.scroll();
                        });
                        store.on('addrecords', function () {
                            me.scroll();
                        });
                    }
                },
                sendMessageBtn: {
                    tap: 'onSendMessage'
                }
            }
        },

        scroll: function () {
            var me = this;
            var list = me.getList();
            var msg = list.el.query('.x-dataview-item:last-child');
            if (!Ext.isEmpty(msg)) {
                msg[0].scrollIntoView(list);
            }
        },

        init: function () {
            var me = this;
            me.getApplication().on('websocket-event-text', function (data) {
                var store = Ext.StoreManager.get('Message');
                store.add(data);
            });
        },

        getTextToSend: function () {
            var me = this;
            var txtField = me.getMessageTxt();
            var message = txtField.getValue();
            txtField.reset();
            return Ext.util.Format.trim(message);
        },

        onSendMessage: function () {
            var me = this;
            var txt = me.getTextToSend();
            if (txt === '') {
                return; // nothing to do.
            }
            if (window.ux.authenticated) {
                postMessage(txt);
            } else {
                setNameAndPost(txt);
            }
        }
    });

}());<|endoftext|>


<commit_before>//========================================//
//          SERVER CONFIGURATION          //
//========================================//
//if( process.env ) {                     // TOGGLE ON FOR OPENSHIFT DEPLOY
//========================================//
//IP ADDRESS                              //
  var SERVER_IP =                         //
  'localhost';                            // toggle on for local testing
//process.env.OPENSHIFT_NODEJS_IP;        // toggle on for openshift deploy
//========================================//
//PORT NUMBER                             //
  var SERVER_PORT =                       //
  8080;                                   // toggle on for local testing
//process.env.OPENSHIFT_NODEJS_PORT;      // toggle on for openshift deploy
//========================================//
//MONGODB CONNECTION INFO                 //
  var MONGO_IP =                          //
  'mongodb://localhost'                     // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_URL;   // toggle on for openshift deploy
//========================================//
  var MONGO_PORT =                        //
  27017                                   // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_PORT;  //
//========================================//
//}                                       // TOGGLE ON FOR OPENSHIFT DEPLOY
//========================================//

//========================================//
//          CLIENT CONFIGURATION          //
//========================================//
//IP ADDRESS                              //
  var CLIENT_IP =                         //
  'localhost';                            // toggle on for local testing
//'435-teamnoname.rhcloud.com';           // toggle on for openshift deploy
//========================================//
//PORT NUMBER                             //
  var CLIENT_PORT =                       //
  8080;                                   // toggle on for local testing
//8000;                                   // neccessary for openshift, as websockets is restricted to this port
//========================================//

if( process == 'SERVER' || process.env ) {
	module.exports.CLIENT_IP   = CLIENT_IP;
	module.exports.CLIENT_PORT = CLIENT_PORT;
	module.exports.SERVER_IP   = SERVER_IP;
	module.exports.SERVER_PORT = SERVER_PORT;
	module.exports.MONGO_IP    = MONGO_IP;
	module.exports.MONGO_PORT  = MONGO_PORT;
}
<commit_msg>added passport<commit_after>//========================================//
//          SERVER CONFIGURATION          //
//========================================//
//if( process.env ) {                     // TOGGLE ON FOR OPENSHIFT DEPLOY
//========================================//
//IP ADDRESS                              //
  var SERVER_IP =                         //
  'localhost';                            // toggle on for local testing
//process.env.OPENSHIFT_NODEJS_IP;        // toggle on for openshift deploy
//========================================//
//PORT NUMBER                             //
  var SERVER_PORT =                       //
  8080;                                   // toggle on for local testing
//process.env.OPENSHIFT_NODEJS_PORT;      // toggle on for openshift deploy
//========================================//
//MONGODB CONNECTION INFO                 //
  var MONGO_IP =                          //
  'mongodb://localhost'                   // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_URL;   // toggle on for openshift deploy
//========================================//
  var MONGO_PORT =                        //
  27017                                   // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_PORT;  //
//========================================//
//}                                       // TOGGLE ON FOR OPENSHIFT DEPLOY
//========================================//

//========================================//
//          CLIENT CONFIGURATION          //
//========================================//
//IP ADDRESS                              //
  var CLIENT_IP =                         //
  'localhost';                            // toggle on for local testing
//'435-teamnoname.rhcloud.com';           // toggle on for openshift deploy
//========================================//
//PORT NUMBER                             //
  var CLIENT_PORT =                       //
  8080;                                   // toggle on for local testing
//8000;                                   // neccessary for openshift, as websockets is restricted to this port
//========================================//

if( process == 'SERVER' || process.env ) {
	module.exports.CLIENT_IP   = CLIENT_IP;
	module.exports.CLIENT_PORT = CLIENT_PORT;
	module.exports.SERVER_IP   = SERVER_IP;
	module.exports.SERVER_PORT = SERVER_PORT;
	module.exports.MONGO_IP    = MONGO_IP;
	module.exports.MONGO_PORT  = MONGO_PORT;
}
<|endoftext|>