<commit_before>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var dbus = { // hook object for dbus types not translated by python-json
		Double: function(value, level) {
			return value;
		}
};

/*****************************************************************************/

var cloudeebus = window.cloudeebus = {version: "0.2"};

cloudeebus.reset = function() {
	cloudeebus.sessionBus = null;
	cloudeebus.systemBus = null;
	cloudeebus.wampSession = null;
	cloudeebus.uri = null;
};

cloudeebus.log = function(msg) {
};

cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
	cloudeebus.reset();
	cloudeebus.uri = uri;

	function onCloudeebusVersionCheckCB(version) {
		if (cloudeebus.version == version) {
			cloudeebus.log("Connected to " + cloudeebus.uri);
			if (successCB)
				successCB();
		} else {
			var errorMsg = "Cloudeebus server version " + version + " and client version " + cloudeebus.version + " mismatch";
			cloudeebus.log(errorMsg);
			if (errorCB)
				errorCB(errorMsg);
		}
	}

	function onWAMPSessionAuthErrorCB(error) {
		cloudeebus.log("Authentication error: " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	function onWAMPSessionAuthenticatedCB(permissions) {
		cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
		cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
		cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
	}

	function onWAMPSessionChallengedCB(challenge) {
		var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
		cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
	}

	function onWAMPSessionConnectedCB(session) {
		cloudeebus.wampSession = session;
		if (manifest)
			cloudeebus.wampSession.authreq(
					manifest.name,
					{permissions: JSON.stringify(manifest.permissions)}
				).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
		else
			cloudeebus.wampSession.authreq().then(function() {
				cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
				}, onWAMPSessionAuthErrorCB);
	}

	function onWAMPSessionErrorCB(code, reason) {
		if (code == ab.CONNECTION_UNSUPPORTED) {
			cloudeebus.log("Browser is not supported");
		}
		else {
			cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
		}
		if (errorCB)
			errorCB(reason);
	}

	return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
};

cloudeebus.SessionBus = function() {
	return cloudeebus.sessionBus;
};

cloudeebus.SystemBus = function() {
	return cloudeebus.systemBus;
};

/*****************************************************************************/

cloudeebus.BusConnection = function(name, session) {
	this.name = name;
	this.wampSession = session;
	return this;
};

cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
	var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
	if (introspectCB)
		proxy._introspect(introspectCB, errorCB);
	return proxy;
};

/*****************************************************************************/

cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
	this.wampSession = session;
	this.busConnection = busConnection;
	this.busName = busName;
	this.objectPath = objectPath;
	return this;
};

cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {

	var self = this;

	function getAllPropertiesSuccessCB(props) {
		for (var prop in props)
			self[prop] = props[prop];
		getAllPropertiesNextInterfaceCB();
	}

	function getAllPropertiesNextInterfaceCB() {
		if (self.propInterfaces.length > 0)
			self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	function introspectSuccessCB(str) {
		var parser = new DOMParser();
		var xmlDoc = parser.parseFromString(str, "text/xml");
		var interfaces = xmlDoc.getElementsByTagName("interface");
		self.propInterfaces = [];
		var supportDBusProperties = false;
		for (var i=0; i < interfaces.length; i++) {
			var ifName = interfaces[i].attributes.getNamedItem("name").value;
			if (ifName == "org.freedesktop.DBus.Properties")
				supportDBusProperties = true;
			var hasProperties = false;
			var ifChild = interfaces[i].firstChild;
			while (ifChild) {
				if (ifChild.nodeName == "method") {
					var nArgs = 0;
					var metChild = ifChild.firstChild;
					while (metChild) {
						if (metChild.nodeName == "arg" &&
							metChild.attributes.getNamedItem("direction").value == "in")
								nArgs++;
						metChild = metChild.nextSibling;
					}
					self._addMethod(ifName,
							ifChild.attributes.getNamedItem("name").value,
							nArgs);
				}
				else if (ifChild.nodeName == "property") {
					if (!hasProperties)
						self.propInterfaces.push(ifName);
					hasProperties = true;
				}
				ifChild = ifChild.nextSibling;
			}
		}
		if (supportDBusProperties && self.propInterfaces.length > 0) {
			self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
		}
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	// call Introspect on self
	self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
};

cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {

	var self = this;

	self[method] = function() {
		if (arguments.length < nArgs || arguments.length > nArgs + 2)
			throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
		var args = [];
		var successCB = null;
		var errorCB = null;
		for (var i=0; i < nArgs; i++ )
			args.push(arguments[i]);
		if (arguments.length > nArgs)
			successCB = arguments[nArgs];
		if (arguments.length > nArgs + 1)
			errorCB = arguments[nArgs + 1];
		self.callMethod(ifName, method, args, successCB, errorCB);
	};

};

cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {

	var self = this;

	function callMethodSuccessCB(str) {
		if (successCB) {
			try { // calling dbus hook object function for un-translated types
				successCB.apply(self, eval(str));
			}
			catch (e) {
				cloudeebus.log("Method callback exception: " + e);
				if (errorCB)
					errorCB(e);
			}
		}
	}

	function callMethodErrorCB(error) {
		cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		method,
		JSON.stringify(args)
	];

	// call dbusSend with bus type, destination, object, message and arguments
	self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
};

cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {

	var self = this;

	function signalHandler(id, data) {
		if (successCB) {
			try { // calling dbus hook object function for un-translated types
				successCB.apply(self, eval(data));
			}
			catch (e) {
				cloudeebus.log("Signal handler exception: " + e);
				if (errorCB)
					errorCB(e);
			}
		}
	}

	function connectToSignalSuccessCB(str) {
		try {
			self.wampSession.subscribe(str, signalHandler);
		}
		catch (e) {
			cloudeebus.log("Subscribe error: " + e);
		}
	}

	function connectToSignalErrorCB(error) {
		cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		signal
	];

	// call dbusSend with bus type, destination, object, message and arguments
	self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
};

cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
	try {
		this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
	}
	catch (e) {
		cloudeebus.log("Unsubscribe error: " + e);
	}
};
<commit_msg>cloudeebus js library v0.2.1<commit_after>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var dbus = { // hook object for dbus types not translated by python-json
		Double: function(value, level) {
			return value;
		}
};

/*****************************************************************************/

var cloudeebus = window.cloudeebus = {version: "0.2.1"};

cloudeebus.reset = function() {
	cloudeebus.sessionBus = null;
	cloudeebus.systemBus = null;
	cloudeebus.wampSession = null;
	cloudeebus.uri = null;
};

cloudeebus.log = function(msg) {
};

cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
	cloudeebus.reset();
	cloudeebus.uri = uri;

	function onCloudeebusVersionCheckCB(version) {
		if (cloudeebus.version == version) {
			cloudeebus.log("Connected to " + cloudeebus.uri);
			if (successCB)
				successCB();
		} else {
			var errorMsg = "Cloudeebus server version " + version + " and client version " + cloudeebus.version + " mismatch";
			cloudeebus.log(errorMsg);
			if (errorCB)
				errorCB(errorMsg);
		}
	}

	function onWAMPSessionAuthErrorCB(error) {
		cloudeebus.log("Authentication error: " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	function onWAMPSessionAuthenticatedCB(permissions) {
		cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
		cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
		cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
	}

	function onWAMPSessionChallengedCB(challenge) {
		var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
		cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
	}

	function onWAMPSessionConnectedCB(session) {
		cloudeebus.wampSession = session;
		if (manifest)
			cloudeebus.wampSession.authreq(
					manifest.name,
					{permissions: JSON.stringify(manifest.permissions)}
				).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
		else
			cloudeebus.wampSession.authreq().then(function() {
				cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
				}, onWAMPSessionAuthErrorCB);
	}

	function onWAMPSessionErrorCB(code, reason) {
		if (code == ab.CONNECTION_UNSUPPORTED) {
			cloudeebus.log("Browser is not supported");
		}
		else {
			cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
		}
		if (errorCB)
			errorCB(reason);
	}

	return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
};

cloudeebus.SessionBus = function() {
	return cloudeebus.sessionBus;
};

cloudeebus.SystemBus = function() {
	return cloudeebus.systemBus;
};

/*****************************************************************************/

cloudeebus.BusConnection = function(name, session) {
	this.name = name;
	this.wampSession = session;
	return this;
};

cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
	var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
	if (introspectCB)
		proxy._introspect(introspectCB, errorCB);
	return proxy;
};

/*****************************************************************************/

cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
	this.wampSession = session;
	this.busConnection = busConnection;
	this.busName = busName;
	this.objectPath = objectPath;
	return this;
};

cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {

	var self = this;

	function getAllPropertiesSuccessCB(props) {
		for (var prop in props)
			self[prop] = props[prop];
		getAllPropertiesNextInterfaceCB();
	}

	function getAllPropertiesNextInterfaceCB() {
		if (self.propInterfaces.length > 0)
			self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	function introspectSuccessCB(str) {
		var parser = new DOMParser();
		var xmlDoc = parser.parseFromString(str, "text/xml");
		var interfaces = xmlDoc.getElementsByTagName("interface");
		self.propInterfaces = [];
		var supportDBusProperties = false;
		for (var i=0; i < interfaces.length; i++) {
			var ifName = interfaces[i].attributes.getNamedItem("name").value;
			if (ifName == "org.freedesktop.DBus.Properties")
				supportDBusProperties = true;
			var hasProperties = false;
			var ifChild = interfaces[i].firstChild;
			while (ifChild) {
				if (ifChild.nodeName == "method") {
					var nArgs = 0;
					var metChild = ifChild.firstChild;
					while (metChild) {
						if (metChild.nodeName == "arg" &&
							metChild.attributes.getNamedItem("direction").value == "in")
								nArgs++;
						metChild = metChild.nextSibling;
					}
					self._addMethod(ifName,
							ifChild.attributes.getNamedItem("name").value,
							nArgs);
				}
				else if (ifChild.nodeName == "property") {
					if (!hasProperties)
						self.propInterfaces.push(ifName);
					hasProperties = true;
				}
				ifChild = ifChild.nextSibling;
			}
		}
		if (supportDBusProperties && self.propInterfaces.length > 0) {
			self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
		}
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	// call Introspect on self
	self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
};

cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {

	var self = this;

	self[method] = function() {
		if (arguments.length < nArgs || arguments.length > nArgs + 2)
			throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
		var args = [];
		var successCB = null;
		var errorCB = null;
		for (var i=0; i < nArgs; i++ )
			args.push(arguments[i]);
		if (arguments.length > nArgs)
			successCB = arguments[nArgs];
		if (arguments.length > nArgs + 1)
			errorCB = arguments[nArgs + 1];
		self.callMethod(ifName, method, args, successCB, errorCB);
	};

};

cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {

	var self = this;

	function callMethodSuccessCB(str) {
		if (successCB) {
			try { // calling dbus hook object function for un-translated types
				successCB.apply(self, eval(str));
			}
			catch (e) {
				cloudeebus.log("Method callback exception: " + e);
				if (errorCB)
					errorCB(e);
			}
		}
	}

	function callMethodErrorCB(error) {
		cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		method,
		JSON.stringify(args)
	];

	// call dbusSend with bus type, destination, object, message and arguments
	self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
};

cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {

	var self = this;

	function signalHandler(id, data) {
		if (successCB) {
			try { // calling dbus hook object function for un-translated types
				successCB.apply(self, eval(data));
			}
			catch (e) {
				cloudeebus.log("Signal handler exception: " + e);
				if (errorCB)
					errorCB(e);
			}
		}
	}

	function connectToSignalSuccessCB(str) {
		try {
			self.wampSession.subscribe(str, signalHandler);
		}
		catch (e) {
			cloudeebus.log("Subscribe error: " + e);
		}
	}

	function connectToSignalErrorCB(error) {
		cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		signal
	];

	// call dbusSend with bus type, destination, object, message and arguments
	self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
};

cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
	try {
		this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
	}
	catch (e) {
		cloudeebus.log("Unsubscribe error: " + e);
	}
};
<|endoftext|>


<commit_before>const webpack = require("webpack");
const config = require("./webpack.base.config");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

config.output.filename = "[name].[chunkhash:8].js";
config.output.chunkFilename = "[id].[chunkhash:8].chunk.js";

config.module.rules.push(
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
            loader: "css-loader?minimize",
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: ["css-loader?minimize", "less-loader"],
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: [
                "css-loader?modules&minimize&localIdentName=[hash:base64:10]",
                "less-loader"
            ],
            fallbackLoader: "style-loader"
        }),
        exclude: /node_modules/
    }
);

config.plugins.push(
    new ExtractTextPlugin("res/[name].[contenthash:8].css"),
    new webpack.DefinePlugin({
        "process.env":
        {
            NODE_ENV: JSON.stringify("production")
        }
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress:
        {
            warnings: false
        }
    })
);

module.exports = config;
<commit_msg>update<commit_after>const webpack = require("webpack");
const config = require("./webpack.base.config");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

config.output.filename = "[name].[chunkhash:8].js";
config.output.chunkFilename = "[id].[chunkhash:8].chunk.js";

config.module.rules.push(
    {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
            loader: "css-loader?minimize",
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: ["css-loader?minimize", "less-loader"],
            fallbackLoader: "style-loader"
        }),
        include: /node_modules/
    },
    {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
            loader: [
                "css-loader?modules&minimize&localIdentName=[name]-[hash:base64:5]",
                "less-loader"
            ],
            fallbackLoader: "style-loader"
        }),
        exclude: /node_modules/
    }
);

config.plugins.push(
    new ExtractTextPlugin("res/[name].[contenthash:8].css"),
    new webpack.DefinePlugin({
        "process.env":
        {
            NODE_ENV: JSON.stringify("production")
        }
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress:
        {
            warnings: false
        }
    })
);

module.exports = config;
<|endoftext|>


<commit_before>
const { resolve, join } = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const config = {
  context: resolve(__dirname, 'src'),
  entry: {
    bundle: [
      './clientRender.js'
    ],
    'vendor/js': [
      'react',
      'react-dom',
      'redux',
      'react-redux'
    ]
  },
  output: {
    path: resolve(__dirname, 'dist/public/static'),
    filename: '[name].js',
    publicPath: '/static/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'babel-loader'
        ],
        exclude: '/node_modules/'
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader',
              options: {
                modules: true,
                importLoaders: 1,
                localIdentName: '[name]_[local]___[hash:base64:5]'
              }
            },
            {
              loader: 'postcss-loader'
            }
          ]
        })
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module) {
         // this assumes your vendor imports exist in the node_modules directory
         return module.context && module.context.indexOf('node_modules') !== -1
      }
    }),
    new ExtractTextPlugin({
      filename: '[name].css',
      disable: false,
      allChunks: true
    })
  ]
}

module.exports = config
<commit_msg>Fix: production config<commit_after>
const { resolve, join } = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const config = {
  context: resolve(__dirname, 'src'),
  entry: {
    bundle: [
      './clientRender.js'
    ],
    'vendor/js': [
      'react',
      'react-dom',
      'redux',
      'react-redux'
    ]
  },
  output: {
    path: resolve(__dirname, 'public/static'),
    filename: '[name].js',
    publicPath: '/static/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'babel-loader'
        ],
        exclude: '/node_modules/'
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader',
              options: {
                modules: true,
                importLoaders: 1,
                localIdentName: '[name]_[local]___[hash:base64:5]'
              }
            },
            {
              loader: 'postcss-loader'
            }
          ]
        })
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module) {
         // this assumes your vendor imports exist in the node_modules directory
         return module.context && module.context.indexOf('node_modules') !== -1
      }
    }),
    new ExtractTextPlugin({
      filename: '[name].css',
      disable: false,
      allChunks: true
    })
  ]
}

module.exports = config
<|endoftext|>


<commit_before>// TODO: есть проблема с использованием этого до того как получены библиотеки по зависимостям
var environ = require('../environ');
try {
    require(environ.getLibPath('bem-core', '.bem/nodes/bundle.js'));
} catch(e) {}

require('bem/lib/nodesregistry').decl('BundleNode', {

    'create-test.js+browser.js+bemhtml-optimizer-node': function(tech, sourceNode, bundleNode) {
        return this.createBorschikOptimizerNode('js', sourceNode, bundleNode);
    }

});
<commit_msg>use test.js+browser.js+bemhtml from bem-core<commit_after>// TODO: есть проблема с использованием этого до того как получены библиотеки по зависимостям
var environ = require('../environ');
try {
    require(environ.getLibPath('bem-core', '.bem/nodes/bundle.js'));
} catch(e) {}
<|endoftext|>


<commit_before>angular.module('app', []);

angular.module('app').controller('mainCntrl', ['$scope',
function ($scope) {

  $scope.master = {}; // MASTER DATA STORED BY YEAR

  // $scope.selected_year = 2005;
  // $scope.years = d3.range(2005, 1865, -5);
  $scope.selected_year = 'Failed';
  $scope.years = ['Passed', 'Failed', 'For', 'Against'];

  $scope.filters = {};
  $scope.hasFilters = false;

  $scope.tooltip = {};

  // FORMATS USED IN TOOLTIP TEMPLATE IN HTML
  $scope.pFormat = d3.format(".1%");  // PERCENT FORMAT
  $scope.qFormat = d3.format(",.0f"); // COMMAS FOR LARGE NUMBERS
  $scope.dFormat = d3.format(",.2f"); // COMMAS FOR LARGE NUMBERS
  // $scope.lowerCase = function(text) {return text.toLowerCase()}
  $scope.ttSwitcher = function(text) {
    if (text === "Passed" | text === "Failed") {
      return "on motions that " + text.toLowerCase();
    }
  }
  $scope.ttSwitcher2 = function(text) {
    if (text === "For") {
      return ' "Yes" '
    }
    if (text === "Against") {
      return ' "No" '
    }
  }
  $scope.ttSwitcher3 = function(text) {
    if (text === "For" | text === "Against") {
      return "when voting " + text.toLowerCase() + " a motion";
    }
    if (text === "Passed" | text === "Failed") {
      return "on motions that " + text.toLowerCase();
    }
  }

  $scope.updateTooltip = function (data) {
    $scope.tooltip = data;
    $scope.$apply();
  }

  $scope.addFilter = function (name) {
    $scope.hasFilters = true;
    $scope.filters[name] = {
      name: name,
      hide: true
    };
    $scope.$apply();
  };

  $scope.update = function () {
    var data = $scope.master[$scope.selected_year];

    if (data && $scope.hasFilters) {
      $scope.drawChords(data.filter(function (d) {
        var fl = $scope.filters;
        var v1 = d.importer1, v2 = d.importer2;

        if ((fl[v1] && fl[v1].hide) || (fl[v2] && fl[v2].hide)) {
          return false;
        }
        return true;
      }));
    } else if (data) {
      $scope.drawChords(data);
    }
  };

  // IMPORT THE CSV DATA
  // d3.csv('../data/trade.csv', function (err, data) {
  //
  //   data.forEach(function (d) {
  //     d.year  = +d.year;
  //     d.flow1 = +d.flow1;
  //     d.flow2 = +d.flow2;
  //
  //     if (!$scope.master[d.year]) {
  //       $scope.master[d.year] = []; // STORED BY YEAR
  //     }
  //     $scope.master[d.year].push(d);
  //   })
  //   $scope.update();
  // });

  d3.csv('../data/Calgary_2013-2017_20160418.csv', function (err, data) {

    var councillors = ["A. Chabot", "B. Pincott", "D. Colley-Urquhart", "D. Farrell", "E. Woolley", "G-C. Carra", "J. Magliocca", "J. Stevenson", "N. Nenshi", "P. Demong", "R. Jones", "R. Pootmans", "S. Chu", "S. Keating", "W. Sutherland"];

    data.forEach(function(d) {
      d.exclude = 0;
      d.Status = (d.Status === 'PASSED' ? 'Passed' : d.Status);
      d.Status = (d.Status === 'FAILED' ? 'Failed' : d.Status);
      councillors.forEach(function(c) {
        d[c] = (d[c] === "Yes" ? 1 : (d[c] === "No" ? 0 : -1));
        d.exclude += d[c];
      })
    })
    data = data.filter(function(d) {return d.exclude != -15 & d.Status != "PASSED UNANIMOUSLY"})
    console.log(data);
    data1 = pairwise(councillors, 'Status', 'Passed');
    data2 = pairwise(councillors, 'Status', 'Failed');
    data3 = pairwise2(councillors, 'For', 1);
    data4 = pairwise2(councillors, 'Against', 0);
    data = data1.concat(data2).concat(data3).concat(data4)
console.log(data)

    data.forEach(function(d) {
      if (!$scope.master[d.year]) {
        $scope.master[d.year] = []; // STORED BY YEAR
      }
      $scope.master[d.year].push(d);
    })
    $scope.update();

    function pairwise(list, comparevar, compareval) {
      if (list.length < 2) { return []; }
      var first = list[0],
          rest  = list.slice(1),
          pairs = rest.map(function (x) {
            return {
              year: compareval, //do for and against?
              importer1: first,
              importer2: x,
              flow1: d3.sum(data, function(d) { //voted the same
                if (d[first] === d[x] & d[comparevar] === compareval) {
                  return 1;
                }
              }),
              flow2: d3.sum(data, function(d) { //voted differently
                if (d[first] === d[x]  & d[comparevar] === compareval) {
                  return 1;
                }
              })
            };
          });
      return pairs.concat(pairwise(rest, comparevar, compareval));
    }

    function pairwise2(list, group, code) {
      if (list.length < 2) { return []; }
      var first = list[0],
          rest  = list.slice(1),
          pairs = rest.map(function (x) {
            return {
              year: group, //do for and against?
              importer1: first,
              importer2: x,
              flow1: d3.sum(data, function(d) { //voted the same
                if (d[first] === d[x] & d[first] === code) {
                  return 1;
                }
              }),
              flow2: d3.sum(data, function(d) { //voted differently
                if (d[first] === d[x]  & d[first] === code) {
                  return 1;
                }
              })
            };
          });
      return pairs.concat(pairwise2(rest, group, code));
    }

  });

  $scope.$watch('selected_year', $scope.update);
  $scope.$watch('filters', $scope.update, true);

}]);
<commit_msg>exclude --not specified-- matches<commit_after>angular.module('app', []);

angular.module('app').controller('mainCntrl', ['$scope',
function ($scope) {

  $scope.master = {}; // MASTER DATA STORED BY YEAR

  // $scope.selected_year = 2005;
  // $scope.years = d3.range(2005, 1865, -5);
  $scope.selected_year = 'Failed';
  $scope.years = ['Passed', 'Failed', 'For', 'Against'];

  $scope.filters = {};
  $scope.hasFilters = false;

  $scope.tooltip = {};

  // FORMATS USED IN TOOLTIP TEMPLATE IN HTML
  $scope.pFormat = d3.format(".1%");  // PERCENT FORMAT
  $scope.qFormat = d3.format(",.0f"); // COMMAS FOR LARGE NUMBERS
  $scope.dFormat = d3.format(",.2f"); // COMMAS FOR LARGE NUMBERS
  // $scope.lowerCase = function(text) {return text.toLowerCase()}
  $scope.ttSwitcher = function(text) {
    if (text === "Passed" | text === "Failed") {
      return "on motions that " + text.toLowerCase();
    }
  }
  $scope.ttSwitcher2 = function(text) {
    if (text === "For") {
      return ' "Yes" '
    }
    if (text === "Against") {
      return ' "No" '
    }
  }
  $scope.ttSwitcher3 = function(text) {
    if (text === "For" | text === "Against") {
      return "when voting " + text.toLowerCase() + " a motion";
    }
    if (text === "Passed" | text === "Failed") {
      return "on motions that " + text.toLowerCase();
    }
  }

  $scope.updateTooltip = function (data) {
    $scope.tooltip = data;
    $scope.$apply();
  }

  $scope.addFilter = function (name) {
    $scope.hasFilters = true;
    $scope.filters[name] = {
      name: name,
      hide: true
    };
    $scope.$apply();
  };

  $scope.update = function () {
    var data = $scope.master[$scope.selected_year];

    if (data && $scope.hasFilters) {
      $scope.drawChords(data.filter(function (d) {
        var fl = $scope.filters;
        var v1 = d.importer1, v2 = d.importer2;

        if ((fl[v1] && fl[v1].hide) || (fl[v2] && fl[v2].hide)) {
          return false;
        }
        return true;
      }));
    } else if (data) {
      $scope.drawChords(data);
    }
  };

  // IMPORT THE CSV DATA
  // d3.csv('../data/trade.csv', function (err, data) {
  //
  //   data.forEach(function (d) {
  //     d.year  = +d.year;
  //     d.flow1 = +d.flow1;
  //     d.flow2 = +d.flow2;
  //
  //     if (!$scope.master[d.year]) {
  //       $scope.master[d.year] = []; // STORED BY YEAR
  //     }
  //     $scope.master[d.year].push(d);
  //   })
  //   $scope.update();
  // });

  d3.csv('../data/Calgary_2013-2017_20160418.csv', function (err, data) {

    var councillors = ["A. Chabot", "B. Pincott", "D. Colley-Urquhart", "D. Farrell", "E. Woolley", "G-C. Carra", "J. Magliocca", "J. Stevenson", "N. Nenshi", "P. Demong", "R. Jones", "R. Pootmans", "S. Chu", "S. Keating", "W. Sutherland"];

    data.forEach(function(d) {
      d.exclude = 0;
      d.Status = (d.Status === 'PASSED' ? 'Passed' : d.Status);
      d.Status = (d.Status === 'FAILED' ? 'Failed' : d.Status);
      councillors.forEach(function(c) {
        d[c] = (d[c] === "Yes" ? 1 : (d[c] === "No" ? 0 : -1));
        d.exclude += d[c];
      })
    })
    data = data.filter(function(d) {return d.exclude != -15 & d.Status != "PASSED UNANIMOUSLY"})
    console.log(data);
    data1 = pairwise(councillors, 'Status', 'Passed');
    data2 = pairwise(councillors, 'Status', 'Failed');
    data3 = pairwise2(councillors, 'For', 1);
    data4 = pairwise2(councillors, 'Against', 0);
    data = data1.concat(data2).concat(data3).concat(data4)
console.log(data)

    data.forEach(function(d) {
      if (!$scope.master[d.year]) {
        $scope.master[d.year] = []; // STORED BY YEAR
      }
      $scope.master[d.year].push(d);
    })
    $scope.update();

    function pairwise(list, comparevar, compareval) {
      if (list.length < 2) { return []; }
      var first = list[0],
          rest  = list.slice(1),
          pairs = rest.map(function (x) {
            return {
              year: compareval, //do for and against?
              importer1: first,
              importer2: x,
              flow1: d3.sum(data, function(d) { //voted the same
                if (d[first] === d[x] & d[first] != '--not specified--' & d[comparevar] === compareval) {
                  return 1;
                }
              }),
              flow2: d3.sum(data, function(d) { //voted differently
                if (d[first] === d[x]  & d[first] != '--not specified--' & d[comparevar] === compareval) {
                  return 1;
                }
              })
            };
          });
      return pairs.concat(pairwise(rest, comparevar, compareval));
    }

    function pairwise2(list, group, code) {
      if (list.length < 2) { return []; }
      var first = list[0],
          rest  = list.slice(1),
          pairs = rest.map(function (x) {
            return {
              year: group, //do for and against?
              importer1: first,
              importer2: x,
              flow1: d3.sum(data, function(d) { //voted the same
                if (d[first] === d[x] & d[first] === code) {
                  return 1;
                }
              }),
              flow2: d3.sum(data, function(d) { //voted differently
                if (d[first] === d[x]  & d[first] === code) {
                  return 1;
                }
              })
            };
          });
      return pairs.concat(pairwise2(rest, group, code));
    }

  });

  $scope.$watch('selected_year', $scope.update);
  $scope.$watch('filters', $scope.update, true);

}]);
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {
    'test': [
      'rxjs',
      'zone.js/dist/zone-microtask',
      'zone.js/dist/long-stack-trace-zone',
      'reflect-metadata',
      path.join(__dirname, 'webpack.test.bootstrap.ts')
    ]
  },

  output: {
    path: path.join(__dirname, './build'),
    filename: '[name].js'
  },
  stats: {
    colors: true,
    reasons: true
  },
  module: {
    loaders: [{
      // Support for .ts files.
      test: /\.ts$/,
      loader: 'ts',
      query: {
        'ignoreDiagnostics': [
          2403, // 2403 -> Subsequent variable declarations
          2300, // 2300 -> Duplicate identifier
          2374, // 2374 -> Duplicate number index signature
          2375  // 2375 -> Duplicate string index signature
        ]
      },
      exclude: [
        /node_modules/
      ]
    }]
  },
  resolve: {
    extensions: ['', '.ts', '.js', '.jsx'],
    modulesDirectories: ['src', 'node_modules']
  },

  node: {
    fs: 'empty'
  }
};
<commit_msg>removed node externals test import<commit_after>var webpack = require('webpack');
var path = require('path');

module.exports = {
  entry: {
    'test': [
      'rxjs',
      'zone.js/dist/zone-microtask',
      'zone.js/dist/long-stack-trace-zone',
      'reflect-metadata',
      path.join(__dirname, 'webpack.test.bootstrap.ts')
    ]
  },

  output: {
    path: path.join(__dirname, './build'),
    filename: '[name].js'
  },
  stats: {
    colors: true,
    reasons: true
  },
  module: {
    loaders: [{
      // Support for .ts files.
      test: /\.ts$/,
      loader: 'ts',
      query: {
        'ignoreDiagnostics': [
          2403, // 2403 -> Subsequent variable declarations
          2300, // 2300 -> Duplicate identifier
          2374, // 2374 -> Duplicate number index signature
          2375  // 2375 -> Duplicate string index signature
        ]
      },
      exclude: [
        /node_modules/
      ]
    }]
  },
  resolve: {
    extensions: ['', '.ts', '.js', '.jsx'],
    modulesDirectories: ['src', 'node_modules']
  },

  node: {
    fs: 'empty'
  }
};
<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

(function() {

  var module = angular.module('pnc.configuration');

  module.controller('ConfigurationListController', [
    '$log',
    '$state',
    'configurationList',
    'ProjectDAO',
    function($log, $state, configurationList, ProjectDAO) {
      var that = this;

      this.configurations = configurationList;
      this.projects = [];

      angular.forEach(this.configurations.data, function(configuration) {
        ProjectDAO.get({
          projectId: configuration.projectId
        }).$promise.then(
          function(result) {
            if (result) {
              that.projects.push(result);
            }
          }
        );
      });
    }
  ]);

  module.controller('ConfigurationCreateController', [
    '$state',
    '$log',
    '$filter',
    'BuildConfigurationDAO',
    'ProductDAO',
    'Notifications',
    'environments',
    'projects',
    'products',
    'configurations',
    function($state, $log, $filter, BuildConfigurationDAO, ProductDAO, Notifications, environments,
      projects, products, configurations) {

      var that = this;

      this.data = new BuildConfigurationDAO(); // TODO is this correct?
      this.environments = environments;
      this.projects = projects;

      this.submit = function() {
        // The REST API takes integer Ids so we need to extract them from
        // our collection of objects first and attach them to our data object
        // for sending back to the server.
        that.data.productVersionIds = gatherIds(that.productVersions.selected);
        that.data.dependencyIds = gatherIds(that.dependencies.selected);

        that.data.$save().then(function(result) {
          $state.go('configuration.detail.show', {
            configurationId: result.id
          });
        });
      };

      // Filtering and selection of linked ProductVersions.
      this.products = {
        all: products,
        selected: null
      };

      // Could not make it work in a nicer way (i.e. via cachedGetter) - avibelli
      this.allProductsMaps = {};
      this.allProductNamesMaps = {};
      this.products.all.forEach(function ( prod ) {
          that.allProductsMaps[ prod.id ] = prod;
      });

      this.productVersions = {
        selected: [],
        all: [],

        update: function() {
          ProductDAO.getVersions({
            productId: that.products.selected.id
          }).then(function(data) {
            that.productVersions.all = data;

            // TOFIX - Ugly but quick - avibelli
            data.forEach(function ( prodVers ) {
                that.allProductNamesMaps[ prodVers.id ] = that.allProductsMaps[ prodVers.productId ].name + ' - ';
            });
          });
        },
        getItems: function($viewValue) {
          return $filter('filter')(that.productVersions.all, {
            version: $viewValue
          });
        }
      };

      // Selection of dependencies.
      this.dependencies = {
        selected: [],

        getItems: function($viewValue) {
          return $filter('filter')(configurations, {
            name: $viewValue
          });
        }
      };
    }
  ]);

  module.controller('ConfigurationDetailController', [
    '$log',
    '$state',
    '$filter',
    'Notifications',
    'ProductDAO',
    'BuildConfigurationDAO',
    'configurationDetail',
    'environments',
    'environmentDetail',
    'projectDetail',
    'linkedProductVersions',
    'dependencies',
    'allProducts',
    'configurations',
    function($log, $state, $filter, Notifications, ProductDAO, BuildConfigurationDAO,
      configurationDetail, environments, environmentDetail, projectDetail,
      linkedProductVersions, dependencies, allProducts, configurations) {

      this.configuration = configurationDetail;
      this.environments = environments;
      this.project = projectDetail;
      this.allProducts = allProducts;

      // We need to set environment from existing environments collections to be able to preselect
      // dropdown element when editing
      this.environment = findEnvironment(this.configuration.environmentId, this.environments);

      var that = this;

      // Filtering and selection of linked ProductVersions.
      this.products = {
        all: allProducts,
        selected: null
      };

      // Could not make it work in a nicer way (i.e. via cachedGetter) - avibelli
      that.allProductsMaps = {};
      that.allProducts.forEach(function ( prod ) {
          that.allProductsMaps[ prod.id ] = prod;
      });

      // TOFIX - Ugly but quick - avibelli
      that.allProductNamesMaps = {};
      linkedProductVersions.forEach(function ( prodVers ) {
          that.allProductNamesMaps[ prodVers.id ] = that.allProductsMaps[ prodVers.productId ].name + ' - ';
      });

      this.productVersions = {
        selected: linkedProductVersions,
        all: [],

        update: function() {
          ProductDAO.getVersions({
            productId: that.products.selected.id
          }).then(function(data) {
            that.productVersions.all = data;
          });
        },
        getItems: function($viewValue) {
          return $filter('filter')(that.productVersions.all, {
            version: $viewValue
          });
        }
      };

      // Bootstrap products, depending on whether the BuildConfiguration
      // already has a ProductVersion attached.
      if (linkedProductVersions && linkedProductVersions.length > 0) {

        ProductDAO.get({
          productId: linkedProductVersions[0].productId
        }).$promise.then(function(result) {
          that.products.selected = result;
          that.productVersions.update();
        });
      }

      // Selection of dependencies.
      this.dependencies = {
        selected: dependencies,

        getItems: function($viewValue) {
          return $filter('filter')(configurations, {
            name: $viewValue
          });
        }
      };

      // Executing a build of a configuration forcing a rebuild
      this.forceBuild = function() {
        $log.debug('Initiating FORCED build of: %O', this.configuration);
        BuildConfigurationDAO.forceBuild({
          configurationId: that.configuration.id
        }, {});
      };

      // Executing a build of a configuration
      this.build = function() {
        $log.debug('Initiating build of: %O', this.configuration);
        BuildConfigurationDAO.build({
          configurationId: that.configuration.id
        }, {});
      };

      // Update a build configuration after editting
      this.update = function() {
        $log.debug('Updating configuration: %O', this.configuration);

        // The REST API takes integer Ids so we need to extract them from
        // our collection of objects first and attach them to our data object
        // for sending back to the server.
        this.configuration.productVersionIds =
          gatherIds(this.productVersions.selected);
        this.configuration.dependencyIds = gatherIds(this.dependencies.selected);

        this.configuration.$update();
      };

      this.updateEnvironment = function() {
          this.configuration.environmentId = this.environment.id;
      };

      // Cloning a build configuration
      this.clone = function() {
        this.configuration.$clone().then(function(result) {
          $state.go('configuration.detail.show', {
            configurationId: result.id
          }, {
            reload: true
          });
        });
      };

      // Deleting a build configuration
      this.delete = function() {
        this.configuration.$delete().then(function() {
          $state.go('configuration.list', {}, {
            reload: true,
            inherit: false,
            notify: true
          });
        });
      };

    }
  ]);

  module.controller('ConfigurationSidebarController', [
    '$log',
    '$stateParams',
    function($log, $stateParams) {
      this.buildConfigurationId = $stateParams.configurationId;
      this.filterBy = {
        buildConfigurationId: $stateParams.configurationId
      };

    }
  ]);

  function findEnvironment(id, environments) {
    for (var i = 0; i < environments.length; i++) {
      if (id === environments[i].id) {
        return environments[i];
      }
    }
  }

  function gatherIds(array) {
    var result = [];
    for (var i = 0; i < array.length; i++) {
      result.push(array[i].id);
    }
    return result;
  }

})();
<commit_msg>Fixed silent NPE; implemented reset and cancel;<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

(function() {

  var module = angular.module('pnc.configuration');

  module.controller('ConfigurationListController', [
    '$log',
    '$state',
    'configurationList',
    'ProjectDAO',
    function($log, $state, configurationList, ProjectDAO) {
      var that = this;

      this.configurations = configurationList;
      this.projects = [];

      angular.forEach(this.configurations.data, function(configuration) {
        ProjectDAO.get({
          projectId: configuration.projectId
        }).$promise.then(
          function(result) {
            if (result) {
              that.projects.push(result);
            }
          }
        );
      });
    }
  ]);

  module.controller('ConfigurationCreateController', [
    '$state',
    '$log',
    '$filter',
    'BuildConfigurationDAO',
    'ProductDAO',
    'Notifications',
    'environments',
    'projects',
    'products',
    'configurations',
    function($state, $log, $filter, BuildConfigurationDAO, ProductDAO, Notifications, environments,
      projects, products, configurations) {

      var that = this;

      this.data = new BuildConfigurationDAO(); // TODO is this correct?
      this.environments = environments;
      this.projects = projects;

      this.submit = function() {
        // The REST API takes integer Ids so we need to extract them from
        // our collection of objects first and attach them to our data object
        // for sending back to the server.
        that.data.productVersionIds = gatherIds(that.productVersions.selected);
        that.data.dependencyIds = gatherIds(that.dependencies.selected);

        that.data.$save().then(function(result) {
          $state.go('configuration.detail.show', {
            configurationId: result.id
          });
        });
      };

      // Filtering and selection of linked ProductVersions.
      this.products = {
        all: products,
        selected: null
      };

      // Could not make it work in a nicer way (i.e. via cachedGetter) - avibelli
      this.allProductsMaps = {};
      this.allProductNamesMaps = {};
      this.products.all.forEach(function ( prod ) {
          that.allProductsMaps[ prod.id ] = prod;
      });

      this.productVersions = {
        selected: [],
        all: [],

        update: function() {

          if (that.products.selected) {
            ProductDAO.getVersions({
              productId: that.products.selected.id
            }).then(function(data) {
              that.productVersions.all = data;

              // TOFIX - Ugly but quick - avibelli
              data.forEach(function ( prodVers ) {
                  that.allProductNamesMaps[ prodVers.id ] = that.allProductsMaps[ prodVers.productId ].name + ' - ';
              });
            });
          }
        },
        getItems: function($viewValue) {
          return $filter('filter')(that.productVersions.all, {
            version: $viewValue
          });
        }
      };

      // Selection of dependencies.
      this.dependencies = {
        selected: [],

        getItems: function($viewValue) {
          return $filter('filter')(configurations, {
            name: $viewValue
          });
        }
      };

      that.reset = function(form) {
        if (form) {
          form.$setPristine();
          form.$setUntouched();
          that.products.selected = null;
          that.productVersions.all = [];
          that.productVersions.selected = [];
          that.dependencies.selected = [];
          that.data = new BuildConfigurationDAO();
        }
      };
    }
  ]);

  module.controller('ConfigurationDetailController', [
    '$log',
    '$state',
    '$filter',
    'Notifications',
    'ProductDAO',
    'BuildConfigurationDAO',
    'configurationDetail',
    'environments',
    'environmentDetail',
    'projectDetail',
    'linkedProductVersions',
    'dependencies',
    'allProducts',
    'configurations',
    function($log, $state, $filter, Notifications, ProductDAO, BuildConfigurationDAO,
      configurationDetail, environments, environmentDetail, projectDetail,
      linkedProductVersions, dependencies, allProducts, configurations) {

      this.configuration = configurationDetail;
      this.environments = environments;
      this.project = projectDetail;
      this.allProducts = allProducts;

      // We need to set environment from existing environments collections to be able to preselect
      // dropdown element when editing
      this.environment = findEnvironment(this.configuration.environmentId, this.environments);

      var that = this;

      // Filtering and selection of linked ProductVersions.
      that.products = {
        all: allProducts,
        selected: null
      };

      // Could not make it work in a nicer way (i.e. via cachedGetter) - avibelli
      that.allProductsMaps = {};
      that.allProducts.forEach(function ( prod ) {
          that.allProductsMaps[ prod.id ] = prod;
      });

      // TOFIX - Ugly but quick - avibelli
      that.allProductNamesMaps = {};
      linkedProductVersions.forEach(function ( prodVers ) {
          that.allProductNamesMaps[ prodVers.id ] = that.allProductsMaps[ prodVers.productId ].name + ' - ';
      });

      that.productVersions = {
        selected: linkedProductVersions,
        all: [],

        update: function() {
          ProductDAO.getVersions({
            productId: that.products.selected.id
          }).then(function(data) {
            that.productVersions.all = data;
          });
        },
        getItems: function($viewValue) {
          return $filter('filter')(that.productVersions.all, {
            version: $viewValue
          });
        }
      };

      // Bootstrap products, depending on whether the BuildConfiguration
      // already has a ProductVersion attached.
      if (linkedProductVersions && linkedProductVersions.length > 0) {

        ProductDAO.get({
          productId: linkedProductVersions[0].productId
        }).$promise.then(function(result) {
          that.products.selected = result;
          that.productVersions.update();
        });
      }

      // Selection of dependencies.
      that.dependencies = {
        selected: dependencies,

        getItems: function($viewValue) {
          return $filter('filter')(configurations, {
            name: $viewValue
          });
        }
      };

      // Executing a build of a configuration forcing a rebuild
      that.forceBuild = function() {
        $log.debug('Initiating FORCED build of: %O', that.configuration);
        BuildConfigurationDAO.forceBuild({
          configurationId: that.configuration.id
        }, {});
      };

      // Executing a build of a configuration
      that.build = function() {
        $log.debug('Initiating build of: %O', that.configuration);
        BuildConfigurationDAO.build({
          configurationId: that.configuration.id
        }, {});
      };

      // Update a build configuration after editting
      that.update = function() {
        $log.debug('Updating configuration: %O', that.configuration);

        // The REST API takes integer Ids so we need to extract them from
        // our collection of objects first and attach them to our data object
        // for sending back to the server.
        that.configuration.productVersionIds =
          gatherIds(that.productVersions.selected);
        that.configuration.dependencyIds = gatherIds(that.dependencies.selected);

        that.configuration.$update().then(function() {
          $state.go('configuration.detail.show', {
            configurationId: that.configuration.id
          }, {
            reload: true
          });
        });
      };

      that.updateEnvironment = function() {
          that.configuration.environmentId = that.environment.id;
      };

      // Cloning a build configuration
      that.clone = function() {
        that.configuration.$clone().then(function(result) {
          $state.go('configuration.detail.show', {
            configurationId: result.id
          }, {
            reload: true
          });
        });
      };

      // Deleting a build configuration
      that.delete = function() {
        that.configuration.$delete().then(function() {
          $state.go('configuration.list', {}, {
            reload: true,
            inherit: false,
            notify: true
          });
        });
      };

      that.cancel = function(form) {
        if (form) {
          $state.go('configuration.detail.show', {
            configurationId: that.configuration.id
          }, {
            reload: true
          });
        }
      };

    }
  ]);

  module.controller('ConfigurationSidebarController', [
    '$log',
    '$stateParams',
    function($log, $stateParams) {
      this.buildConfigurationId = $stateParams.configurationId;
      this.filterBy = {
        buildConfigurationId: $stateParams.configurationId
      };

    }
  ]);

  function findEnvironment(id, environments) {
    for (var i = 0; i < environments.length; i++) {
      if (id === environments[i].id) {
        return environments[i];
      }
    }
  }

  function gatherIds(array) {
    var result = [];
    for (var i = 0; i < array.length; i++) {
      result.push(array[i].id);
    }
    return result;
  }

})();
<|endoftext|>


<commit_before>var Bitstamp = require("bitstamp");
var _ = require('lodash');
var moment = require('moment');
var log = require('../core/log');

var Trader = function(config) {
  _.bindAll(this);
  if(_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.clientID = config.username;
    this.asset = config.asset.toLowerCase();
    this.currency = config.currency.toLowerCase();
    this.market = this.asset + this.currency;
  }
  this.name = 'Bitstamp';

  this.bitstamp = new Bitstamp(this.key, this.secret, this.clientID);
}

// if the exchange errors we try the same call again after
// waiting 10 seconds
Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying..');

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var args = _.toArray(arguments);
  var set = function(err, data) {

    if(!_.isEmpty(data.error)) {
      log.error('BITSTAMP API ERROR: ' + data.error);
      return this.retry(this.getPortfolio, args);
    }

    var portfolio = [];
    _.each(data, function(amount, asset) {
      if(asset.indexOf('available') !== -1) {
        asset = asset.substr(0, 3).toUpperCase();
        portfolio.push({name: asset, amount: parseFloat(amount)});
      }
    });
    callback(err, portfolio);
  }.bind(this);

  this.bitstamp.balance(this.market, set);
}

Trader.prototype.getTicker = function(callback) {
  this.bitstamp.ticker(this.market, callback);
}

Trader.prototype.getFee = function(callback) {
  var set = function(err, data) {
    if(err)
      callback(err);

    callback(false, data.fee / 100);
  }.bind(this);

  this.bitstamp.balance(this.market, set);
}

Trader.prototype.buy = function(amount, price, callback) {
  var args = _.toArray(arguments);
  var set = function(err, result) {
    if(err || result.status === "error") {
      log.error('unable to buy:', err, result.reason, 'retrying...');
      return this.retry(this.buy, args);
    }

    callback(null, result.id);
  }.bind(this);

  //Decrease amount by 1% to avoid trying to buy more than balance allows.
  amount -= amount / 100;

  amount *= 100000000;
  amount = Math.floor(amount);
  amount /= 100000000;

  // prevent:
  // 'Ensure that there are no more than 2 decimal places.'
  price *= 100;
  price = Math.floor(price);
  price /= 100;

  this.bitstamp.buy(this.market, amount, price, undefined, set);
}

Trader.prototype.sell = function(amount, price, callback) {
  var args = _.toArray(arguments);
  var set = function(err, result) {
    if(err || result.status === "error") {
      log.error('unable to sell:', err, result.reason, 'retrying...');
      return this.retry(this.sell, args);
    }

    callback(null, result.id);
  }.bind(this);

  // prevent:
  // 'Ensure that there are no more than 8 decimal places.'
  amount *= 100000000;
  amount = Math.floor(amount);
  amount /= 100000000;

  // prevent:
  // 'Ensure that there are no more than 2 decimal places.'
  price *= 100;
  price = Math.ceil(price);
  price /= 100;

  this.bitstamp.sell(this.market, amount, price, undefined, set);
}

Trader.prototype.getOrder = function(id, callback) {
  var args = _.toArray(arguments);
  var get = function(err, data) {
    if(!err && _.isEmpty(data) && _.isEmpty(data.result))
      err = 'no data';

    else if(!err && !_.isEmpty(data.error))
      err = data.error;

    if(err) {
      log.error('Unable to get order', order, JSON.stringify(err));
      return this.retry(this.getOrder, args);
    }

    var order = _.find(data, o => o.order_id === +id);

    if(!order) {
      // if the order was cancelled we are unable
      // to retrieve it, assume that this is what
      // is happening.
      return callback(err, {
        price: 0,
        amount: 0,
        date: moment(0)
      });
    }

    var price = parseFloat( order[this.market] );
    var amount = Math.abs(parseFloat( order[this.asset] ));
    var date = moment( order.datetime );

    callback(err, {price, amount, date});
  }.bind(this);

  this.bitstamp.user_transactions(this.market, {}, get);
}

Trader.prototype.checkOrder = function(order, callback) {
  var check = function(err, result) {
    var stillThere = _.find(result, function(o) { return o.id === order });
    callback(err, !stillThere);
  }.bind(this);

  this.bitstamp.open_orders(this.market, check);
}

Trader.prototype.cancelOrder = function(order, callback) {
  var args = _.toArray(arguments);
  var cancel = function(err, result) {
    if(err || !result) {
      log.error('unable to cancel order', order, '(', err, result, ')');
      return this.retry(this.cancelOrder, args);
    }

    callback();
  }.bind(this);

  this.bitstamp.cancel_order(order, cancel);
}

Trader.prototype.getTrades = function(since, callback, descending) {
  var args = _.toArray(arguments);
  var process = function(err, trades) {
    if(err)
      return this.retry(this.getTrades, args);

    var result = _.map(trades, t => {
      return {
        date: t.date,
        tid: +t.tid,
        price: +t.price,
        amount: +t.amount
      }
    })

    callback(null, result.reverse());
  }.bind(this);

  // NOTE: temporary disabled, see https://github.com/askmike/gekko/issues/794
  // if(since)
  //   this.bitstamp.transactions(this.market, {time: 'day'}, process);
  // else
  this.bitstamp.transactions(this.market, process);
}

Trader.getCapabilities = function () {
  return {
    name: 'Bitstamp',
    slug: 'bitstamp',
    currencies: ['USD', 'EUR'],
    assets: ['BTC', 'EUR'],
    maxTradesAge: 60,
    maxHistoryFetch: null,
    markets: [
      { pair: ['USD', 'BTC'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['EUR', 'BTC'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['USD', 'EUR'], minimalOrder: { amount: 5, unit: 'currency' } }
    ],
    requires: ['key', 'secret', 'username'],
    fetchTimespan: 60,
    tid: 'tid',
    tradable: true
  };
}

module.exports = Trader;
<commit_msg>add all bitstamp markets, fix #745<commit_after>var Bitstamp = require("bitstamp");
var _ = require('lodash');
var moment = require('moment');
var log = require('../core/log');

var Trader = function(config) {
  _.bindAll(this);
  if(_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.clientID = config.username;
    this.asset = config.asset.toLowerCase();
    this.currency = config.currency.toLowerCase();
    this.market = this.asset + this.currency;
  }
  this.name = 'Bitstamp';

  this.bitstamp = new Bitstamp(this.key, this.secret, this.clientID);
}

// if the exchange errors we try the same call again after
// waiting 10 seconds
Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying..');

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var args = _.toArray(arguments);
  var set = function(err, data) {

    if(!_.isEmpty(data.error)) {
      log.error('BITSTAMP API ERROR: ' + data.error);
      return this.retry(this.getPortfolio, args);
    }

    var portfolio = [];
    _.each(data, function(amount, asset) {
      if(asset.indexOf('available') !== -1) {
        asset = asset.substr(0, 3).toUpperCase();
        portfolio.push({name: asset, amount: parseFloat(amount)});
      }
    });
    callback(err, portfolio);
  }.bind(this);

  this.bitstamp.balance(this.market, set);
}

Trader.prototype.getTicker = function(callback) {
  this.bitstamp.ticker(this.market, callback);
}

Trader.prototype.getFee = function(callback) {
  var set = function(err, data) {
    if(err)
      callback(err);

    callback(false, data.fee / 100);
  }.bind(this);

  this.bitstamp.balance(this.market, set);
}

Trader.prototype.buy = function(amount, price, callback) {
  var args = _.toArray(arguments);
  var set = function(err, result) {
    if(err || result.status === "error") {
      log.error('unable to buy:', err, result.reason, 'retrying...');
      return this.retry(this.buy, args);
    }

    callback(null, result.id);
  }.bind(this);

  //Decrease amount by 1% to avoid trying to buy more than balance allows.
  amount -= amount / 100;

  amount *= 100000000;
  amount = Math.floor(amount);
  amount /= 100000000;

  // prevent:
  // 'Ensure that there are no more than 2 decimal places.'
  price *= 100;
  price = Math.floor(price);
  price /= 100;

  this.bitstamp.buy(this.market, amount, price, undefined, set);
}

Trader.prototype.sell = function(amount, price, callback) {
  var args = _.toArray(arguments);
  var set = function(err, result) {
    if(err || result.status === "error") {
      log.error('unable to sell:', err, result.reason, 'retrying...');
      return this.retry(this.sell, args);
    }

    callback(null, result.id);
  }.bind(this);

  // prevent:
  // 'Ensure that there are no more than 8 decimal places.'
  amount *= 100000000;
  amount = Math.floor(amount);
  amount /= 100000000;

  // prevent:
  // 'Ensure that there are no more than 2 decimal places.'
  price *= 100;
  price = Math.ceil(price);
  price /= 100;

  this.bitstamp.sell(this.market, amount, price, undefined, set);
}

Trader.prototype.getOrder = function(id, callback) {
  var args = _.toArray(arguments);
  var get = function(err, data) {
    if(!err && _.isEmpty(data) && _.isEmpty(data.result))
      err = 'no data';

    else if(!err && !_.isEmpty(data.error))
      err = data.error;

    if(err) {
      log.error('Unable to get order', order, JSON.stringify(err));
      return this.retry(this.getOrder, args);
    }

    var order = _.find(data, o => o.order_id === +id);

    if(!order) {
      // if the order was cancelled we are unable
      // to retrieve it, assume that this is what
      // is happening.
      return callback(err, {
        price: 0,
        amount: 0,
        date: moment(0)
      });
    }

    var price = parseFloat( order[this.market] );
    var amount = Math.abs(parseFloat( order[this.asset] ));
    var date = moment( order.datetime );

    callback(err, {price, amount, date});
  }.bind(this);

  this.bitstamp.user_transactions(this.market, {}, get);
}

Trader.prototype.checkOrder = function(order, callback) {
  var check = function(err, result) {
    var stillThere = _.find(result, function(o) { return o.id === order });
    callback(err, !stillThere);
  }.bind(this);

  this.bitstamp.open_orders(this.market, check);
}

Trader.prototype.cancelOrder = function(order, callback) {
  var args = _.toArray(arguments);
  var cancel = function(err, result) {
    if(err || !result) {
      log.error('unable to cancel order', order, '(', err, result, ')');
      return this.retry(this.cancelOrder, args);
    }

    callback();
  }.bind(this);

  this.bitstamp.cancel_order(order, cancel);
}

Trader.prototype.getTrades = function(since, callback, descending) {
  var args = _.toArray(arguments);
  var process = function(err, trades) {
    if(err)
      return this.retry(this.getTrades, args);

    var result = _.map(trades, t => {
      return {
        date: t.date,
        tid: +t.tid,
        price: +t.price,
        amount: +t.amount
      }
    })

    callback(null, result.reverse());
  }.bind(this);

  // NOTE: temporary disabled, see https://github.com/askmike/gekko/issues/794
  // if(since)
  //   this.bitstamp.transactions(this.market, {time: 'day'}, process);
  // else
  this.bitstamp.transactions(this.market, process);
}

Trader.getCapabilities = function () {
  return {
    name: 'Bitstamp',
    slug: 'bitstamp',
    currencies: ['USD', 'EUR', 'BTC'],
    assets: ['BTC', 'EUR', 'LTC', 'ETH', 'XRP'],
    maxTradesAge: 60,
    maxHistoryFetch: null,
    markets: [
      { pair: ['USD', 'EUR'], minimalOrder: { amount: 5, unit: 'currency' } },

      { pair: ['USD', 'BTC'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['EUR', 'BTC'], minimalOrder: { amount: 5, unit: 'currency' } },

      { pair: ['USD', 'XRP'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['EUR', 'XRP'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['BTC', 'XRP'], minimalOrder: { amount: 5, unit: 'currency' } },

      { pair: ['USD', 'LTC'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['EUR', 'LTC'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['BTC', 'LTC'], minimalOrder: { amount: 5, unit: 'currency' } },

      { pair: ['USD', 'ETH'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['EUR', 'ETH'], minimalOrder: { amount: 5, unit: 'currency' } },
      { pair: ['BTC', 'ETH'], minimalOrder: { amount: 5, unit: 'currency' } },
    ],
    requires: ['key', 'secret', 'username'],
    fetchTimespan: 60,
    tid: 'tid',
    tradable: true
  };
}

module.exports = Trader;
<|endoftext|>


<commit_before>/* global describe, it, beforeEach, afterEach */

// eslint-disable-next-line no-unused-vars
var should = require('should');
var assert = require('assert');
var local = require('../../config/local');
var monk = require('monk');

// DB
var db = monk(local.mongo.url);

var TEST_COLLECTION_NAME = 'test_collection';

// The Unit
var iter = require('../lib/iter');

// Test data
var fixture = [
  {
    name: 'Harrison',
  },
  {
    name: 'Barry',
  },
  {
    name: 'Iris',
  },
];

describe('iter.updateEach', function () {
  var collection;

  beforeEach(function (done) {
    collection = db.get(TEST_COLLECTION_NAME);
    collection.insert(fixture, done);
  });

  afterEach(function (done) {
    collection.drop(done);
  });

  it('should add Dr. prefix', function (done) {
    iter.updateEach(collection, function (person, next) {
      person.name = 'Dr. ' + person.name;
      next(person);
    }, function (err) {
      assert.ok(!err);
      collection.find({ name: { $regex: (/^Dr\./) } }).then(function (doctors) {
        assert.equal(doctors.length, fixture.length);
        done();
      }).catch(function (err2) {
        done(err2);
      });
    });
  });

  it('should replace instead of extend', function (done) {
    iter.updateEach(collection, function (person, next) {
      next({ username: person.name });
    }, function (err) {
      assert.ifError(err);
      collection.find({}).then(function (users) {
        users[0].should.not.have.ownProperty('name');
        assert.ok(!users[1].hasOwnProperty('name'));
        done();
      });
    });
  });
});
<commit_msg>tests: use test db in iter.spec<commit_after>/* global describe, it, beforeEach, afterEach */

// eslint-disable-next-line no-unused-vars
var should = require('should');
var assert = require('assert');
var local = require('../../config/local');
var monk = require('monk');

// DB
var db = monk(local.mongo.testUrl);

var TEST_COLLECTION_NAME = 'test_collection';

// The Unit
var iter = require('../lib/iter');

// Test data
var fixture = [
  {
    name: 'Harrison',
  },
  {
    name: 'Barry',
  },
  {
    name: 'Iris',
  },
];

describe('iter.updateEach', function () {
  var collection;

  beforeEach(function (done) {
    collection = db.get(TEST_COLLECTION_NAME);
    collection.insert(fixture, done);
  });

  afterEach(function (done) {
    collection.drop(done);
  });

  it('should add Dr. prefix', function (done) {
    iter.updateEach(collection, function (person, next) {
      person.name = 'Dr. ' + person.name;
      next(person);
    }, function (err) {
      assert.ok(!err);
      collection.find({ name: { $regex: (/^Dr\./) } }).then(function (doctors) {
        assert.equal(doctors.length, fixture.length);
        done();
      }).catch(function (err2) {
        done(err2);
      });
    });
  });

  it('should replace instead of extend', function (done) {
    iter.updateEach(collection, function (person, next) {
      next({ username: person.name });
    }, function (err) {
      assert.ifError(err);
      collection.find({}).then(function (users) {
        users[0].should.not.have.ownProperty('name');
        assert.ok(!users[1].hasOwnProperty('name'));
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

angular.module('riwebApp')
    .service('RippleWalletService', function (RippleRemoteService, RippleAccountService,
        Auth, RIPPLE_ROOT_ACCOUNT, socket, $log) {

        var walletInfo = {
            wallet: {}
        };

        var currentUser = Auth.getCurrentUser();

        function getCurrentUserWallet(callback) {
            currentUser = Auth.getCurrentUser();

            if (!currentUser.email) {
                return; // not logged in
            }

            socket.socket.on('post:create_wallet', function (rippleAddress) {
                socket.socket.removeAllListeners('post:create_wallet');
                walletInfo.wallet = rippleAddress;

                RippleAccountService.accountInfo.account = currentUser.name;
                RippleAccountService.accountInfo.iban = currentUser.iban;

                callback();
            });
            socket.socket.emit('create_wallet', { ownerEmail: currentUser.email });
        }

        function loadCurrentUserBalance() {
            $log.debug('loadCurrentUserBalance');
            var user = Auth.getCurrentUser();

            if (!user.email) {
                return; // No user is logged in, please go away
            }

            socket.socket.on('post:list_transactions', function (result) {
                if (result.status === 'success') {
                    RippleAccountService.accountInfo.transactions = result.transactions;
                    if (console.table) {
                        console.log('post:list_transactions');
                        console.table(result.transactions);
                    }
                }
            });

            // socket.socket.emit('account_info', user.email);
            socket.socket.emit('list_transactions', user.email);
        }

        return {
            getCurrentUserWallet: getCurrentUserWallet,
            loadCurrentUserBalance: loadCurrentUserBalance,
            walletInfo: walletInfo
        };
    });
<commit_msg>send user role as well for consuming in create_wallet<commit_after>'use strict';

angular.module('riwebApp')
    .service('RippleWalletService', function (RippleRemoteService, RippleAccountService,
        Auth, RIPPLE_ROOT_ACCOUNT, socket, $log) {

        var walletInfo = {
            wallet: {}
        };

        var currentUser = Auth.getCurrentUser();

        function getCurrentUserWallet(callback) {
            currentUser = Auth.getCurrentUser();

            if (!currentUser.email) {
                return; // not logged in
            }

            socket.socket.on('post:create_wallet', function (rippleAddress) {
                socket.socket.removeAllListeners('post:create_wallet');
                walletInfo.wallet = rippleAddress;

                RippleAccountService.accountInfo.account = currentUser.name;
                RippleAccountService.accountInfo.iban = currentUser.iban;

                callback();
            });
            socket.socket.emit('create_wallet', { ownerEmail: currentUser.email, role: currentUser.role });
        }

        function loadCurrentUserBalance() {
            $log.debug('loadCurrentUserBalance');
            var user = Auth.getCurrentUser();

            if (!user.email) {
                return; // No user is logged in, please go away
            }

            socket.socket.on('post:list_transactions', function (result) {
                if (result.status === 'success') {
                    RippleAccountService.accountInfo.transactions = result.transactions;
                    if (console.table) {
                        console.log('post:list_transactions');
                        console.table(result.transactions);
                    }
                }
            });

            // socket.socket.emit('account_info', user.email);
            socket.socket.emit('list_transactions', user.email);
        }

        return {
            getCurrentUserWallet: getCurrentUserWallet,
            loadCurrentUserBalance: loadCurrentUserBalance,
            walletInfo: walletInfo
        };
    });
<|endoftext|>


<commit_before>app.controller('mapaController', function ($scope, $http, toastr) {
    alert('funci');
});

var map;
var directionsDisplay;
var directionsService;
var objResultRout = {};
var objRotaCaminho = {};

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();

    var latlng = new google.maps.LatLng(-16.7696477, -49.3319283);

    var options = {
        zoom: 17,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("mapa"), options);
    directionsService = new google.maps.DirectionsService();

    directionsDisplay.setMap(map);
}

function calcRoute(end) {
    var start = '-16.7690814, -49.3283556'
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.TRANSIT
    };
    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
            objResultRout = result;
        }
    });

}

function carregarPontos() {
    var infowindow = new google.maps.InfoWindow();
    $.getJSON('pontos.json', function (pontos) {
        $.each(pontos, function (index, ponto) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(ponto.Latitude, ponto.Longitude),
                title: ponto.INSTITUICAO,
                map: map
            });
            google.maps.event.addListener(marker, 'click', function () {
                calcRoute(ponto.Latitude + ', ' + ponto.Longitude);

                var caminho = '';
                if (objResultRout) {
                    if (objResultRout.routes[0]) {
                        if (objResultRout.routes[0].legs[0]) {
                            objRotaCaminho = objResultRout.routes[0].legs[0].steps;
                            for (var i = 0; i < objRotaCaminho.length; i++) {
                                var onibus = "";
                                if (objResultRout.routes[0].legs[0].steps[i].travel_mode == "TRANSIT") {
                                    onibus = objResultRout.routes[0].legs[0].steps[i].transit.line.short_name + " - " + objResultRout.routes[0].legs[0].steps[i].transit.line.name;
                                } else {
                                    onibus = "";
                                }
                                //console.log(objResultRout.routes[0].legs[0].steps[i].instructions);
                                caminho = caminho + ', ' + objResultRout.routes[0].legs[0].steps[i].instructions + ",  " + onibus + " - " + objResultRout.routes[0].legs[0].steps[i].distance.value + 'metros';
                                //console.log(objResultRout.routes[0].legs[0]);
                            };
                        }
                    }
                }

                infowindow.setContent('
' + ponto.INSTITUICAO + '
' +
                  'ENDERECO: ' + ponto.ENDERECO + '
 Distancia: ' + objResultRout.routes[0].legs[0].distance.text
                  + '
 Duracao ' + objResultRout.routes[0].legs[0].duration.text + '
 Caminho: ' + caminho + '
');
                infowindow.open(map, this);
            });
        });

    });

}

carregarPontos();

initialize();

<commit_msg>Update mapaController.js<commit_after>app.controller('mapaController', function ($scope, $http, toastr) {
    $scope.Endereco = {
        id: 0,
        logradouro: '',
        numero: '',
        complemento: '',
        bairro: '',
        cidade_id: 0,
        cep: 0,
        latitude: 0,
        longetude: 0,
        ponto_referencia: ''
    };
});

var map;

function initialize(lat, long, ponto) {
    var latlng = new google.maps.LatLng(lat, long);
    var options = {
        zoom: 17,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapa"), options);
    carregaEndereco(lat, long, ponto);
}

function carregaEndereco(lat, long, ponto) {
    var infowindow = new google.maps.InfoWindow();

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, long),
        map: map
    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent('
Endereço
' +
          'Rua/Avenida: ' + ponto.logradouro + ', Número: ' + ponto.numero + '
 Complemento: '
          + ponto.complemento + '
 Bairro/Setor: ' + ponto.bairro + '
 Ponto de Referencia: ' + ponto.ponto_referencia + '
');
        infowindow.open(map, this);
        console.log(ponto);
    });

}

function fechaMapa() {
    $('#mapaPainel').hide();
}
<|endoftext|>


<commit_before>// Webpack config for creating the production bundle.

var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');

var relativeAssetsPath = '../static/dist';
var assetsPath = path.join(__dirname, relativeAssetsPath);

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'))

module.exports = {
  devtool: 'source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': './src/client.js'
  },
  output: {
    path: assetsPath,
    filename: '[name]-[chunkhash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: '/dist/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel?stage=0&optional=runtime&plugins=typecheck']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.(otf.*|woff.*|eot.*|ttf.*|svg.*)$/, loader: 'url?limit=100000' },
      { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  progress: true,
  resolve: {
    modulesDirectories: [
      'src',
      'node_modules'
    ],
    extensions: ['', '.json', '.js']
  },
  plugins: [
    new CleanPlugin([relativeAssetsPath]),

    // css files from the extract-text-plugin loader
    new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: false,
      __DEVTOOLS__: false
    }),

    // ignore dev config
    new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),

    // set global vars
    new webpack.DefinePlugin({
      'process.env': {
        // Useful to reduce the size of client-side libraries, e.g. react
        NODE_ENV: JSON.stringify('production'),
        API_URL: JSON.stringify('http://hub-api.herokuapp.com'),
        APP_DOMAIN: JSON.stringify('reboo.org')
      }
    }),

    // optimizations
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
          warnings: false
        }
    }),

    webpackIsomorphicToolsPlugin
  ]
};
<commit_msg>Debug staging env<commit_after>// Webpack config for creating the production bundle.

var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');

var relativeAssetsPath = '../static/dist';
var assetsPath = path.join(__dirname, relativeAssetsPath);

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'))

module.exports = {
  devtool: 'source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': './src/client.js'
  },
  output: {
    path: assetsPath,
    filename: '[name]-[chunkhash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: '/dist/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel?stage=0&optional=runtime&plugins=typecheck']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.(otf.*|woff.*|eot.*|ttf.*|svg.*)$/, loader: 'url?limit=100000' },
      { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  progress: true,
  resolve: {
    modulesDirectories: [
      'src',
      'node_modules'
    ],
    extensions: ['', '.json', '.js']
  },
  plugins: [
    new CleanPlugin([relativeAssetsPath]),

    // css files from the extract-text-plugin loader
    new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: false,
      __DEVTOOLS__: false
    }),

    // ignore dev config
    new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),

    // set global vars
    // new webpack.DefinePlugin({
    //   'process.env': {
    //     // Useful to reduce the size of client-side libraries, e.g. react
    //     NODE_ENV: JSON.stringify('production'),
    //     API_URL: JSON.stringify('http://hub-api.herokuapp.com'),
    //     APP_DOMAIN: JSON.stringify('reboo.org')
    //   }
    // }),

    // optimizations
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
          warnings: false
        }
    }),

    webpackIsomorphicToolsPlugin
  ]
};
<|endoftext|>


<commit_before>var isInScrollBar = function(canvas, context, x, y){
	var height = 400;
	var width = 30;
	var distanceFromTop = 100;

	return x > canvas.width - width && y > distanceFromTop && y < distanceFromTop + height;
}

var getScrollPositionFromScrollBar = function(canvas, context, y, maxScroll){
	var height = 400;
	var width = 20;
	var distanceFromTop = 100;

	return (y - distanceFromTop) * maxScroll / height;
}

var drawScrollBar = function(canvas, context, scrollPosition, maxScroll){
	var height = 400;
	var width = 30;
	var distanceFromTop = 100;

	context.strokeStyle=staveColour;
	context.rect(canvas.width - width, distanceFromTop, width, height);
	context.stroke();

	context.beginPath();
	context.strokeStyle=noteColour;
	context.lineWidth =4;
	context.moveTo(canvas.width - width, scrollPosition * height / maxScroll + distanceFromTop);
	context.lineTo(canvas.width, scrollPosition * height / maxScroll + distanceFromTop);
	context.stroke();
	context.lineWidth = 1;
}

function getCurrentLine(y, lines, maxScroll){
	var height = 400;
	var distanceFromTop = 100;

	for(var i = 0; i < lines.length; i++){
		if(lines[i].y > (y - distanceFromTop) * maxScroll / height )
		return lines[i].barNumber;
	}
	return false;
}

var drawScrollPreview = function(canvas, context, y, lines, maxScroll){
	var rightMargin = 30;
	var width = 100;
	var height = 100;
	var farLeft = canvas.width - (rightMargin + width) - 15;

	context.beginPath();
	context.moveTo(farLeft, y);
	context.lineTo(farLeft + width + 10, y);
	context.lineTo(farLeft + width, y + 5)
	context.lineTo(farLeft + width, y + height);
	context.lineTo(farLeft, y + height);
	context.lineTo(farLeft, y);
	context.strokeStyle = "black";
	context.lineWidth = 4;
	context.stroke();
	context.fillStyle="white";
	context.fill();
	context.lineWidth = 1;

	var tempCurrentLine = getCurrentLine(y, lines, maxScroll);
	if(tempCurrentLine != false){
		context.font = "bold 16px Arial";
		context.fillStyle="black";
		context.fillText(tempCurrentLine + "", farLeft + width / 2 - 8, y + height / 2 + 8);
	}
}
<commit_msg>Update scrollbar.js<commit_after>var isInScrollBar = function(canvas, context, x, y){
	var height = 400;
	var width = 30;
	var distanceFromTop = 100;

	return x > canvas.width - width && y > distanceFromTop && y < distanceFromTop + height;
}

var getScrollPositionFromScrollBar = function(canvas, context, y, maxScroll){
	var height = 400;
	var width = 20;
	var distanceFromTop = 100;

	return (y - distanceFromTop) * maxScroll / height;
}

var drawScrollBar = function(canvas, context, scrollPosition, maxScroll){
	var height = 400;
	var width = 30;
	var distanceFromTop = 100;

	context.strokeStyle=staveColour;
	context.rect(canvas.width - width, distanceFromTop, width, height);
	context.stroke();

	context.beginPath();
	context.strokeStyle=noteColour;
	context.lineWidth =4;
	context.moveTo(canvas.width - width, scrollPosition * height / maxScroll + distanceFromTop);
	context.lineTo(canvas.width, scrollPosition * height / maxScroll + distanceFromTop);
	context.stroke();
	context.lineWidth = 1;
}

function getCurrentLine(y, lines, maxScroll){
	var height = 400;
	var distanceFromTop = 100;

	for(var i = 0; i < lines.length; i++){
		if(lines[i].y > (y - distanceFromTop) * maxScroll / height )
		return lines[i].barNumber;
	}
	return false;
}

var drawScrollPreview = function(canvas, context, y, lines, maxScroll){
	var rightMargin = 30;
	var width = 100;
	var height = 100;
	var farLeft = canvas.width - (rightMargin + width) - 15;

	context.beginPath();
	context.moveTo(farLeft, y);
	context.lineTo(farLeft + width + 10, y);
	context.lineTo(farLeft + width, y + 5)
	context.lineTo(farLeft + width, y + height);
	context.lineTo(farLeft, y + height);
	context.lineTo(farLeft, y);
	context.strokeStyle = "black";
	context.lineWidth = 4;
	context.stroke();
	context.fillStyle="white";
	context.fill();
	context.lineWidth = 1;

	var tempCurrentLine = getCurrentLine(y, lines, maxScroll);
	if(tempCurrentLine != false){
		context.font = "bold 16px Arial";
		context.fillStyle="black";
		context.fillText(tempCurrentLine + "", farLeft + width / 2 - 5, y + height / 2 + 6);
	}
}
<|endoftext|>