<commit_before>"
 \n// Flagged as a potential virus " +
$('#basic-info > div > div > table > tbody > tr:has(> td:contains("Detection ratio:") ) > td:nth-child(2)').text().trim().split(' / ')[0] +
" times
 \n// TrID: " +
$('div#file-details.extra-info > div > div > table > tbody').children('tr:has(> td.field-key:contains("TrID") )').children('td.field-value').text().trim() +
"
 \n// Comments: " +
$('#file-details > div > div:has( > span:contains("Comments") )').contents().filter(function() { return this.nodeType == 3; }).text().trim() +
"
 \n// ProductName: " +
$('#file-details > div > div:has(> span:contains("Product"))').contents().filter(function() { return this.nodeType == 3; }).text().trim() +
"
 \n// ProductVersion: " +
$('#file-details > div > div:has( > div:contains("ProductVersionNumber") )').children('div.floated-field-value').text().trim() +
"
 \nprefetch " +
$('#basic-info > div > div > table > tbody > tr:has(> td:contains("File name:") ) > td:nth-child(2)').text().trim() +
" sha1:" +
$('div#file-details.extra-info').children('div').children('div:has(> span:contains("SHA1") )').contents().filter(function() { return this.nodeType == 3; }).text().trim() +
" size:" +
$('div#file-details.extra-info').children('div').children('div:has(> span:contains("File size") )').contents().filter(function() { return this.nodeType == 3; }).text().split(' ( ')[1].split(' bytes ')[0] +
" http://PUT_URL_TO_FILE_HERE sha256:" +
$('div#file-details.extra-info').children('div').children('div:has(> span:contains("SHA256") )').contents().filter(function() { return this.nodeType == 3; }).text().trim();
<commit_msg>try to pull first url from comments as URL<commit_after>"
 \n// Flagged as a potential virus " +
$('#basic-info > div > div > table > tbody > tr:has(> td:contains("Detection ratio:") ) > td:nth-child(2)').text().trim().split(' / ')[0] +
" times
 \n// TrID: " +
$('div#file-details.extra-info > div > div > table > tbody').children('tr:has(> td.field-key:contains("TrID") )').children('td.field-value').text().trim() +
"
 \n// Comments: " +
$('#file-details > div > div:has( > span:contains("Comments") )').contents().filter(function() { return this.nodeType == 3; }).text().trim() +
"
 \n// ProductName: " +
$('#file-details > div > div:has(> span:contains("Product"))').contents().filter(function() { return this.nodeType == 3; }).text().trim() +
"
 \n// ProductVersion: " +
$('#file-details > div > div:has( > div:contains("ProductVersionNumber") )').children('div.floated-field-value').text().trim() +
"
 \nprefetch " +
$('#basic-info > div > div > table > tbody > tr:has(> td:contains("File name:") ) > td:nth-child(2)').text().trim() +
" sha1:" +
$('div#file-details.extra-info').children('div').children('div:has(> span:contains("SHA1") )').contents().filter(function() { return this.nodeType == 3; }).text().trim() +
" size:" +
$('div#file-details.extra-info').children('div').children('div:has(> span:contains("File size") )').contents().filter(function() { return this.nodeType == 3; }).text().split(' ( ')[1].split(' bytes ')[0] +
" " +
( ($('div.comment-text > table > tbody > tr > td:contains("http")').first().text().trim().length)? $('div.comment-text > table > tbody > tr > td:contains("http")').first().text().trim() : "http://PUT_URL_TO_FILE_HERE" ) +
" sha256:" +
$('div#file-details.extra-info').children('div').children('div:has(> span:contains("SHA256") )').contents().filter(function() { return this.nodeType == 3; }).text().trim();
<|endoftext|>


<commit_before>var React = require('react');
var {
  View,
  ViewPagerAndroid,
} = require('react-native');

var CarouselPager = React.createClass({

  scrollToPage(page, animated) {
    if (typeof animated === 'undefined') {
      animated = true;
    }
    if (animated) {
      this.refs.viewPager.setPage(page);
    } else {
      this.refs.viewPager.setPageWithoutAnimation(page);
    }
    this._onPageSelected(page);
  },

  _onPageSelected(page) {
    this.props.onEnd(page);
  },

  render() {
    return <ViewPagerAndroid
      ref={(viewPager) => this.refs = { viewPager }}
      style={{flex: 1}}
      contentContainerStyle={this.props.contentContainerStyle}
      automaticallyAdjustContentInsets={false}
      horizontal={this.props.isHorizontal}
      showsHorizontalScrollIndicator={false}
      bounces={false}
      onPageScroll={this.props.onBegin}
      onPageSelected={(e) => this._onPageSelected(e.nativeEvent.position)}
      scrollsToTop={false}
      >
        {this.props.children.map((c, idx) => <View key={idx} style={{flex: 1}}>{c}</View>)}
      </ViewPagerAndroid>;
  },
});

module.exports = CarouselPager;
<commit_msg>Android fix vertical paging<commit_after>var React = require('react');
var {
  ScrollView,
} = require('react-native');

const slideOffset = 0.10;

var CarouselPager = React.createClass({
  currentPage: 0,

  componentDidMount() {
    setTimeout(() => {
      // this.refs.scrollView.scrollTo(300);
    }, 1500);
  },

  scrollToPage(page, animated) {
    if (typeof animated === 'undefined') {
      animated = true;
    }

    if (this.props.isHorizontal) {
      this.refs.scrollView.scrollTo({x: page * this.props.width, y: 0, animated: animated});
    } else {
      this.refs.scrollView.scrollTo({y: page * this.props.height, x: 0, animated: animated});
    }
  },

  adjustPageOffset(activePage) {
    let nextPage = this.currentPage;
    let toAnimate = true;

    if (this.currentPage < activePage &&
      (this.currentPage + slideOffset) < activePage) {
      nextPage = this.currentPage + 1;
      toAnimate = (nextPage + 1) > activePage;

    } else if (this.currentPage > activePage &&
      (this.currentPage - slideOffset) > activePage) {
        nextPage = this.currentPage - 1;
        toAnimate = (nextPage - 1) < activePage;
    }

    return {
      nextPage,
      toAnimate,
    };
  },

  _onMomentumScrollEnd(e) {
    if (this.props.isHorizontal) {
      var activePage = e.nativeEvent.contentOffset.x / this.props.width;
    } else {
      var activePage = e.nativeEvent.contentOffset.y / this.props.height;
    }
    const adjusted = this.adjustPageOffset(activePage);
    this.currentPage = adjusted.nextPage;
    this.props.onEnd(this.currentPage);
    this.scrollToPage(this.currentPage, adjusted.toAnimate);
  },

  render() {
    return <ScrollView
      ref={(scrollView) => this.refs = { scrollView }}
      contentContainerStyle={this.props.contentContainerStyle}
      automaticallyAdjustContentInsets={false}
      horizontal={this.props.isHorizontal}
      pagingEnabled={true}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      bounces={true}
      onTouchStart={this.props.onBegin}
      scrollsToTop={false}
      style={{ height: this.props.height, width: this.props.width, backgroundColor: 'transparent' }}
      onScrollEndDrag={this._onMomentumScrollEnd}
    >
      {this.props.children}
    </ScrollView>;
  },
});

module.exports = CarouselPager;
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
*/

"use strict";

const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
const chunkHasJs = require("../javascript/JavascriptModulesPlugin").chunkHasJs;
const compileBooleanMatcher = require("../util/compileBooleanMatcher");

class RequireChunkLoadingRuntimeModule extends RuntimeModule {
	constructor(runtimeRequirements) {
		super("require chunk loading", 10);
		this.runtimeRequirements = runtimeRequirements;
	}

	/**
	 * @returns {string} runtime code
	 */
	generate() {
		const { chunk } = this;
		const { chunkGraph } = this.compilation;
		const fn = RuntimeGlobals.ensureChunkHandlers;
		const withLoading = this.runtimeRequirements.has(
			RuntimeGlobals.ensureChunkHandlers
		);
		const withHmr = this.runtimeRequirements.has(
			RuntimeGlobals.hmrDownloadUpdateHandlers
		);
		const withHmrManifest = this.runtimeRequirements.has(
			RuntimeGlobals.hmrDownloadManifest
		);
		const hasJsMatcher = compileBooleanMatcher(
			chunkGraph.getChunkConditionMap(chunk, chunkHasJs)
		);

		let rootOutputDir = "'./'";
		if (chunk.hasEntryModule()) {
			const outputName = this.compilation.getPath(
				this.compilation.outputOptions.filename + "",
				{
					chunk,
					contentHashType: "javascript"
				}
			);
			const chunkInnerDirsCount = outputName.split("/").length - 1;
			rootOutputDir =
				chunkInnerDirsCount > 0
					? JSON.stringify("../".repeat(chunkInnerDirsCount))
					: '"./"';
		}

		return Template.asString([
			"// object to store loaded chunks",
			'// "1" means "loaded", otherwise not loaded yet',
			"var installedChunks = {",
			Template.indent(
				chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n")
			),
			"};",
			"",
			withLoading
				? Template.asString([
						"// require() chunk loading for javascript",
						`${fn}.require = function(chunkId, promises) {`,
						hasJsMatcher !== false
							? Template.indent([
									"",
									'// "1" is the signal for "already loaded"',
									"if(!installedChunks[chunkId]) {",
									Template.indent([
										hasJsMatcher === true
											? "if(true) { // all chunks have JS"
											: `if(${hasJsMatcher("chunkId")}) {`,
										Template.indent([
											`var chunk = require(${rootOutputDir} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId));`,
											"var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;",
											"for(var moduleId in moreModules) {",
											Template.indent([
												`if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
												Template.indent([
													`${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
												]),
												"}"
											]),
											"}",
											`if(runtime) runtime(__webpack_require__);`,
											"for(var i = 0; i < chunkIds.length; i++)",
											Template.indent("installedChunks[chunkIds[i]] = 1;")
										]),
										"} else installedChunks[chunkId] = 1;",
										"",
										withHmr
											? Template.asString([
													"if(currentUpdateChunks && currentUpdateChunks[chunkId]) loadUpdateChunk(chunkId);"
											  ])
											: "// no HMR"
									]),
									"}"
							  ])
							: Template.asString([
									"installedChunks[chunkId] = 1;",
									withHmr
										? Template.asString([
												"if(currentUpdateChunks && currentUpdateChunks[chunkId]) loadUpdateChunk(chunkId);"
										  ])
										: "// no HMR"
							  ]),
						"};"
				  ])
				: "// no chunk loading",
			"",
			withHmr
				? Template.asString([
						"var currentUpdateChunks;",
						"var currentUpdate;",
						"var currentUpdateRuntime;",
						"function loadUpdateChunk(chunkId, updatedModulesList) {",
						Template.indent([
							`var update = require("./" + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
							"var updatedModules = update.modules;",
							"var runtime = update.runtime;",
							"for(var moduleId in updatedModules) {",
							Template.indent([
								`if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
								Template.indent([
									`currentUpdate[moduleId] = updatedModules[moduleId];`,
									"if(updatedModulesList) updatedModulesList.push(moduleId);"
								]),
								"}"
							]),
							"}",
							"if(runtime) currentUpdateRuntime.push(runtime);"
						]),
						"}",
						"",
						`${RuntimeGlobals.hmrDownloadUpdateHandlers}.require = function(chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList) {`,
						Template.indent([
							"applyHandlers.push(function(options) {",
							Template.indent([
								"currentUpdateChunks = undefined;",
								Template.getFunctionContent(
									require("../hmr/JavascriptHotModuleReplacement.runtime.js")
								)
									.replace(/\$options\$/g, "options")
									.replace(/\$updateModuleFactories\$/g, "currentUpdate")
									.replace(/\$updateRuntimeModules\$/g, "currentUpdateRuntime")
									.replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
									.replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
									.replace(
										/\$moduleFactories\$/g,
										RuntimeGlobals.moduleFactories
									)
									.replace(
										/\/\/ \$dispose\$/g,
										Template.asString([
											"removedChunks.forEach(function(chunkId) { delete installedChunks[chunkId]; });"
										])
									)
							]),
							"});",
							"currentUpdateChunks = {};",
							"currentUpdate = removedModules.reduce(function(obj, key) { obj[key] = false; return obj; }, {});",
							"currentUpdateRuntime = [];",
							"chunkIds.forEach(function(chunkId) {",
							Template.indent([
								"if(installedChunks[chunkId] !== undefined) {",
								Template.indent([
									"loadUpdateChunk(chunkId, updatedModulesList);"
								]),
								"}",
								"currentUpdateChunks[chunkId] = true;"
							]),
							"});"
						]),
						"};"
				  ])
				: "// no HMR",
			"",
			withHmrManifest
				? Template.asString([
						`${RuntimeGlobals.hmrDownloadManifest} = function() {`,
						Template.indent([
							"return Promise.resolve().then(function() {",
							Template.indent([
								`return require("./" + ${RuntimeGlobals.getUpdateManifestFilename}());`
							]),
							'}).catch(function(err) { if(err.code !== "MODULE_NOT_FOUND") throw err; });'
						]),
						"}"
				  ])
				: "// no HMR manifest"
		]);
	}
}

module.exports = RequireChunkLoadingRuntimeModule;
<commit_msg>Use chunkGraph API directly<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
*/

"use strict";

const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
const chunkHasJs = require("../javascript/JavascriptModulesPlugin").chunkHasJs;
const compileBooleanMatcher = require("../util/compileBooleanMatcher");

class RequireChunkLoadingRuntimeModule extends RuntimeModule {
	constructor(runtimeRequirements) {
		super("require chunk loading", 10);
		this.runtimeRequirements = runtimeRequirements;
	}

	/**
	 * @returns {string} runtime code
	 */
	generate() {
		const { chunk } = this;
		const { chunkGraph } = this.compilation;
		const fn = RuntimeGlobals.ensureChunkHandlers;
		const withLoading = this.runtimeRequirements.has(
			RuntimeGlobals.ensureChunkHandlers
		);
		const withHmr = this.runtimeRequirements.has(
			RuntimeGlobals.hmrDownloadUpdateHandlers
		);
		const withHmrManifest = this.runtimeRequirements.has(
			RuntimeGlobals.hmrDownloadManifest
		);
		const hasJsMatcher = compileBooleanMatcher(
			chunkGraph.getChunkConditionMap(chunk, chunkHasJs)
		);

		let rootOutputDir = "'./'";
		const chunkHasEntryModule = chunkGraph.getNumberOfEntryModules(chunk) > 0;
		if (chunkHasEntryModule) {
			const outputName = this.compilation.getPath(
				this.compilation.outputOptions.filename + "",
				{
					chunk,
					contentHashType: "javascript"
				}
			);
			const chunkInnerDirsCount = outputName.split("/").length - 1;
			rootOutputDir =
				chunkInnerDirsCount > 0
					? JSON.stringify("../".repeat(chunkInnerDirsCount))
					: '"./"';
		}

		return Template.asString([
			"// object to store loaded chunks",
			'// "1" means "loaded", otherwise not loaded yet',
			"var installedChunks = {",
			Template.indent(
				chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n")
			),
			"};",
			"",
			withLoading
				? Template.asString([
						"// require() chunk loading for javascript",
						`${fn}.require = function(chunkId, promises) {`,
						hasJsMatcher !== false
							? Template.indent([
									"",
									'// "1" is the signal for "already loaded"',
									"if(!installedChunks[chunkId]) {",
									Template.indent([
										hasJsMatcher === true
											? "if(true) { // all chunks have JS"
											: `if(${hasJsMatcher("chunkId")}) {`,
										Template.indent([
											`var chunk = require(${rootOutputDir} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId));`,
											"var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;",
											"for(var moduleId in moreModules) {",
											Template.indent([
												`if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
												Template.indent([
													`${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`
												]),
												"}"
											]),
											"}",
											`if(runtime) runtime(__webpack_require__);`,
											"for(var i = 0; i < chunkIds.length; i++)",
											Template.indent("installedChunks[chunkIds[i]] = 1;")
										]),
										"} else installedChunks[chunkId] = 1;",
										"",
										withHmr
											? Template.asString([
													"if(currentUpdateChunks && currentUpdateChunks[chunkId]) loadUpdateChunk(chunkId);"
											  ])
											: "// no HMR"
									]),
									"}"
							  ])
							: Template.asString([
									"installedChunks[chunkId] = 1;",
									withHmr
										? Template.asString([
												"if(currentUpdateChunks && currentUpdateChunks[chunkId]) loadUpdateChunk(chunkId);"
										  ])
										: "// no HMR"
							  ]),
						"};"
				  ])
				: "// no chunk loading",
			"",
			withHmr
				? Template.asString([
						"var currentUpdateChunks;",
						"var currentUpdate;",
						"var currentUpdateRuntime;",
						"function loadUpdateChunk(chunkId, updatedModulesList) {",
						Template.indent([
							`var update = require("./" + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
							"var updatedModules = update.modules;",
							"var runtime = update.runtime;",
							"for(var moduleId in updatedModules) {",
							Template.indent([
								`if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
								Template.indent([
									`currentUpdate[moduleId] = updatedModules[moduleId];`,
									"if(updatedModulesList) updatedModulesList.push(moduleId);"
								]),
								"}"
							]),
							"}",
							"if(runtime) currentUpdateRuntime.push(runtime);"
						]),
						"}",
						"",
						`${RuntimeGlobals.hmrDownloadUpdateHandlers}.require = function(chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList) {`,
						Template.indent([
							"applyHandlers.push(function(options) {",
							Template.indent([
								"currentUpdateChunks = undefined;",
								Template.getFunctionContent(
									require("../hmr/JavascriptHotModuleReplacement.runtime.js")
								)
									.replace(/\$options\$/g, "options")
									.replace(/\$updateModuleFactories\$/g, "currentUpdate")
									.replace(/\$updateRuntimeModules\$/g, "currentUpdateRuntime")
									.replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
									.replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
									.replace(
										/\$moduleFactories\$/g,
										RuntimeGlobals.moduleFactories
									)
									.replace(
										/\/\/ \$dispose\$/g,
										Template.asString([
											"removedChunks.forEach(function(chunkId) { delete installedChunks[chunkId]; });"
										])
									)
							]),
							"});",
							"currentUpdateChunks = {};",
							"currentUpdate = removedModules.reduce(function(obj, key) { obj[key] = false; return obj; }, {});",
							"currentUpdateRuntime = [];",
							"chunkIds.forEach(function(chunkId) {",
							Template.indent([
								"if(installedChunks[chunkId] !== undefined) {",
								Template.indent([
									"loadUpdateChunk(chunkId, updatedModulesList);"
								]),
								"}",
								"currentUpdateChunks[chunkId] = true;"
							]),
							"});"
						]),
						"};"
				  ])
				: "// no HMR",
			"",
			withHmrManifest
				? Template.asString([
						`${RuntimeGlobals.hmrDownloadManifest} = function() {`,
						Template.indent([
							"return Promise.resolve().then(function() {",
							Template.indent([
								`return require("./" + ${RuntimeGlobals.getUpdateManifestFilename}());`
							]),
							'}).catch(function(err) { if(err.code !== "MODULE_NOT_FOUND") throw err; });'
						]),
						"}"
				  ])
				: "// no HMR manifest"
		]);
	}
}

module.exports = RequireChunkLoadingRuntimeModule;
<|endoftext|>


<commit_before>/**
 * Created by grahamclapham on 04/12/2014.
 */
// create a global paperScope var

if(!_paper) var _paper =  new paper.PaperScope();

function PaperRenderer(target, opt_data, opt_config){

    if(opt_config){
        opt_config.createCanvas = false;
        opt_config.canvasId = target;
    }else{
        opt_config = {createCanvas:false, canvasId:target};
    }
    //The vars
    this.backgroundColour = "rgba(19,19,19,1)"
    this.fillColour1 = "rgba(226,114,43,1)"
    this.fillColour2 = "rgba(226,114,43,0)"
    this.gridLineStyle = {
        strokeColor: 'white',
        strokeWidth: .3,
       // dashArray: [2, 2],
        fillColor: 'red'
    };

    this.dotColor = "red"
    BaseChart.call(this, target, opt_data, opt_config); // call super constructor.
};

PaperRenderer.prototype = Object.create(BaseChart.prototype);
PaperRenderer.prototype.constructor = PaperRenderer;
PaperRenderer.prototype.postInit = function(){
    this.setPlaying(false)

    var _canv = document.getElementById(this.getCanvasId())
    if(!_canv){
        throw new Error(this.getCanvasId()+ " cannot be found.")
    }else{
        this.setCanvas(_canv)
    }

    _paper.setup(_canv);
    //this._circle = new paper.Path.Circle(new paper.Point(80, 50), 10);

    this. pointArray = [];
    this._circleArray =[];
    this._yLineArray = [];

// Pass a color name to the fillColor property, which is internally
// converted to a Color.
    this._layer2 = new _paper.Layer();
    this._path = new _paper.Path();
    this._start = new _paper.Point(100, 100);
    this._path.moveTo(this._start);

    var _this = this;

    _drawBackground.call(this);
    _drawAreaChart.call(this);
    _drawYlines.call(this);

    _paper.view.onFrame = function(e){
        _onFrame.call(_this);
    }
}

PaperRenderer.prototype.activate = function(opt_layer){
    //If there is a layer with this ID use activate that layer.
    //if(opt_layer) console.log("L2 ",this[opt_layer]);

    if(opt_layer && this[opt_layer]){
        try{
            this._view = this[opt_layer];
            this._view.activate();
        }catch(e){
            console.log(e);
        }

    }else{
        this._view =  _paper.View._viewsById[ this.getCanvasId() ];
        this._view._project.activate();
    }

    return this._view;
}

PaperRenderer.prototype.makeDot = function(x,y){
    var _dot = new _paper.Shape.Circle(x,y, 6);
    _dot.fillColor = "rgba(100,200,89,1)";
    console.log("_dot ",_dot);
    return _dot;
}

var _drawBackground = function(){
    //this.activate()
    var layer = this.activate('_layer2')
    //console.log("ACTIVATED ...",layer);
    //layer.sendToBack();

    var __point = new _paper.Point(0, 0);
    var _size = new _paper.Point(this.getWidth(), this.getHeight())
    this._background = new _paper.Shape.Rectangle(__point, _size);
    this._background.fillColor = this.backgroundColour;
}

/*

 var diff;
 if(this._circleArray.length != this.getData().length){
 diff =  this.getData().length - this._circleArray.length
 }
 ///////////////
 if(diff>0){
 for(var i=0; i<diff; i++){
 // var _dot = this.makeDot( this.getData()[i].x, this.getData()[i].y );
 //console.log("DOT>>>>>>>>>>>>> ",_dot)
 this.activate();
 var _circle = new _paper.Path.Circle(new _paper.Point(this.getData()[i].x, this.getData()[i].y), 6);
 this._circleArray.push(_circle)
 _circle.fillColor = this.dotColor;
 }
 // console.log(this._circleArray)
 }
 ////////////
 if(diff<0){
 var _removealArray = this._circleArray.splice(this._circleArray.length+diff,  0-diff )

 for(var i=0; i<_removealArray.length; i++){
 // var _dot = this.makeDot( this.getData()[i].x, this.getData()[i].y );
 this.activate();
 //var _circle = new _paper.Path.Circle(new _paper.Point(this.getData()[i].x, this.getData()[i].y), 6);
 var toDelete = _removealArray[i]
 try{
 toDelete.remove();
 delete toDelete;
 }catch(e){
 ///---
 }
 }
 }

 */

var _createLine = (function(from, to, displayValue, opt_config){
    var _scope = function(from, to, displayValue, opt_config){
        console.log("OPT CONFIG + ",opt_config)
        this.config = opt_config || {}
        for(var prop in this.config){
            this[prop] = this.config[prop]
        }
        this.style = this.config.style || { strokeWeight : 0.5, strokeColor: "rgba(255,0,255, 1)"}
        this.from = from;
        this.to = to;
        this.displayValue = displayValue;
        this.line = new _paper.Path.Line(from,to);

        this.line.style = this.style
    }
    _scope.prototype.setPosition = function(points){

    }

    //var _line = _paper.Path.Line(from,to);
    //_line.strokeWeight = .5;
    //_line.strokeColor = "rgba(255,0,255, 1)";
    return _scope // {line:_line, from:from, to:to, displayValue:displayValue}
})();

var _drawYlines = function(){
    this.activate();
    if(this.maxY && this.minY && this.maxY.y && this.minY.y){
        var range = this.maxY.y - this.minY.y;

        var steps = Math.ceil((this._roundedYValues.max-this._roundedYValues.min) / this._roundedYValues.division)
        console.log("The number of steps is --- ", steps);

        var diff;
        if(this._yLineArray.length != steps){
            diff =  this._yLineArray.length != steps
            for(var i=0; i<this._yLineArray.length; i++){
                this._yLineArray[i].line.remove();
                delete this._yLineArray[i].line;
            }
            this._yLineArray = []
        }

        for(var i = 0; i<steps; i++){
            var displayValue = i*this._roundedYValues.division
            var yPos = this.getHeight() - this.getYscale().map(displayValue);

            var from = new _paper.Point(this.leftMargin, yPos);
            var to = new _paper.Point(this.getWidth()-this.rightMargin, yPos);

            var lyn = new _createLine(from,to,displayValue, {style:this.gridLineStyle});
            console.log(lyn)
            this._yLineArray[i] = lyn;
            //sketch.line(sketch._leftOffset, yPos, sketch.width-sketch._rightOffset,  yPos);
            //sketch.textAlign(sketch.RIGHT);
            //sketch.fill("rgba(255,255,255,255)");
            //sketch.text(i,sketch._leftOffset-5, yPos);
        }
    }
}

var _addToolTip = function(data){

}

var _positionYlines = function(){
    for(var i=0; i<this._yLineArray.length; i++){
        var o = this._yLineArray[i]
        // o.line.position =
    }
}

var _drawAreaChart = function(){
    this.myPath = new _paper.Path();
    this.myPath.add(new _paper.Point(0, 0));
    this.myPath.strokeColor = this.dotColor;
}

var _drawDots =function(){

    var diff;
    if(this._circleArray.length != this.getData().length){
         diff =  this.getData().length - this._circleArray.length
    }
    ///////////////
    if(diff>0){
        for(var i=0; i<diff; i++){
            // var _dot = this.makeDot( this.getData()[i].x, this.getData()[i].y );
            //console.log("DOT>>>>>>>>>>>>> ",_dot)
            this.activate();
            var _circle = new _paper.Path.Circle(new _paper.Point(this.getData()[i].x, this.getData()[i].y), 6);
            _circle.data = this.getData()[i];
            _circle.data.index=i;

            _circle.on('mouseenter', function(e){
                console.log(this.data)
            })
            this._circleArray.push(_circle)
            _circle.fillColor = this.dotColor;
        }
       // console.log(this._circleArray)
    }
    ////////////
    if(diff<0){
        var _removealArray = this._circleArray.splice(this._circleArray.length+diff,  0-diff )

        for(var i=0; i<_removealArray.length; i++){
            // var _dot = this.makeDot( this.getData()[i].x, this.getData()[i].y );
            this.activate();
            //var _circle = new _paper.Path.Circle(new _paper.Point(this.getData()[i].x, this.getData()[i].y), 6);
            var toDelete = _removealArray[i]
            try{
                toDelete.remove();
                delete toDelete;
            }catch(e){
                ///---
            }
        }
    }
}
//---------------------------
var _drawLine = function(){
    if( this.myPath.segments.length < this.getData().length){
        for(var i=this.myPath.segments.length; i<this.getData().length; i++){
            this.myPath.add(new _paper.Point(0, 0));
        }
    }
    if( this.myPath.segments.length > this.getData().length){
        //for(var i=this.getData().length ; i<this.myPath.segments.length; i++){
        //    this.myPath.add(new _paper.Point(0, 0));
        //}
        console.log(this.myPath.segments.length, this.getData().length)
        this.myPath.removeSegments(this.getData().length-1, this.myPath.segments.length-1)
    }

    //this.myPath.selected = true;

}
var _onFrame = function(){
   // this.activate();
    for(var i =0; i<this.getData().length; i++){
        if(this.myPath.segments[i]){
            var currentPos = new _paper.Point(this.myPath.segments[i].getPoint().x , this.myPath.segments[i].getPoint().y);
            var xp =  this.getXscale()  ? this.getXscale().map( this.getData()[i].x ) : this.getData()[i].x;
            var yp =  this.getYscale()  ? this.getYscale().map( this.getData()[i].y ) : this.getData()[i].y;
            var desiredPos = new _paper.Point( xp, yp );
            var diff = desiredPos.subtract(currentPos);
            var velocity = diff.divide(6);
            var se = this.myPath.segments[i];
            var newpos = currentPos.add(velocity); //new __paper.Point(_this.getData()[i].x, _this.getData()[i].y)
            se.setPoint( newpos );
            if(this._circleArray[i]) this._circleArray[i].position = newpos;
        }
    }
    //this.myPath.smooth();
    this.myPath.insert(this.getData().length, new _paper.Point(this.getWidth()-this.rightMargin, this.getHeight() - this.bottomMargin));
    this.myPath.insert(this.getData().length+1, new _paper.Point(this.leftMargin, this.getHeight() - this.bottomMargin ));
    this.myPath.closed = true;
    this.myPath.fillColor = {
        gradient: {
            stops: [this.fillColour1, this.fillColour2]
        },
        origin: [0,this.getHeight()/2],
            destination: [0,this.getHeight()]
    }
}

var _scribble = function(){
    this._path.strokeColor = '#cccccc';
    this._path.lineTo(this._start.add([ Math.random()*300, Math.random()*300 ]));
    this._path.smooth();
    this._path.dashArray = [10, 4];
    _paper.view.draw();
}

PaperRenderer.prototype.render = function(){
    this.initScale();
    console.log("RENDER: ",this.getYscale() )
    _drawLine.call(this);
    _drawDots.call(this);
    _drawYlines.call(this);

    //this._path.lineTo(this._start.add([ Math.random()*300, Math.random()*300 ]));
    // Draw the view now:
    //_paper.view.draw();
    //_paper2.view.draw();
    //_paper.remove( this._circle );
   // this.myPath.fullySelected = true;
    //this.myPath.smooth();
    _paper.view.draw();
}
<commit_msg>The Dot class to create dynamic dots created.<commit_after>/**
 * Created by grahamclapham on 04/12/2014.
 */
// create a global paperScope var

if(!_paper) var _paper =  new paper.PaperScope();

function PaperRenderer(target, opt_data, opt_config){

    if(opt_config){
        opt_config.createCanvas = false;
        opt_config.canvasId = target;
    }else{
        opt_config = {createCanvas:false, canvasId:target};
    }
    //The vars
    this.backgroundColour = "rgba(19,19,19,1)"
    this.fillColour1 = "rgba(226,114,43,1)"
    this.fillColour2 = "rgba(226,114,43,0)"
    this.gridLineStyle = {
        strokeColor: 'white',
        strokeWidth: .3,
       // dashArray: [2, 2],
        fillColor: 'red'
    };

    this.dotColor = "red"
    BaseChart.call(this, target, opt_data, opt_config); // call super constructor.
};

PaperRenderer.prototype = Object.create(BaseChart.prototype);
PaperRenderer.prototype.constructor = PaperRenderer;
PaperRenderer.prototype.postInit = function(){
    this.setPlaying(false)

    var _canv = document.getElementById(this.getCanvasId())
    if(!_canv){
        throw new Error(this.getCanvasId()+ " cannot be found.")
    }else{
        this.setCanvas(_canv)
    }

    _paper.setup(_canv);
    //this._circle = new paper.Path.Circle(new paper.Point(80, 50), 10);

    this. pointArray = [];
    this._circleArray =[];
    this._yLineArray = [];
    this._dynamicDotArray = []

// Pass a color name to the fillColor property, which is internally
// converted to a Color.
    this._layer2 = new _paper.Layer();
    this._path = new _paper.Path();
    this._start = new _paper.Point(100, 100);
    this._path.moveTo(this._start);

    var _this = this;

    _drawBackground.call(this);
    _drawAreaChart.call(this);
    _drawYlines.call(this);
    _createToolTip.call(this);

    _paper.view.onFrame = function(e){
        _onFrame.call(_this);
    }
}

PaperRenderer.prototype.activate = function(opt_layer){
    //If there is a layer with this ID use activate that layer.
    //if(opt_layer) console.log("L2 ",this[opt_layer]);

    if(opt_layer && this[opt_layer]){
        try{
            this._view = this[opt_layer];
            this._view.activate();
        }catch(e){
            console.log(e);
        }

    }else{
        this._view =  _paper.View._viewsById[ this.getCanvasId() ];
        this._view._project.activate();
    }

    return this._view;
}

PaperRenderer.prototype.makeDot = function(x,y){
    var _dot = new _paper.Shape.Circle(x,y, 6);
    _dot.fillColor = "rgba(100,200,89,1)";
    console.log("_dot ",_dot);
    return _dot;
}

PaperRenderer.prototype.getTooltip = function() {
    return this._tooltipelement;
}

var _drawBackground = function(){
    //this.activate()
    var layer = this.activate('_layer2')
    //console.log("ACTIVATED ...",layer);
    //layer.sendToBack();

    var __point = new _paper.Point(0, 0);
    var _size = new _paper.Point(this.getWidth(), this.getHeight())
    this._background = new _paper.Shape.Rectangle(__point, _size);
    this._background.fillColor = this.backgroundColour;
}

var _createLine = (function(from, to, displayValue, opt_config){
    var _scope = function(from, to, displayValue, opt_config){
        this.config = opt_config || {}
        for(var prop in this.config){
            this[prop] = this.config[prop]
        }
        this.style = this.config.style || { strokeWeight : 0.5, strokeColor: "rgba(255,0,255, 1)"}
        this.from = from;
        this.to = to;
        this.displayValue = displayValue;
        this.line = new _paper.Path.Line(from,to);

        this.line.style = this.style
    }
    _scope.prototype.setPosition = function(points){

    }

    //var _line = _paper.Path.Line(from,to);
    //_line.strokeWeight = .5;
    //_line.strokeColor = "rgba(255,0,255, 1)";
    return _scope // {line:_line, from:from, to:to, displayValue:displayValue}
})();

var _drawYlines = function(){
    this.activate();
    if(this.maxY && this.minY && this.maxY.y && this.minY.y){
        var range = this.maxY.y - this.minY.y;

        var steps = Math.ceil((this._roundedYValues.max-this._roundedYValues.min) / this._roundedYValues.division)
        console.log("The number of steps is --- ", steps);

        var diff;
        if(this._yLineArray.length != steps){
            diff =  this._yLineArray.length != steps
            for(var i=0; i<this._yLineArray.length; i++){
                this._yLineArray[i].line.remove();
                delete this._yLineArray[i].line;
            }
            this._yLineArray = []
        }

        for(var i = 0; i<steps; i++){
            var displayValue = i*this._roundedYValues.division
            var yPos = this.getHeight() - this.getYscale().map(displayValue);

            var from = new _paper.Point(this.leftMargin, yPos);
            var to = new _paper.Point(this.getWidth()-this.rightMargin, yPos);

            var lyn = new _createLine(from,to,displayValue, {style:this.gridLineStyle});
            this._yLineArray[i] = lyn;
        }
    }
}

var Tooltip = (function(parent){
    var _scope = function(parent){
        this._text = "default text"
        this._position = null;
        this._parent = parent
        _init.call(this);
    }
    var _init = function(){
        console.log("Making the tooltip")
        if(!this._position ) this._position =  new _paper.Point(30, 30);
        this._toolTipTextElement = new _paper.PointText(this._position );
        this._toolTipTextElement.fillColor = '#ff00ff';
        _onTextChanged.call(this);
    }
    var _onPositionChanged = function(){

    }
    var _onTextChanged = function(){
        this._toolTipTextElement.content = this._text;
    }

    _scope.prototype = {
        setPosition:function(value){
            this._position = value
            _onPositionChanged.call(this);
        },
        getPosition:function(){
            return this._position
        },
        setText:function(value){
            this._text = value;
            _onTextChanged.call(this)
            console.log("TExt changed... ")
        },
        getText:function(){
            return this._text
        }
    }

    return _scope
})();

var _createToolTip = function(){
    this.activate();
    this._tooltipelement = new Tooltip(this)
    console.log(this._tooltipelement)
}

var _addToolTip = function(data){

}

var _positionYlines = function(){
    for(var i=0; i<this._yLineArray.length; i++){
        var o = this._yLineArray[i]
    }
}

var _drawAreaChart = function(){
    this.myPath = new _paper.Path();
    this.myPath.add(new _paper.Point(0, 0));
    this.myPath.strokeColor = this.dotColor;
}

///-- class for the dots

var Dot = (function(parent, position, data){
    var _scope = function(parent, position, data){
        this._position = position;
        this.parent = parent;
        this.data = data;
        this._unselectedOuterColour = "rgba(255, 0, 255, 1)"
        this._outerRadius = 12;
        this._innerGraphic;
        this._outerGraphic;
        this._group;

        _init.call(this);
    }
    _scope.prototype = {
        remove:function(){
           if( this._innerGraphic ) this._innerGraphic.remove();
           if( this._outerGraphic ) this._outerGraphic.remove();
        },
        setPosition:function(value){
            this._position = value;
            _onPositionChanged.call(this);
        },
        getPosition:function(){

        }
    }
    var _init = function(){
        console.log("INIT CALLED ON DOT.... ")
        this._innerGraphic = new _paper.Path.Circle(this._position,  this._outerRadius);
        this._innerGraphic.fillColor = this._unselectedOuterColour;
        this._innerGraphic.blendMode = 'multiply';

        this._outerGraphic = new _paper.Path.Circle(this._position,  this._outerRadius/2);
        this._outerGraphic.fillColor = "rgba(0,255,255,1)";
        //this._outerGraphic.blendMode = 'multiply';

        this._group = new _paper.Group([this._innerGraphic, this._outerGraphic])

    }
    var _onPositionChanged = function(){
        this._group.setPosition( this._position );
    }
    return _scope;
})();

var _drawDynamicDots = function(){
    var diff;
    if(this._dynamicDotArray.length != this.getData().length){
        diff =  this.getData().length - this._dynamicDotArray.length
    }
    ///////////////
    if(diff>0){
        for(var i=0; i<diff; i++){
            this.activate();

            var _circle = new Dot(this, new _paper.Point(this.getData()[i].x, this.getData()[i].y), this.getData()[i]);
            //console.log(" - - ------ - -- - -",_circle)
            //var _circle = new _paper.Path.Circle(new _paper.Point(this.getData()[i].x, this.getData()[i].y), 6);
            //_circle.data = this.getData()[i];
            //_circle.data.index=i;
            //_circle.data.parent=this;
            //
            //_circle.on('mouseenter', function(e){
            //    console.log(this.data);
            //    this.data.parent.getTooltip().setText(this.data.y);
            //})
            this._dynamicDotArray.push(_circle);
            //_circle.fillColor = this.dotColor;
        }
    }
    ////////////
    if(diff<0){
        var _removealArray = this._dynamicDotArray.splice(this._dynamicDotArray.length+diff,  0-diff )

        for(var i=0; i<_removealArray.length; i++){
            this.activate();
            var toDelete = _removealArray[i]
            try{
                toDelete.remove();
                delete toDelete;
            }catch(e){
                ///---
            }
        }
    }
}

var _drawDots =function(){
    var diff;
    if(this._circleArray.length != this.getData().length){
         diff =  this.getData().length - this._circleArray.length
    }
    ///////////////
    if(diff>0){
        for(var i=0; i<diff; i++){
            this.activate();
            var _circle = new _paper.Path.Circle(new _paper.Point(this.getData()[i].x, this.getData()[i].y), 6);
            _circle.data = this.getData()[i];
            _circle.data.index=i;
            _circle.data.parent=this;

            _circle.on('mouseenter', function(e){
                console.log(this.data);
                this.data.parent.getTooltip().setText(this.data.y);
            })
            this._circleArray.push(_circle);
            _circle.fillColor = this.dotColor;
        }
       // console.log(this._circleArray)
    }
    ////////////
    if(diff<0){
        var _removealArray = this._circleArray.splice(this._circleArray.length+diff,  0-diff )

        for(var i=0; i<_removealArray.length; i++){
            this.activate();
            var toDelete = _removealArray[i]
            try{
                toDelete.remove();
                delete toDelete;
            }catch(e){
                ///---
            }
        }
    }
}
//---------------------------
var _drawLine = function(){
    if( this.myPath.segments.length < this.getData().length){
        for(var i=this.myPath.segments.length; i<this.getData().length; i++){
            this.myPath.add(new _paper.Point(0, 0));
        }
    }
    if( this.myPath.segments.length > this.getData().length){
        //for(var i=this.getData().length ; i<this.myPath.segments.length; i++){
        //    this.myPath.add(new _paper.Point(0, 0));
        //}
        console.log(this.myPath.segments.length, this.getData().length)
        this.myPath.removeSegments(this.getData().length-1, this.myPath.segments.length-1)
    }

    //this.myPath.selected = true;

}
var _onFrame = function(){
   // this.activate();
    for(var i =0; i<this.getData().length; i++){
        if(this.myPath.segments[i]){
            var currentPos = new _paper.Point(this.myPath.segments[i].getPoint().x , this.myPath.segments[i].getPoint().y);
            var xp =  this.getXscale()  ? this.getXscale().map( this.getData()[i].x ) : this.getData()[i].x;
            var yp =  this.getYscale()  ? this.getYscale().map( this.getData()[i].y ) : this.getData()[i].y;
            var desiredPos = new _paper.Point( xp, yp );
            var diff = desiredPos.subtract(currentPos);
            var velocity = diff.divide(6);
            var se = this.myPath.segments[i];
            var newpos = currentPos.add(velocity); //new __paper.Point(_this.getData()[i].x, _this.getData()[i].y)
            se.setPoint( newpos );
            if(this._circleArray[i]) this._circleArray[i].position = newpos;
            if(this._dynamicDotArray[i]) this._dynamicDotArray[i].setPosition(newpos);
        }
    }
    //this.myPath.smooth();
    this.myPath.insert(this.getData().length, new _paper.Point(this.getWidth()-this.rightMargin, this.getHeight() - this.bottomMargin));
    this.myPath.insert(this.getData().length+1, new _paper.Point(this.leftMargin, this.getHeight() - this.bottomMargin ));
    this.myPath.closed = true;
    this.myPath.fillColor = {
        gradient: {
            stops: [this.fillColour1, this.fillColour2]
        },
        origin: [0,this.getHeight()/2],
            destination: [0,this.getHeight()]
    }
}

var _scribble = function(){
    this._path.strokeColor = '#cccccc';
    this._path.lineTo(this._start.add([ Math.random()*300, Math.random()*300 ]));
    this._path.smooth();
    this._path.dashArray = [10, 4];
    _paper.view.draw();
}

PaperRenderer.prototype.render = function(){
    this.initScale();
    console.log("RENDER: ",this.getYscale() )
    _drawLine.call(this);
    _drawDots.call(this);
    _drawYlines.call(this);
    _drawDynamicDots.call(this);
    //this._path.lineTo(this._start.add([ Math.random()*300, Math.random()*300 ]));
    // Draw the view now:
    //_paper.view.draw();
    //_paper2.view.draw();
    //_paper.remove( this._circle );
   // this.myPath.fullySelected = true;
    //this.myPath.smooth();
    _paper.view.draw();
}
<|endoftext|>


<commit_before>import THREE from "three";

class PhysicsSystem {
  constructor(gameState) {
    this._gameState = gameState;
    this._playerGeometry = new THREE.Geometry();
  }

  tick(dt) {
    const input = this._gameState.input;
    const player = this._gameState.player;

    player.rotation += player.angularVelocity * dt;
    player.position.x += player.velocity * Math.sin(player.rotation) * dt;
    player.position.y += player.velocity * Math.cos(player.rotation) * dt;

    const forwardBackward = input.backward - input.forward;
    player.velocity = forwardBackward * player.moveRate;

    const turnLeftRight = input.turnLeft - input.turnRight;
    player.angularVelocity = turnLeftRight * player.turnRate;

    player.bbox = this._computePlayerBBox();

    this._checkCollisions(player.bbox);
  }

  _checkCollisions(playerBBox) {
    // TODO smarter broadphase
    const gs = this._gameState;
    for (let x = 0; x < gs.width; ++x) {
      for (let y = 0; y < gs.height; ++y) {
        const cellData = gs.getCellData(x, y);
        cellData.isCollision = false;
        if (!cellData.isWalkable) {
          const overlap = this._checkAABBCollision(cellData.bbox, playerBBox);
          if (overlap) {
            cellData.isCollision = true;
          }
        }
      }
    }
  }

  /**
   * Return a vector that indicates where to move boxB so that it is not
   * colliding with boxA or return `undefined` if there is no collision.
   */
  _checkAABBCollision(boxA, boxB) {
    const centerDelta = boxA.center().sub(boxB.center());
    const overlap = boxA.size().add(boxB.size())
                        .multiplyScalar(0.5)
                        .sub(vec2Abs(centerDelta));

    if (overlap.x <= 0 || overlap.y <= 0) {
      return;
    }

    // No separating axis, so figure out the projection vector
    if (overlap.x < overlap.y) {
      if (centerDelta.x < 0) {
        overlap.x = -overlap.x;
      }
      overlap.y = 0;
    } else {
      overlap.x = 0;
      if (centerDelta.y < 0) {
        overlap.y = -overlap.y;
      }
    }
    return overlap;
  }

  _computePlayerBBox() {
    const player = this._gameState.player;
    const position = new THREE.Vector2(player.position.x, player.position.y);
    const geometry = this._playerGeometry.copy(player.geometry);

    geometry.rotateY(player.rotation);
    geometry.computeBoundingBox();

    const bbox3 = geometry.boundingBox;
    const bbox = new THREE.Box2(new THREE.Vector2(bbox3.min.x, bbox3.min.z),
                                new THREE.Vector2(bbox3.max.x, bbox3.max.z));
    bbox.translate(position);
    return bbox;
  }
}

function vec2Abs(vec) {
  vec.x = Math.abs(vec.x);
  vec.y = Math.abs(vec.y);
  return vec;
}

export default PhysicsSystem;
<commit_msg>Initial (flawed) collision resolution<commit_after>import THREE from "three";

class PhysicsSystem {
  constructor(gameState) {
    this._gameState = gameState;
    this._playerGeometry = new THREE.Geometry();
  }

  tick(dt) {
    const input = this._gameState.input;
    const player = this._gameState.player;

    player.rotation += player.angularVelocity * dt;
    player.position.x += player.velocity * Math.sin(player.rotation) * dt;
    player.position.y += player.velocity * Math.cos(player.rotation) * dt;

    const forwardBackward = input.backward - input.forward;
    player.velocity = forwardBackward * player.moveRate;

    const turnLeftRight = input.turnLeft - input.turnRight;
    player.angularVelocity = turnLeftRight * player.turnRate;

    player.bbox = this._computePlayerBBox();

    this._checkCollisions(player.bbox);
  }

  _checkCollisions(playerBBox) {
    // TODO smarter broadphase
    const gs = this._gameState;
    const collisionVectors = [];
    for (let x = 0; x < gs.width; ++x) {
      for (let y = 0; y < gs.height; ++y) {
        const cellData = gs.getCellData(x, y);
        cellData.isCollision = false;
        if (!cellData.isWalkable) {
          const overlap = this._checkAABBCollision(cellData.bbox, playerBBox);
          if (overlap) {
            collisionVectors.push(overlap);
            cellData.isCollision = true;
          }
        }
      }
    }

    if (collisionVectors.length) {
      const resolution = new THREE.Vector2();
      collisionVectors.forEach(v => {
        resolution.add(v);
      });
      this._gameState.player.position.sub(resolution);
    }
  }

  /**
   * Return a vector that indicates where to move boxB so that it is not
   * colliding with boxA or return `undefined` if there is no collision.
   */
  _checkAABBCollision(boxA, boxB) {
    const centerDelta = boxA.center().sub(boxB.center());
    const overlap = boxA.size().add(boxB.size())
                        .multiplyScalar(0.5)
                        .sub(vec2Abs(centerDelta.clone()));

    if (overlap.x <= 0 || overlap.y <= 0) {
      return;
    }

    // No separating axis, so figure out the projection vector
    if (overlap.x < overlap.y) {
      if (centerDelta.x < 0) {
        overlap.x = -overlap.x;
      }
      overlap.y = 0;
    } else {
      overlap.x = 0;
      if (centerDelta.y < 0) {
        overlap.y = -overlap.y;
      }
    }
    return overlap;
  }

  _computePlayerBBox() {
    const player = this._gameState.player;
    const position = new THREE.Vector2(player.position.x, player.position.y);
    const geometry = this._playerGeometry.copy(player.geometry);

    geometry.rotateY(player.rotation);
    geometry.computeBoundingBox();

    const bbox3 = geometry.boundingBox;
    const bbox = new THREE.Box2(new THREE.Vector2(bbox3.min.x, bbox3.min.z),
                                new THREE.Vector2(bbox3.max.x, bbox3.max.z));
    bbox.translate(position);
    return bbox;
  }
}

function vec2Abs(vec) {
  vec.x = Math.abs(vec.x);
  vec.y = Math.abs(vec.y);
  return vec;
}

export default PhysicsSystem;
<|endoftext|>


<commit_before>angular.module('app')

.directive('draggable', ['$parse', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var el = element[0];
      var drag = null;
      var style = null;

      el.draggable = true;

      el.addEventListener('dragstart', function(event) {
        event.dataTransfer.effectAllowed = 'move';
        this.classList.add(style);

        if (drag) $parse(drag)(scope)(event);
      }, false);

      el.addEventListener('dragend', function(event) {
        this.classList.remove(style);
        return false;
      }, false);

      attrs.$observe('drag', function(d) {
        drag = d;
      });
      attrs.$observe('dragstyle', function(s) {
        style = s;
      })
    }
  }
}])

.directive('droppable', ['$parse', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      // again we need the native object
      var el = element[0];

      el.addEventListener('dragover', function(event) {
        event.dataTransfer.dropEffect = 'move';
        // allows us to drop
        if (event.preventDefault) event.preventDefault();
        this.classList.add('over');
      }, false);

      el.addEventListener('dragenter', function(event) {
        this.classList.add('over');
      }, false);

      el.addEventListener('dragleave', function(event) {
        this.classList.remove('over');
      }, false);

      el.addEventListener('drop', function(event) {
        // Stops some browsers from redirecting.
        if (event.stopPropagation) event.stopPropagation();
        this.classList.remove('over');
        if (drop) $parse(drop)(scope)(event);

        return false;
      }, false);

      attrs.$observe('drop', function(d) {
        drop = d;
      });
    }
  }
}]);<commit_msg>Add missing declaration<commit_after>angular.module('app')

.directive('draggable', ['$parse', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var el = element[0];
      var drag = null;
      var style = null;

      el.draggable = true;

      el.addEventListener('dragstart', function(event) {
        event.dataTransfer.effectAllowed = 'move';
        this.classList.add(style);

        if (drag) $parse(drag)(scope)(event);
      }, false);

      el.addEventListener('dragend', function(event) {
        this.classList.remove(style);
        return false;
      }, false);

      attrs.$observe('drag', function(d) {
        drag = d;
      });
      attrs.$observe('dragstyle', function(s) {
        style = s;
      })
    }
  }
}])

.directive('droppable', ['$parse', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      // again we need the native object
      var el = element[0];
      var drop = null;

      el.addEventListener('dragover', function(event) {
        event.dataTransfer.dropEffect = 'move';
        // allows us to drop
        if (event.preventDefault) event.preventDefault();
        this.classList.add('over');
      }, false);

      el.addEventListener('dragenter', function(event) {
        this.classList.add('over');
      }, false);

      el.addEventListener('dragleave', function(event) {
        this.classList.remove('over');
      }, false);

      el.addEventListener('drop', function(event) {
        // Stops some browsers from redirecting.
        if (event.stopPropagation) event.stopPropagation();
        this.classList.remove('over');
        if (drop) $parse(drop)(scope)(event);

        return false;
      }, false);

      attrs.$observe('drop', function(d) {
        drop = d;
      });
    }
  }
}]);<|endoftext|>


<commit_before>define([], function() {

	var Art = function(canvas) {
		this.canvas = canvas;

		canvas.width = $(canvas).width();
		canvas.height = $(canvas).height();

		this.ctx = canvas.getContext("2d");
		this.ctx.lineCap = "round";
		this.ctx.lineJoin = "round";
		this.ctx.lineWidth = 1;

		this.ctx.strokeStyle = "black";

		this.ctx.translate(0.5, 0.5);
		this.ctx.font = "20px sans-serif";
		this.ctx.textBaseline = "top";
	}

	Art.prototype.setColor = function(c) {
		this.ctx.strokeStyle = c;
		this.ctx.fillStyle = c;
	}

	Art.prototype.line = function(x1,y1,x2,y2) {
		this.ctx.beginPath();
		this.ctx.moveTo(x1,y1);
		this.ctx.lineTo(x2,y2);
		this.ctx.stroke();
	}

	Art.prototype.spot = function(x,y,radius) {
		this.ctx.beginPath();
		this.ctx.arc(x,y,radius,0,Math.PI * 2);
		this.ctx.fill();
	}

	Art.prototype.circle = function(x,y,radius) {
		this.ctx.beginPath();
		this.ctx.arc(x,y,radius,0,7);
		this.ctx.stroke();
	}

	Art.prototype.box = function(x,y,width,height) {
		this.ctx.fillRect(x-0.5,y-0.5,width,height);
	}

	Art.prototype.rectangle = function(x,y,width,height) {
		this.ctx.strokeRect(x-0.5,y-0.5,width,height);
	}

	Art.prototype.image = function(x,y,path) {

		return window.getImgPromise("assets/images/" + path).then(function(i) {
			this.ctx.drawImage(i, x, y);
		}.bind(this));

	}

	Art.prototype.text = function(x,y,string) {
		this.ctx.fillText(string, x, y);
	}

	Art.prototype.font = function(font) {
		this.ctx.font = font;
	}

	Art.prototype.background = function(path) {
		return window.getImgPromise("assets/backgrounds/" + path).then(function(i) {
			this.ctx.drawImage(i, 0, 0, i.width, i.height, 0, 0, this.canvas.width, this.canvas.height);
		}.bind(this));
	}

	var poly = function(ctx, vertices) {
		ctx.beginPath();
		ctx.moveTo(vertices[0][0], vertices[0][1]);

		for (var i = 1; i < vertices.length; i++) {
			ctx.lineTo(vertices[i][0], vertices[i][1]);
		}

		ctx.closePath();
	}

	Art.prototype.polygon = function(vertices) {
		poly(this.ctx, vertices)
		this.ctx.stroke();
	}

	Art.prototype.fillPolygon = function(vertices) {
		poly(this.ctx, vertices)
		this.ctx.fill();
	}

	return Art;
});
<commit_msg>Add external image loading<commit_after>define([], function() {

	var Art = function(canvas) {
		this.canvas = canvas;

		canvas.width = $(canvas).width();
		canvas.height = $(canvas).height();

		this.ctx = canvas.getContext("2d");
		this.ctx.lineCap = "round";
		this.ctx.lineJoin = "round";
		this.ctx.lineWidth = 1;

		this.ctx.strokeStyle = "black";

		this.ctx.translate(0.5, 0.5);
		this.ctx.font = "20px sans-serif";
		this.ctx.textBaseline = "top";
	}

	Art.prototype.setColor = function(c) {
		this.ctx.strokeStyle = c;
		this.ctx.fillStyle = c;
	}

	Art.prototype.line = function(x1,y1,x2,y2) {
		this.ctx.beginPath();
		this.ctx.moveTo(x1,y1);
		this.ctx.lineTo(x2,y2);
		this.ctx.stroke();
	}

	Art.prototype.spot = function(x,y,radius) {
		this.ctx.beginPath();
		this.ctx.arc(x,y,radius,0,Math.PI * 2);
		this.ctx.fill();
	}

	Art.prototype.circle = function(x,y,radius) {
		this.ctx.beginPath();
		this.ctx.arc(x,y,radius,0,7);
		this.ctx.stroke();
	}

	Art.prototype.box = function(x,y,width,height) {
		this.ctx.fillRect(x-0.5,y-0.5,width,height);
	}

	Art.prototype.rectangle = function(x,y,width,height) {
		this.ctx.strokeRect(x-0.5,y-0.5,width,height);
	}

	Art.prototype.image = function(x,y,path) {
        if (path.indexOf("://") == -1)
            path = "assets/images/" + path

		return window.getImgPromise(path).then(function(i) {
			this.ctx.drawImage(i, x, y);
		}.bind(this));

	}

	Art.prototype.text = function(x,y,string) {
		this.ctx.fillText(string, x, y);
	}

	Art.prototype.font = function(font) {
		this.ctx.font = font;
	}

	Art.prototype.background = function(path) {
        if (path.indexOf("://") == -1)
            path = "assets/backgrounds/" + path

		return window.getImgPromise(path).then(function(i) {
			this.ctx.drawImage(i, 0, 0, i.width, i.height, 0, 0, this.canvas.width, this.canvas.height);
		}.bind(this));
	}

	var poly = function(ctx, vertices) {
		ctx.beginPath();
		ctx.moveTo(vertices[0][0], vertices[0][1]);

		for (var i = 1; i < vertices.length; i++) {
			ctx.lineTo(vertices[i][0], vertices[i][1]);
		}

		ctx.closePath();
	}

	Art.prototype.polygon = function(vertices) {
		poly(this.ctx, vertices)
		this.ctx.stroke();
	}

	Art.prototype.fillPolygon = function(vertices) {
		poly(this.ctx, vertices)
		this.ctx.fill();
	}

	return Art;
});
<|endoftext|>


<commit_before>(function(BlockChainInfo, Models) {

  function Wallet() {
    this.unspentOutputs = {};

    this._btcToSatoshis = function(btc) {
      return btc * 100000000;
    };

    this._satoshisToBtc = function(satoshis) {
      return satoshis / 100000000;
    };

    this._eachUnspentOutput = function(action) {
      for (var id in this.unspentOutputs) {
        var unspentOutput = this.unspentOutputs[id];
        // explicitly return false to break
        if (action(unspentOutput) === false) {
          break;
        }
      }
    };
  }

  Wallet.prototype.updateUnspentOutputs = function(unspentOutputs) {
    for (var i=0; i<unspentOutputs.length; i++) {
      var unspentOutput = unspentOutputs[i];
      var id = unspentOutput.tx_hash + '-' + unspentOutput.tx_output_n;

      if (unspentOutput.confirmations > 0) {
        this.unspentOutputs[id] = {
          tx_hash: unspentOutput.tx_hash,
          tx_output_n: unspentOutput.tx_output_n,
          script: unspentOutput.script,
          value: unspentOutput.value,
          confirmations: unspentOutput.confirmations
        };
      }
    }
  };

  Wallet.prototype.fetchUnspentOutputs = function(address, hollaback) {
    var self = this;
    BlockChainInfo.unspent(address, function(data) {
      var result = [];
      if (data.unspent_outputs && data.unspent_outputs.length > 0) {
        result = data.unspent_outputs;
        self.unspentOutputs = {};
        self.updateUnspentOutputs(result);
      }

      hollaback(result);
    });
  };

  Wallet.prototype.balanceBTC = function() {
    var value = 0;
    this._eachUnspentOutput(function(unspentOutput) {
      value += unspentOutput.value;
    });

    return this._satoshisToBtc(value);
  };

  Wallet.prototype.selectCoins = function(opts) {
    var totalRequested = opts.amountBTC + opts.minerFeeBTC,
        totalAvailable = this.balanceBTC(),
        selectedCoins = [],
        self = this;

    if (totalRequested <= totalAvailable) {
      // return the only output
      if (Object.keys(self.unspentOutputs).length === 1) {
        selectedCoins.push(self.unspentOutputs[Object.keys(self.unspentOutputs)[0]]);
      }
      if (selectedCoins.length > 0) { return selectedCoins };

      // look for an output that has the exact amount
      self._eachUnspentOutput(function(unspentOutput) {
        if (totalRequested === self._satoshisToBtc(unspentOutput.value)) {
          selectedCoins.push(unspentOutput);
          return false;
        }
      });
      if (selectedCoins.length > 0) { return selectedCoins };

      // collect outputs until requested amount is matched or exceeded
      var totalOutputValue = 0;
      self._eachUnspentOutput(function(unspentOutput) {
        selectedCoins.push(unspentOutput);
        totalOutputValue += self._satoshisToBtc(unspentOutput.value);

        if (totalRequested <= totalOutputValue) {
          return false;
        }
      });

    }

    return selectedCoins;
  };

  Models.Wallet = Wallet;
  Models.wallet = new Wallet();
})(BlockChainInfo, CoinPocketApp.Models);
<commit_msg>Fix semi colon<commit_after>(function(BlockChainInfo, Models) {

  function Wallet() {
    this.unspentOutputs = {};

    this._btcToSatoshis = function(btc) {
      return btc * 100000000;
    };

    this._satoshisToBtc = function(satoshis) {
      return satoshis / 100000000;
    };

    this._eachUnspentOutput = function(action) {
      for (var id in this.unspentOutputs) {
        var unspentOutput = this.unspentOutputs[id];
        // explicitly return false to break
        if (action(unspentOutput) === false) {
          break;
        }
      }
    };
  }

  Wallet.prototype.updateUnspentOutputs = function(unspentOutputs) {
    for (var i=0; i<unspentOutputs.length; i++) {
      var unspentOutput = unspentOutputs[i];
      var id = unspentOutput.tx_hash + '-' + unspentOutput.tx_output_n;

      if (unspentOutput.confirmations > 0) {
        this.unspentOutputs[id] = {
          tx_hash: unspentOutput.tx_hash,
          tx_output_n: unspentOutput.tx_output_n,
          script: unspentOutput.script,
          value: unspentOutput.value,
          confirmations: unspentOutput.confirmations
        };
      }
    }
  };

  Wallet.prototype.fetchUnspentOutputs = function(address, hollaback) {
    var self = this;
    BlockChainInfo.unspent(address, function(data) {
      var result = [];
      if (data.unspent_outputs && data.unspent_outputs.length > 0) {
        result = data.unspent_outputs;
        self.unspentOutputs = {};
        self.updateUnspentOutputs(result);
      }

      hollaback(result);
    });
  };

  Wallet.prototype.balanceBTC = function() {
    var value = 0;
    this._eachUnspentOutput(function(unspentOutput) {
      value += unspentOutput.value;
    });

    return this._satoshisToBtc(value);
  };

  Wallet.prototype.selectCoins = function(opts) {
    var totalRequested = opts.amountBTC + opts.minerFeeBTC,
        totalAvailable = this.balanceBTC(),
        selectedCoins = [],
        self = this;

    if (totalRequested <= totalAvailable) {
      // return the only output
      if (Object.keys(self.unspentOutputs).length === 1) {
        selectedCoins.push(self.unspentOutputs[Object.keys(self.unspentOutputs)[0]]);
      }
      if (selectedCoins.length > 0) { return selectedCoins; }

      // look for an output that has the exact amount
      self._eachUnspentOutput(function(unspentOutput) {
        if (totalRequested === self._satoshisToBtc(unspentOutput.value)) {
          selectedCoins.push(unspentOutput);
          return false;
        }
      });
      if (selectedCoins.length > 0) { return selectedCoins; }

      // collect outputs until requested amount is matched or exceeded
      var totalOutputValue = 0;
      self._eachUnspentOutput(function(unspentOutput) {
        selectedCoins.push(unspentOutput);
        totalOutputValue += self._satoshisToBtc(unspentOutput.value);

        if (totalRequested <= totalOutputValue) {
          return false;
        }
      });

    }

    return selectedCoins;
  };

  Models.Wallet = Wallet;
  Models.wallet = new Wallet();
})(BlockChainInfo, CoinPocketApp.Models);
<|endoftext|>


<commit_before>mol.modules.map.query = function(mol) {

    mol.map.query = {};

    mol.map.query.QueryEngine = mol.mvp.Engine.extend(
    {
        init : function(proxy, bus, map) {
                this.proxy = proxy;
                this.bus = bus;
                this.map = map;
                this.sql = "" +
                        "SELECT DISTINCT p.scientificname as scientificname, t.common_names_eng as english, t._order as order, t.Family as family, t.red_list_status as redlist, CONCAT(initcap(t.class),' assessed in ', t.year_assessed) as year_assessed " +
                        "FROM polygons p LEFT JOIN master_taxonomy t ON p.scientificname = t.scientific " +
                        "WHERE ST_DWithin(p.the_geom_webmercator,ST_Transform(ST_PointFromText('POINT({0})',4326),3857),{1}) " +
                        //"WHERE ST_DWithin(the_geom,ST_PointFromText('POINT({0})',4326),0.1) " +
                        " {2} ORDER BY \"order\", scientificname";

        },
        start : function() {
            this.addQueryDisplay();
            this.addEventHandlers();
        },
        /*
         *  Build the loading display and add it as a control to the top center of the map display.
         */
        addQueryDisplay : function() {
                var params = {
                    display: null,
                    slot: mol.map.ControlDisplay.Slot.BOTTOM,
                    position: google.maps.ControlPosition.RIGHT_BOTTOM
                 };
                this.bus.fireEvent(new mol.bus.Event('register-list-click'));
                this.enabled=true;
                this.features={};
                this.display = new mol.map.QueryDisplay();
                params.display = this.display;
                this.bus.fireEvent( new mol.bus.Event('add-map-control', params));
        },
        getList: function(lat, lng, listradius, constraints, className, typeName) {
                var self = this,
                    sql = this.sql.format((lng+' '+lat), listradius.radius, constraints),
                    params = {sql:sql, key: '{0}'.format((lat+'-'+lng+'-'+listradius.radius+constraints))},
                    action = new mol.services.Action('cartodb-sql-query', params),
                    success = function(action, response) {
                        var results = {listradius:listradius, className : className, typeName : typeName, constraints: constraints, response:response},
                        event = new mol.bus.Event('species-list-query-results', results);
                        self.bus.fireEvent(event);
                    },
                    failure = function(action, response) {

                    };

                this.proxy.execute(action, new mol.services.Callback(success, failure));

        },
        addEventHandlers : function () {
            var self = this;
            /*
             * Handler in case other modules want to switch the query tool
             */
            this.bus.addHandler(
                'query-type-toggle',
                function (params) {
                    var e = {
                        params : params
                    };
                    self.changeTool(e);
                }
            );
            this.bus.addHandler(
                'species-list-query-click',
                function (event) {
                    var listradius,
                        constraints = $(self.display.classInput).val() + $(self.display.typeInput).val(),
                        className =  $("option:selected", $(self.display.classInput)).text(),
                        typeName = $("option:selected", $(self.display.typeInput)).text();

                    if (self.enabled) {
                        listradius = new google.maps.Circle(
                            {
                                map: event.map,
                                radius: parseInt(self.display.radiusInput.val())*1000, // 50 km
                                center: event.gmaps_event.latLng,
                                strokeWeight: 0,
                                clickable:false
                            }
                        );
                        self.bus.fireEvent( new mol.bus.Event('show-loading-indicator', {source : 'listradius'}));
                        self.getList(event.gmaps_event.latLng.lat(),event.gmaps_event.latLng.lng(),listradius, constraints, className, typeName);
                    }
                 }
            );
             this.bus.addHandler(
                'species-list-query-results',
                function (event) {
                    var content,
                        contentHeader,
                        listradius  = event.listradius,
                        className,
                        typeName,
                        typeStr,
                        content,
                        scientificnames = [],
                        infoWindow,
                        latHem,
                        lngHem,
                        redlistCt = {},
                        yearassessed = {},
                        speciesthreatened = 0,
                        speciesdd = 0,
                        infoDiv;

                    if(!event.response.error) {
                            className = event.className.toLowerCase(),
                            typeName = event.typeName,
                            typeStr = '';

                        typeStr = ' with ' + typeName.replace(/maps/i, '').toLowerCase() + ' maps ';
                        latHem = (listradius.center.lat() > 0) ? 'North' : 'South';
                        lngHem = (listradius.center.lng() > 0) ? 'East' : 'West';

                        contentHeader='
' +
                                '
 ' +
                                event.response.total_rows +
                                '       ' +
                                className +
                                '       species ' +
                                typeStr +
                                '       found within ' +
                                listradius.radius/1000 + ' km of ' +
                                Math.abs(Math.round(listradius.center.lat()*1000)/1000) + '° ' + latHem + ' ' +
                                Math.abs(Math.round(listradius.center.lng()*1000)/1000) + '° ' + lngHem + '
';

                        content = '
'+
                                '
' +
                                '
' +
                                '

Scientific Name	English Name	Order	Family	Red List Status

';
                        _.each(
                            event.response.rows,
                            function(name) {
                                 content += "
" +
                                    name.scientificname + "	" +
                                    name.english + "	" +
                                    name.order + "	" +
                                    name.family + "	" +
                                    name.redlist + "
";

                                 speciesthreatened += (name.redlist == 'RN' || name.redlist == 'VU' || name.redlist == 'CR' )  ? 1 : 0;
                                 speciesdd += (name.redlist == 'DD')  ? 1 : 0;
                                 yearassessed[name.year_assessed] = name.year_assessed;
                            }
                        );
                        content += '
' +
                                   '

' +
                                   '
';

                        stats = (speciesthreatened > 0) ? (speciesthreatened+" species threatened.
") : "";
                        stats += (speciesdd > 0) ? (speciesdd+" species data deficient.
") : "";
                        _.each(
                            yearassessed,
                            function(yearstr) {
                                stats+=yearstr;
                            }
                        )
                        infoWindow= new google.maps.InfoWindow( {
                            content: $(contentHeader+stats+content)[0],
                            position: listradius.center
                        });

                        self.features[listradius.center.toString()+listradius.radius] = {
                             listradius : listradius,
                             infoWindow : infoWindow
                        };

                        google.maps.event.addListener(
                            infoWindow,
                            "closeclick",
                            function (event) {
                                listradius.setMap(null);
                                delete(self.features[listradius.center.toString()+listradius.radius]);
                            }
                         );
                         self.features[listradius.center.toString()+listradius.radius] = {
                             listradius : listradius,
                             infoWindow : infoWindow
                         };

                        infoWindow.open(self.map);
                        $(".tablesorter", $(infoWindow.content)
                         ).tablesorter({widthFixed: true}
                         )
                        } else {
                            listradius.setMap(null);
                            delete(self.features[listradius.center.toString()+listradius.radius]);
                        }
                    self.bus.fireEvent( new mol.bus.Event('hide-loading-indicator', {source : 'listradius'}));

                }
             );

            this.bus.addHandler(
                'species-list-tool-toggle',
                function(event) {
                    self.enabled = !self.enabled;
                    if (self.listradius) {
                            self.listradius.setMap(null);
                        }
                    if(self.enabled == true) {
                        $(self.display).show();
                        _.each(
                            self.features,
                            function(feature) {
                                feature.listradius.setMap(self.map);
                                feature.infoWindow.setMap(self.map);
                            }
                        );
                    } else {
                        $(self.display).hide();
                        _.each(
                            self.features,
                            function(feature) {
                                feature.listradius.setMap(null);
                                feature.infoWindow.setMap(null);
                            }
                        );
                   }
                }
            );
            this.display.radiusInput.blur(
                function(event) {
                    if(this.value>1000) {
                        this.value=1000;
                        alert('Please choose a radius between 50 km and 1000 km.');
                    }
                    if(this.value<50) {
                        this.value=50;
                        alert('Please choose a radius between 50 km and 1000 km.');
                    }
                }
            );
        }
    }
    );

    mol.map.QueryDisplay = mol.mvp.View.extend(
    {
        init : function(names) {
            var className = 'mol-Map-QueryDisplay',
                html = '' +
                        '
' +
                        '
' +
                        '     Search Radius <select class="radius">' +
                        '       <option selected value="50">50 km</option>' +
                        '       <option value="100">100 km</option>' +
                        '       <option value="500">500 km</option>' +
                        '       <option value="1000">1000 km</option>' +
                        '     </select>' +
                        '     Class <select class="class" value="">' +
                        '       <option value="">All</option>' +
                        '       <option selected value=" and p.class=\'aves\'">Bird</option>' +
                        '       <option value=" and p.class=\' osteichthyes\'">Fish</option>' + //note the space, leaving till we can clean up polygons
                        '       <option value=" and p.class=\'reptilia\'">Reptile</option>' +
                        '       <option value=" and p.class=\'amphibia\'">Amphibian</option>' +
                        '       <option value=" and p.class=\'mammalia\'">Mammal</option>' +
                        '     </select>' +
                        '     Type <select class="type" value="">' +
                        '       <option value="">All</option>' +
                        '       <option selected value="and p.type=\'range\' ">Range maps</option>' +
                        '       <option value=" and p.type=\'protectedarea\'">Protected Areas</option>' +
                        '       <option value=" and p.type=\'ecoregion\'">Ecoregions</option>' +
                        '       <option value=" and p.type=\'point\'">Point records</option>' +
                        '     </select>' +
                        '
' +
                        //'
Click on the map to find bird species within 50km of that point.
' +
                        '
';

            this._super(html);
            this.resultslist=$(this).find('.resultslist');
            this.radiusInput=$(this).find('.radius');
            //$(this.radiusInput).numeric({negative : false, decimal : false});
            this.classInput=$(this).find('.class');
            this.typeInput=$(this).find('.type');
        }
    }
    );
    mol.map.QueryResultDisplay = mol.mvp.View.extend(
    {
        init : function(scientificname) {
            var className = 'mol-Map-QueryResultDisplay',
                 html = '{0}';
            this._super(html.format(scientificname));

        }
    }
    );
};<commit_msg>More list tool tweaks..<commit_after>mol.modules.map.query = function(mol) {

    mol.map.query = {};

    mol.map.query.QueryEngine = mol.mvp.Engine.extend(
    {
        init : function(proxy, bus, map) {
                this.proxy = proxy;
                this.bus = bus;
                this.map = map;
                this.sql = "" +
                        "SELECT DISTINCT p.scientificname as scientificname, t.common_names_eng as english, t._order as order, t.Family as family, t.red_list_status as redlist, CASE WHEN t.class is not null THEN CONCAT('The ', initcap(t.class), ' class was assessed in ', t.year_assessed, '. ') ELSE '' END as year_assessed " +
                        "FROM polygons p LEFT JOIN master_taxonomy t ON p.scientificname = t.scientific " +
                        "WHERE ST_DWithin(p.the_geom_webmercator,ST_Transform(ST_PointFromText('POINT({0})',4326),3857),{1}) " +
                        //"WHERE ST_DWithin(the_geom,ST_PointFromText('POINT({0})',4326),0.1) " +
                        " {2} ORDER BY \"order\", scientificname";

        },
        start : function() {
            this.addQueryDisplay();
            this.addEventHandlers();
        },
        /*
         *  Build the loading display and add it as a control to the top center of the map display.
         */
        addQueryDisplay : function() {
                var params = {
                    display: null,
                    slot: mol.map.ControlDisplay.Slot.BOTTOM,
                    position: google.maps.ControlPosition.RIGHT_BOTTOM
                 };
                this.bus.fireEvent(new mol.bus.Event('register-list-click'));
                this.enabled=true;
                this.features={};
                this.display = new mol.map.QueryDisplay();
                params.display = this.display;
                this.bus.fireEvent( new mol.bus.Event('add-map-control', params));
        },
        getList: function(lat, lng, listradius, constraints, className, typeName) {
                var self = this,
                    sql = this.sql.format((lng+' '+lat), listradius.radius, constraints),
                    params = {sql:sql, key: '{0}'.format((lat+'-'+lng+'-'+listradius.radius+constraints))},
                    action = new mol.services.Action('cartodb-sql-query', params),
                    success = function(action, response) {
                        var results = {listradius:listradius, className : className, typeName : typeName, constraints: constraints, response:response},
                        event = new mol.bus.Event('species-list-query-results', results);
                        self.bus.fireEvent(event);
                    },
                    failure = function(action, response) {

                    };

                this.proxy.execute(action, new mol.services.Callback(success, failure));

        },
        addEventHandlers : function () {
            var self = this;
            /*
             * Handler in case other modules want to switch the query tool
             */
            this.bus.addHandler(
                'query-type-toggle',
                function (params) {
                    var e = {
                        params : params
                    };
                    self.changeTool(e);
                }
            );
            this.bus.addHandler(
                'species-list-query-click',
                function (event) {
                    var listradius,
                        constraints = $(self.display.classInput).val() + $(self.display.typeInput).val(),
                        className =  $("option:selected", $(self.display.classInput)).text(),
                        typeName = $("option:selected", $(self.display.typeInput)).text();

                    if (self.enabled) {
                        listradius = new google.maps.Circle(
                            {
                                map: event.map,
                                radius: parseInt(self.display.radiusInput.val())*1000, // 50 km
                                center: event.gmaps_event.latLng,
                                strokeWeight: 0,
                                clickable:false
                            }
                        );
                        self.bus.fireEvent( new mol.bus.Event('show-loading-indicator', {source : 'listradius'}));
                        self.getList(event.gmaps_event.latLng.lat(),event.gmaps_event.latLng.lng(),listradius, constraints, className, typeName);
                    }
                 }
            );
             this.bus.addHandler(
                'species-list-query-results',
                function (event) {
                    var content,
                        contentHeader,
                        listradius  = event.listradius,
                        className,
                        typeName,
                        typeStr,
                        content,
                        scientificnames = [],
                        infoWindow,
                        latHem,
                        lngHem,
                        redlistCt = {},
                        yearassessed = {},
                        speciesthreatened = 0,
                        speciesdd = 0,
                        infoDiv;

                    if(!event.response.error) {
                            className = event.className.toLowerCase(),
                            typeName = event.typeName,
                            typeStr = '';

                        typeStr = ' with ' + typeName.replace(/maps/i, '').toLowerCase() + ' maps ';
                        latHem = (listradius.center.lat() > 0) ? 'North' : 'South';
                        lngHem = (listradius.center.lng() > 0) ? 'East' : 'West';

                        contentHeader='
' +
                                '
 ' +
                                event.response.total_rows +
                                '       ' +
                                className +
                                '       species ' +
                                typeStr +
                                '       found within ' +
                                listradius.radius/1000 + ' km of ' +
                                Math.abs(Math.round(listradius.center.lat()*1000)/1000) + '° ' + latHem + ' ' +
                                Math.abs(Math.round(listradius.center.lng()*1000)/1000) + '° ' + lngHem + '
';

                        content = '
'+
                                '
' +
                                '
' +
                                '

Scientific Name	English Name	Order	Family	Red List Status

';
                        _.each(
                            event.response.rows,
                            function(name) {
                                 content += "
" +
                                    name.scientificname + "	" +
                                    name.english + "	" +
                                    name.order + "	" +
                                    name.family + "	" +
                                    name.redlist + "
";

                                 speciesthreatened += (name.redlist == 'RN' || name.redlist == 'VU' || name.redlist == 'CR' )  ? 1 : 0;
                                 speciesdd += (name.redlist == 'DD')  ? 1 : 0;
                                 yearassessed[name.year_assessed] = name.year_assessed;
                            }
                        );
                        content += '
' +
                                   '

' +
                                   '
';

                        stats = (speciesthreatened > 0) ? (speciesthreatened+" species are threatened (IUCN Red List codes RN, VU, or CR).
") : "";
                        stats += (speciesdd > 0) ? (speciesdd+" species are data deficient (IUCN Red LIst code DD).
") : "";
                        _.each(
                            yearassessed,
                            function(yearstr) {
                                stats+=yearstr + '
';
                            }
                        )
                        infoWindow= new google.maps.InfoWindow( {
                            content: $(contentHeader+stats+content)[0],
                            position: listradius.center
                        });

                        self.features[listradius.center.toString()+listradius.radius] = {
                             listradius : listradius,
                             infoWindow : infoWindow
                        };

                        google.maps.event.addListener(
                            infoWindow,
                            "closeclick",
                            function (event) {
                                listradius.setMap(null);
                                delete(self.features[listradius.center.toString()+listradius.radius]);
                            }
                         );
                         self.features[listradius.center.toString()+listradius.radius] = {
                             listradius : listradius,
                             infoWindow : infoWindow
                         };

                        infoWindow.open(self.map);
                        $(".tablesorter", $(infoWindow.content)
                         ).tablesorter({widthFixed: true}
                         );

                         _each(
                             $('.scientificname',$(infoWindow.content)),
                             function(cell) {
                                 cell.click = function(event) {
                                     self.bus.fireEvent('search', new mol.bus.Event('search',cell.innerText));
                                 }
                             }
                         );
                        } else {
                            listradius.setMap(null);
                            delete(self.features[listradius.center.toString()+listradius.radius]);
                        }

                    self.bus.fireEvent( new mol.bus.Event('hide-loading-indicator', {source : 'listradius'}));

                }
             );

            this.bus.addHandler(
                'species-list-tool-toggle',
                function(event) {
                    self.enabled = !self.enabled;
                    if (self.listradius) {
                            self.listradius.setMap(null);
                        }
                    if(self.enabled == true) {
                        $(self.display).show();
                        _.each(
                            self.features,
                            function(feature) {
                                feature.listradius.setMap(self.map);
                                feature.infoWindow.setMap(self.map);
                            }
                        );
                    } else {
                        $(self.display).hide();
                        _.each(
                            self.features,
                            function(feature) {
                                feature.listradius.setMap(null);
                                feature.infoWindow.setMap(null);
                            }
                        );
                   }
                }
            );
            this.display.radiusInput.blur(
                function(event) {
                    if(this.value>1000) {
                        this.value=1000;
                        alert('Please choose a radius between 50 km and 1000 km.');
                    }
                    if(this.value<50) {
                        this.value=50;
                        alert('Please choose a radius between 50 km and 1000 km.');
                    }
                }
            );
        }
    }
    );

    mol.map.QueryDisplay = mol.mvp.View.extend(
    {
        init : function(names) {
            var className = 'mol-Map-QueryDisplay',
                html = '' +
                        '
' +
                        '
' +
                        '     Search Radius <select class="radius">' +
                        '       <option selected value="50">50 km</option>' +
                        '       <option value="100">100 km</option>' +
                        '       <option value="500">500 km</option>' +
                        '       <option value="1000">1000 km</option>' +
                        '     </select>' +
                        '     Class <select class="class" value="">' +
                        '       <option value="">All</option>' +
                        '       <option selected value=" and p.class=\'aves\'">Bird</option>' +
                        '       <option value=" and p.class=\' osteichthyes\'">Fish</option>' + //note the space, leaving till we can clean up polygons
                        '       <option value=" and p.class=\'reptilia\'">Reptile</option>' +
                        '       <option value=" and p.class=\'amphibia\'">Amphibian</option>' +
                        '       <option value=" and p.class=\'mammalia\'">Mammal</option>' +
                        '     </select>' +
                        '     Type <select class="type" value="">' +
                        '       <option value="">All</option>' +
                        '       <option selected value="and p.type=\'range\' ">Range maps</option>' +
                        '       <option value=" and p.type=\'protectedarea\'">Protected Areas</option>' +
                        '       <option value=" and p.type=\'ecoregion\'">Ecoregions</option>' +
                        '       <option value=" and p.type=\'point\'">Point records</option>' +
                        '     </select>' +
                        '
' +
                        //'
Click on the map to find bird species within 50km of that point.
' +
                        '
';

            this._super(html);
            this.resultslist=$(this).find('.resultslist');
            this.radiusInput=$(this).find('.radius');
            //$(this.radiusInput).numeric({negative : false, decimal : false});
            this.classInput=$(this).find('.class');
            this.typeInput=$(this).find('.type');
        }
    }
    );
    mol.map.QueryResultDisplay = mol.mvp.View.extend(
    {
        init : function(scientificname) {
            var className = 'mol-Map-QueryResultDisplay',
                 html = '{0}';
            this._super(html.format(scientificname));

        }
    }
    );
};<|endoftext|>


<commit_before>var Promise = require('bluebird'),
    ini = require('ini'),
    fs = require('fs'),
    Apache = require('./service/Apache');

var writeFile = Promise.promisify(fs.writeFile),
    unlink = Promise.promisify(fs.unlink);

function createPoolFile(hostname, data) {
    return writeFile('/etc/php/7.0/fpm/pool.d/' + hostname + '.conf', data);
}

function removePoolFile(hostname) {
    return unlink('/etc/php/7.0/fpm/pool.d/' + hostname + '.conf');
}

var Pool = function(host) {
    this.host = host;
};

Pool.prototype.create = function() {
    var data = ini.encode({
        user: this.host.customer.name,
        group: this.host.customer.name,
        listen: '/run/php/' + this.host.name + '.sock',
        'listen.owner': 'www-data',
        'listen.group': 'www-data',
        pm: 'dynamic',
        'pm.max_children': 6,
        'pm.start_servers': 1,
        'pm.min_spare_servers': 1,
        'pm.max_spare_servers': 3,
        'php_admin_value[open_basedir]': '/var/www/' + this.host.customer.name + '/' + this.host.name
    }, {
        section: this.host.name
    });
    return createPoolFile(this.host.name, data)
        .then(Fpm.restart.bind(Fpm));
};

Pool.prototype.remove = function() {
    return removePoolFile(this.host.name)
        .then(Fpm.restart.bind(Fpm));
};

module.exports = Pool;
<commit_msg>fix wrong file include<commit_after>var Promise = require('bluebird'),
    ini = require('ini'),
    fs = require('fs'),
    Fpm = require('./service/Fpm');

var writeFile = Promise.promisify(fs.writeFile),
    unlink = Promise.promisify(fs.unlink);

function createPoolFile(hostname, data) {
    return writeFile('/etc/php/7.0/fpm/pool.d/' + hostname + '.conf', data);
}

function removePoolFile(hostname) {
    return unlink('/etc/php/7.0/fpm/pool.d/' + hostname + '.conf');
}

var Pool = function(host) {
    this.host = host;
};

Pool.prototype.create = function() {
    var data = ini.encode({
        user: this.host.customer.name,
        group: this.host.customer.name,
        listen: '/run/php/' + this.host.name + '.sock',
        'listen.owner': 'www-data',
        'listen.group': 'www-data',
        pm: 'dynamic',
        'pm.max_children': 6,
        'pm.start_servers': 1,
        'pm.min_spare_servers': 1,
        'pm.max_spare_servers': 3,
        'php_admin_value[open_basedir]': '/var/www/' + this.host.customer.name + '/' + this.host.name
    }, {
        section: this.host.name
    });
    return createPoolFile(this.host.name, data)
        .then(Fpm.restart.bind(Fpm));
};

Pool.prototype.remove = function() {
    return removePoolFile(this.host.name)
        .then(Fpm.restart.bind(Fpm));
};

module.exports = Pool;
<|endoftext|>


<commit_before>var _privateObject;

export default const {expose, via} = {
  expose(privateObject) {
    _privateObject = privateObject;
  },

  via(publicObject, transform = x => x) {
    return Object.defineProperties(publicObject, Object.keys(_privateObject)
                                                       .reduce((m, n) => {
                                                         m[n] = {
                                                           configurable: true,
                                                           enumerable: true,
                                                           get: () => _privateObject[n],
                                                           set: x => _privateObject[n] = transform(x)
                                                         };

                                                         return m;
                                                       }, {}));
  }
};
<commit_msg>Fix syntax error<commit_after>var _privateObject;

export default {expose, via} = {
  expose(privateObject) {
    _privateObject = privateObject;
  },

  via(publicObject, transform = x => x) {
    return Object.defineProperties(publicObject, Object.keys(_privateObject)
                                                       .reduce((m, n) => {
                                                         m[n] = {
                                                           configurable: true,
                                                           enumerable: true,
                                                           get: () => _privateObject[n],
                                                           set: x => _privateObject[n] = transform(x)
                                                         };

                                                         return m;
                                                       }, {}));
  }
};
<|endoftext|>