text:
'use strict';

var _ = require('lodash');
var async = require('async');
var BlockReward = require('../logic/blockReward.js');
var ByteBuffer = require('bytebuffer');
var constants = require('../helpers/constants.js');
var crypto = require('crypto');
var genesisblock = null;
var Inserts = require('../helpers/inserts.js');
var ip = require('ip');
var OrderBy = require('../helpers/orderBy.js');
var Router = require('../helpers/router.js');
var schema = require('../schema/blocks.js');
var slots = require('../helpers/slots.js');
var sql = require('../sql/blocks.js');
var transactionTypes = require('../helpers/transactionTypes.js');

// Private fields
var modules, library, self, __private = {}, shared = {};

//Last time received a block
__private.lastReceipt = null;

//Block reward calculation
__private.blockReward = new BlockReward();

//Blockchain is loaded from peers
__private.loaded = false;

//Request for shutdown, please clean/stop your job, will shutdown when isActive = false
__private.cleanup = false;
//To prevent from shutdown if true, that would lead to unstable database state
__private.noShutdownRequired = false;

// @formatter:off
__private.blocksDataFields = {
	'b_id': String,
	'b_version': Number,
	'b_timestamp': Number,
	'b_height': Number,
	'b_previousBlock': String,
	'b_numberOfTransactions': Number,
	'b_totalAmount': String,
	'b_totalFee': String,
	'b_reward': String,
	'b_payloadLength': Number,
	'b_payloadHash': String,
	'b_generatorPublicKey': String,
	'b_blockSignature': String,
	't_id': String,
	't_type': Number,
	't_timestamp': Number,
	't_senderPublicKey': String,
	't_senderId': String,
	't_recipientId': String,
	't_vendorField': String,
	't_amount': String,
	't_fee': String,
	't_signature': String,
	't_signSignature': String,
	's_publicKey': String,
	'd_username': String,
	'v_votes': String,
	'm_min': Number,
	'm_lifetime': Number,
	'm_keysgroup': String,
	't_requesterPublicKey': String,
	't_signatures': String
};
// @formatter:on

// Constructor
function Blocks (cb, scope) {
	library = scope;
	genesisblock = library.genesisblock;
	self = this;

	__private.saveGenesisBlock(function (err) {
		return cb(err, self);
	});
}

// Private methods
__private.attachApi = function () {
	var router = new Router();

	router.use(function (req, res, next) {
		if (modules) { return next(); }
		res.status(500).send({success: false, error: 'Blockchain is loading'});
	});

	router.map(shared, {
		'get /get': 'getBlock',
		'get /': 'getBlocks',
		'get /getEpoch': 'getEpoch',
		'get /getHeight': 'getHeight',
		'get /getNethash': 'getNethash',
		'get /getFee': 'getFee',
		'get /getFees': 'getFees',
		'get /getMilestone': 'getMilestone',
		'get /getReward': 'getReward',
		'get /getSupply': 'getSupply',
		'get /getStatus': 'getStatus'
	});

	router.use(function (req, res, next) {
		res.status(500).send({success: false, error: 'API endpoint not found'});
	});

	library.network.app.use('/api/blocks', router);
	library.network.app.use(function (err, req, res, next) {
		if (!err) { return next(); }
		library.logger.error('API error ' + req.url, err);
		res.status(500).send({success: false, error: 'API error: ' + err.message});
	});
};

__private.saveGenesisBlock = function (cb) {
	library.db.query(sql.getGenesisBlockId, { id: genesisblock.block.id }).then(function (rows) {
		var blockId = rows.length && rows[0].id;

		if (!blockId) {
			__private.saveBlock(genesisblock.block, function (err) {
				return cb(err);
			});
		} else {
			return cb();
		}
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#saveGenesisBlock error');
	});
};

__private.deleteBlock = function (blockId, cb) {
	library.db.none(sql.deleteBlock, {id: blockId}).then(function () {
		return cb();
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#deleteBlock error');
	});
};

__private.list = function (filter, cb) {
	var params = {}, where = [];

	if (filter.generatorPublicKey) {
		where.push('"b_generatorPublicKey"::bytea = ${generatorPublicKey}');
		params.generatorPublicKey = filter.generatorPublicKey;
	}

	if (filter.numberOfTransactions) {
		where.push('"b_numberOfTransactions" = ${numberOfTransactions}');
		params.numberOfTransactions = filter.numberOfTransactions;
	}

	if (filter.previousBlock) {
		where.push('"b_previousBlock" = ${previousBlock}');
		params.previousBlock = filter.previousBlock;
	}

	if (filter.height === 0 || filter.height > 0) {
		where.push('"b_height" = ${height}');
		params.height = filter.height;
	}

	if (filter.totalAmount >= 0) {
		where.push('"b_totalAmount" = ${totalAmount}');
		params.totalAmount = filter.totalAmount;
	}

	if (filter.totalFee >= 0) {
		where.push('"b_totalFee" = ${totalFee}');
		params.totalFee = filter.totalFee;
	}

	if (filter.reward >= 0) {
		where.push('"b_reward" = ${reward}');
		params.reward = filter.reward;
	}

	if (!filter.limit) {
		params.limit = 100;
	} else {
		params.limit = Math.abs(filter.limit);
	}

	if (!filter.offset) {
		params.offset = 0;
	} else {
		params.offset = Math.abs(filter.offset);
	}

	if (params.limit > 100) {
		return cb('Invalid limit. Maximum is 100');
	}

	var orderBy = OrderBy(
		(filter.orderBy || 'height:desc'), {
			sortFields: sql.sortFields,
			fieldPrefix: 'b_'
		}
	);

	if (orderBy.error) {
		return cb(orderBy.error);
	}

	library.db.query(sql.countList({
		where: where
	}), params).then(function (rows) {
		var count = rows[0].count;

		library.db.query(sql.list({
			where: where,
			sortField: orderBy.sortField,
			sortMethod: orderBy.sortMethod
		}), params).then(function (rows) {
			var blocks = [];

			for (var i = 0; i < rows.length; i++) {
				blocks.push(library.logic.block.dbRead(rows[i]));
			}

			var data = {
				blocks: blocks,
				count: count
			};

			return cb(null, data);
		}).catch(function (err) {
			library.logger.error("stack", err.stack);
			return cb('Blocks#list error');
		});
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#list error');
	});
};

__private.getById = function (id, cb) {
	library.db.query(sql.getById, {id: id}).then(function (rows) {
		if (!rows.length) {
			return cb('Block not found');
		}

		var block = library.logic.block.dbRead(rows[0]);

		return cb(null, block);
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#getById error');
	});
};

__private.saveBlock = function (block, cb) {
	library.db.tx(function (t) {
		var promise = library.logic.block.dbSave(block);
		var inserts = new Inserts(promise, promise.values);

		var promises = [
			t.none(inserts.template(), promise.values)
		];

		t = __private.promiseTransactions(t, block, promises);
		t.batch(promises);
	}).then(function () {
		return __private.afterSave(block, cb);
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#saveBlock error');
	});
};

__private.promiseTransactions = function (t, block, blockPromises) {
	if (_.isEmpty(block.transactions)) {
		return t;
	}

	var transactionIterator = function (transaction) {
		transaction.blockId = block.id;
		return library.logic.transaction.dbSave(transaction);
	};

	var promiseGrouper = function (promise) {
		if (promise && promise.table) {
			return promise.table;
		} else {
			throw 'Invalid promise';
		}
	};

	var typeIterator = function (type) {
		var values = [];

		_.each(type, function (promise) {
			if (promise && promise.values) {
				values = values.concat(promise.values);
			} else {
				throw 'Invalid promise';
			}
		});

		var inserts = new Inserts(type[0], values, true);
		t.none(inserts.template(), inserts);
	};

	var promises = _.flatMap(block.transactions, transactionIterator);
	_.each(_.groupBy(promises, promiseGrouper), typeIterator);

	return t;
};

__private.afterSave = function (block, cb) {
	async.eachSeries(block.transactions, function (transaction, cb) {
		return library.logic.transaction.afterSave(transaction, cb);
	}, function (err) {
		return cb(err);
	});
};

__private.getPreviousBlock = function(block, cb){
	var previousBlock = modules.blockchain.getPreviousBlock(block);
	if(previousBlock){
		cb(null, previousBlock);
	}
	else { //let's get from database
		library.db.query(sql.getBlockById, {
			id: block.previousBlock
		}).then(function (rows) {

			previousBlock = rows[0];

			//TODO: get this right without this cleaning
			previousBlock.reward = parseInt(previousBlock.reward);
			previousBlock.totalAmount = parseInt(previousBlock.totalAmount);
			previousBlock.totalFee = parseInt(previousBlock.totalFee);

			// we add this previous block in the mem blockchain
			modules.blockchain.upsertBlock(previousBlock);

			cb(null, previousBlock);
		}).catch(function (err) {
			cb(err);
		});
	}
}

__private.popLastBlock = function (oldLastBlock, cb) {
	library.blockSequence.add(function (sequenceCb) {
		if(!oldLastBlock.previousBlock){
			self.simpleDeleteAfterBlock(oldLastBlock.id, function (err) {
				library.logger.warn("removing block", oldLastBlock.height);
				modules.blockchain.removeBlock(oldLastBlock);
			});
			return sequenceCb("No previous block");
		}
		__private.getPreviousBlock(oldLastBlock, function (err, previousBlock) {
			if (err) {
				return sequenceCb(err);
			}
			if (!previousBlock) {
				// very wrong removing block from db only
				self.simpleDeleteAfterBlock(oldLastBlock.id, function (err) {
					library.logger.warn("removing block", oldLastBlock.height);
					modules.blockchain.removeBlock(oldLastBlock);
				});

				return sequenceCb("No previous block");
			}

			async.eachSeries(oldLastBlock.transactions.reverse(), function (transaction, eachSeriesCb) {
				async.series([
					function (seriesCb) {
						modules.transactions.undo(transaction, oldLastBlock, seriesCb);
					}, function (seriesCb) {
						modules.transactions.undoUnconfirmed(transaction, seriesCb);
					}
				], eachSeriesCb);
			}, function (err) {
				// TODO: reinject transaction into pool: better than this
				// library.bus.message("receiveTransactions")
				modules.rounds.backwardTick(oldLastBlock, function () {
					__private.deleteBlock(oldLastBlock.id, function (err) {
						library.logger.warn("removing block", oldLastBlock.height);
						modules.blockchain.removeBlock(oldLastBlock, sequenceCb);
					});
				});
			});
		});
	}, cb);
};

__private.getIdSequence = function (height, cb) {
	library.db.query(sql.getIdSequence, { height: height, limit: 10, delegates: slots.delegates, activeDelegates: constants.activeDelegates }).then(function (rows) {
		if (rows.length === 0) {
			return cb('Failed to get id sequence for height: ' + height);
		}

		var ids = [];

		if (genesisblock && genesisblock.block) {
			var __genesisblock = {
				id: genesisblock.block.id,
				height: genesisblock.block.height
			};

			if (!_.includes(rows, __genesisblock.id)) {
				rows.push(__genesisblock);
			}
		}

		// multithread will eat you
		var lastBlock = modules.blockchain.getLastBlock();

		if (lastBlock && !_.includes(rows, lastBlock.id)) {
			rows.unshift({
				id: lastBlock.id,
				height: lastBlock.height
			});
		}

		rows.forEach(function (row) {
			if (!_.includes(ids, row.id)) {
				ids.push(row.id);
			}
		});

		return cb(null, { firstHeight: rows[0].height, ids: ids.join(',') });
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#getIdSequence error');
	});
};

__private.readDbRows = function (rows) {
	var blocks = {};
	var order = [];

	for (var i = 0, length = rows.length; i < length; i++) {
		var block = library.logic.block.dbRead(rows[i]);

		if (block) {
			if (!blocks[block.id]) {
				if (block.id === genesisblock.block.id) {
					block.generationSignature = (new Array(65)).join('0');
				}

				order.push(block.id);
				blocks[block.id] = block;
			}

			var transaction = library.logic.transaction.dbRead(rows[i]);
			blocks[block.id].transactions = blocks[block.id].transactions || [];

			if (transaction) {
				if (!blocks[block.id].transactions[transaction.id]) {
					blocks[block.id].transactions[transaction.id] = transaction;
				}
			}
		}
	}

	blocks = order.map(function (v) {
		blocks[v].transactions = Object.keys(blocks[v].transactions).map(function (t) {
			return blocks[v].transactions[t];
		});
		return blocks[v];
	});

	return blocks;
};

__private.applyGenesisTransaction = function (block, transaction, sender, cb) {
	transaction.blockId=block.id;
	modules.transactions.applyUnconfirmed(transaction, function (err) {
		if (err) {
			return cb({
				message: err,
				transaction: transaction,
				block: block
			});
		}

		modules.transactions.apply(transaction, block, function (err) {
			if (err) {
				return cb({
					message: 'Failed to apply transaction: ' + transaction.id,
					transaction: transaction,
					block: block
				});
			}
			return cb();
		});
	});
};

// Public methods
//
//__API__ `lastReceipt`

//
Blocks.prototype.lastReceipt = function (lastReceipt) {
	if(lastReceipt){
		__private.lastReceipt = lastReceipt;
	}
	if (!__private.lastReceipt) {
		__private.lastReceipt = new Date();
		__private.lastReceipt.stale = true;
		__private.lastReceipt.rebuild = false;
		__private.lastReceipt.secondsAgo = 100000;
	}
	else {
		var timeNow = new Date().getTime();
		__private.lastReceipt.secondsAgo = Math.floor((timeNow -  __private.lastReceipt.getTime()) / 1000);
		if(modules.delegates.isActiveDelegate()){
			__private.lastReceipt.stale = __private.lastReceipt.secondsAgo > 8;
			__private.lastReceipt.rebuild = __private.lastReceipt.secondsAgo > 60;
		}

		else if(modules.delegates.isForging()){
			__private.lastReceipt.stale = __private.lastReceipt.secondsAgo > 30;
			__private.lastReceipt.rebuild = __private.lastReceipt.secondsAgo > 100;
		}

		else {
			__private.lastReceipt.stale = __private.lastReceipt.secondsAgo > 60;
			__private.lastReceipt.rebuild = __private.lastReceipt.secondsAgo > 200;
		}
	}
	return __private.lastReceipt;
};

//
//__API__ `getTransactionsFromIds`

//
Blocks.prototype.getTransactionsFromIds = function(blockid, ids, cb){
	__private.getById(blockid, function (err, block) {
		if (!block || err) {
			return cb('Block not found');
		}
		var transactions=[];
		for(var i=0;i<block.transactions.length;i++){
			if(block.transactions[i].id in ids){
				transactions.push[block.transactions[i]];
			}
		}
		return cb(null, transactions);
	});
}

//
//__API__ `getCommonBlock`

//
Blocks.prototype.getCommonBlock = function (peer, height, cb) {
	async.waterfall([
		function (waterCb) {
			__private.getIdSequence(height, function (err, res) {
				return waterCb(err, res);
			});
		},
		function (res, waterCb) {
			var ids = res.ids;

			modules.transport.requestFromPeer(peer, {
				api: '/blocks/common?ids=' + ids,
				method: 'GET'
			}, function (err, res) {
				if (err || res.body.error) {
					return waterCb(err || res.body.error.toString());
				} else if (!res.body.common) {
					return waterCb(['Chain comparison failed with peer:', peer.string, 'using ids:', ids].join(' '));
				} else {
					return waterCb(null, res);
				}
			});
		},
		function (res, waterCb) {

			library.db.query(sql.getCommonBlock(res.body.common.previousBlock), {
				id: res.body.common.id,
				previousBlock: res.body.common.previousBlock,
				height: res.body.common.height
			}).then(function (rows) {
				if (!rows.length || !rows[0].count) {
					return waterCb(['Chain comparison failed with peer:', peer.string, 'using block:', JSON.stringify(res.body.common)].join(' '));
				} else {
					return waterCb(null, res.body);
				}
			}).catch(function (err) {
				library.logger.error("stack", err.stack);
				return waterCb('Blocks#getCommonBlock error');
			});
		}
	], function (err, res) {
		return cb(err, res);
	});
};

//
//__API__ `count`

//
Blocks.prototype.count = function (cb) {
	library.db.query(sql.countByRowId).then(function (rows) {
		var res = rows.length ? rows[0].count : 0;

		return cb(null, res);
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#count error');
	});
};

//
//__API__ `loadBlocksData`

//
Blocks.prototype.loadBlocksData = function (filter, options, cb) {
	if (arguments.length < 3) {
		cb = options;
		options = {};
	}

	options = options || {};

	var params = { limit: filter.limit || 1 };

	if (filter.id && filter.lastId) {
		return cb('Invalid filter: Received both id and lastId');
	} else if (filter.id) {
		params.id = filter.id;
	} else if (filter.lastId) {
		params.lastId = filter.lastId;
	}

	var fields = __private.blocksDataFields;

	library.dbSequence.add(function (cb) {
		library.db.query(sql.getHeightByLastId, { lastId: filter.lastId || null }).then(function (rows) {

			var height = rows.length ? rows[0].height : 0;
			var realLimit = height + (parseInt(filter.limit) || 1);

			params.limit = realLimit;
			params.height = height;

			library.db.query(sql.loadBlocksData(filter), params).then(function (rows) {
				return cb(null, rows);
			});
		}).catch(function (err ) {
			library.logger.error("stack", err.stack);
			return cb('Blocks#loadBlockData error');
		});
	}, cb);
};

//
//__API__ `loadBlocksPart`

//
Blocks.prototype.loadBlocksPart = function (filter, cb) {
	self.loadBlocksData(filter, function (err, rows) {
		var blocks = [];

		if (!err) {
			blocks = __private.readDbRows(rows);
		}

		return cb(err, blocks);
	});
};

//
//__API__ `loadBlocksOffset`

//
Blocks.prototype.loadBlocksOffset = function (limit, offset, verify, cb) {
	var newLimit = limit + (offset || 0);
	var params = { limit: newLimit, offset: offset || 0 };

	library.logger.debug('Loading blocks offset', {limit: limit, offset: offset, verify: verify});

	var lastBlock;
	library.db.query(sql.loadBlocksOffset, params).then(function (blocks) {

		//var blocks = __private.readDbRows(rows);

		async.eachSeries(blocks, function (block, seriesCb) {
			// TODO: dirty fix due to ill sql request
			block.reward = parseInt(block.reward);
			block.totalAmount = parseInt(block.totalAmount);
			block.totalFee = parseInt(block.totalFee);
			if(block.height%100 == 0){
				library.logger.info("Processing block height", block.height);
			}
			if (verify && block.id !== genesisblock.block.id) {
				// Sanity check of the block, if values are coherent.
				// No access to database.
				var check = self.verifyBlock(block, true);

				if (!check.verified) {
					library.logger.error(['loadBlocksOffset: Block ', block.id, 'verification failed'].join(' '), check.errors.join(', '));
					return seriesCb(check.errors[0], block);
				}
			}
			block.verified = true;
			block.processed = true;
			modules.blockchain.upsertBlock(block);
			if (block.id === genesisblock.block.id) {
				__private.applyGenesisBlock(block, seriesCb);
			}
			else {
				async.waterfall([
					function(waterfallCb){
						if(block.numberOfTransactions>0){
							__private.applyBlock(block, waterfallCb);
						}
						else{
							return waterfallCb();
						}
					},
					function(waterfallCb){
						modules.rounds.tick(block, waterfallCb);
					}
				], seriesCb);
			}
			lastBlock = block;
		}, function (err) {
			return cb(err, lastBlock);
		});
	}).catch(function (err) {
		library.logger.error(err.stack, lastBlock);
		return cb('Blocks#loadBlocksOffset error', lastBlock);
	});
};

//
//__API__ `removeSomeBlocks`

//
Blocks.prototype.removeSomeBlocks = function(numbers, cb){
	if (modules.blockchain.getLastBlock().height === 1) {
		return cb();
	}

	// Don't shutdown now
	__private.noShutdownRequired = true;

	async.series({
		// Rewind any unconfirmed transactions before removing blocks.
		// We won't apply them again since we will have to resync blocks back from network
		undoUnconfirmedList: function (seriesCb) {
			modules.transactionPool.undoUnconfirmedList([],seriesCb);
		},
   	popLastBlock: function (seriesCb) {
			async.whilst(
				function () {
					// if numbers = 50, on average remove 50 Blocks, roughly 1 round
					return (Math.random() > 1/(numbers+1));
				},
				function (next) {
					var block = modules.blockchain.getLastBlock();
					__private.popLastBlock(block, function (err, newLastBlock) {
		   			if (err) {
		   				library.logger.error('Error deleting last block', block);
							library.logger.error('Error deleting last block', err);
		   			}
		   			next(err);
		   		});
				},
				function(err) {
					return seriesCb(err);
				}
			);
   	}
	}, function (err) {
		// Reset the last receipt
		self.lastReceipt(new Date());
		// Allow shutdown, database writes are finished.
		__private.noShutdownRequired = false;
		return cb(err, modules.blockchain.getLastBlock());
	});
}

//
//__API__ `removeLastBlock`

//
Blocks.prototype.removeLastBlock = function(cb){
	if (modules.blockchain.getLastBlock().height === 1) {
		return cb();
	}
	// Don't shutdown now
	__private.noShutdownRequired = true;

	async.series({
		// Rewind any unconfirmed transactions before removing blocks.
		// We won't apply them again since we will have to resync blocks back from network
		undoUnconfirmedList: function (seriesCb) {
			modules.transactionPool.undoUnconfirmedList([], seriesCb);
		},
   	popLastBlock: function (seriesCb) {
			var block = modules.blockchain.getLastBlock();
			__private.popLastBlock(block, function (err, newLastBlock) {
				if (err) {
					library.logger.error('Error deleting last block', block);
					library.logger.error('Error deleting last block', err);
				}
				return seriesCb(err, newLastBlock);
			});
   	}
	}, function (err) {
		// Reset the last receipt
		self.lastReceipt(new Date());
		// Allow shutdown, database writes are finished.
		__private.noShutdownRequired = false;
		return cb(err, modules.blockchain.getLastBlock());
	});
}

//
//__API__ `loadLastBlock`

// get the last block from the db
Blocks.prototype.loadLastBlock = function (cb) {
	library.dbSequence.add(function (cb) {
		library.db.query(sql.loadLastBlock).then(function (rows) {
			var block=rows[0];
			// TODO: dirty fix due to ill sql request
			block.reward = parseInt(block.reward);
			block.totalAmount = parseInt(block.totalAmount);
			block.totalFee = parseInt(block.totalFee);
			if(!block.transactions){
				block.transactions=[];
			}
			return cb(null, block);
		}).catch(function (err) {
			library.logger.error("stack", err.stack);
			return cb('Blocks#loadLastBlock error');
		});
	}, cb);
};

//
//__API__ `getLastBlock`

//
Blocks.prototype.getLastBlock = function () {
	var lastBlock = modules.blockchain.getLastBlock();

	if (lastBlock) {
		var epoch = constants.epochTime / 1000;
		var lastBlockTime = epoch + lastBlock.timestamp;
		var currentTime = new Date().getTime() / 1000;

		lastBlock.secondsAgo = currentTime - lastBlockTime;
		lastBlock.fresh = (lastBlock.secondsAgo < 120);
	}

	return lastBlock;
};

//
//__EVENT__ `onVerifyBlock`

//
Blocks.prototype.onVerifyBlock = function (block, cb) {
	var result = self.verifyBlock(block, true);

	if(result.verified){
		return library.bus.message("blockVerified", block, cb);
	}
	else{
		return cb && cb(result.errors.join(" - "), block);
	}
}

//
//__API__ `verifyBlockHeader`

// TODO: verify transactions if transactionIds is present
// should be equivalent to full verification
Blocks.prototype.verifyBlockHeader = function (block) {
	var result = { verified: false, errors: [] };
	if(!block.transactions){
		block.transactions=[];
	}

	try {
		block = library.logic.block.objectNormalize(block);
	} catch (err) {
		result.errors.push(err);
	}

	if(!block.id){
		result.errors.push("No block id");
	}

	var expectedReward = __private.blockReward.calcReward(block.height);

	if (block.height !== 1 && expectedReward !== block.reward) {
		result.errors.push(['Invalid block reward:', block.reward, 'expected:', expectedReward].join(' '));
	}

	var lastBlock = modules.blockchain.getLastBlock();

	// TODO: make extrapolation for a refined check:
	// if (block.timestamp - lastBlock.timestamp)/(block.height-lastBlock.height) < blocktime (here 8s)
	if( block.height > lastBlock.height && block.timestamp < lastBlock.timestamp){
		result.errors.push('Invalid block timestamp, block forged on another chain');
	}

	var valid;

	try {
		valid = library.logic.block.verifySignature(block);
	} catch (e) {
		result.errors.push(e.toString());
	}

	if (!valid) {
		result.errors.push('Failed to verify block signature');
	}

	if (block.version > 0) {
		result.errors.push('Invalid block version');
	}

	var blockSlotNumber = slots.getSlotNumber(block.timestamp);

	if (blockSlotNumber > slots.getSlotNumber()){
		result.errors.push('Invalid block timestamp');
	}

	if (block.payloadLength > constants.maxPayloadLength) {
		result.errors.push('Payload length is too high');
	}

	if (block.numberOfTransactions > constants.maxTxsPerBlock) {
		result.errors.push('Transactions length is too high');
	}

	result.verified = block.height === 1 || result.errors.length === 0;
	return result;
};

// Will return all possible errors that are intrinsic to the block.
// NO DATABASE access
// checkPreviousBlock: includes check if we have the previous block of the internal chain
//
//__API__ `verifyBlock`

//
Blocks.prototype.verifyBlock = function (block, checkPreviousBlock) {
	var result = { verified: false, errors: [] };

	try {
		block = library.logic.block.objectNormalize(block);
	} catch (err) {
		result.errors.push(err);
	}

	if(!block.id){
		result.errors.push("No block id");
	}

	var previousBlock = null;

	if(block.height !== 1){
		if (!block.previousBlock) {
			result.errors.push('Invalid previous block');
		} else if (checkPreviousBlock){
			previousBlock = modules.blockchain.getPreviousBlock(block);
			if(!previousBlock) {
				library.bus.message("fork", block, 1);
				result.errors.push(['Invalid previous block:', block.previousBlock, 'height:', block.height].join(' '));
			}
		}
	}

	var expectedReward = __private.blockReward.calcReward(block.height);

	if (block.height !== 1 && expectedReward !== block.reward) {
		result.errors.push(['Invalid block reward:', block.reward, 'expected:', expectedReward].join(' '));
	}

	var valid;

	try {
		valid = library.logic.block.verifySignature(block);
	} catch (e) {
		result.errors.push(e.toString());
	}

	if (!valid) {
		result.errors.push('Failed to verify block signature');
	}

	if (block.version > 0) {
		result.errors.push('Invalid block version');
	}

	var blockSlotNumber = slots.getSlotNumber(block.timestamp);

	if (blockSlotNumber > slots.getSlotNumber()){
		result.errors.push('Invalid block timestamp');
	}

	// Disabling to allow orphanedBlocks?
	if(previousBlock){
		var lastBlockSlotNumber = slots.getSlotNumber(previousBlock.timestamp);
		if(blockSlotNumber < lastBlockSlotNumber) {
		 	result.errors.push('block timestamp is smaller than previous block timestamp');
		}
	}

	if (block.payloadLength > constants.maxPayloadLength) {
		result.errors.push('Payload length is too high');
	}

	if (block.transactions.length !== block.numberOfTransactions) {
		result.errors.push('Invalid number of transactions');
	}

	if (block.transactions.length > constants.maxTxsPerBlock) {
		result.errors.push('Transactions length is too high');
	}

	// Checking if transactions of the block adds up to block values.
	var totalAmount = 0,
	    totalFee = 0,
			size = 0,
	    payloadHash = crypto.createHash('sha256'),
	    appliedTransactions = {};

	var transactions = block.transactions;

	for (var i in transactions) {
		var transaction = transactions[i];

		if(!transaction.id){
			transaction.id = library.logic.transaction.getId(transaction);
		}

		var bytes;

		try {
			bytes = new Buffer(transaction.id, "hex");
		} catch (e) {
			result.errors.push(e.toString());
		}

		if (size + bytes.length > constants.maxPayloadLength) {
			result.errors.push("Payload is too large");
		}

		size += bytes.length;

		if (appliedTransactions[transaction.id]) {
			result.errors.push('Encountered duplicate transaction: ' + transaction.id);
		}

		appliedTransactions[transaction.id] = transaction;

		payloadHash.update(bytes);

		totalAmount += transaction.amount;

		totalFee += transaction.fee;
	}

	var calculatedHash=payloadHash.digest().toString('hex');
	if (calculatedHash !== block.payloadHash) {
		result.errors.push('Invalid payload hash');
	}

	if (totalAmount !== block.totalAmount) {
		result.errors.push('Invalid total amount');
	}

	if (totalFee !== block.totalFee) {
		result.errors.push('Invalid total fee');
	}

	result.verified = result.errors.length === 0;
	return result;
};

// Apply the block, provided it has been verified.
__private.applyBlock = function (block, cb) {

	// Prevent shutdown during database writes.
	__private.noShutdownRequired = true;

	// Transactions to rewind in case of error.
	var appliedUnconfirmedTransactions = {}, appliedTransactions = {};

	// List of currrently unconfirmed transactions that have been popped and unconfirmed transactions from the block already present in the node
	var removedTransactionsIds, keptTransactions;

	async.series({
		// Rewind any unconfirmed transactions before applying block.
		// TODO: It should be possible to remove this call if we can guarantee that only this function is processing transactions atomically. Then speed should be improved further.
		// TODO: Other possibility, when we rebuild from block chain this action should be moved out of the rebuild function.
		undoUnconfirmedList: function (seriesCb) {
			modules.transactionPool.undoUnconfirmedList(block.transactions, function (err, removedTransactionsIds, alreadyUnconfirmedTransactionIds) {
				if (err) {
					return seriesCb(err);
				} else {
					removedTransactionsIds = removedTransactionsIds;
					// filter out tx that have been already applied as unconfirmed, or applied in a previous block
					keptTransactions = block.transactions.filter(function(tx){
						return alreadyUnconfirmedTransactionIds.indexOf(tx.id) == -1 && !tx.applied;
					});
					return seriesCb();
				}
			});
		},
		// Apply transactions to unconfirmed mem_accounts fields.
		applyUnconfirmed: function (seriesCb) {
			async.eachSeries(keptTransactions, function (transaction, eachSeriesCb) {
				modules.transactions.applyUnconfirmed(transaction, function (err) {
					if (err) {
						library.logger.error('Failed to apply transaction:', transaction.id);
						library.logger.error('Error', err);
						library.logger.error('Transaction', transaction);
						return eachSeriesCb(err);
					}

					appliedUnconfirmedTransactions[transaction.id] = transaction;

					return eachSeriesCb();
				});
			}, function (err) {
				if (err) {
					// Rewind any already applied unconfirmed transactions.
					// Leaves the database state as per the previous block.
					async.eachSeries(keptTransactions, function (transaction, eachSeriesCb) {
						// The transaction has been applied?
						if (appliedUnconfirmedTransactions[transaction.id]) {
							// DATABASE: write
							modules.transactions.undoUnconfirmed(transaction, eachSeriesCb);
						} else {
							return eachSeriesCb();
						}
					}, function (error) {
						return seriesCb(err);
					});
				} else {
					return seriesCb();
				}
			});
		},
		// Block and transactions are ok.
		// Apply transactions to confirmed mem_accounts fields.
		applyConfirmed: function (seriesCb) {
			async.eachSeries(block.transactions, function (transaction, eachSeriesCb) {
				// DATABASE: write
				modules.transactions.apply(transaction, block, function (err) {
					if (err) {
						err = ['Failed to apply transaction:', transaction.id, '-', err].join(' ');
						library.logger.error("error:",err);
						library.logger.error('Transaction', transaction);
						return eachSeriesCb(err);
					}
					appliedTransactions[transaction.id] = transaction;
					// Transaction applied, removed from the unconfirmed list.
					modules.transactionPool.removeUnconfirmedTransaction(transaction.id);
					return eachSeriesCb();
				});
			}, function (err) {
				if(err){
					async.eachSeries(block.transactions, function (transaction, eachSeriesCb) {
						// The transaction has been applied?
						if (appliedTransactions[transaction.id]) {
							// DATABASE: write
							modules.transactions.undo(transaction, block, eachSeriesCb);
						} else {
							return eachSeriesCb();
						}
					}, function (error) {
						return seriesCb(err);
					});
				}
				else{
					return seriesCb();
				}
			});
		}
	}, function (err) {
		// Allow shutdown, database writes are finished.
		__private.noShutdownRequired = false;

		// Nullify large objects.
		// Prevents memory leak during synchronisation.
		keptTransactions = appliedTransactions = appliedUnconfirmedTransactions = removedTransactionsIds = block = null;

		if(err){
			modules.nodeManager.fixDatabase(function(error){
				library.logger.warn("Performed database maintenance after block error", err);
				if(error){
					library.logger.error("Database maintenance error", error);
				}
				return cb(err);
			});
		}
		else return cb();
	});
};

// Apply the genesis block, provided it has been verified.
// Shortcuting the unconfirmed/confirmed states.
__private.applyGenesisBlock = function (block, cb) {
	block.transactions = block.transactions.sort(function (a, b) {
		if (a.type === transactionTypes.VOTE) {
			return 1;
		} else {
			return 0;
		}
	});
	async.eachSeries(block.transactions, function (transaction, cb) {
			modules.accounts.setAccountAndGet({publicKey: transaction.senderPublicKey}, function (err, sender) {
				if (err) {
					return cb({
						message: err,
						transaction: transaction,
						block: block
					});
				}
				__private.applyGenesisTransaction(block, transaction, sender, cb);
			});
	}, function (err) {
		if (err) {
			// If genesis block is invalid, kill the node...
			library.logger.fatal("Can't validate load genesis block");
			library.logger.fatal("Error", err);
			return process.exit(0);
		} else {
			modules.rounds.tick(block, cb);
		}
	});
};

// Main function to process a Verified Block.
// * Verify the block is compatible with database state (DATABASE readonly)
// * Apply the block to database if both verifications are ok
//
//__API__ `processBlock`

//
Blocks.prototype.processBlock = function (block, cb) {
	if (__private.cleanup) {
		return cb('Cleaning up');
	}

	// be sure to apply only one block after the other

		// Check if block id is already in the database (very low probability of hash collision).
		// TODO: In case of hash-collision, to me it would be a special autofork...
		// DATABASE: read only
		library.db.query(sql.getBlockId, { id: block.id }).then(function (rows) {
			if (rows.length > 0) {
				return cb(['Block', block.id, 'already exists'].join(' '));
			}

			// Check if block was generated by the right active delagate. Otherwise, fork 3.
			// DATABASE: Read only to mem_accounts to extract active delegate list
			modules.delegates.validateBlockSlot(block, function (err) {
				if (err) {
					library.bus.message("fork", block, 3);
					return cb(err);
				}

				// Check against the mem_* tables that we can perform the transactions included in the block.
				async.eachSeries(block.transactions, function (transaction, cb) {
					async.waterfall([
						function (waterfallCb) {
							transaction.blockId = block.id;
							// Check if transaction is already in database, otherwise fork 2.
							// TODO: Uncle forging: Double inclusion is allowed.
							// DATABASE: read only
							// TODO: keep a special mem pools of recently applied transactions:
							// - never apply old transactions (ie timestamp > blocktimestamp + 72 hours)
							// - keep in mem pool all tx younger than 73 hours.
							library.db.query(sql.getTransactionId, { id: transaction.id }).then(function (rows) {
								if (rows.length > 0) {
									library.bus.message("fork",block, 0);
									//we just don't process tx
									return waterfallCb("Transaction already applied");
								}
								// Get account from database if any (otherwise cold wallet).
								// DATABASE: read only
								modules.accounts.getAccount({publicKey: transaction.senderPublicKey}, cb);
							}).catch(function (err) {
								library.logger.error("stack", err.stack);
								return waterfallCb('Blocks#processBlock error');
							});
						},
						function (sender, waterfallCb) {
							// Check if transaction id valid against database state (mem_* tables).
							// DATABASE: read only
							// TODO: remove this check and create a processGenesisBlock instead
							if(block.height!=1){
								library.logic.transaction.verify(transaction, sender, waterfallCb);
							}
							else{
								// Don't verify transaction in Genesis block
								return waterfallCb();
							}
						}
					],
					function (err) {
						return cb(err);
					});
				},
				function (err) {
					if (err) {
						return cb(err);
					} else {
						// The block and the transactions are OK i.e:
						// * Block and transactions have valid values (signatures, block slots, etc...)
						// * The check against database state passed (for instance sender has enough SKP, votes are under 101, etc...)
						// We thus update the database with the transactions values, save the block and tick it.
						async.waterfall([
							function(waterfallCb){
								__private.applyBlock(block, waterfallCb);
							},
							function(waterfallCb){
								__private.saveBlock(block, waterfallCb);
							},
							function(waterfallCb){
								modules.rounds.tick(block, waterfallCb);
							}
						],function(error, errblock){
							if(error){
								return cb(error, errblock);
							}
							else{
								return library.bus.message("blockProcessed", block, cb)
							}
						});
					}
				});
			});
		});
};

//
//__API__ `processEmptyBlock`

//
Blocks.prototype.processEmptyBlock = function (block, cb) {
	if (__private.cleanup) {
		return cb('Cleaning up');
	}
	if(block.numberOfTransactions>0){
		return cb('Not an empty block', block);
	}

	return async.applyEachSeries([
		function(block, applycb){
			modules.delegates.validateBlockSlot(block, applycb);
		},
		function(block, applycb){
			return __private.saveBlock(block, applycb);
		},
		function(block, applycb){
			return modules.rounds.tick(block, applycb);
		}
	],
	block,
	function(error, errblock){
		if(error){
			library.logger.debug("error", error)
			return cb(error, errblock);
		}
		else{
			return library.bus.message("blockProcessed", block, cb)
		}
	});

};

//
//__API__ `simpleDeleteAfterBlock`

//
Blocks.prototype.simpleDeleteAfterBlock = function (blockId, cb) {
	library.db.query(sql.simpleDeleteAfterBlock, {id: blockId}).then(function (res) {
		return cb(null, res);
	}).catch(function (err) {
		library.logger.error("stack", err.stack);
		return cb('Blocks#simpleDeleteAfterBlock error');
	});
};

//
//__API__ `loadBlocksFromPeer`

//
Blocks.prototype.loadBlocksFromPeer = function (peer, cb) {
	var lastValidBlock = modules.blockchain.getLastBlock();

	library.logger.info('Loading blocks from: ' + peer);

	// we increase timeout as it can be a big payload
	modules.transport.requestFromPeer(peer, {
		method: 'GET',
		api: '/blocks?lastBlockHeight=' + lastValidBlock.height,
		timeout: 60000
	}, function (err, res) {
		if (err || res.body.error) {
			return cb(err, lastValidBlock);
		}
		var blocks = res.body.blocks;
		// update with last version of peer data (height, blockheader)
		if(res.peer){
			peer=res.peer;
		}

		var report = library.schema.validate(res.body.blocks, schema.loadBlocksFromPeer);

		if (!report) {
			return cb('Received invalid blocks data', lastValidBlock);
		}
		return library.bus.message("blocksReceived", blocks, peer, cb);
	});
};

//
//__API__ `deleteBlocksBefore`

//
Blocks.prototype.deleteBlocksBefore = function (block, cb) {
	var blocks = [];

	async.whilst(
		function () {
			return (block.height < lastBlock.height);
		},
		function (next) {
			blocks.unshift(lastBlock);
			__private.popLastBlock(modules.blockchain.getLastBlock(), function (err, newLastBlock) {
				if(err){
					library.logger.error('error removing block', block);
					library.logger.error('error removing block', err);
				}
				library.logger.debug('removing block', block);
				next(err);
			});
		},
		function (err) {
			// reset the last receipt and try to rebuild now
			self.lastReceipt(new Date());
			return cb(err, blocks);
		}
	);
};

//
//__API__ `generateBlock`

//
Blocks.prototype.generateBlock = function (keypair, timestamp, cb) {

	var transactions = modules.transactionPool.getUnconfirmedTransactionList(false, constants.maxTxsPerBlock);
	var ready = [];

	async.eachSeries(transactions, function (transaction, cb) {

		if(!transaction){
			library.logger.debug('no tx!!!');
			return cb();
		}
		// Check if tx id is already in blockchain
		// TODO: to remove.
		library.db.query(sql.getTransactionId, { id: transaction.id }).then(function (rows) {
			if (rows.length > 0) {
				modules.transactionPool.removeUnconfirmedTransaction(transaction.id);
				library.logger.debug('removing tx from unconfirmed', transaction.id);
				return cb('Transaction ID is already in blockchain - ' + transaction.id);
			}
			modules.accounts.getAccount({ publicKey: transaction.senderPublicKey }, function (err, sender) {
				if (err || !sender) {
					return cb('Sender not found');
				}

				if (library.logic.transaction.ready(transaction, sender)) {
					library.logic.transaction.verify(transaction, sender, function (err) {
						ready.push(transaction);
						return cb();
					});
				} else {
					return cb();
				}
			});
		});
	}, function () {
		var block;
		var lastBlock = modules.blockchain.getLastBlock();

		// ok sometimes it takes time to get there so timestamp
		// could have been calculated BEFORE the lastBlock received.
		// imagine the disaster...
		if(timestamp <= lastBlock.timestamp){
			return cb("New block received while forging. Forging canceled");
		}

		try {
			block = library.logic.block.create({
				keypair: keypair,
				timestamp: timestamp,
				previousBlock: lastBlock,
				transactions: ready
			});
		} catch (e) {
			library.logger.error("stack", e.stack);
			return cb(e);
		}

		return cb(null, block);
	});
};

// Events
//
//__EVENT__ `onProcessBlock`

//
Blocks.prototype.onProcessBlock = function (block, cb) {
	library.blockSequence.add(function(sequenceCb){
		if(block.numberOfTransactions == 0){

			return self.processEmptyBlock(block, sequenceCb);
		}
		else{
			return self.processBlock(block, sequenceCb);
		}
	}, cb);
};

//
//__EVENT__ `onBind`

//
Blocks.prototype.onBind = function (scope) {
	modules = scope;
};

//
//__EVENT__ `onAttachPublicApi`

//
Blocks.prototype.onAttachPublicApi = function () {
 	__private.attachApi();
};

//
//__API__ `cleanup`

//
Blocks.prototype.cleanup = function (cb) {
	__private.cleanup = true;

	var count = 0;

	if (!__private.noShutdownRequired) {
		return cb();
	} else {
		setImmediate(function nextWatch () {
			if (__private.noShutdownRequired || count++ > 10) {
				library.logger.info('Waiting for block processing to finish...');
				setTimeout(nextWatch, 1 * 1000);
			} else {
				return cb();
			}
		});
	}
};

// Shared public API
shared.getBlock = function (req, cb) {

	library.schema.validate(req.body, schema.getBlock, function (err) {
		if (err) {
			return cb(err[0].message);
		}

		library.dbSequence.add(function (sequenceCb) {
			__private.getById(req.body.id, function (err, block) {
				if (!block || err) {
					return sequenceCb('Block not found');
				}
				return sequenceCb(null, {block: block});
			});
		}, cb);
	});
};

shared.getBlocks = function (req, cb) {

	library.schema.validate(req.body, schema.getBlocks, function (err) {
		if (err) {
			return cb(err[0].message);
		}

		library.dbSequence.add(function (sequenceCb) {
			__private.list(req.body, function (err, data) {
				if (err) {
					return sequenceCb(err);
				}
				return sequenceCb(null, {blocks: data.blocks, count: data.count});
			});
		}, cb);
	});
};

shared.getEpoch = function (req, cb) {

	return cb(null, {epoch: constants.epochTime});
};

shared.getHeight = function (req, cb) {
	var block=modules.blockchain.getLastBlock();

	return cb(null, {height: block.height, id:block.id});
};

shared.getFee = function (req, cb) {

	return cb(null, {fee: library.logic.block.calculateFee()});
};

shared.getFees = function (req, cb) {

	return cb(null, {fees: constants.fees});
};

shared.getNethash = function (req, cb) {

	return cb(null, {nethash: library.config.nethash});
};

shared.getMilestone = function (req, cb) {
	return cb(null, {milestone: __private.blockReward.calcMilestone(modules.blockchain.getLastBlock().height)});
};

shared.getReward = function (req, cb) {
	return cb(null, {reward: __private.blockReward.calcReward(modules.blockchain.getLastBlock().height)});
};

shared.getSupply = function (req, cb) {
	return cb(null, {supply: __private.blockReward.calcSupply(modules.blockchain.getLastBlock().height)});
};

shared.getStatus = function (req, cb) {

	var block = modules.blockchain.getLastBlock();

	return cb(null, {
		epoch:     constants.epochTime,
		height:    block.height,
		fee:       library.logic.block.calculateFee(),
		milestone: __private.blockReward.calcMilestone(block.height),
		nethash:   library.config.nethash,
		reward:    __private.blockReward.calcReward(block.height),
		supply:    __private.blockReward.calcSupply(block.height)
	});
};

// Export
module.exports = Blocks;


text:
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jun 09, 2015 at 10:48 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `vremenskaprognoza`
--

-- --------------------------------------------------------

--
-- Table structure for table `autor`
--

CREATE TABLE IF NOT EXISTS `autor` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Ime` varchar(50) COLLATE utf8_slovenian_ci NOT NULL,
  `Prezime` varchar(50) COLLATE utf8_slovenian_ci NOT NULL,
  `Username` varchar(50) COLLATE utf8_slovenian_ci DEFAULT NULL,
  `Password` varchar(50) COLLATE utf8_slovenian_ci DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_slovenian_ci AUTO_INCREMENT=7 ;

--
-- Dumping data for table `autor`
--

INSERT INTO `autor` (`Id`, `Ime`, `Prezime`, `Username`, `Password`) VALUES
(2, 'Ime', 'Prezime', 'iprezime1', 'lozinka'),
(3, 'Haris', 'Čustović', 'hcustovic1', 'tajna'),
(4, 'Novi', 'Autor', NULL, NULL),
(5, 'Samo', 'Polako', NULL, NULL),
(6, 'dsdaskdcas', 'vjslfjdsklfs', NULL, NULL);

-- --------------------------------------------------------

--
-- Table structure for table `komentar`
--

CREATE TABLE IF NOT EXISTS `komentar` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `NovostID` int(11) NOT NULL,
  `KorisnikID` int(11) DEFAULT NULL,
  `Komentator` varchar(100) COLLATE utf8_slovenian_ci DEFAULT NULL,
  `Email` varchar(100) COLLATE utf8_slovenian_ci DEFAULT NULL,
  `Poruka` text COLLATE utf8_slovenian_ci NOT NULL,
  `DatumObjave` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`),
  KEY `NovostKomentar_FK` (`NovostID`),
  KEY `KomentarKorisnik_FK` (`KorisnikID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_slovenian_ci AUTO_INCREMENT=17 ;

--
-- Dumping data for table `komentar`
--

INSERT INTO `komentar` (`Id`, `NovostID`, `KorisnikID`, `Komentator`, `Email`, `Poruka`, `DatumObjave`) VALUES
(1, 1, NULL, 'Ime', 'dasdas@dsds.com', 'Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!! Ovo je super!!!!!', '2015-05-27 10:45:48'),
(2, 1, NULL, NULL, NULL, 'Ovo je anonimno super!', '2015-05-27 10:45:48'),
(4, 1, NULL, '', '', 'dasdfafadfdasdasdcdads', '2015-06-09 19:56:09'),
(5, 1, NULL, 'dsadsada', '', 'sadasds', '2015-06-09 20:07:31'),
(8, 1, NULL, '', '', 'dasdfasdasd', '2015-06-09 20:16:46'),
(11, 1, NULL, 'Orhan', 'mail@mail.com', 'lsjdasldjasldasd', '2015-06-09 20:19:25'),
(12, 1, NULL, '', '', 'Još adn dasdkasd', '2015-06-09 20:20:01'),
(13, 1, NULL, 'Orhan', 'mail@mail.com', 'dsadasdasd', '2015-06-09 20:39:23'),
(14, 1, NULL, 'Orhan', 'mail@mail.com', 'fdsgrgf', '2015-06-09 20:40:11'),
(15, 3, NULL, '', '', 'djlasdjasld', '2015-06-09 20:46:31'),
(16, 3, 5, 'Orhan', 'mail@mail.com', 'Ovo nije anonimno!', '2015-06-09 20:46:43');

-- --------------------------------------------------------

--
-- Table structure for table `korisnik`
--

CREATE TABLE IF NOT EXISTS `korisnik` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) COLLATE utf8_slovenian_ci NOT NULL,
  `password` varchar(100) COLLATE utf8_slovenian_ci NOT NULL,
  `administrator` tinyint(1) NOT NULL DEFAULT '0',
  `mail` varchar(100) COLLATE utf8_slovenian_ci NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_slovenian_ci AUTO_INCREMENT=8 ;

--
-- Dumping data for table `korisnik`
--

INSERT INTO `korisnik` (`Id`, `username`, `password`, `administrator`, `mail`) VALUES
(1, 'admin', 'tajna', 1, 'dsds@asa.com'),
(5, 'Orhan', 'pisarica', 0, 'mail@mail.com'),
(6, 'Gamad', 'gamad', 0, 'gamad@fsdas.com'),
(7, 'fasdas', 'fdfdsfds', 0, '123124@dsas.com');

-- --------------------------------------------------------

--
-- Table structure for table `novost`
--

CREATE TABLE IF NOT EXISTS `novost` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `AutorID` int(11) NOT NULL,
  `Naslov` varchar(100) COLLATE utf8_slovenian_ci NOT NULL,
  `Slika` varchar(100) COLLATE utf8_slovenian_ci NOT NULL,
  `Opis` varchar(500) COLLATE utf8_slovenian_ci NOT NULL,
  `Detaljno` text COLLATE utf8_slovenian_ci NOT NULL,
  `DatumObjave` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`),
  KEY `AutorNovost_FK` (`AutorID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_slovenian_ci AUTO_INCREMENT=7 ;

--
-- Dumping data for table `novost`
--

INSERT INTO `novost` (`Id`, `AutorID`, `Naslov`, `Slika`, `Opis`, `Detaljno`, `DatumObjave`) VALUES
(1, 2, 'LIJEP SARAJEVSKI DAN', 'Images/Sunny-Sarajevo.jpg', 'U Sarajevu se očekuje lijepo vrijeme danas. Na sjeveru zemlje su moguće padavine.', 'U Sarajevu se očekuje pretežno sunčano i veoma toplo vrijeme. Uvečer postoji mala mogućnost za kratkotrajnom pojavom lokalnih pljuskova sa grmljavinom. Puhat će umjeren zapadni i jugozapadni vetar. Minimalna temperatura 12°C, maksimalna dnevna 28°C.\r\nSjever zemlje s druge strane će pogoditi intenzivne padavine, čije se smirenje očekuje tek predveče.', '2015-05-27 09:21:31'),
(3, 3, 'MOGUĆNOST POPLAVA', 'Images/poplave.jpg', 'Nakon prošlogodišnih nesretnih okolnosti vezanih za poplave, građani cijele BiH opet ne mogu odahnuti...', 'U većem dijelu Bosni i Hercegovini sutra se očekuje opasno vrijeme, piše novinska agencija Patria. Kako je najavljeno u Federalnom hidrometeorološkog zavodu očekuju se obilnije padavine i to čak 20 do 50, a negdje i više od 50 mm kiše. Crveni meteoalarm upaljen je na području Višegrada, što znači da je vrijeme izuzetno opasno te da se prognozira iznimno intenzivan meteorološki događaj.\nObilnije padavine najviše se očekuju u centralnim i sjeveroistočnim dijelovima BiH. Većina rijeka, izuzev Bosne imala je trend opadanja vodostaja, ali će tokom noći usljed padavina doći do porasta te nisu isključene poplave. EDIT!!!!!', '2015-05-27 09:22:53'),
(4, 2, 'MOGUĆNOST POPLAVA', 'Images/poplave.jpg', 'Nakon prošlogodišnih nesretnih okolnosti vezanih za poplave, građani cijele BiH opet ne mogu odahnuti...', '', '2015-05-27 09:22:53'),
(5, 2, 'Neka Nova vijest', 'http://metro-portal.hr/img/repository/2010/06/medium/shutterstock_vrijeme_prognoza.jpg', 'Probni tekst! Probni tekst! Probni tekst! Probni tekst!', '', '2015-05-28 19:00:27');

--
-- Constraints for dumped tables
--

--
-- Constraints for table `komentar`
--
ALTER TABLE `komentar`
  ADD CONSTRAINT `komentar_ibfk_2` FOREIGN KEY (`KorisnikID`) REFERENCES `korisnik` (`Id`),
  ADD CONSTRAINT `komentar_ibfk_1` FOREIGN KEY (`NovostID`) REFERENCES `novost` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `novost`
--
ALTER TABLE `novost`
  ADD CONSTRAINT `novost_ibfk_1` FOREIGN KEY (`AutorID`) REFERENCES `autor` (`Id`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

redpajama_set_name: RedPajamaGithub


text:
#include "El.hpp"

namespace El {

template<typename T>
void Broadcast( AbstractDistMatrix<T>& A, mpi::Comm comm, Int rank )
{
    DEBUG_ONLY(CSE cse("Broadcast"))
    if( mpi::Size(comm) == 1 )
        return;
    if( !A.Participating() )
        return;

    const Int localHeight = A.LocalHeight();
    const Int localWidth = A.LocalWidth();
    const Int localSize = localHeight*localWidth;
    if( localHeight == A.LDim() )
    {
        mpi::Broadcast( A.Buffer(), localSize, rank, comm );
    }
    else
    {
        vector<T> buf( localSize );

        // Pack
        if( mpi::Rank(comm) == rank )
            copy::util::InterleaveMatrix
            ( localHeight, localWidth,
              A.LockedBuffer(), 1, A.LDim(),
              buf.data(),       1, localHeight );

        mpi::Broadcast( buf.data(), localSize, rank, comm );

        // Unpack
        if( mpi::Rank(comm) != rank )
            copy::util::InterleaveMatrix
            ( localHeight, localWidth,
              buf.data(), 1, localHeight,
              A.Buffer(), 1, A.LDim() );
    }
}

template<typename T>
void Broadcast( AbstractBlockDistMatrix<T>& A, mpi::Comm comm, Int rank )
{
    DEBUG_ONLY(CSE cse("Broadcast"))
    if( mpi::Size(comm) == 1 )
        return;
    if( !A.Participating() )
        return;

    const Int localHeight = A.LocalHeight();
    const Int localWidth = A.LocalWidth();
    const Int localSize = localHeight*localWidth;
    if( localHeight == A.LDim() )
    {
        mpi::Broadcast( A.Buffer(), localSize, rank, comm );
    }
    else
    {
        vector<T> buf( localSize );

        // Pack
        if( mpi::Rank(comm) == rank )
            copy::util::InterleaveMatrix
            ( localHeight, localWidth,
              A.LockedBuffer(), 1, A.LDim(),
              buf.data(),       1, localHeight );

        mpi::Broadcast( buf.data(), localSize, rank, comm );

        // Unpack
        if( mpi::Rank(comm) != rank )
            copy::util::InterleaveMatrix
            ( localHeight, localWidth,
              buf.data(), 1, localHeight,
              A.Buffer(), 1, A.LDim() );
    }
}

#define PROTO(T) \
  template void Broadcast \
  ( AbstractDistMatrix<T>& A, mpi::Comm comm, Int rank ); \
  template void Broadcast \
  ( AbstractBlockDistMatrix<T>& A, mpi::Comm comm, Int rank );

#define EL_ENABLE_QUAD
#include "El/macros/Instantiate.h"

} // namespace El


text:
const https = require('https')
const execa = require('execa')

console.log('Env:')
for (const env of Object.keys(process.env)) {
  console.log(`${env}=${process.env[env]}`)
}

const { TOKEN, GITHUB_PR_NUMBER, BUILD_SOURCEVERSIONMESSAGE } = process.env

if (!TOKEN) {
  throw new Error('Missing TOKEN env variable')
}

const githubApi = async ({ payload }) =>
  new Promise((resolve, reject) => {
    const request = https.request(
      {
        protocol: 'https:',
        host: 'api.github.com',
        path: `/graphql`,
        method: 'POST',
        headers: {
          'User-Agent': 'KafkaJS Azure Pipeline',
          'Content-Type': 'application/json',
          Authorization: `token ${TOKEN}`,
        },
      },
      res => {
        let rawData = ''

        res.setEncoding('utf8')
        res.on('data', chunk => (rawData += chunk))
        res.on('end', () => {
          try {
            if (res.statusCode !== 200) {
              return reject(new Error(`Error: ${res.statusCode} - ${rawData}`))
            }

            resolve(JSON.parse(rawData))
          } catch (e) {
            reject(e)
          }
        })
      }
    )

    request.on('error', reject)
    request.write(JSON.stringify(payload))
    request.end()
  })

const commentOnPR = async () => {
  const commitMessage =
    BUILD_SOURCEVERSIONMESSAGE ||
    execa
      .commandSync('git log -1 --pretty=%B', { shell: true })
      .stdout.toString('utf-8')
      .trim()

  const PR_NUMBER_REGEXP = /^Merge pull request #([^\s]+)/
  const result = commitMessage.match(PR_NUMBER_REGEXP)

  if (!GITHUB_PR_NUMBER || !result || !result[1]) {
    console.warn('PR number not found!')
    return
  }

  const prNumber = GITHUB_PR_NUMBER ? parseInt(GITHUB_PR_NUMBER, 10) : parseInt(result[1], 10)
  console.log(`PR number: ${prNumber}`)

  const { data, errors: errorsOnGetPrId } = await githubApi({
    payload: {
      query: `
        query GetPRId($prNumber: Int!) {
          repository(owner: "tulios", name: "kafkajs") {
            pullRequest(number: $prNumber) {
              id
            }
          }
        }
      `,
      variables: { prNumber },
    },
  })

  if (errorsOnGetPrId) {
    console.error(errorsOnGetPrId)
    process.exit(1)
  }

  const subjectId = data.repository.pullRequest.id
  console.log(`subjectId: ${subjectId}`)
  const { version } = require('../../package.json')

  const { errors: errorsOnCommentOnPR } = await githubApi({
    payload: {
      query: `
        mutation CommentOnPR($subjectId: ID!) {
          addComment(input: {
            subjectId: $subjectId,
            clientMutationId: "azure_pipelines_pre_release_hook",
            body: "\`${version}\` released :tada:\nhttps://www.npmjs.com/package/kafkajs/v/${version}"
          }) {
            clientMutationId
          }
        }
      `,
      variables: { subjectId },
    },
  })

  if (errorsOnCommentOnPR) {
    console.error(errorsOnCommentOnPR)
    process.exit(1)
  }
}

commentOnPR()
  .then(console.log)
  .catch(console.error)


text:
"""
Created on Mon Jun 19 15:56:32 2017

@author: Alessandro
"""

import pandas as pd
import numpy as np
import pickle
import h5py
#%%

df_views_1= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch1_views.p",'rb'))
df_views_2= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch2_views.p",'rb'))
df_views_3= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch3_views.p",'rb'))
#%%
df_views_4= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch4_views.p",'rb'))
#%%
list_df_views=[df_views_1, df_views_2, df_views_3]

df_views_24m=pd.concat(list_df_views)
#%%
pickle.dump(df_views_24m,open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_views_24m.p",'wb'))

#%%
df_tags_1= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch1_tags.p",'rb'))
df_tags_2= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch2_tags.p",'rb'))
df_tags_3= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch3_tags.p",'rb'))
#%%
df_tags_4= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_batch4_tags.p",'rb'))
#%%
list_df_tags=[df_tags_1, df_tags_2, df_tags_3]
df_tags_24m=pd.concat(list_df_tags)
#%%
pickle.dump(df_tags_24m,open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_tags_24m.p",'wb'))
#%%
df= pickle.load(open("C:/Users/Alessandro/windows-share/Portfolio/DATA/df_views_24m.p",'rb'))
#%%
df.to_csv('C:/Users/Alessandro/windows-share/Portfolio/DATA/df_views_24m.csv')


text:
using System.Linq;
using ALaCarte.IisAdministration;
using Microsoft.AspNetCore.Mvc;

namespace ALaCarte.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly WebServer _webServer;

        public HomeController(WebServer webServer)
        {
            _webServer = webServer;
        }

        public IActionResult Index()
        {
            var sites = _webServer.GetSites();
            return View(sites);
        }

        public IActionResult About()
        {
            ViewData["Message"] = "a'la carte - your IIS menu with all sites and apps";

            return View();
        }

        public IActionResult Contact()
        {
            return View();
        }

        public IActionResult Error()
        {
            return View();
        }

        public IActionResult Applications(int id)
        {
            ViewData["SiteName"] = _webServer.GetSites().First(x => x.Id == id).Name;
            var applications = _webServer.GetSiteApplications(id);
            return View(applications);
        }

        public IActionResult WebSites() => View();
    }
}


text:
GLOG_logtostderr=1 /CaffeOnSpark/caffe-public/.build_release/tools/convert_imageset \
   --resize_height=200 --resize_width=1000 --shuffle --encoded \
   /caffe-test/train/data/ \
   /caffe-test/train/data/labels.txt \
   /caffe-test/train/lmdb


text:
%**************************************************************************
%
% rep_std_single.m                              (c) Spectrum GmbH, 04/2015
%
%**************************************************************************
%
% Example for all SpcMDrv based (M2i, M4i) generator cards.
% Shows standard data replay using single mode
%
% Feel free to use this source for own projects and modify it in any kind
%
%**************************************************************************

% helper maps to use label names for registers and errors
mRegs = spcMCreateRegMap ();
mErrors = spcMCreateErrorMap ();

% ***** init card and store infos in cardInfo struct *****
[success, cardInfo] = spcMInitCardByIdx (0);

if (success == true)
    % ----- print info about the board -----
    cardInfoText = spcMPrintCardInfo (cardInfo);
    fprintf (cardInfoText);
else
    spcMErrorMessageStdOut (cardInfo, 'Error: Could not open card\n', true);
    return;
end

% ----- check whether we support this card type in the example -----
if ((cardInfo.cardFunction ~= mRegs('SPCM_TYPE_AO')) & (cardInfo.cardFunction ~= mRegs('SPCM_TYPE_DO')) & (cardInfo.cardFunction ~= mRegs('SPCM_TYPE_DIO')))
    spcMErrorMessageStdOut (cardInfo, 'Error: Card function not supported by this example\n', false);
    return;
end

% ----- replay mode selected by user -----
%Let user select replay mode
fprintf ('\nPlease select the output mode:\n');
fprintf ('  (1) Singleshot\n  (2) Continuous\n  (3) Single Restart\n  (0) Quit\n');

replayMode = input ('Select: ');

if (replayMode < 1) | (replayMode > 3)
    spcMCloseCard (cardInfo);
    return;
end

% ***** do card settings *****
timeout_ms = 10000;

%Define sample rate
samplerate = 1000000;
if cardInfo.isM4i == true
    samplerate = 50000000;
end

%Set sample rate
% ----- set the samplerate and internal PLL, no clock output -----
[success, cardInfo] = spcMSetupClockPLL (cardInfo, samplerate, 0);  % clock output : enable = 1, disable = 0
if (success == false)
    spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupClockPLL:\n\t', true);
    return;
end
fprintf ('\n ..... Sampling rate set to %.1f MHz\n', cardInfo.setSamplerate / 1000000);

% ----- set channel mask for max channels -----
if cardInfo.maxChannels == 64
    chMaskH = hex2dec ('FFFFFFFF');
    chMaskL = hex2dec ('FFFFFFFF');
else
    chMaskH = 0;
    chMaskL = bitshift (1, cardInfo.maxChannels) - 1;
end

%Set generation/replay mode
switch replayMode

    case 1
        % ----- singleshot replay -----
        % Sets the generation mode to standard single and programs all necessary settings.
        [success, cardInfo] = spcMSetupModeRepStdSingle (cardInfo, chMaskH, chMaskL, 64 * 1024);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupModeRecStdSingle:\n\t', true);
            return;
        end
        fprintf (' .............. Set singleshot mode\n');

        % ----- set software trigger, no trigger output -----
        % Programs the trigger event to software. Card is started immediately after the start command without waiting for any external signals.
        [success, cardInfo] = spcMSetupTrigSoftware (cardInfo, 0);  % trigger output : enable = 1, disable = 0
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupTrigSoftware:\n\t', true);
            return;
        end
        fprintf (' ............. Set software trigger\n');

    case 2
        % ----- endless continuous mode -----
        % Sets the generation mode to standard continuous mode and programs all necessary settings.
        memSamples=64 * 1024; %2^16=65536
        [success, cardInfo] = spcMSetupModeRepStdLoops (cardInfo, chMaskH, chMaskL, memSamples, 0);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupModeRecStdSingle:\n\t', true);
            return;
        end
        fprintf (' .............. Set continuous mode\n');

        % ----- set software trigger, no trigger output -----
        % Programs the trigger event to software. Card is started immediately after the start command without waiting for any external signals.
        [success, cardInfo] = spcMSetupTrigSoftware (cardInfo, 0);  % trigger output : enable = 1, disable = 0
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupTrigSoftware:\n\t', true);

            return;
        end
        fprintf (' ............. Set software trigger\n Wait for timeout (%d sec) .....', timeout_ms / 1000);

    case 3
        % ----- single restart (one signal on every trigger edge) -----
        %The memory is replayed once on each received trigger event.
        [success, cardInfo] = spcMSetupModeRepStdSingleRestart (cardInfo, chMaskH, chMaskL, 64 * 1024, 0);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupTrigSoftware:\n\t', true);
            return;
        end
        fprintf (' .......... Set single restart mode\n');

        % ----- set extern trigger, positive edge -----
        % Programs the trigger event to external.
        [success, cardInfo] = spcMSetupTrigExternal (cardInfo, mRegs('SPC_TM_POS'), 1, 0, 1, 0);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupTrigSoftware:\n\t', true);
            return;
        end
        fprintf (' ............... Set extern trigger\n Wait for timeout (%d sec) .....', timeout_ms / 1000);
end

% ----- type dependent card setup -----
%Set analog/digital output channels
switch cardInfo.cardFunction

    % ----- analog generator card setup -----
    case mRegs('SPCM_TYPE_AO') %Analog output card (arbitrary waveform generators)
        % ----- program all output channels to +/- 1 V with no offset and no filter -----
        %Set parameters of all analog output channels
        for i=0 : cardInfo.maxChannels-1
            %spcMSetupAnalogOutputChannel (cardInfo, channel, amplitude (mV), outputOffset, filter,stopMode, doubleOut, differential);
            [success, cardInfo] = spcMSetupAnalogOutputChannel (cardInfo, i, 1000, 0, 0, 16, 0, 0); % 16 = SPCM_STOPLVL_ZERO, doubleOut = disabled, differential = disabled
            if (success == false)
                spcMErrorMessageStdOut (cardInfo, 'Error: spcMSetupInputChannel:\n\t', true);
                return;
            end
        end

   % ----- digital acquisition card setup -----
   case { mRegs('SPCM_TYPE_DO'), mRegs('SPCM_TYPE_DIO') }
       % ----- set all output channel groups -----
       %Set digital output channels
       for i=0 : cardInfo.DIO.groups-1
           [success, cardInfo] = spcMSetupDigitalOutput (cardInfo, i, mRegs('SPCM_STOPLVL_LOW'), 0, 3300, 0);
       end
end

if cardInfo.cardFunction == mRegs('SPCM_TYPE_AO')

    % ----- analog data -----

    % ***** calculate waveforms *****
    %Compute Dat_Ch%i
    if cardInfo.setChannels >= 1
        % ----- ch0 = sine waveform -----
        [success, cardInfo, Dat_Ch0] = spcMCalcSignal (cardInfo, cardInfo.setMemsize, 1, 1, 100);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMCalcSignal:\n\t', true);
            return;
        end
    end

    if cardInfo.setChannels >= 2
        % ----- ch1 = rectangle waveform -----
        [success, cardInfo, Dat_Ch1] = spcMCalcSignal (cardInfo, cardInfo.setMemsize, 2, 1, 100);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMCalcSignal:\n\t', true);
            return;
        end
    end

    if cardInfo.setChannels == 4
        % ----- ch2 = triangle waveform -----
        [success, cardInfo, Dat_Ch2] = spcMCalcSignal (cardInfo, cardInfo.setMemsize, 3, 1, 100);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMCalcSignal:\n\t', true);
            return;
        end

        % ----- ch3 = sawtooth waveform -----
        [success, cardInfo, Dat_Ch3] = spcMCalcSignal (cardInfo, cardInfo.setMemsize, 4, 1, 100);
        if (success == false)
            spcMErrorMessageStdOut (cardInfo, 'Error: spcMCalcSignal:\n\t', true);
            return;
        end
    end

    switch cardInfo.setChannels

        case 1
            % ----- get the whole data for one channel with offset = 0 -----
            errorCode = spcm_dwSetData (cardInfo.hDrv, 0, cardInfo.setMemsize, cardInfo.setChannels, 0, Dat_Ch0);
        case 2
            % ----- get the whole data for two channels with offset = 0 -----
            errorCode = spcm_dwSetData (cardInfo.hDrv, 0, cardInfo.setMemsize, cardInfo.setChannels, 0, Dat_Ch0, Dat_Ch1);
        case 4
            % ----- set data for four channels with offset = 0 -----
            errorCode = spcm_dwSetData (cardInfo.hDrv, 0, cardInfo.setMemsize, cardInfo.setChannels, 0, Dat_Ch0, Dat_Ch1, Dat_Ch2, Dat_Ch3);
    end

else

    % ----- digital data -----
    [success, Data] = spcMCalcDigitalSignal (cardInfo.setMemsize, cardInfo.setChannels);

    errorCode = spcm_dwSetRawData (cardInfo.hDrv, 0, length (Data), Data, 1);
end

if (errorCode ~= 0)
    [success, cardInfo] = spcMCheckSetError (errorCode, cardInfo);
    spcMErrorMessageStdOut (cardInfo, 'Error: spcm_dwSetData:\n\t', true);
    return;
end

% ----- we'll start and wait until the card has finished or until a timeout occurs -----
%All hardware settings are based on software registers that can be set by
%one of the functions spcm_dwSetParam. These functions sets a register to a
%defined value or executes a command.
errorCode = spcm_dwSetParam_i32 (cardInfo.hDrv, mRegs('SPC_TIMEOUT'), timeout_ms);
if (errorCode ~= 0)
    [success, cardInfo] = spcMCheckSetError (errorCode, cardInfo);
    spcMErrorMessageStdOut (cardInfo, 'Error: spcm_dwSetParam_i32:\n\t', true);
    return;
end

% ----- set command flags -----
%Define set of commands: (1) Start card, (2) enable trigger, (3) wait until the card
%has completed the current run
commandMask = bitor (mRegs('M2CMD_CARD_START'), mRegs('M2CMD_CARD_ENABLETRIGGER'));
commandMask = bitor (commandMask, mRegs('M2CMD_CARD_WAITREADY'));

%Execute set of commands (commandMask)
errorCode = spcm_dwSetParam_i32 (cardInfo.hDrv, mRegs('SPC_M2CMD'), commandMask);
if (errorCode ~= 0)

    [success, cardInfo] = spcMCheckSetError (errorCode, cardInfo);

    if errorCode == 263  % 263 = ERR_TIMEOUT
        errorCode = spcm_dwSetParam_i32 (cardInfo.hDrv, mRegs('SPC_M2CMD'), mRegs('M2CMD_CARD_STOP'));
        fprintf (' OK\n ................... replay stopped\n');

    else
        spcMErrorMessageStdOut (cardInfo, 'Error: spcm_dwSetParam_i32:\n\t', true);
        return;
    end
end

fprintf (' ...................... replay done\n');

% ***** close card *****
spcMCloseCard (cardInfo);


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.ComponentModel;
using System.Drawing.Design;
using System.Drawing.Html;
using System.Drawing;

namespace System.Windows.Forms
{
    public class HtmlPanel
        : ScrollableControl
    {
        #region Fields
        protected InitialContainer _htmlContainer;

        #endregion

        #region Ctor

        /// <summary>
        /// Creates a new HtmlPanel
        /// </summary>
        public HtmlPanel()
        {
            _htmlContainer = new InitialContainer();

            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.Opaque, true);
            //SetStyle(ControlStyles.Selectable, true);

            DoubleBuffered = true;

            BackColor = SystemColors.Window;
            AutoScroll = true;

            HtmlRenderer.AddReference(Assembly.GetCallingAssembly());
        }

        #endregion

        #region Properties

        [DesignerSerializationVisibility( DesignerSerializationVisibility.Visible)]
        public override bool AutoSize
        {
            get
            {
                return base.AutoSize;
            }
            set
            {
                base.AutoSize = value;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public override bool AutoScroll
        {
            get
            {
                return base.AutoScroll;
            }
            set
            {
                base.AutoScroll = value;
            }
        }

        /// <summary>
        /// Gets the Initial HtmlContainer of this HtmlPanel
        /// </summary>
        public InitialContainer HtmlContainer
        {
            get { return _htmlContainer; }
        }

        /// <summary>
        /// Gets or sets the text of this panel
        /// </summary>
        [Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), Localizable(true), Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;

                CreateFragment();
                MeasureBounds();
                Invalidate();
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Creates the fragment of HTML that is rendered
        /// </summary>
        protected virtual void CreateFragment()
        {
            _htmlContainer = new InitialContainer(Text);
        }

        /// <summary>
        /// Measures the bounds of the container
        /// </summary>
        public virtual void MeasureBounds()
        {
            _htmlContainer.SetBounds(this is HtmlLabel ? new Rectangle(0, 0, 10, 10) : ClientRectangle);

            using (Graphics g = CreateGraphics())
            {
                _htmlContainer.MeasureBounds(g);
            }

            AutoScrollMinSize = Size.Round(_htmlContainer.MaximumSize);
        }

        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);

            Focus();
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            MeasureBounds();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (!(this is  HtmlLabel)) e.Graphics.Clear(SystemColors.Window);

            _htmlContainer.ScrollOffset = AutoScrollPosition;
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            _htmlContainer.Paint(e.Graphics);

        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            foreach (CssBox box in _htmlContainer.LinkRegions.Keys)
            {
                RectangleF rect = _htmlContainer.LinkRegions[box];
                if (Rectangle.Round(rect).Contains(e.X, e.Y))
                {
                    Cursor = Cursors.Hand;
                    return;
                }
            }

            Cursor = Cursors.Default;
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            foreach (CssBox box in _htmlContainer.LinkRegions.Keys)
            {
                RectangleF rect = _htmlContainer.LinkRegions[box];
                if (Rectangle.Round(rect).Contains(e.X, e.Y))
                {
                    CssValue.GoLink(box.GetAttribute("href", string.Empty));
                    return;
                }
            }

        }

        #endregion
    }
}


text:
import os
from setuptools import setup, find_packages

setup(
    name='huey',
    version=__import__('huey').__version__,
    description='huey, a little task queue',
    author='Charles Leifer',
    author_email='coleifer@gmail.com',
    url='http://github.com/coleifer/huey/',
    packages=find_packages(),
    package_data = {
        'huey': [
        ],
    },
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
    test_suite='runtests.runtests',
    entry_points={
        'console_scripts': [
            'huey_consumer = huey.bin.huey_consumer:consumer_main'
            ]
    },
    scripts = ['huey/bin/huey_consumer.py'],
)


text:
var ck = window.ck = {

};

var ckUrl = {
    resetGetParams: function (params) {
        var url = new Url();
        url.query.clear();

        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                url.query[key] = params[key];
            }
        }

        return url.toString();
    },
    addGetParams: function (params) {
        var url = new Url();
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                url.query[key] = params[key];
            }
        }
        return url.toString();
    }
};

var app = angular.module("ckApp", [
	'cgBusy',
	'angular.filter',
    'ui.bootstrap'
]);

ck.flashbag = {
    subscribers: {},
    add: function (items) {
        for(var category in items) {
            if(!items.hasOwnProperty(category))
                continue;
            var catItems = items[category];
            if(ck.flashbag.subscribers.hasOwnProperty(category)) {
                var subs = ck.flashbag.subscribers[category];
                for(var i = 0; i < subs.length; i++) {
                    subs[i] (catItems);
                }
            }
        }
    },
    subscribe: function (category, callback) {
        if(!ck.flashbag.subscribers.hasOwnProperty(category)) {
            ck.flashbag.subscribers[category] = [];
        }

        ck.flashbag.subscribers[category].push (callback);
    }
}

var GenerateAPIFactory = function (make_call_real) {
    var make_call = function (url, params, urlOnly) {
        url += "&ajax=true";
        if(urlOnly) {
            return url;
        }
        return make_call_real(url, params);
    };

    var apis = {
    	page: {
    		func: function (page_id, func_name, params) {
    			return make_call(ckUrl.resetGetParams({
    				page: page_id,
    				func: func_name,
    				action: "page_function"
    			}), params);
    		},
    		get_colSpec: function (page_id, params) {
                params = params ? params : {};
    			return apis.page.func(page_id, "get_colSpec", params);
    		},
            get_data: function (page_id, params) {
                return apis.page.func(page_id, "get_data", params);
            },
            get_foreign: function (page_id, item_id, key, params) {
                params = params ? params : {};
                params.foreign_key = key;
                params['item_id'] = item_id;
                return apis.page.func(page_id, "get_foreign", params);
            },
            get_form_values: function (page_id, item_id, params) {
                params = params ? params : {};
                params['item_id'] = item_id;

                return apis.page.func(page_id, "get_form_values", params);
            },
            set_form_values: function (page_id, item_id, values, params) {
                params = params ? params : {};
                params['item_id'] = item_id;
                params['values_json'] = JSON.stringify(values);

                return apis.page.func(page_id, "set_form_values", params);
            },
            create_item: function (page_id, values, params) {
                params = params ? params : {};
                params['values_json'] = JSON.stringify(values);

                return apis.page.func(page_id, "create_item", params);
            }
    	}
    };

    return apis;
};

ck.fatalError = function (title, message) {
    BootstrapDialog.show ({
        title: title,
        message: message,
        type: "type-danger",
        buttons: [{
            icon: "fa fa-reload",
            label: "Reload Page",
            action: function () {
                window.location.reload()
            }
        }],
        closable: false
    })
};

ck.converters = {
    standard_to_js: function (schema, object) {
        var resultObject = {};
        for(var key in schema) {
            if(!object.hasOwnProperty(key)) {
                continue;
            }
            var type = schema[key].type;
            var input = object[key];
            var result = null;

            switch(type) {
                case "string":
                    result = input;
                break;
                case "number":
                    result = parseFloat(input);
                break;
                case "datetime":
                    // Server sends a timestamp in UTC. We use that in UTC and convert to JS date
                    result = moment.unix(parseInt(input)).tz("UTC").toDate();
                break;
            }

            resultObject[key] = result;
        }

        return resultObject;
    },
    js_to_standard: function (schema, object) {
        var resultObject = {};
        for(var key in schema) {
            if(!object.hasOwnProperty(key)) {
                continue;
            }
            var type = schema[key].type;
            var input = object[key];
            var result = null;

            switch(type) {
                case "string":
                    result = input.toString();
                break;
                case "number":
                    result = input.toString();
                break;
                case "datetime":
                    result = moment(input).tz("UTC").unix();
                break;
            }
            resultObject[key] = result;
        }

        return resultObject;
    },
    standard_to_js_table: function (schema, data) {
        var len = data.length;
        var processed = [];
        for(var i = 0; i < len; i ++) {
            processed.push(ck.converters.standard_to_js(schema, data[i]));
        }
        return processed;
    }
}

app.factory ("ckAPI", function ($http, $q) {
    var make_call_real = function (url, params) {
        var deferred = $q.defer();

        $http.post(url, params).error(function (data) {
            console.error("XHR Failed!!", data);
            deferred.reject($q.reject(data));
            if(data.error) {
                ck.fatalError("Error", "
There was an error in the server.

" + data.error.type + "

" + data.error.message + "
");
            }
            else {
                ck.fatalError("Error", "There was an unknown error in the server");
            }
        }).success(function (data) {
            if(data.flashbag) {
                ck.flashbag.add(data.flashbag);
            }
            if(data.success === false) {
                deferred.reject("Unknown error. Conflicting success codes");
                return;
            }
            deferred.resolve(data);
        });
        return deferred.promise;
    };

    return GenerateAPIFactory(make_call_real);
});

app.controller("SummaryTableController", function ($scope, ckAPI) {
	var forceDataRefresh = false; // Flag to indicate whether we want to refresh the whole table data(advance filter dependency)

	$scope.pageId = window.pageId;
	$scope.perPage = 10;
	$scope.currentPage = 1;
    $scope.pageCount = 1;
    $scope.advancedSearchHidden = true;
    $scope.searchTerm = "";
    $scope.advFilterItems = [];
    $scope.schema = [];
    $scope.advFilterOptions = [];

	var update_data = function (params) {
		params = params ? params : {};
		params['pageNumber'] = $scope.currentPage;
		params['perPage'] = $scope.perPage;
        params['filters_json'] = JSON.stringify(getFilters());
        $scope.loadingPromise = ckAPI.page.get_data($scope.pageId, params).then(function (data) {
            $scope.rows = data.rows;
        });
	};

    $scope.startAdvancedSearch = function() {
        if($scope.advancedSearchHidden) {
            $scope.addConditionButtonClicked ();
            $scope.advancedSearchHidden = false;
        }
    }

    // First load
    $scope.loadingPromise = ckAPI.page.get_colSpec($scope.pageId).then(function (colSpec) {
        $scope.rowCount = colSpec.count;
        $scope.pageCount = colSpec/$scope.perPage;

        $scope.columns = _.map(colSpec.columns, function (val) {
            return _.extend(val, colSpec.schema[val.key]);
        });

        $scope.schema = colSpec.schema;
        $scope.advFilterOptions = _.map(colSpec.schema, function (val, key) {
            return _.extend(val, {id: key});
        });

        update_data ();
    });

    $scope.filterColumnSelected = function (item) {
        var id = item.id;
        var type = $scope.schema[id].type;

        var availableCmp = [];
        var defCmpType; // default comparison type

        if(type === "string") {
            availableCmp = [
                {id:"eq", label:"Equals", inputType: "string"},
                {id:"sw", label:"Starts With", inputType: "string"},
                {id:"ew", label:"Ends With", inputType: "string"},
                {id:"contains", label:"Contains", inputType: "string"}
            ];
            defCmpType = availableCmp[0];
        }
        else if(type === "number") {
            availableCmp = [
                {id:"eq", label:"Equals", inputType: "number"},
                {id:"gt", label:">", inputType: "number"},
                {id:"gte", label:">=",inputType: "number"},
                {id:"lt", label:"<", inputType: "number"},
                {id:"lte", label:"<=", inputType: "number"}
            ];
            defCmpType = availableCmp[0];
        }

        item.availableCmp = availableCmp;
        item.cmp = defCmpType;
    };

    var getFilters = function () {
        var filters = [];

        if($scope.searchTerm !== "") {
            filters.push({
                id: "_ck_all_summary",
                type: "like",
                value: $scope.searchTerm
            })
        }
        for(var i = 0; i < $scope.advFilterItems.length; i ++) {
            var filterItem = $scope.advFilterItems[i];
            filters.push({
                id: filterItem.id,
                type: typeof filterItem.cmp === 'undefined' ? 'null' : filterItem.cmp.id,
                value: filterItem.value
            })
        }

        return filters;
    };

    // Empty the advance filter items array
    var clearAdvFilterItems = function() {
      $scope.advFilterItems = [];
    };

    // Initial state for the advace filter
    var initAdvFilterState = function() {
      $scope.advFilterItems.push ({
          id: 'null',
          type: 'null',
          value: ''
      });
    };

    // Clear the search term input
    var clearSearchTerm = function() {
      $scope.searchTerm = "";
    };

    // Check if entire table refres is needed.
    var needsDataRefresh = function() {
      // Returns true if:
      // `advFilterItems` is the default input box and if the comparator param is `null`
      // OR `searchTerm` is non-empty
      return !($scope.advFilterItems.length === 1 && $scope.advFilterItems[0]['id'] === 'null') || $scope.searchTerm !== '';
    }

    $scope.addConditionButtonClicked = function () {
      initAdvFilterState();
    };

    $scope.filterColumns = function () {
        var params = {
            filters_json: JSON.stringify(getFilters())
        };
        $scope.loadingPromise = ckAPI.page.get_colSpec($scope.pageId, params).then(function (colSpec) {
            $scope.rowCount = colSpec.count;
            $scope.pageCount = colSpec/$scope.perPage;
            update_data ();

            forceDataRefresh = needsDataRefresh();
        });
    };

	$scope.pageChanged = function () {
		update_data ();
	};

	$scope.itemLink = function (row, col) {
		return ckUrl.resetGetParams ({
			action: "page_function",
			func: "edit_item",
			item_id: row[col.primaryColumn],
			page: $scope.pageId
		})
	};

	// Reset advanced search filter and search term.
  $scope.resetAdvSearch = function() {
    clearAdvFilterItems();
    initAdvFilterState();
    clearSearchTerm();

    // Reload the whole table data
    if(forceDataRefresh) {
      $scope.filterColumns();
    }
  }
});

app.controller("CKFormController", function ($scope, ckAPI) {
    $scope.formItems = {};
    $scope.loadingPromise = null;
    $scope.openStatus = {};
    $scope.schema = {};
    var formConfig = {};

    $scope.selectValues = {

    };

    var activate_relationships = function () {
        var relId = formConfig.itemId ? formConfig.itemId : "new";
        if(formConfig.hasRelationships) {
            for(var i = 0; i < formConfig.relationships.length; i++) {
                (function (relItem) {
                    var relKey = "" + relItem.key;

                    // TODO: how will ckloader work with multiple loaders ?
                    $scope.loadingPromise = ckAPI.page.get_foreign(formConfig.pageId,relId, relKey, {}).then(function (data) {
                        if(relItem.type === "manyToOne")
                            $scope.selectValues[relKey] = data.values;
                        else if(relItem.type === "oneToMany")
                            $scope.formItems[relKey] = data.values;
                    });

                })(formConfig.relationships[i]);
            }
        }
    };

    $scope.changedValues = {};
    $scope.extraClasses = {};
    $scope.registerChange = function (key) {
        $scope.changedValues[key] = $scope.formItems[key];
        $scope.extraClasses[key] = "has-change";
    };

    var activate_edit = function () {
        $scope.loadingPromise = ckAPI.page.get_form_values(formConfig.pageId, formConfig.itemId).then(function(data) {
            $scope.schema = data.schema;
            $scope.formItems = ck.converters.standard_to_js(data.schema, data.values);
        });
        activate_relationships();
    };

    var activate_new = function () {
        $scope.loadingPromise = ckAPI.page.get_form_values(formConfig.pageId, "_ck_new").then(function(data) {
            $scope.schema = data.schema;
            $scope.formItems = ck.converters.standard_to_js(data.schema, data.values);
        });
        activate_relationships();
    };

    $scope.$watch('form_id', function(newVal, oldVal) {
        formConfig = window.ckValues[newVal];

        if(formConfig.newItem) {
            activate_new();
        }
        else {
            activate_edit();
        }
    });

    $scope.saveValues = function () {
        var vals = ck.converters.js_to_standard($scope.schema, $scope.changedValues);
        if(formConfig.newItem) {
            $scope.loadingPromise = ckAPI.page.create_item(formConfig.pageId, vals).then(function(data) {
                if(!data.dataValid) {
                    $scope.failedValues = data.failedValues;
                }
            });
        }
        else {
            $scope.loadingPromise = ckAPI.page.set_form_values(formConfig.pageId, formConfig.itemId, vals).then(function(data) {
                if(!data.dataValid) {
                    $scope.failedValues = data.failedValues;
                }
                console.log($scope.failedValues)
            });
        }
    };
});

$(function () {
    // subscribe to push alerts
    ck.flashbag.subscribe("alert", function(items) {
        var alertContainer = $("#alertTarget");
        items.forEach(function (item) {
            // ugh this is disgusting. I know. Sorry.
            var $alert = $("
", {'class':"alert alert-dismissable alert-" + item.extra});
            $alert.append($("<button/>", {
                'class': 'close',
                'text': '×'
            }).attr({
                'data-role': 'close'
            })).append($("
", {
                text: item.message
            }));
            alertContainer.append($alert);
        })
    });

    ck.flashbag.subscribe("log", function(items) {
        items.forEach(function (item) {
            if(item.extra === "json") {
                var obj = JSON.parse(item.message);
                console.log("[SERVER] ", obj);
            }
            else {
                console.log("[SERVER] " + item.message);
            }
        })
    });

    ck.flashbag.add(window.ckValues.flashbag);
})


text:
[jvm]
Content
abstract fun [methods](methods.md)(value: [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[MethodDeclaration](../../-method-declaration/index.md)>): [S](index.md)
open fun [methods](methods.md)(vararg values: [MethodDeclaration](../../-method-declaration/index.md)): [S](index.md)
open fun [methods](methods.md)(value: [MethodDeclaration](../../-method-declaration/index.md)): [S](index.md)
More info

See [ElementsHolder.methods](../methods.md)


text:
import urlparse

from django.conf.urls.defaults import url

from canvas.exceptions import ServiceError

re_slug = lambda name: "(?P<%s>[a-zA-Z0-9_.,-]+)" % name
re_group_slug = lambda name: "(?P<%s>[-a-zA-Z0-9_]+)" % name
re_int = lambda name: "(?P<%s>\d+)" % name

re_year = re_int('year')
re_month = re_year + "/" + re_int("month")
re_day = re_month + "/" + re_int('day')

def url_decorator(urls):
    def decorator(url_regexp, *args, **kwargs):
        def wrapper(fun):
            urls.append(url(url_regexp, fun, *args, **kwargs))
            return fun
        return wrapper
    return decorator

def dynamic_urls():
    """
    Usage Example:
    urls, api = dynamic_urls()
    """
    urls = []
    return urls, url_decorator(urls)

def maybe(regexp):
    return '(%s|)' % regexp

def verify_first_party_url(url):
    """
    Also allows iTunes store URLs.
    """
    if not url or not url.startswith('/'):
        parsed_url = urlparse.urlparse(url)

        try:
            protocol = parsed_url[0]
            domain = parsed_url[1]
        except IndexError:
            raise ServiceError("Invalid share url.")

        if protocol not in ['http', 'https'] or domain not in  ['itunes.apple.com', 'example.com']:
            # Only 1st party redirects, to avoid security holes that 3rd party redirects imply
            raise ServiceError("Invalid share url.")


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Person</title>
<meta name="date" content="2014-01-24">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

model

Class Person

java.lang.Object

model.Person

Direct Known Subclasses:

Administrator, Borrower

public abstract class Person
extends java.lang.Object

The Class Person.

Field Summary

Fields

Modifier and Type
Field and Description

private java.lang.String
id

The id.

private java.lang.String
name

The name.

private java.lang.String
password

The password.

private static java.util.List<Person>
person

The person.

private java.lang.String
type

The type.

Constructor Summary

Constructors

Constructor and Description

Person(java.lang.String name,
      java.lang.String id,
      java.lang.String password)

Instantiates a new person.

Method Summary

Methods

Modifier and Type
Method and Description

static boolean
exist(java.lang.String id)

Exist.

java.lang.String
getId()

Gets the id.

java.lang.String
getName()

Gets the name.

java.lang.String
getPassword()

Gets the password.

static java.util.List<Person>
getPersons()

Gets the persons.

java.lang.String
getType()

Gets the type.

void
setId(java.lang.String id)

Sets the id.

void
setName(java.lang.String name)

Sets the name.

void
setPassword(java.lang.String password)

Sets the password.

protected void
setType(java.lang.String type)

Sets the type.

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

name

private java.lang.String name

The name.

type

private java.lang.String type

The type.

id

private java.lang.String id

The id.

person

private static java.util.List<Person> person

The person.

password

private java.lang.String password

The password.

Constructor Detail

Person

public Person(java.lang.String name,
      java.lang.String id,
      java.lang.String password)
       throws MiniProjectException

Instantiates a new person.

Parameters:

name - the name

id - the id

password - the password

Throws:

MiniProjectException - the invalid parameter exception

Method Detail

exist

public static boolean exist(java.lang.String id)

Exist.

Parameters:

id - the id

Returns:

true, if successful

getPersons

public static java.util.List<Person> getPersons()

Gets the persons.

Returns:

the persons

getId

public java.lang.String getId()

Gets the id.

Returns:

the id

getName

public java.lang.String getName()

Gets the name.

Returns:

the name

getPassword

public java.lang.String getPassword()

Gets the password.

Returns:

the password

getType

public java.lang.String getType()

Gets the type.

Returns:

the type

setId

public void setId(java.lang.String id)

Sets the id.

Parameters:

id - the new id

setName

public void setName(java.lang.String name)

Sets the name.

Parameters:

name - the new name

setPassword

public void setPassword(java.lang.String password)

Sets the password.

Parameters:

password - the new password

setType

protected void setType(java.lang.String type)

Sets the type.

Parameters:

type - the new type

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method