<commit_before>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * 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.
 */

angular.module(`${PKG.name}.feature.experimental`)
  .controller('ComplexSchemaController', function(avsc) {
    var schema = '{"type":"record","name":"rec","fields":[{"name":"bool_field","type":["boolean","null"]},{"name":"int_field","type":"int"},{"name":"long_field","type":"long"},{"name":"float_field","type":"float"},{"name":"double_field","type":"double"},{"name":"bytes_field","type":"bytes"},{"name":"array_field","type":{"type":"array","items":["string","null"]}},{"name":"enum_field","type":{"type":"enum","symbols":["Monday","Tuesday","Wednesday"]}},{"name":"union_field","type":["double","float","bytes"]},{"name":"map_field","type":{"type":"map","keys":["string","null"],"values":["int","null"]}},{"name":"record_field","type":[{"type":"record","name":"rec1","fields":[{"name":"x","type":["int","null"]},{"name":"y","type":["double","null"]}]},"null"]},{"name":"string_field","type":["string","null"]}]}';

    // let union = {
    //   name: 'test',
    //   type: 'record',
    //   fields: [
    //     {
    //       name: 'string_field',
    //       type: ['float', 'int']
    //     }
    //   ]
    // };
    // let parsed = avsc.parse(union, { wrapUnions: true });
    // console.log('parsed', parsed);

    let parsed = avsc.parse(schema, { wrapUnions: true }).getFields();

    angular.forEach(parsed, (field) => {
      let name = field.getName();
      let type = field.getType();

      if (type.getTypeName() === 'union:wrapped') {
        let temp = '';

        type = type.getTypes();
        angular.forEach(type, (tempType) => {
          temp = temp + tempType.getTypeName() + ' ';
        });
        type = temp;

      } else {
        type = type.getTypeName();
      }

      console.log(name + ': ' + type);
    });

    // function parseSchemaType (field) {

    // }

  });
<commit_msg>add schema types array<commit_after>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * 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.
 */

angular.module(`${PKG.name}.feature.experimental`)
  .controller('ComplexSchemaController', function(avsc) {
    var schema = '{"type":"record","name":"rec","fields":[{"name":"bool_field","type":["boolean","null"]},{"name":"int_field","type":"int"},{"name":"long_field","type":"long"},{"name":"float_field","type":"float"},{"name":"double_field","type":"double"},{"name":"bytes_field","type":"bytes"},{"name":"array_field","type":{"type":"array","items":["string","null"]}},{"name":"enum_field","type":{"type":"enum","symbols":["Monday","Tuesday","Wednesday"]}},{"name":"union_field","type":["double","float","bytes"]},{"name":"map_field","type":{"type":"map","keys":["string","null"],"values":["int","null"]}},{"name":"record_field","type":[{"type":"record","name":"rec1","fields":[{"name":"x","type":["int","null"]},{"name":"y","type":["double","null"]}]},"null"]},{"name":"string_field","type":["string","null"]}]}';

    // let union = {
    //   name: 'test',
    //   type: 'record',
    //   fields: [
    //     {
    //       name: 'string_field',
    //       type: ['float', 'int']
    //     }
    //   ]
    // };
    // let parsed = avsc.parse(union, { wrapUnions: true });
    // console.log('parsed', parsed);

    const SCHEMA_TYPES = [
      'string',
      'int',
      'long',
      'float',
      'double',
      'boolean',
      'bytes',
      'enum',
      'array',
      'map',
      'record',
      'union'
    ];

    let parsed = avsc.parse(schema, { wrapUnions: true }).getFields();

    angular.forEach(parsed, (field) => {
      let name = field.getName();
      let type = field.getType();

      if (type.getTypeName() === 'union:wrapped') {
        let temp = '';

        type = type.getTypes();
        angular.forEach(type, (tempType) => {
          temp = temp + tempType.getTypeName() + ' ';
        });
        type = temp;

      } else {
        type = type.getTypeName();
      }

      console.log(name + ': ' + type);

      console.log(SCHEMA_TYPES);
    });

    // function parseSchemaType (field) {

    // }

  });
<|endoftext|>


<commit_before>/**
 * twitter harvester wrapper
 *
 * MIT Licensed, see License.txt
 *
 */

var async = require('async');

// utilities module
var utilities = require('./bower_components/chrisweb-utilities/utilities');

// NODE_ENV can be "development", "staging" or "production"
if (typeof(process.env.NODE_ENV) === 'undefined') {

    //process.env.NODE_ENV = 'production';
    process.env.NODE_ENV = 'development';

    utilities.log('NODE_ENV NOT FOUND, setting it by default to "' + process.env.NODE_ENV.toUpperCase() + '"', 'fontColor:red', 'backgroundColor:white');

}

// get the environment variable
var environment = process.env.NODE_ENV;

// get configuration
var configurationModule = require('./server/configuration/configuration.js');
var configuration = configurationModule.get(process.env.NODE_ENV);

// mongo module
var mongoModule = require('./server/library/mongo');

var mongoClient;

// mongodb connection
mongoModule.getClient(function mongooseConnectCallback(error, mongooseConnection) {

    if (error) {

        utilities.log('[MONGODB]' + error, 'fontColor:red');

    } else {

        utilities.log('[MONGODB] connected', 'fontColor:green');

        mongoClient = mongooseConnection;

    }

});

// get the tweets mongoose model
var TweetModel = require('./server/models/tweet');

var tweetModel = new TweetModel();

// load jamendo from twitter
// try/catch because it is a github module and might be missing
try {

    var JamendoFromTwitter = require('./node_modules/jamendo-from-twitter/index');

} catch(exception) {

    utilities.log('loading jamendo-from-twitter failed: ', 'fontColor:red');

    utilities.log(exception);

}

/**
 *
 * save a tweet
 *
 * @param {type} trackId
 * @returns {undefined}
 */
var saveTweet = function(trackId) {

    utilities.log('harvester saveTweet.. ', 'fontColor:blue');

    var message = this.message;

    //utilities.log(message);

    var twitterData = {
        jamendo_unit_id: trackId,
        jamendo_unit: 'track',
        twitter_user_id: message.user.id_str,
        twitter_user_name: message.user.screen_name,
        twitter_user_image: message.profile_image_url,
        twitter_tweet_date: message.raw.created_at,
        twitter_tweet_id: message.id_str,
        twitter_tweet_original_text: message.fulltext
    };

    tweetModel.saveOne(twitterData, function(error) {

        utilities.log('error: ' + error, 'fontColor:red');

    });

};

// get an harvester
var harvester = new JamendoFromTwitter(configuration);

// on twitter message listener ("jamendo from twitter" event)
harvester.on('message', function(message) {

    utilities.log('harvester incoming message: ', 'fontColor:green');

    utilities.log(message.extracted);

    if (message.extracted.nothing === false) {

        // if a track id was found save it in our database
        if (typeof(message.extracted.track_ids) !== 'undefined') {

            this.message = message;

            async.each(message.extracted.track_ids, saveTweet.bind(this), function(error, model){

                if (error) {

                    utilities.log('async saveTweet error response: ', 'fontColor:red');

                    utilities.log(error);

                } else {

                    utilities.log('tweet got saved successfully', 'fontColor:green');

                    utilities.log(model);

                }

            });

        }

        // TODO: if an id of an album or playlist got found ...

    }

});

harvester.on('error', function(error) {

    utilities.log('harvester on error');

    utilities.log(error);

});

var streamOptions = {};
var searchOptions = {};

streamOptions.track = ['jamendo', 'jamen.do', '@jamendo', '#cooldiscovery', '#freedownload', '#goodmusic'];
searchOptions.track = 'jamendo OR jamen.do';

try {

    // do a search to get some initial data for the db
    //harvester.executeSearch(searchOptions);

} catch(exception) {

    utilities.log('twitter harvester error: ' + exception, 'fontColor:red');

}

// start harvesting
try {

    // the harvester will listen to the twitter stream API and when a track
    // gets tweeted we will fetch it and then save it in our database
    harvester.startStream(streamOptions);

} catch(exception) {

    utilities.log('twitter harvester error: ' + exception);

}

// close db connections on shutdown
process.on('SIGINT', function() {

    mongoModule.disconnect(mongoClient, function (error) {

        if (error) {

            utilities.log('mongodb disconnect: ' + error, 'fontColor:red');

        }

        utilities.log('[TWITTER HARVESTER] process is shutting down...');

        process.exit(0);

    });

});<commit_msg>dont log error if error is false<commit_after>/**
 * twitter harvester wrapper
 *
 * MIT Licensed, see License.txt
 *
 */

var async = require('async');

// utilities module
var utilities = require('./bower_components/chrisweb-utilities/utilities');

// NODE_ENV can be "development", "staging" or "production"
if (typeof(process.env.NODE_ENV) === 'undefined') {

    //process.env.NODE_ENV = 'production';
    process.env.NODE_ENV = 'development';

    utilities.log('NODE_ENV NOT FOUND, setting it by default to "' + process.env.NODE_ENV.toUpperCase() + '"', 'fontColor:red', 'backgroundColor:white');

}

// get the environment variable
var environment = process.env.NODE_ENV;

// get configuration
var configurationModule = require('./server/configuration/configuration.js');
var configuration = configurationModule.get(process.env.NODE_ENV);

// mongo module
var mongoModule = require('./server/library/mongo');

var mongoClient;

// mongodb connection
mongoModule.getClient(function mongooseConnectCallback(error, mongooseConnection) {

    if (error) {

        utilities.log('[MONGODB]' + error, 'fontColor:red');

    } else {

        utilities.log('[MONGODB] connected', 'fontColor:green');

        mongoClient = mongooseConnection;

    }

});

// get the tweets mongoose model
var TweetModel = require('./server/models/tweet');

var tweetModel = new TweetModel();

// load jamendo from twitter
// try/catch because it is a github module and might be missing
try {

    var JamendoFromTwitter = require('./node_modules/jamendo-from-twitter/index');

} catch(exception) {

    utilities.log('loading jamendo-from-twitter failed: ', 'fontColor:red');

    utilities.log(exception);

}

/**
 *
 * save a tweet
 *
 * @param {type} trackId
 * @returns {undefined}
 */
var saveTweet = function(trackId) {

    utilities.log('harvester saveTweet.. ', 'fontColor:blue');

    var message = this.message;

    //utilities.log(message);

    var twitterData = {
        jamendo_unit_id: trackId,
        jamendo_unit: 'track',
        twitter_user_id: message.user.id_str,
        twitter_user_name: message.user.screen_name,
        twitter_user_image: message.profile_image_url,
        twitter_tweet_date: message.raw.created_at,
        twitter_tweet_id: message.id_str,
        twitter_tweet_original_text: message.fulltext
    };

    tweetModel.saveOne(twitterData, function(error) {

        if (error) {

            utilities.log('error: ' + error, 'fontColor:red');

        } else {

            utilities.log('success: saved', 'fontColor:green');

        }

    });

};

// get an harvester
var harvester = new JamendoFromTwitter(configuration);

// on twitter message listener ("jamendo from twitter" event)
harvester.on('message', function(message) {

    utilities.log('harvester incoming message: ', 'fontColor:green');

    utilities.log(message.extracted);

    if (message.extracted.nothing === false) {

        // if a track id was found save it in our database
        if (typeof(message.extracted.track_ids) !== 'undefined') {

            this.message = message;

            async.each(message.extracted.track_ids, saveTweet.bind(this), function(error, model){

                if (error) {

                    utilities.log('async saveTweet error response: ', 'fontColor:red');

                    utilities.log(error);

                } else {

                    utilities.log('tweet got saved successfully', 'fontColor:green');

                    utilities.log(model);

                }

            });

        }

        // TODO: if an id of an album or playlist got found ...

    }

});

harvester.on('error', function(error) {

    utilities.log('harvester on error');

    utilities.log(error);

});

var streamOptions = {};
var searchOptions = {};

streamOptions.track = ['jamendo', 'jamen.do', '@jamendo', '#cooldiscovery', '#freedownload', '#goodmusic'];
searchOptions.track = 'jamendo OR jamen.do';

try {

    // do a search to get some initial data for the db
    //harvester.executeSearch(searchOptions);

} catch(exception) {

    utilities.log('twitter harvester error: ' + exception, 'fontColor:red');

}

// start harvesting
try {

    // the harvester will listen to the twitter stream API and when a track
    // gets tweeted we will fetch it and then save it in our database
    harvester.startStream(streamOptions);

} catch(exception) {

    utilities.log('twitter harvester error: ' + exception);

}

// close db connections on shutdown
process.on('SIGINT', function() {

    mongoModule.disconnect(mongoClient, function (error) {

        if (error) {

            utilities.log('mongodb disconnect: ' + error, 'fontColor:red');

        }

        utilities.log('[TWITTER HARVESTER] process is shutting down...');

        process.exit(0);

    });

});<|endoftext|>


<commit_before>var crypto = require("crypto-browserify");

if (typeof Buffer === "undefined") {
	Buffer = require("buffer/").Buffer;
}

var ByteBuffer = require("bytebuffer");
var bignum = require("browserify-bignum");
var nacl_factory = require("js-nacl");
var nacl = nacl_factory.instantiate();

var fixedPoint = Math.pow(10, 6);

function getSignatureBytes(signature) {
	var bb = new ByteBuffer(32, true);
	var publicKeyBuffer = new Buffer(signature.publicKey, "hex");

	for (var i = 0; i < publicKeyBuffer.length; i++) {
		bb.writeByte(publicKeyBuffer[i]);
	}

	bb.flip();
	return new Uint8Array(bb.toArrayBuffer());
}

function getDAppBytes(dapp) {
	try {
		var buf = new Buffer([]);
		var nameBuf = new Buffer(dapp.name, "utf8");
		buf = Buffer.concat([buf, nameBuf]);

		if (dapp.description) {
			var descriptionBuf = new Buffer(dapp.description, "utf8");
			buf = Buffer.concat([buf, descriptionBuf]);
		}

		if (dapp.tags) {
			var tagsBuf = new Buffer(dapp.tags, "utf8");
			buf = Buffer.concat([buf, tagsBuf]);
		}

		if (dapp.link) {
			buf = Buffer.concat([buf, new Buffer(dapp.link, "utf8")]);
		}

		if (dapp.icon) {
			buf = Buffer.concat([buf, new Buffer(dapp.icon, "utf8")]);
		}

		var bb = new ByteBuffer(4 + 4, true);
		bb.writeInt(dapp.type);
		bb.writeInt(dapp.category);
		bb.flip();

		buf = Buffer.concat([buf, bb.toBuffer()]);
	} catch (e) {
		throw Error(e.toString());
	}

	return buf;
}

function getTransferBytes(dapptransfer) {
	try {
		var buf = new Buffer([]);
		var nameBuf = new Buffer(dapptransfer.dappid, "utf8");
		buf = Buffer.concat([buf, nameBuf]);
	} catch (e) {
		throw Error(e.toString());
	}

	return buf;
}

function getBytes(transaction) {
	var assetSize = 0,
		assetBytes = null;

	switch (transaction.type) {
		case 1: // Signature
			assetSize = 32;
			assetBytes = getSignatureBytes(transaction.asset.signature);
			break;

		case 2: // Delegate
			assetBytes = new Buffer(transaction.asset.delegate.username, "utf8");
			assetSize = assetBytes.length;
			break;

		case 3: // Vote
			if (transaction.asset.vote.votes !== null) {
				assetBytes = new Buffer(transaction.asset.vote.votes.join(""), "utf8");
				assetSize = assetBytes.length;
			}
			break;

		case 4: // Multi-Signature
			var keysgroupBuffer = new Buffer(transaction.asset.multisignature.keysgroup.join(""), "utf8");
			var bb = new ByteBuffer(1 + 1 + keysgroupBuffer.length, true);

			bb.writeByte(transaction.asset.multisignature.min);
			bb.writeByte(transaction.asset.multisignature.lifetime);

			for (var i = 0; i < keysgroupBuffer.length; i++) {
				bb.writeByte(keysgroupBuffer[i]);
			}

			bb.flip();

			assetBytes = bb.toBuffer();
			assetSize = assetBytes.length;
			break;

		case 5: // Dapp
			assetBytes = getDAppBytes(transaction.asset.dapp);
			assetSize = assetBytes.length;
			break;

		case 6: // In Transfer (Dapp Deposit)
			assetBytes = getTransferBytes(transaction.asset.dapptransfer);
			assetSize = assetBytes.length;
			break;
	}
	if (transaction.__assetBytes__) {
		assetBytes = transaction.__assetBytes__;
		assetSize = assetBytes.length;
	}

	if (transaction.requesterPublicKey) {
		assetSize += 32;
	}

	var bb = new ByteBuffer(1, true);
	bb.writeByte(transaction.type);
	bb.writeInt(transaction.timestamp);

	var senderPublicKeyBuffer = new Buffer(transaction.senderPublicKey, "hex");
	for (var i = 0; i < senderPublicKeyBuffer.length; i++) {
		bb.writeByte(senderPublicKeyBuffer[i]);
	}

	if (transaction.requesterPublicKey) {
		var requesterPublicKey = new Buffer(transaction.requesterPublicKey, "hex");

		for (var i = 0; i < requesterPublicKey.length; i++) {
			bb.writeByte(requesterPublicKey[i]);
		}
	}

	bb.writeString(transaction.recipientId || '0');

	bb.writeString(transaction.amount);
	bb.writeString(transaction.currency || '0')

	if (transaction.message) bb.writeString(transaction.message)

	if (assetSize > 0) {
		for (var i = 0; i < assetSize; i++) {
			bb.writeByte(assetBytes[i]);
		}
	}

	if (transaction.signature) {
		var signatureBuffer = new Buffer(transaction.signature, "hex");
		for (var i = 0; i < signatureBuffer.length; i++) {
			bb.writeByte(signatureBuffer[i]);
		}
	}

	if (transaction.signSignature) {
		var signSignatureBuffer = new Buffer(transaction.signSignature, "hex");
		for (var i = 0; i < signSignatureBuffer.length; i++) {
			bb.writeByte(signSignatureBuffer[i]);
		}
	}

	bb.flip();
	var arrayBuffer = new Uint8Array(bb.toArrayBuffer());
	var buffer = [];
	for (var i = 0; i < arrayBuffer.length; i++) {
		buffer[i] = arrayBuffer[i];
	}
	return new Buffer(buffer);
}

function getId(transaction) {
	//return
	var hash = crypto.createHash("sha256").update(getBytes(transaction).toString("hex"), "hex").digest();
	var temp = new Buffer(8);
	for (var i = 0; i < 8; i++) {
		temp[i] = hash[7 - i];
	}

	var id = bignum.fromBuffer(temp).toString();
	return id;
}
function getHash(transaction) {
	var bytes = getBytes(transaction)
	return crypto.createHash("sha256").update(bytes).digest();
}

function getFee(transaction) {
	switch (transaction.type) {
		case 0: // Normal
			return 0.1 * fixedPoint;
			break;

		case 1: // Signature
			return 100 * fixedPoint;
			break;

		case 2: // Delegate
			return 10000 * fixedPoint;
			break;

		case 3: // Vote
			return 1 * fixedPoint;
			break;
	}
}

function sign(transaction, keys) {
	var hash = getHash(transaction);
	var signature = nacl.crypto_sign_detached(hash, new Buffer(keys.privateKey, "hex"));

	if (!transaction.signature) {
		transaction.signature = new Buffer(signature).toString("hex");
	} else {
		return new Buffer(signature).toString("hex");
	}
}

function secondSign(transaction, keys) {
	var hash = getHash(transaction);
	var signature = nacl.crypto_sign_detached(hash, new Buffer(keys.privateKey, "hex"));
	transaction.signSignature = new Buffer(signature).toString("hex")
}

function verify(transaction) {
	var remove = 64;

	if (transaction.signSignature) {
		remove = 128;
	}

	var bytes = getBytes(transaction);
	var data2 = new Buffer(bytes.length - remove);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash("sha256").update(data2.toString("hex"), "hex").digest();

	var signatureBuffer = new Buffer(transaction.signature, "hex");
	var senderPublicKeyBuffer = new Buffer(transaction.senderPublicKey, "hex");
	var res = nacl.crypto_sign_verify_detached(signatureBuffer, hash, senderPublicKeyBuffer);

	return res;
}

function verifySecondSignature(transaction, publicKey) {
	var bytes = getBytes(transaction);
	var data2 = new Buffer(bytes.length - 64);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash("sha256").update(data2.toString("hex"), "hex").digest();

	var signSignatureBuffer = new Buffer(transaction.signSignature, "hex");
	var publicKeyBuffer = new Buffer(publicKey, "hex");
	var res = nacl.crypto_sign_verify_detached(signSignatureBuffer, hash, publicKeyBuffer);

	return res;
}

function getKeys(secret) {
	var hash = crypto.createHash("sha256").update(secret, "utf8").digest();
	var keypair = nacl.crypto_sign_keypair_from_seed(hash);

	return {
		publicKey: new Buffer(keypair.signPk).toString("hex"),
		privateKey: new Buffer(keypair.signSk).toString("hex")
	}
}

function getAddress(publicKey) {
	var publicKeyHash = crypto.createHash("sha256").update(publicKey.toString("hex"), "hex").digest();
	var temp = new Buffer(8);

	for (var i = 0; i < 8; i++) {
		temp[i] = publicKeyHash[7 - i];
	}

	var address = bignum.fromBuffer(temp).toString();
	return address;
}

module.exports = {
	getBytes: getBytes,
	getHash: getHash,
	getId: getId,
	getFee: getFee,
	sign: sign,
	secondSign: secondSign,
	getKeys: getKeys,
	getAddress: getAddress,
	verify: verify,
	verifySecondSignature: verifySecondSignature,
	fixedPoint: fixedPoint
}
<commit_msg>修改dapp注册的id生成算法<commit_after>var crypto = require("crypto-browserify");

if (typeof Buffer === "undefined") {
	Buffer = require("buffer/").Buffer;
}

var ByteBuffer = require("bytebuffer");
var bignum = require("browserify-bignum");
var nacl_factory = require("js-nacl");
var nacl = nacl_factory.instantiate();

var fixedPoint = Math.pow(10, 6);

function getSignatureBytes(signature) {
	var bb = new ByteBuffer(32, true);
	var publicKeyBuffer = new Buffer(signature.publicKey, "hex");

	for (var i = 0; i < publicKeyBuffer.length; i++) {
		bb.writeByte(publicKeyBuffer[i]);
	}

	bb.flip();
	return new Uint8Array(bb.toArrayBuffer());
}

function getDAppBytes(dapp) {
	try {
		var buf = new Buffer([]);
		var nameBuf = new Buffer(dapp.name, "utf8");
		buf = Buffer.concat([buf, nameBuf]);

		if (dapp.description) {
			var descriptionBuf = new Buffer(dapp.description, "utf8");
			buf = Buffer.concat([buf, descriptionBuf]);
		}

		if (dapp.tags) {
			var tagsBuf = new Buffer(dapp.tags, "utf8");
			buf = Buffer.concat([buf, tagsBuf]);
		}

		if (dapp.link) {
			buf = Buffer.concat([buf, new Buffer(dapp.link, "utf8")]);
		}

		if (dapp.icon) {
			buf = Buffer.concat([buf, new Buffer(dapp.icon, "utf8")]);
		}

		var bb = new ByteBuffer(4 + 4, true);
		bb.writeInt(dapp.type);
		bb.writeInt(dapp.category);
		bb.flip();

		buf = Buffer.concat([buf, bb.toBuffer()]);
	} catch (e) {
		throw Error(e.toString());
	}

	return buf;
}

function getTransferBytes(dapptransfer) {
	try {
		var buf = new Buffer([]);
		var nameBuf = new Buffer(dapptransfer.dappid, "utf8");
		buf = Buffer.concat([buf, nameBuf]);
	} catch (e) {
		throw Error(e.toString());
	}

	return buf;
}

function getBytes(transaction) {
	var assetSize = 0,
		assetBytes = null;

	switch (transaction.type) {
		case 1: // Signature
			assetSize = 32;
			assetBytes = getSignatureBytes(transaction.asset.signature);
			break;

		case 2: // Delegate
			assetBytes = new Buffer(transaction.asset.delegate.username, "utf8");
			assetSize = assetBytes.length;
			break;

		case 3: // Vote
			if (transaction.asset.vote.votes !== null) {
				assetBytes = new Buffer(transaction.asset.vote.votes.join(""), "utf8");
				assetSize = assetBytes.length;
			}
			break;

		case 4: // Multi-Signature
			var keysgroupBuffer = new Buffer(transaction.asset.multisignature.keysgroup.join(""), "utf8");
			var bb = new ByteBuffer(1 + 1 + keysgroupBuffer.length, true);

			bb.writeByte(transaction.asset.multisignature.min);
			bb.writeByte(transaction.asset.multisignature.lifetime);

			for (var i = 0; i < keysgroupBuffer.length; i++) {
				bb.writeByte(keysgroupBuffer[i]);
			}

			bb.flip();

			assetBytes = bb.toBuffer();
			assetSize = assetBytes.length;
			break;

		case 5: // Dapp
			assetBytes = getDAppBytes(transaction.asset.dapp);
			assetSize = assetBytes.length;
			break;

		case 6: // In Transfer (Dapp Deposit)
			assetBytes = getTransferBytes(transaction.asset.dapptransfer);
			assetSize = assetBytes.length;
			break;
	}
	if (transaction.__assetBytes__) {
		assetBytes = transaction.__assetBytes__;
		assetSize = assetBytes.length;
	}

	if (transaction.requesterPublicKey) {
		assetSize += 32;
	}

	var bb = new ByteBuffer(1, true);
	bb.writeByte(transaction.type);
	bb.writeInt(transaction.timestamp);

	var senderPublicKeyBuffer = new Buffer(transaction.senderPublicKey, "hex");
	for (var i = 0; i < senderPublicKeyBuffer.length; i++) {
		bb.writeByte(senderPublicKeyBuffer[i]);
	}

	if (transaction.requesterPublicKey) {
		var requesterPublicKey = new Buffer(transaction.requesterPublicKey, "hex");

		for (var i = 0; i < requesterPublicKey.length; i++) {
			bb.writeByte(requesterPublicKey[i]);
		}
	}

	bb.writeString(transaction.recipientId || '0');

	bb.writeString(transaction.amount);
	bb.writeString(transaction.currency || '0')

	if (transaction.message) bb.writeString(transaction.message)

	if (assetSize > 0) {
		for (var i = 0; i < assetSize; i++) {
			bb.writeByte(assetBytes[i]);
		}
	}

	if (transaction.signature) {
		var signatureBuffer = new Buffer(transaction.signature, "hex");
		for (var i = 0; i < signatureBuffer.length; i++) {
			bb.writeByte(signatureBuffer[i]);
		}
	}

	if (transaction.signSignature) {
		var signSignatureBuffer = new Buffer(transaction.signSignature, "hex");
		for (var i = 0; i < signSignatureBuffer.length; i++) {
			bb.writeByte(signSignatureBuffer[i]);
		}
	}

	bb.flip();
	var arrayBuffer = new Uint8Array(bb.toArrayBuffer());
	var buffer = [];
	for (var i = 0; i < arrayBuffer.length; i++) {
		buffer[i] = arrayBuffer[i];
	}
	return new Buffer(buffer);
}

function getId(transaction) {
	//return
	//var hash = crypto.createHash("sha256").update(getBytes(transaction).toString("hex"), "hex").digest();
        var hash = crypto.createHash("sha256").update(getBytes(transaction)).digest();
	//var temp = new Buffer(8);
	//for (var i = 0; i < 8; i++) {
	//	temp[i] = hash[7 - i];
	//}

	//var id = bignum.fromBuffer(temp).toString();
	return hash.toString("hex");
}
function getHash(transaction) {
	var bytes = getBytes(transaction)
	return crypto.createHash("sha256").update(bytes).digest();
}

function getFee(transaction) {
	switch (transaction.type) {
		case 0: // Normal
			return 0.1 * fixedPoint;
			break;

		case 1: // Signature
			return 100 * fixedPoint;
			break;

		case 2: // Delegate
			return 10000 * fixedPoint;
			break;

		case 3: // Vote
			return 1 * fixedPoint;
			break;
	}
}

function sign(transaction, keys) {
	var hash = getHash(transaction);
	var signature = nacl.crypto_sign_detached(hash, new Buffer(keys.privateKey, "hex"));

	if (!transaction.signature) {
		transaction.signature = new Buffer(signature).toString("hex");
	} else {
		return new Buffer(signature).toString("hex");
	}
}

function secondSign(transaction, keys) {
	var hash = getHash(transaction);
	var signature = nacl.crypto_sign_detached(hash, new Buffer(keys.privateKey, "hex"));
	transaction.signSignature = new Buffer(signature).toString("hex")
}

function verify(transaction) {
	var remove = 64;

	if (transaction.signSignature) {
		remove = 128;
	}

	var bytes = getBytes(transaction);
	var data2 = new Buffer(bytes.length - remove);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash("sha256").update(data2.toString("hex"), "hex").digest();

	var signatureBuffer = new Buffer(transaction.signature, "hex");
	var senderPublicKeyBuffer = new Buffer(transaction.senderPublicKey, "hex");
	var res = nacl.crypto_sign_verify_detached(signatureBuffer, hash, senderPublicKeyBuffer);

	return res;
}

function verifySecondSignature(transaction, publicKey) {
	var bytes = getBytes(transaction);
	var data2 = new Buffer(bytes.length - 64);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash("sha256").update(data2.toString("hex"), "hex").digest();

	var signSignatureBuffer = new Buffer(transaction.signSignature, "hex");
	var publicKeyBuffer = new Buffer(publicKey, "hex");
	var res = nacl.crypto_sign_verify_detached(signSignatureBuffer, hash, publicKeyBuffer);

	return res;
}

function getKeys(secret) {
	var hash = crypto.createHash("sha256").update(secret, "utf8").digest();
	var keypair = nacl.crypto_sign_keypair_from_seed(hash);

	return {
		publicKey: new Buffer(keypair.signPk).toString("hex"),
		privateKey: new Buffer(keypair.signSk).toString("hex")
	}
}

function getAddress(publicKey) {
	var publicKeyHash = crypto.createHash("sha256").update(publicKey.toString("hex"), "hex").digest();
	var temp = new Buffer(8);

	for (var i = 0; i < 8; i++) {
		temp[i] = publicKeyHash[7 - i];
	}

	var address = bignum.fromBuffer(temp).toString();
	return address;
}

module.exports = {
	getBytes: getBytes,
	getHash: getHash,
	getId: getId,
	getFee: getFee,
	sign: sign,
	secondSign: secondSign,
	getKeys: getKeys,
	getAddress: getAddress,
	verify: verify,
	verifySecondSignature: verifySecondSignature,
	fixedPoint: fixedPoint
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import PikadayMixin from 'ember-pikaday/mixins/pikaday';
import layout from 'ember-pikaday/templates/pikaday-inputless';

export default Ember.Component.extend(PikadayMixin, {
  layout,

  didInsertElement() {
    this.set('field', this.$('.ember-pikaday-input')[0]);
    this.set('pikadayContainer', this.$('.ember-pikaday-container')[0]);
    this.setupPikaday();
  },

  onPikadayOpen: Ember.K,
  onPikadayClose: Ember.K,
});
<commit_msg>Replace Ember.K with JavaScript syntax<commit_after>import Ember from 'ember';
import PikadayMixin from 'ember-pikaday/mixins/pikaday';
import layout from 'ember-pikaday/templates/pikaday-inputless';

export default Ember.Component.extend(PikadayMixin, {
  layout,

  didInsertElement() {
    this.set('field', this.$('.ember-pikaday-input')[0]);
    this.set('pikadayContainer', this.$('.ember-pikaday-container')[0]);
    this.setupPikaday();
  },

  onPikadayOpen() {},
  onPikadayClose() {},
});
<|endoftext|>


<commit_before>'use strict';

var util		= require('util'),
path			= require('path'),
yeoman			= require('yeoman-generator'),
chalk			= require('chalk'),
sys				= require('sys'),
exec			= require('child_process').exec;

var TollwerkTypo3SetupGenerator = module.exports = function TollwerkTypo3SetupGenerator(args, options, config) {
	var self	= this;

	yeoman.generators.Base.apply(this, arguments);

	this.pkg	= JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(TollwerkTypo3SetupGenerator, yeoman.generators.Base);

/**
 * Install a TYPO3 extension
 *
 * @param {TollwerkTypo3SetupGenerator} generator		Generator reference
 * @param {String} extension							Extension key
 * @param {Function} callback							Callback
 * @return {void}
 */
function installExtension(generator, extension, callback) {
	exec("./typo3/cli_dispatch.phpsh extbase extension:install " + extension, function (error, stdout, stderr) {
		generator.log(stdout);
		callback(error);
	});
}

/**
 * Generator dialog
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.askFor = function() {
	var done		= this.async();

	if (!this.options.nested) {
		this.log(this.yeoman);
		this.log(chalk.magenta('You\'re about scaffolding a tollwerk style TYPO3 project.'));
	}
	this.log();

	var prompts = [{
		name	: 'project',
		message	: 'How should this project be called?'
	},{
		name	: 'baseurl',
		message	: 'What is the base URL of the site?'
	},{
		name	: 'sbaseurl',
		message	: 'What is the staging site base URL?'
	},{
		name	: 'author',
		message	: 'What is the site author\'s name?'
	},{
		type	: 'list',
		name	: 'templating',
		message	: 'Which templating system are you going to use?',
		choices	: [{name: 'FluidTYPO3', value: 'ft3'}, {name: 'TemplaVoila!', value: 'tv'}, {name: 'None', value: 'none'}],
		'default'	: 'ft3'
	},{
		type	: 'confirm',
		name	: 'sass',
		message	: 'Would you like to use Sass?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'iconizr',
		message	: 'Would you like to use iconizr?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'favicon',
		message	: 'Would you like to include favicon / touch icon support?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'ga',
		message	: 'Would you like to install the Google Analytics extension (tw_googleanalytics)?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'squeezr',
		message	: 'Would you like to install the squeezr extension (squeezr)?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'defr',
		message	: 'Would you like to install the defr extension?',
		'default'	: true
	}];

	this.prompt(prompts, function(props) {

		// TODO: What happens if no project name is given?
	 	this.project		= props.project.toLowerCase();

	 	this.baseurl		= props.baseurl.length ? ((props.baseurl.toLowerCase().indexOf('http') !== 0) ? ('http://' + props.baseurl) : props.baseurl) : '';
	 	this.baseurl		= this.baseurl.length ? (this.baseurl + ((this.baseurl.lastIndexOf('/') == (this.baseurl.length - 1)) ? '' : '/')) : '';
	 	this.sbaseurl		= props.sbaseurl.length ? ((props.sbaseurl.toLowerCase().indexOf('http') !== 0) ? ('http://' + props.sbaseurl) : props.sbaseurl) : '';
	 	this.sbaseurl		= this.sbaseurl.length ? (this.sbaseurl + ((this.sbaseurl.lastIndexOf('/') == (this.sbaseurl.length - 1)) ? '' : '/')) : '';
		this.author			= props.author;
		this.templating		= props.templating;
		this.sass			= props.sass;
		this.iconizr		= props.iconizr;
		this.favicon		= props.favicon;
		this.ga				= props.ga;
		this.squeezr		= props.squeezr;
		this.defr			= props.defr;

		this.deps			= {};
		if (this.templating == 'ft3') {
			this.deps.flux						= 'fluidtypo3-flux#latest';
			this.deps.fluidpages				= 'fluidtypo3-fluidpages#latest';
			this.deps.fluidcontent				= 'fluidtypo3-fluidcontent#latest';
			this.deps.vhs						= 'fluidtypo3-vhs#latest';
		}
		if (this.ga) {
			this.deps.tw_googleanalytics		= 'googleanalytics-typo3#latest';
		}
		if (this.squeezr) {
			this.deps.squeezr					= 'squeezr-typo3#latest';
		}
		if (this.defr) {
			// TODO: Create TYPO3 extension for defr
			// this.deps.defr						= 'defr-typo3#latest';
		}

		done();
	}.bind(this));
}

/**
 * NPM & Bower file installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.app = function() {
	this.template('_package.json', 'package.json');
	this.template('_bower.json', 'bower.json');
}

/**
 * Project & Gruntfile installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.projectfiles = function() {
	this.copy('editorconfig', '.editorconfig');
	this.copy('jshintrc', '.jshintrc');
	this.copy('bowerrc', '.bowerrc');
	this.template('Gruntfile.js', 'Gruntfile.js');
}

/**
 * Base resource installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.baseresources = function() {
	this.copy('README.md', 'fileadmin/' + this.project + '/README.md');

	// Create the fileadmin directory structure
	this.directory('fileadmin', 'fileadmin/' + this.project);

 	// Create Sass directory (if needed)
 	if (this.sass) {
 		this.directory('options/sass/fileadmin', 'fileadmin/' + this.project);
 	}

 	switch (this.templating) {

 		// TemplaVoila!
 		case 'tv':
 			this.directory('options/tv/fileadmin', 'fileadmin/' + this.project);
 			break;
 	}

 	// Page configuration
 	this.template('fileadmin/.templates/ts/page/10_page_config.ts', 'fileadmin/' + this.project + '/.templates/ts/page/10_page_config.ts');
 	this.template('fileadmin/.templates/ts/page/30_page_head.ts', 'fileadmin/' + this.project + '/.templates/ts/page/30_page_head.ts');
}

/**
 * iconizr installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.iconizr = function() {
	if (this.iconizr) {
		this.mkdir('fileadmin/' + this.project + '/.templates/icons');
		this.mkdir('fileadmin/' + this.project + '/css/icons');
	}
}

/**
 * Favicon / touch icon installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.favicon = function() {
	if (this.favicon) {
		this.directory('options/favicon/fileadmin', 'fileadmin/' + this.project);
		this.mkdir('fileadmin/' + this.project + '/favicons');
	}
}

/**
 * Pull in dependencies
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.dependencies = function() {
	var done		= this.async();
	this.installDependencies({
		skipInstall: this.options['skip-install'],
        callback: function() {
            done();
        }.bind(this)
	});
}

/**
 * Install the templating extensions
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.templating = function() {
	switch (this.templating) {

		// FluidTYPO3
		case 'ft3':
			var that		= this;
			installExtension(that, 'flux', function() {
				installExtension(that, 'fluidpages', function() {
					installExtension(that, 'fluidcontent', function() {
						installExtension(that, 'vhs', that.async());
					});
				});
			});
			break;

		// TemplaVoila!
		case 'tv':
			installExtension(this, 'templavoila', this.async());
			break;
	}
}

/**
 * Install the Google Analytics extension
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.googleanalytics = function() {
	if (this.ga) {
		installExtension(this, 'tw_googleanalytics', this.async());

		// TODO: Add TypoScript
	}
}

/**
 * Install the squeezr extension
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.squeezr = function() {
	if (this.squeezr) {
		installExtension(this, 'squeezr', this.async());

		// TODO: Run update script or add a user hint
	}
}

/**
 * Install the defr extension
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.defr = function() {
	if (this.defr) {
		// TODO: Create TYPO3 extension for defr
	}
}

/**
 * Running the setup Grunt task
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.grunt = function() {
	this.log('run grunt');
}<commit_msg>Prepared TemplaVoila templating support<commit_after>'use strict';

var util		= require('util'),
path			= require('path'),
yeoman			= require('yeoman-generator'),
chalk			= require('chalk'),
sys				= require('sys'),
exec			= require('child_process').exec;

var TollwerkTypo3SetupGenerator = module.exports = function TollwerkTypo3SetupGenerator(args, options, config) {
	var self	= this;

	yeoman.generators.Base.apply(this, arguments);

	this.pkg	= JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(TollwerkTypo3SetupGenerator, yeoman.generators.Base);

/**
 * Install a TYPO3 extension
 *
 * @param {TollwerkTypo3SetupGenerator} generator		Generator reference
 * @param {String} extension							Extension key
 * @param {Function} callback							Callback
 * @return {void}
 */
function installExtension(generator, extension, callback) {
	exec("./typo3/cli_dispatch.phpsh extbase extension:install " + extension, function (error, stdout, stderr) {
		generator.log(stdout);
		callback(error);
	});
}

/**
 * Generator dialog
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.askFor = function() {
	var done		= this.async();

	if (!this.options.nested) {
		this.log(this.yeoman);
		this.log(chalk.magenta('You\'re about scaffolding a tollwerk style TYPO3 project.'));
	}
	this.log();

	var prompts = [{
		name	: 'project',
		message	: 'How should this project be called?'
	},{
		name	: 'baseurl',
		message	: 'What is the base URL of the site?'
	},{
		name	: 'sbaseurl',
		message	: 'What is the staging site base URL?'
	},{
		name	: 'author',
		message	: 'What is the site author\'s name?'
	},{
		type	: 'list',
		name	: 'templating',
		message	: 'Which templating system are you going to use?',
		choices	: [{name: 'FluidTYPO3', value: 'ft3'}, {name: 'TemplaVoila!', value: 'tv'}, {name: 'None', value: 'none'}],
		'default'	: 'ft3'
	},{
		type	: 'confirm',
		name	: 'sass',
		message	: 'Would you like to use Sass?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'iconizr',
		message	: 'Would you like to use iconizr?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'favicon',
		message	: 'Would you like to include favicon / touch icon support?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'ga',
		message	: 'Would you like to install the Google Analytics extension (tw_googleanalytics)?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'squeezr',
		message	: 'Would you like to install the squeezr extension (squeezr)?',
		'default'	: true
	},{
		type	: 'confirm',
		name	: 'defr',
		message	: 'Would you like to install the defr extension?',
		'default'	: true
	}];

	this.prompt(prompts, function(props) {

		// TODO: What happens if no project name is given?
	 	this.project		= props.project.toLowerCase();

	 	this.baseurl		= props.baseurl.length ? ((props.baseurl.toLowerCase().indexOf('http') !== 0) ? ('http://' + props.baseurl) : props.baseurl) : '';
	 	this.baseurl		= this.baseurl.length ? (this.baseurl + ((this.baseurl.lastIndexOf('/') == (this.baseurl.length - 1)) ? '' : '/')) : '';
	 	this.sbaseurl		= props.sbaseurl.length ? ((props.sbaseurl.toLowerCase().indexOf('http') !== 0) ? ('http://' + props.sbaseurl) : props.sbaseurl) : '';
	 	this.sbaseurl		= this.sbaseurl.length ? (this.sbaseurl + ((this.sbaseurl.lastIndexOf('/') == (this.sbaseurl.length - 1)) ? '' : '/')) : '';
		this.author			= props.author;
		this.templating		= props.templating;
		this.sass			= props.sass;
		this.iconizr		= props.iconizr;
		this.favicon		= props.favicon;
		this.ga				= props.ga;
		this.squeezr		= props.squeezr;
		this.defr			= props.defr;

		this.deps			= {};
		switch(this.templating) {
			case 'ft3':
				this.deps.flux					= 'fluidtypo3-flux#latest';
				this.deps.fluidpages			= 'fluidtypo3-fluidpages#latest';
				this.deps.fluidcontent			= 'fluidtypo3-fluidcontent#latest';
				this.deps.vhs					= 'fluidtypo3-vhs#latest';
				break;
			case 'tv':
//				TODO: Activate once the TemplaVoila Git repository contains a bower.json file
//				this.deps.templavoila			= 'templavoila#latest';
				break;
		}
		if (this.ga) {
			this.deps.tw_googleanalytics		= 'googleanalytics-typo3#latest';
		}
		if (this.squeezr) {
			this.deps.squeezr					= 'squeezr-typo3#latest';
		}
		if (this.defr) {
			// TODO: Create TYPO3 extension for defr
			// this.deps.defr						= 'defr-typo3#latest';
		}

		done();
	}.bind(this));
}

/**
 * NPM & Bower file installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.app = function() {
	this.template('_package.json', 'package.json');
	this.template('_bower.json', 'bower.json');
}

/**
 * Project & Gruntfile installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.projectfiles = function() {
	this.copy('editorconfig', '.editorconfig');
	this.copy('jshintrc', '.jshintrc');
	this.copy('bowerrc', '.bowerrc');
	this.template('Gruntfile.js', 'Gruntfile.js');
}

/**
 * Base resource installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.baseresources = function() {
	this.copy('README.md', 'fileadmin/' + this.project + '/README.md');

	// Create the fileadmin directory structure
	this.directory('fileadmin', 'fileadmin/' + this.project);

 	// Create Sass directory (if needed)
 	if (this.sass) {
 		this.directory('options/sass/fileadmin', 'fileadmin/' + this.project);
 	}

 	switch (this.templating) {

 		// TemplaVoila!
 		case 'tv':
 			this.directory('options/tv/fileadmin', 'fileadmin/' + this.project);
 			break;
 	}

 	// Page configuration
 	this.template('fileadmin/.templates/ts/page/10_page_config.ts', 'fileadmin/' + this.project + '/.templates/ts/page/10_page_config.ts');
 	this.template('fileadmin/.templates/ts/page/30_page_head.ts', 'fileadmin/' + this.project + '/.templates/ts/page/30_page_head.ts');
}

/**
 * iconizr installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.iconizr = function() {
	if (this.iconizr) {
		this.mkdir('fileadmin/' + this.project + '/.templates/icons');
		this.mkdir('fileadmin/' + this.project + '/css/icons');
	}
}

/**
 * Favicon / touch icon installation
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.favicon = function() {
	if (this.favicon) {
		this.directory('options/favicon/fileadmin', 'fileadmin/' + this.project);
		this.mkdir('fileadmin/' + this.project + '/favicons');
	}
}

/**
 * Pull in dependencies
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.dependencies = function() {
	var done		= this.async();
	this.installDependencies({
		skipInstall: this.options['skip-install'],
        callback: function() {
            done();
        }.bind(this)
	});
}

/**
 * Install the templating extensions
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.templating = function() {
	switch (this.templating) {

		// FluidTYPO3
		case 'ft3':
			var that		= this;
			installExtension(that, 'flux', function() {
				installExtension(that, 'fluidpages', function() {
					installExtension(that, 'fluidcontent', function() {
						installExtension(that, 'vhs', that.async());
					});
				});
			});
			break;

		// TemplaVoila!
		case 'tv':
//			TODO: Activate once the TemplaVoila Git repository contains a bower.json file
//			installExtension(this, 'templavoila', this.async());
			break;
	}
}

/**
 * Install the Google Analytics extension
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.googleanalytics = function() {
	if (this.ga) {
		installExtension(this, 'tw_googleanalytics', this.async());

		// TODO: Add TypoScript
	}
}

/**
 * Install the squeezr extension
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.squeezr = function() {
	if (this.squeezr) {
		installExtension(this, 'squeezr', this.async());

		// TODO: Run update script or add a user hint
	}
}

/**
 * Install the defr extension
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.defr = function() {
	if (this.defr) {
		// TODO: Create TYPO3 extension for defr
	}
}

/**
 * Running the setup Grunt task
 *
 * @return {void}
 */
TollwerkTypo3SetupGenerator.prototype.grunt = function() {
	this.log('run grunt');
}<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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';

var ObjectTests = {
    testBasicTypesPropertyGetters: function() {
        var basicTypesValues = [true, 1, 1.1, 1.11, 'string', new Date(1), 'DATA'];
        var realm = new Realm({schema: [BasicTypesObjectSchema]});
        var object = null;
        realm.write(function() {
            object = realm.create('BasicTypesObject', basicTypesValues);
        });

        for (var i = 0; i < BasicTypesObjectSchema.properties.length; i++) {
            var prop = BasicTypesObjectSchema.properties[i];
            if (prop.type == Realm.Types.FLOAT) {
                TestCase.assertEqualWithTolerance(object[prop.name], basicTypesValues[i], 0.000001);
            }
            else if (prop.type == Realm.Types.DATE) {
                TestCase.assertEqual(object[prop.name].getTime(), basicTypesValues[i].getTime());
            }
            else {
                TestCase.assertEqual(object[prop.name], basicTypesValues[i]);
            }
        }
    },
    testBasicTypesPropertySetters: function() {
        var basicTypesValues = [true, 1, 1.1, 1.11, 'string', new Date(1), 'DATA'];
        var realm = new Realm({schema: [BasicTypesObjectSchema]});
        var obj = null;

        realm.write(function() {
            obj = realm.create('BasicTypesObject', basicTypesValues);
            obj.boolCol = false;
            obj.intCol = 2;
            obj.floatCol = 2.2;
            obj.doubleCol = 2.22;
            obj.stringCol = 'STRING';
            obj.dateCol = new Date(2);
            obj.dataCol = 'b';
        });

        TestCase.assertThrows(function() {
            obj.boolCol = true;
        }, 'can only set property values in a write transaction');

        TestCase.assertEqual(obj.boolCol, false, 'wrong bool value');
        TestCase.assertEqual(obj.intCol, 2, 'wrong int value');
        TestCase.assertEqualWithTolerance(obj.floatCol, 2.2, 0.000001, 'wrong float value');
        TestCase.assertEqual(obj.doubleCol, 2.22, 'wrong double value');
        TestCase.assertEqual(obj.stringCol, 'STRING', 'wrong string value');
        TestCase.assertEqual(obj.dateCol.getTime(), 2, 'wrong date value');
        TestCase.assertEqual(obj.dataCol, 'b', 'wrong data value');
    },
    testLinkTypesPropertyGetters: function() {
        var realm = new Realm({schema: [LinkTypesObjectSchema, TestObjectSchema]});
        var obj = null;
        realm.write(function() {
            obj = realm.create('LinkTypesObject', [[1], null, [[3]]]);
        });

        var objVal = obj.objectCol;
        TestCase.assertEqual(typeof objVal, 'object');
        TestCase.assertNotEqual(objVal, null);
        TestCase.assertEqual(objVal.doubleCol, 1);

        TestCase.assertEqual(obj.objectCol1, null);

        var arrayVal = obj.arrayCol;
        TestCase.assertEqual(typeof arrayVal, 'object');
        TestCase.assertNotEqual(arrayVal, null);
        TestCase.assertEqual(arrayVal.length, 1);
        TestCase.assertEqual(arrayVal[0].doubleCol, 3);
    },
    testLinkTypesPropertySetters: function() {
        var realm = new Realm({schema: [LinkTypesObjectSchema, TestObjectSchema]});
        var obj = null;
        realm.write(function() {
            obj = realm.create('LinkTypesObject', [[1], null, [[3]]]);
        });
        TestCase.assertEqual(realm.objects('TestObject').length, 2);

        TestCase.assertThrows(function() {
            obj.objectCol1 = obj.objectCol;
        }, 'can only set property values in a write transaction');

        // set/reuse object property
        realm.write(function() {
            obj.objectCol1 = obj.objectCol;
        });
        TestCase.assertEqual(obj.objectCol1.doubleCol, 1);
        //TestCase.assertEqual(obj.objectCol, obj.objectCol1);
        TestCase.assertEqual(realm.objects('TestObject').length, 2);

        realm.write(function() {
            obj.objectCol = null;
            obj.objectCol1 = null;
        });
        TestCase.assertEqual(obj.objectCol, null);
        TestCase.assertEqual(obj.objectCol1, null);

        // set object as JSON
        realm.write(function() {
            obj.objectCol = { doubleCol: 1 };
        });
        TestCase.assertEqual(obj.objectCol.doubleCol, 1);
        TestCase.assertEqual(realm.objects('TestObject').length, 3);

        // set array property
        realm.write(function() {
            obj.arrayCol = [obj.arrayCol[0], obj.objectCol, realm.create('TestObject', [2])];
        });
        TestCase.assertEqual(obj.arrayCol.length, 3);
        TestCase.assertEqual(obj.arrayCol[0].doubleCol, 3);
        TestCase.assertEqual(obj.arrayCol[1].doubleCol, 1);
        TestCase.assertEqual(obj.arrayCol[2].doubleCol, 2);
    },
};
<commit_msg>Move object property setter assert downward<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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';

var ObjectTests = {
    testBasicTypesPropertyGetters: function() {
        var basicTypesValues = [true, 1, 1.1, 1.11, 'string', new Date(1), 'DATA'];
        var realm = new Realm({schema: [BasicTypesObjectSchema]});
        var object = null;
        realm.write(function() {
            object = realm.create('BasicTypesObject', basicTypesValues);
        });

        for (var i = 0; i < BasicTypesObjectSchema.properties.length; i++) {
            var prop = BasicTypesObjectSchema.properties[i];
            if (prop.type == Realm.Types.FLOAT) {
                TestCase.assertEqualWithTolerance(object[prop.name], basicTypesValues[i], 0.000001);
            }
            else if (prop.type == Realm.Types.DATE) {
                TestCase.assertEqual(object[prop.name].getTime(), basicTypesValues[i].getTime());
            }
            else {
                TestCase.assertEqual(object[prop.name], basicTypesValues[i]);
            }
        }
    },
    testBasicTypesPropertySetters: function() {
        var basicTypesValues = [true, 1, 1.1, 1.11, 'string', new Date(1), 'DATA'];
        var realm = new Realm({schema: [BasicTypesObjectSchema]});
        var obj = null;

        realm.write(function() {
            obj = realm.create('BasicTypesObject', basicTypesValues);
            obj.boolCol = false;
            obj.intCol = 2;
            obj.floatCol = 2.2;
            obj.doubleCol = 2.22;
            obj.stringCol = 'STRING';
            obj.dateCol = new Date(2);
            obj.dataCol = 'b';
        });

        TestCase.assertEqual(obj.boolCol, false, 'wrong bool value');
        TestCase.assertEqual(obj.intCol, 2, 'wrong int value');
        TestCase.assertEqualWithTolerance(obj.floatCol, 2.2, 0.000001, 'wrong float value');
        TestCase.assertEqual(obj.doubleCol, 2.22, 'wrong double value');
        TestCase.assertEqual(obj.stringCol, 'STRING', 'wrong string value');
        TestCase.assertEqual(obj.dateCol.getTime(), 2, 'wrong date value');
        TestCase.assertEqual(obj.dataCol, 'b', 'wrong data value');

        TestCase.assertThrows(function() {
            obj.boolCol = true;
        }, 'can only set property values in a write transaction');

        TestCase.assertEqual(obj.boolCol, false, 'bool value changed outside transaction');
    },
    testLinkTypesPropertyGetters: function() {
        var realm = new Realm({schema: [LinkTypesObjectSchema, TestObjectSchema]});
        var obj = null;
        realm.write(function() {
            obj = realm.create('LinkTypesObject', [[1], null, [[3]]]);
        });

        var objVal = obj.objectCol;
        TestCase.assertEqual(typeof objVal, 'object');
        TestCase.assertNotEqual(objVal, null);
        TestCase.assertEqual(objVal.doubleCol, 1);

        TestCase.assertEqual(obj.objectCol1, null);

        var arrayVal = obj.arrayCol;
        TestCase.assertEqual(typeof arrayVal, 'object');
        TestCase.assertNotEqual(arrayVal, null);
        TestCase.assertEqual(arrayVal.length, 1);
        TestCase.assertEqual(arrayVal[0].doubleCol, 3);
    },
    testLinkTypesPropertySetters: function() {
        var realm = new Realm({schema: [LinkTypesObjectSchema, TestObjectSchema]});
        var obj = null;
        realm.write(function() {
            obj = realm.create('LinkTypesObject', [[1], null, [[3]]]);
        });
        TestCase.assertEqual(realm.objects('TestObject').length, 2);

        TestCase.assertThrows(function() {
            obj.objectCol1 = obj.objectCol;
        }, 'can only set property values in a write transaction');

        // set/reuse object property
        realm.write(function() {
            obj.objectCol1 = obj.objectCol;
        });
        TestCase.assertEqual(obj.objectCol1.doubleCol, 1);
        //TestCase.assertEqual(obj.objectCol, obj.objectCol1);
        TestCase.assertEqual(realm.objects('TestObject').length, 2);

        realm.write(function() {
            obj.objectCol = null;
            obj.objectCol1 = null;
        });
        TestCase.assertEqual(obj.objectCol, null);
        TestCase.assertEqual(obj.objectCol1, null);

        // set object as JSON
        realm.write(function() {
            obj.objectCol = { doubleCol: 1 };
        });
        TestCase.assertEqual(obj.objectCol.doubleCol, 1);
        TestCase.assertEqual(realm.objects('TestObject').length, 3);

        // set array property
        realm.write(function() {
            obj.arrayCol = [obj.arrayCol[0], obj.objectCol, realm.create('TestObject', [2])];
        });
        TestCase.assertEqual(obj.arrayCol.length, 3);
        TestCase.assertEqual(obj.arrayCol[0].doubleCol, 3);
        TestCase.assertEqual(obj.arrayCol[1].doubleCol, 1);
        TestCase.assertEqual(obj.arrayCol[2].doubleCol, 2);
    },
};
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var amock = require('../');

// test 1
amock('users', {
  id: 'id',
  age: 'random-number:10-20',
  login: 'words:1',
  name: 'names:2',
  description: 'sentences:5'
});

// simple test;
var result = amock.get(5);
assert.equal(result, 5);
assert.equal(typeof result[0], 'object');
assert.equal(typeof result[0].id, 'number');
assert(result[0].id >= 0);
assert.equal(typeof result[0].name, 'string');
assert.equal(result[0].name.split(' ').length, 2);
<commit_msg>:helicopter: tests fixed<commit_after>'use strict';

var assert = require('assert');
var amock = require('../');

// test 1
amock('users', {
  id: 'id',
  age: 'random-number:10-20',
  login: 'words:1',
  name: 'names:2',
  description: 'sentences:5'
});

// general tests
var result = amock.get(5);
assert.equal(result.length, 5);
assert.equal(typeof result[0], 'object');

// id tests
assert.equal(typeof result[0].id, 'number');
assert.equal(result[0].id+1,  result[1].id);

// random numbers tests
assert.equal(typeof result[0].age, 'number');
assert(result[0].age >= 10);
assert(result[0].age <= 20);

// words
assert.equal(typeof result[0].login, 'string');

// name
assert.equal(typeof result[0].name, 'string');
assert.equal(result[0].name.split(' ').length, 2);

// sentences
assert.equal(typeof result[0].description, 'string');
assert.equal(result[0].description.split('.').length, 5+1);
<|endoftext|>


<commit_before>QUnit.module( "Core" );

/**
 * Test the constructor logic.
 */
QUnit.test( "constructor", function( assert ) {
  var $wrapper = $( '

' ).appendTo( '#qunit-fixture' ),
      app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $wrapper );

  assert.ok( !!app.getItemDatabase(), "The item database is correctly set." );
  assert.ok( app.getWrapper().length, "The wrapper is correctly set." );
  assert.notEqual( '', $wrapper[ 0 ].id, "The wrapper received an ID." );
});

/**
 * Test the settings extension logic.
 */
QUnit.test( "settings extension", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ), {
    dummySetting: true,
    itemView: { fake: true }
  } );

  assert.ok(
    app.getSettings().dummySetting,
    "Unknown settings are correctly set."
  );
  assert.deepEqual(
    { fake: true },
    app.getSettings().itemView,
    "The settings are correctly set and extended."
  );
  assert.deepEqual(
    ArchibaldCurriculum.ItemListView,
    app.getSettings().itemListView,
    "The default settings are correctly kept."
  );
});

/**
 * Test the column collection event binding.
 */
QUnit.test( "column collection events", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      columns = app.getColumnDatabase(),
      $dummy = $( '
Column
' ).appendTo( '#qunit-fixture' ),
      model = new ArchibaldCurriculum.ColumnModel({ column: $dummy });

  // Add the column, and then remove it again. This should trigger the remove
  // event, which should remove the $dummy element from the DOM.
  assert.ok(
    document.contains( $dummy[ 0 ] ),
    "The column was correctly added to the DOM."
  );
  columns.add( model );
  columns.remove( model );
  assert.notOk(
    document.contains( $dummy[ 0 ] ),
    "The column was correctly removed from the DOM."
  );
});

/**
 * Test the column creation helper.
 */
QUnit.test( "column creation helper", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      column = app.createColumn( _testGetJSONItems()[ 'root' ] );

  // Check the defaults.
  assert.notOk( column.isCollapsed(), "The column is not collapsed by default." );
  assert.notOk( column.settings.editable, "The column is not editable by default." );
  // Check the column was added to the DOM.
  assert.ok(
    document.contains( column.$el[ 0 ] ),
    "The column was correctly added to the DOM."
  );
  // Check it was added to the column database.
  assert.ok(
    !!app.getColumnDatabase().where({ column: column }).length,
    "The column was correctly added to the database."
  );

  // Check passing params.
  column = app.createColumn( _testGetJSONItems()[ 'root' ], true, true );
  assert.ok( column.isCollapsed(), "The column is collapsed." );
  assert.ok( column.settings.editable, "The column is editable." );
});

/**
 * Test the column left/right selection helpers.
 */
QUnit.test( "column left/right selection helpers", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      column1 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column2 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column3 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column4 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column5 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      mapCallback = function( item ) {
        return item.get( 'column' );
      };

  assert.deepEqual(
    [],
    _.map( app.getColumnLeftSiblings( column1 ), mapCallback ),
    "Correctly found all columns on the left of column1."
  );
  assert.deepEqual(
    [ column1, column2 ],
    _.map( app.getColumnLeftSiblings( column3 ), mapCallback ),
    "Correctly found all columns on the left of column3."
  );
  assert.deepEqual(
    [ column4, column5 ],
    _.map( app.getColumnRightSiblings( column3 ), mapCallback ),
    "Correctly found all columns on the right of column3."
  );
  assert.deepEqual(
    [],
    _.map( app.getColumnRightSiblings( column5 ), mapCallback ),
    "Correctly found all columns on the right of column5."
  );
});

/**
 * Test the recursive (un)checking logic.
 */
QUnit.test( "recursive (un)checking logic", function( assert ) {
  // Store the original confirm function. We will replace it with a new one.
  var realConfirm = window.confirm;

  var doneConfirmEvent = assert.async( 2 ),
      done = assert.async(),
      app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      chain = [ 'id-6', 'id-5', 'id-1' ],
      database = app.getItemDatabase();

  // Checking item with the id-6 will also check items id-5 and id-1.
  var item6 = database.get( 'id-6' );
  item6.set( 'active', true );
  app.recursiveCheck( item6 );
  for ( var i = 0; i < chain.length; i++ ) {
    assert.ok(
      database.get( chain[ i ] ).get( 'active' ),
      "Correctly checked item " + chain[ i ]
    );
  }

  // Unchecking item id-1 will also uncheck items id-5 and id-6.
  var item1 = database.get( 'id-1' );
  item1.set( 'active', false );
  app.recursiveCheck( item1 );
  for ( var j = 0; j < chain.length; j++ ) {
    assert.notOk(
      database.get( chain[ j ] ).get( 'active' ),
      "Correctly unchecked item " + chain[ j ]
    );
  }

  // Try recursively unchecking, and prompting the user for confirmation. First
  // test if the user confirms (return true).
  window.confirm = function( message ) {
    doneConfirmEvent();
    return true;
  }
  // Check all items in the chain.
  for ( var i = 0; i < chain.length; i++ ) {
    database.get( chain[ i ] ).set( 'active', true );
  }
  // Uncheck item 1, and recursively uncheck its children. Confirm when
  // prompted.
  item1.set( 'active', false );
  app.recursiveCheck( item1, true );
  for ( var j = 0; j < chain.length; j++ ) {
    assert.notOk(
      database.get( chain[ j ] ).get( 'active' ),
      "Correctly unchecked item " + chain[ j ]  + " when asked for confirmation."
    );
  }

  // Check all items in the chain again.
  for ( var i = 0; i < chain.length; i++ ) {
    database.get( chain[ i ] ).set( 'active', true );
  }
  // This time cancel when prompted.
  window.confirm = function( message ) {
    doneConfirmEvent();
    return false;
  }
  // Uncheck item 1, and recursively uncheck its children. Cancel when
  // prompted.
  item1.set( 'active', false );
  app.recursiveCheck( item1, true );
  for ( var j = 0; j < chain.length; j++ ) {
    assert.ok(
      database.get( chain[ j ] ).get( 'active' ),
      "Correctly left item " + chain[ j ]  + " checked when asked for confirmation."
    );
  }

  // Restore the confirm function.
  window.confirm = realConfirm;
  done();
});

/**
 * Define a test item database, mimicking the structure a JSON file would
 * contain.
 */
function _testGetJSONItems() {
  return {
    root: [
      {
        type: "type-a",
        name: [ "Root item A" ],
        hasChildren: true,
        id: "id-1"
      },
      {
        type: "type-a",
        name: [ "Root item B" ],
        hasChildren: false,
        id: "id-2"
      },
      {
        type: "type-b",
        name: [ "Root item C" ],
        hasChildren: true,
        id: "id-3"
      }
    ],
    "id-1": [
      {
        type: "type-c",
        name: [ "Root item A; child item A" ],
        hasChildren: false,
        id: "id-4"
      },
      {
        type: "type-c",
        name: [ "Root item A; child item B" ],
        hasChildren: true,
        id: "id-5"
      }
    ],
    "id-5": [
      {
        type: "type-d",
        name: [ "Root item A; child item B; child item A" ],
        hasChildren: false,
        id: "id-6"
      },
      {
        type: "type-d",
        name: [ "Root item A; child item B; child item B" ],
        hasChildren: false,
        id: "id-7"
      }
    ],
    "id-3": [
      {
        type: "type-e",
        name: [ "Root item C; child item A" ],
        hasChildren: false,
        id: "id-8"
      },
      {
        type: "type-f",
        name: [ "Root item C; child item B" ],
        hasChildren: false,
        id: "id-9"
      }
    ]
  }
}
<commit_msg>Add unit tests for the responsive helpers<commit_after>QUnit.module( "Core" );

/**
 * Test the constructor logic.
 */
QUnit.test( "constructor", function( assert ) {
  var $wrapper = $( '

' ).appendTo( '#qunit-fixture' ),
      app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $wrapper );

  assert.ok( !!app.getItemDatabase(), "The item database is correctly set." );
  assert.ok( app.getWrapper().length, "The wrapper is correctly set." );
  assert.notEqual( '', $wrapper[ 0 ].id, "The wrapper received an ID." );
});

/**
 * Test the settings extension logic.
 */
QUnit.test( "settings extension", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ), {
    dummySetting: true,
    itemView: { fake: true }
  } );

  assert.ok(
    app.getSettings().dummySetting,
    "Unknown settings are correctly set."
  );
  assert.deepEqual(
    { fake: true },
    app.getSettings().itemView,
    "The settings are correctly set and extended."
  );
  assert.deepEqual(
    ArchibaldCurriculum.ItemListView,
    app.getSettings().itemListView,
    "The default settings are correctly kept."
  );
});

/**
 * Test the column collection event binding.
 */
QUnit.test( "column collection events", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      columns = app.getColumnDatabase(),
      $dummy = $( '
Column
' ).appendTo( '#qunit-fixture' ),
      model = new ArchibaldCurriculum.ColumnModel({ column: $dummy });

  // Add the column, and then remove it again. This should trigger the remove
  // event, which should remove the $dummy element from the DOM.
  assert.ok(
    document.contains( $dummy[ 0 ] ),
    "The column was correctly added to the DOM."
  );
  columns.add( model );
  columns.remove( model );
  assert.notOk(
    document.contains( $dummy[ 0 ] ),
    "The column was correctly removed from the DOM."
  );
});

/**
 * Test the column creation helper.
 */
QUnit.test( "column creation helper", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      column = app.createColumn( _testGetJSONItems()[ 'root' ] );

  // Check the defaults.
  assert.notOk( column.isCollapsed(), "The column is not collapsed by default." );
  assert.notOk( column.settings.editable, "The column is not editable by default." );
  // Check the column was added to the DOM.
  assert.ok(
    document.contains( column.$el[ 0 ] ),
    "The column was correctly added to the DOM."
  );
  // Check it was added to the column database.
  assert.ok(
    !!app.getColumnDatabase().where({ column: column }).length,
    "The column was correctly added to the database."
  );

  // Check passing params.
  column = app.createColumn( _testGetJSONItems()[ 'root' ], true, true );
  assert.ok( column.isCollapsed(), "The column is collapsed." );
  assert.ok( column.settings.editable, "The column is editable." );
});

/**
 * Test the column left/right selection helpers.
 */
QUnit.test( "column left/right selection helpers", function( assert ) {
  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      column1 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column2 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column3 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column4 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      column5 = app.createColumn( _testGetJSONItems()[ 'root' ] ),
      mapCallback = function( item ) {
        return item.get( 'column' );
      };

  assert.deepEqual(
    [],
    _.map( app.getColumnLeftSiblings( column1 ), mapCallback ),
    "Correctly found all columns on the left of column1."
  );
  assert.deepEqual(
    [ column1, column2 ],
    _.map( app.getColumnLeftSiblings( column3 ), mapCallback ),
    "Correctly found all columns on the left of column3."
  );
  assert.deepEqual(
    [ column4, column5 ],
    _.map( app.getColumnRightSiblings( column3 ), mapCallback ),
    "Correctly found all columns on the right of column3."
  );
  assert.deepEqual(
    [],
    _.map( app.getColumnRightSiblings( column5 ), mapCallback ),
    "Correctly found all columns on the right of column5."
  );
});

/**
 * Test the recursive (un)checking logic.
 */
QUnit.test( "recursive (un)checking logic", function( assert ) {
  // Store the original confirm function. We will replace it with a new one.
  var realConfirm = window.confirm;

  var doneConfirmEvent = assert.async( 2 ),
      done = assert.async(),
      app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      chain = [ 'id-6', 'id-5', 'id-1' ],
      database = app.getItemDatabase();

  // Checking item with the id-6 will also check items id-5 and id-1.
  var item6 = database.get( 'id-6' );
  item6.set( 'active', true );
  app.recursiveCheck( item6 );
  for ( var i = 0; i < chain.length; i++ ) {
    assert.ok(
      database.get( chain[ i ] ).get( 'active' ),
      "Correctly checked item " + chain[ i ]
    );
  }

  // Unchecking item id-1 will also uncheck items id-5 and id-6.
  var item1 = database.get( 'id-1' );
  item1.set( 'active', false );
  app.recursiveCheck( item1 );
  for ( var j = 0; j < chain.length; j++ ) {
    assert.notOk(
      database.get( chain[ j ] ).get( 'active' ),
      "Correctly unchecked item " + chain[ j ]
    );
  }

  // Try recursively unchecking, and prompting the user for confirmation. First
  // test if the user confirms (return true).
  window.confirm = function( message ) {
    doneConfirmEvent();
    return true;
  }
  // Check all items in the chain.
  for ( var i = 0; i < chain.length; i++ ) {
    database.get( chain[ i ] ).set( 'active', true );
  }
  // Uncheck item 1, and recursively uncheck its children. Confirm when
  // prompted.
  item1.set( 'active', false );
  app.recursiveCheck( item1, true );
  for ( var j = 0; j < chain.length; j++ ) {
    assert.notOk(
      database.get( chain[ j ] ).get( 'active' ),
      "Correctly unchecked item " + chain[ j ]  + " when asked for confirmation."
    );
  }

  // Check all items in the chain again.
  for ( var i = 0; i < chain.length; i++ ) {
    database.get( chain[ i ] ).set( 'active', true );
  }
  // This time cancel when prompted.
  window.confirm = function( message ) {
    doneConfirmEvent();
    return false;
  }
  // Uncheck item 1, and recursively uncheck its children. Cancel when
  // prompted.
  item1.set( 'active', false );
  app.recursiveCheck( item1, true );
  for ( var j = 0; j < chain.length; j++ ) {
    assert.ok(
      database.get( chain[ j ] ).get( 'active' ),
      "Correctly left item " + chain[ j ]  + " checked when asked for confirmation."
    );
  }

  // Restore the confirm function.
  window.confirm = realConfirm;
  done();
});

/**
 * Test the responsive logic helpers.
 */
QUnit.test( "responsive logic helpers", function( assert ) {
  var done = assert.async();

  var app = new ArchibaldCurriculum.Core( _testGetJSONItems(), $( '#qunit-fixture' ) ),
      column, model, i;

  // Activate the responsive logic. In order to have full control over our test
  // environment, we do this before we add any columns.
  app.activateResponsiveLogic();

  // Because the responsive activation will trigger a resize in 100ms, we wait
  // for it to finish, and then trigger our test code.
  setTimeout( function() {
    // Create 5 dummy columns, all expanded.
    for ( i = 5; i > 0; --i ) {
      column = app.createColumn( _testGetJSONItems()[ 'root' ] );
      column.expand();
      console.log( column, column.isExpanded() );
    }
    // Make the application think we are showing all 5.
    app.maxCols = 5;

    // Trigger a resize. A width of 900 should allow for 3 columns.
    app.resize( 900 );
    assert.equal( 3, app.maxCols, "A width of 900 allows the application to show 3 columns." );

    // Check the columns. Only the last 3 should still be expanded.
    for ( i in { 0: 0, 1: 1 } ) {
      assert.ok(
        app.getColumnDatabase().at( i ).get( 'column' ).isCollapsed(),
        "Column " + i + " is correctly collapsed."
      );
    }
    for ( i in { 2: 2, 3: 3, 4: 4 } ) {
      assert.ok(
        app.getColumnDatabase().at( i ).get( 'column' ).isExpanded(),
        "Column " + i + " is correctly expanded."
      );
    }

    // Now do the inverse. Resize to 1200, which should show 1 more column.
    app.resize( 1200 );
    assert.equal( 4, app.maxCols, "A width of 1200 allows the application to show 4 columns." );

    // Check the columns. Only the 1st one should be collapsed.
    assert.ok(
      app.getColumnDatabase().at( 0 ).get( 'column' ).isCollapsed(),
      "Column 0 is correctly collapsed."
    );
    for ( i in { 1: 1, 2: 2, 3: 3, 4: 4 } ) {
      assert.ok(
        app.getColumnDatabase().at( i ).get( 'column' ).isExpanded(),
        "Column " + i + " is correctly expanded."
      );
    }

    // Clean up.
    app.$style.remove();
    $( 'iframe.__archibald-curricula-ui--hacky-scrollbar-resize-listener__' ).remove();

    done();
  }, 200 );
});

/**
 * Define a test item database, mimicking the structure a JSON file would
 * contain.
 */
function _testGetJSONItems() {
  return {
    root: [
      {
        type: "type-a",
        name: [ "Root item A" ],
        hasChildren: true,
        id: "id-1"
      },
      {
        type: "type-a",
        name: [ "Root item B" ],
        hasChildren: false,
        id: "id-2"
      },
      {
        type: "type-b",
        name: [ "Root item C" ],
        hasChildren: true,
        id: "id-3"
      }
    ],
    "id-1": [
      {
        type: "type-c",
        name: [ "Root item A; child item A" ],
        hasChildren: false,
        id: "id-4"
      },
      {
        type: "type-c",
        name: [ "Root item A; child item B" ],
        hasChildren: true,
        id: "id-5"
      }
    ],
    "id-5": [
      {
        type: "type-d",
        name: [ "Root item A; child item B; child item A" ],
        hasChildren: false,
        id: "id-6"
      },
      {
        type: "type-d",
        name: [ "Root item A; child item B; child item B" ],
        hasChildren: false,
        id: "id-7"
      }
    ],
    "id-3": [
      {
        type: "type-e",
        name: [ "Root item C; child item A" ],
        hasChildren: false,
        id: "id-8"
      },
      {
        type: "type-f",
        name: [ "Root item C; child item B" ],
        hasChildren: false,
        id: "id-9"
      }
    ]
  }
}
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import moment from 'moment';
import { Link } from 'react-router-dom';
import { getPageLink } from '../../Domain/Global';
import type { Trigger } from '../../Domain/Trigger.js';
import type { Status } from '../../Domain/Status';
import type { Metric } from '../../Domain/Metric';
import type { Maintenance } from '../../Domain/Maintenance';
import { Statuses, getStatusColor, getStatusCaption } from '../../Domain/Status';
import Icon from 'retail-ui/components/Icon';
import StatusIndicator from '../StatusIndicator/StatusIndicator';
import TagGroup from '../TagGroup/TagGroup';
import Tabs, { Tab } from '../Tabs/Tabs';
import MetricList from '../MetricList/MetricList';
import cn from './TriggerListItem.less';

type Props = {|
    data: Trigger;
    onChange?: (maintenance: Maintenance, metric: string) => void;
    onRemove?: (metric: string) => void;
|};
type State = {|
    showMetrics: boolean;
|};

export default class TriggerListItem extends React.Component {
    props: Props;
    state: State;

    constructor() {
        super();
        this.state = {
            showMetrics: false,
        };
    }

    filterMetricsByStatus(status: Status): { [metric: string]: Metric } {
        const { metrics } = this.props.data.last_check || {};
        return Object.keys(metrics)
            .filter(x => metrics[x].state === status)
            .reduce((data, key) => {
                return { ...data, [key]: metrics[key] };
            }, {});
    }

    sortMetricsByValue(metrics: { [metric: string]: Metric }): { [metric: string]: Metric } {
        return Object.keys(metrics)
            .sort((x, y) => {
                const valueA = metrics[x].value || 0;
                const valueB = metrics[y].value || 0;
                if (valueA < valueB) {
                    return -1;
                }
                if (valueA > valueB) {
                    return 1;
                }
                return 0;
            })
            .reduce((data, key) => {
                return { ...data, [key]: metrics[key] };
            }, {});
    }

    toggleMetrics() {
        const { showMetrics } = this.state;
        this.setState({ showMetrics: !showMetrics });
    }

    renderCounters(): React.Element<*> {
        const counters = Object.keys(Statuses)
            .map(status => ({
                status,
                count: Object.keys(this.filterMetricsByStatus(status)).length,
            }))
            .filter(({ count }) => count !== 0)
            .map(({ status, count }) => (

                    {count}

            ));
        return (

                {counters.length !== 0 ? counters : N/A}

        );
    }

    renderStatus(): React.Element<*> {
        const { state: triggerStatus } = this.props.data.last_check || {};
        const metricStatuses = Object.keys(Statuses).filter(
            x => Object.keys(this.filterMetricsByStatus(x)).length !== 0
        );
        const notOkStatuses = metricStatuses.filter(x => x !== Statuses.OK);
        let statuses;
        if (metricStatuses.length === 0) {
            statuses = [triggerStatus];
        }
        else if (notOkStatuses.length === 0) {
            statuses = [Statuses.OK];
        }
        else {
            statuses = notOkStatuses;
        }
        return (

                <StatusIndicator statuses={statuses} />

        );
    }

    renderMetrics(): ?React.Element<*> {
        const { onChange, onRemove } = this.props;
        if (!onChange || !onRemove) {
            return null;
        }
        const statuses = Object.keys(Statuses).filter(x => Object.keys(this.filterMetricsByStatus(x)).length !== 0);
        if (statuses.length === 0) {
            return null;
        }
        const metrics = statuses.map(x => (
            <Tab key={x} id={x} label={getStatusCaption(x)}>
                <MetricList
                    items={this.sortMetricsByValue(this.filterMetricsByStatus(x))}
                    sortingColumn='value'
                    sortingDown
                    onChange={(maintenance, metric) => onChange(maintenance, metric)}
                    onRemove={metric => onRemove(metric)}
                />
            </Tab>
        ));
        return (

                <Tabs value={statuses[0]}>{metrics}</Tabs>

        );
    }

    render(): React.Element<*> {
        const { id, name, targets, tags, throttling } = this.props.data;
        const { showMetrics } = this.state;
        const metrics = this.renderMetrics();

        return (

 this.toggleMetrics())}>
                    {this.renderStatus()}
                    {this.renderCounters()}

                        <Link className={cn('link')} to={getPageLink('trigger', id)}>

{name}

                                {throttling !== 0 && (

                                        <Icon name='FlagSolid' />

                                )}

                                {targets.map((target, i) => (

                                        {target}

                                ))}

                        </Link>

                        <TagGroup tags={tags} />

                    {showMetrics && metrics}

        );
    }
}
<commit_msg>Fixed #51<commit_after>// @flow
import React from 'react';
import moment from 'moment';
import { Link } from 'react-router-dom';
import { getPageLink } from '../../Domain/Global';
import type { Trigger } from '../../Domain/Trigger.js';
import type { Status } from '../../Domain/Status';
import type { Metric } from '../../Domain/Metric';
import type { Maintenance } from '../../Domain/Maintenance';
import { Statuses, getStatusColor, getStatusCaption } from '../../Domain/Status';
import Icon from 'retail-ui/components/Icon';
import StatusIndicator from '../StatusIndicator/StatusIndicator';
import TagGroup from '../TagGroup/TagGroup';
import Tabs, { Tab } from '../Tabs/Tabs';
import MetricList from '../MetricList/MetricList';
import cn from './TriggerListItem.less';

type Props = {|
    data: Trigger;
    onChange?: (maintenance: Maintenance, metric: string) => void;
    onRemove?: (metric: string) => void;
|};
type State = {|
    showMetrics: boolean;
|};

export default class TriggerListItem extends React.Component {
    props: Props;
    state: State;

    constructor() {
        super();
        this.state = {
            showMetrics: false,
        };
    }

    filterMetricsByStatus(status: Status): { [metric: string]: Metric } {
        const { metrics } = this.props.data.last_check || {};
        return Object.keys(metrics)
            .filter(x => metrics[x].state === status)
            .reduce((data, key) => {
                return { ...data, [key]: metrics[key] };
            }, {});
    }

    sortMetricsByValue(metrics: { [metric: string]: Metric }): { [metric: string]: Metric } {
        return Object.keys(metrics)
            .sort((x, y) => {
                const valueA = metrics[x].value || 0;
                const valueB = metrics[y].value || 0;
                if (valueA < valueB) {
                    return -1;
                }
                if (valueA > valueB) {
                    return 1;
                }
                return 0;
            })
            .reduce((data, key) => {
                return { ...data, [key]: metrics[key] };
            }, {});
    }

    toggleMetrics() {
        const { showMetrics } = this.state;
        this.setState({ showMetrics: !showMetrics });
    }

    renderCounters(): React.Element<*> {
        const counters = Object.keys(Statuses)
            .map(status => ({
                status,
                count: Object.keys(this.filterMetricsByStatus(status)).length,
            }))
            .filter(({ count }) => count !== 0)
            .map(({ status, count }) => (

                    {count}

            ));
        return (

                {counters.length !== 0 ? counters : N/A}

        );
    }

    renderStatus(): React.Element<*> {
        const { state: triggerStatus } = this.props.data.last_check || {};
        const metricStatuses = Object.keys(Statuses).filter(
            x => Object.keys(this.filterMetricsByStatus(x)).length !== 0
        );
        const notOkStatuses = metricStatuses.filter(x => x !== Statuses.OK);
        let statuses;
        if (triggerStatus === Statuses.EXCEPTION) {
            statuses = [Statuses.EXCEPTION];
        }
        else if (metricStatuses.length === 0) {
            statuses = [triggerStatus];
        }
        else if (notOkStatuses.length === 0) {
            statuses = [Statuses.OK];
        }
        else {
            statuses = notOkStatuses;
        }
        return (

                <StatusIndicator statuses={statuses} />

        );
    }

    renderMetrics(): ?React.Element<*> {
        const { onChange, onRemove } = this.props;
        if (!onChange || !onRemove) {
            return null;
        }
        const statuses = Object.keys(Statuses).filter(x => Object.keys(this.filterMetricsByStatus(x)).length !== 0);
        if (statuses.length === 0) {
            return null;
        }
        const metrics = statuses.map(x => (
            <Tab key={x} id={x} label={getStatusCaption(x)}>
                <MetricList
                    items={this.sortMetricsByValue(this.filterMetricsByStatus(x))}
                    sortingColumn='value'
                    sortingDown
                    onChange={(maintenance, metric) => onChange(maintenance, metric)}
                    onRemove={metric => onRemove(metric)}
                />
            </Tab>
        ));
        return (

                <Tabs value={statuses[0]}>{metrics}</Tabs>

        );
    }

    render(): React.Element<*> {
        const { id, name, targets, tags, throttling } = this.props.data;
        const { showMetrics } = this.state;
        const metrics = this.renderMetrics();

        return (

 this.toggleMetrics())}>
                    {this.renderStatus()}
                    {this.renderCounters()}

                        <Link className={cn('link')} to={getPageLink('trigger', id)}>

{name}

                                {throttling !== 0 && (

                                        <Icon name='FlagSolid' />

                                )}

                                {targets.map((target, i) => (

                                        {target}

                                ))}

                        </Link>

                        <TagGroup tags={tags} />

                    {showMetrics && metrics}

        );
    }
}
<|endoftext|>


<commit_before>function nexusHost(nexusServer, hostName, disableDefaultCallbacks=false) {
  if(!nexusServer) throw new Error('Missing nexusServer address');
  if(!hostName) throw new Error('Missing hostName');
  if(!disableDefaultCallbacks) this.setDefaultCallbacks();
  this.ws = new WebSocket(nexusServer);

  this.ws.onopen = () => {
    this.ws.send(JSON.stringify({
      type: 'HOST',
      payload: hostName,
    }));
  };

  this.ws.onerror = (event) => (this.onError? this.onError(event) : undefined);
  this.ws.onclose = (event) => (this.onClose? this.onClose(event) : undefined);
  this.ws.onmessage = (event) => {
  //     console.log('Received:', event.data);
    const req = JSON.parse(event.data);
    switch(req.type) {
      case 'NEW_CLIENT':
        this.onNewClient && this.onNewClient(req.clientID, req.request);
        break;
      case 'FROM_CLIENT':
        this.onClientMessage && this.onClientMessage(req.clientID, req.payload);
        break;
      case 'LOST_CLIENT':
        this.onClientLost && this.onClientLost(req.payload); // TODO change to req.clientID
        break;
      case 'REGISTERED':
        this.onRegistered && this.onRegistered(req.hostID);
        break;
    }
  };

}

nexusHost.prototype.setDefaultCallbacks = function() {
  /* You can set any of these to null to have no callback */

  this.onRegistered = (hostID) => {
    /* example callback */
    console.log("+ Registered as host with id:", hostID);
  };
  this.onError = (event)=>{
    /* example callback */
    console.error('+ Nexus Error:', event);
  };
  this.onClose = (event)=>{
    /* example callback */
    console.warn('+ Connection Closed:', event);
  };
  this.onNewClient = (clientID, request)=>{
    /* example callback*/
    console.log("+ User #%s joined. Their connection request was:", clientID, request);
  };
  this.onClientMessage = (clientID, message)=>{
    /* example callback*/
    console.log("+ User #%s sent you:", clientID, message);
  };
  this.onClientLost = (clientID)=>{
    /* example callback*/
    console.log("+ User #%s disconnected", clientID);
  };
};

nexusHost.prototype.send = function(payload, clientID=undefined) {
  this.ws.send(JSON.stringify({
    type: 'SEND',
    clientID,
    payload,
  }));
};

nexusHost.prototype.close = function(code=1000, reason="Host closed their connection") {
  this.ws.close(code, reason);
}<commit_msg>Change 'this.ws' to 'this._ws'<commit_after>function nexusHost(nexusServer, hostName, disableDefaultCallbacks=false) {
  if(!nexusServer) throw new Error('Missing nexusServer address');
  if(!hostName) throw new Error('Missing hostName');
  if(!disableDefaultCallbacks) this.setDefaultCallbacks();
  this._ws = new WebSocket(nexusServer);

  this._ws.onopen = () => {
    this._ws.send(JSON.stringify({
      type: 'HOST',
      payload: hostName,
    }));
  };

  this._ws.onerror = (event) => (this.onError? this.onError(event) : undefined);
  this._ws.onclose = (event) => (this.onClose? this.onClose(event) : undefined);
  this._ws.onmessage = (event) => {
  //     console.log('Received:', event.data);
    const req = JSON.parse(event.data);
    switch(req.type) {
      case 'NEW_CLIENT':
        this.onNewClient && this.onNewClient(req.clientID, req.request);
        break;
      case 'FROM_CLIENT':
        this.onClientMessage && this.onClientMessage(req.clientID, req.payload);
        break;
      case 'LOST_CLIENT':
        this.onClientLost && this.onClientLost(req.payload); // TODO change to req.clientID
        break;
      case 'REGISTERED':
        this.onRegistered && this.onRegistered(req.hostID);
        break;
    }
  };

}

nexusHost.prototype.setDefaultCallbacks = function() {
  /* You can set any of these to null to have no callback */

  this.onRegistered = (hostID) => {
    /* example callback */
    console.log("+ Registered as host with id:", hostID);
  };
  this.onError = (event)=>{
    /* example callback */
    console.error('+ Nexus Error:', event);
  };
  this.onClose = (event)=>{
    /* example callback */
    console.warn('+ Connection Closed:', event);
  };
  this.onNewClient = (clientID, request)=>{
    /* example callback*/
    console.log("+ User #%s joined. Their connection request was:", clientID, request);
  };
  this.onClientMessage = (clientID, message)=>{
    /* example callback*/
    console.log("+ User #%s sent you:", clientID, message);
  };
  this.onClientLost = (clientID)=>{
    /* example callback*/
    console.log("+ User #%s disconnected", clientID);
  };
};

nexusHost.prototype.send = function(payload, clientID=undefined) {
  this._ws.send(JSON.stringify({
    type: 'SEND',
    clientID,
    payload,
  }));
};

nexusHost.prototype.close = function(code=1000, reason="Host closed their connection") {
  this._ws.close(code, reason);
}<|endoftext|>