text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml ;
using System.Xml.XPath ;
using System.Data ;
using System.Data.Sql ;
using System.Data.SqlClient ;
using System.Data.SqlTypes ;

namespace alby.codegen.generator
{
	public partial class Program
	{
		static int Main(string[] args)
		{
			int rc = 0 ;
			Console.OutputEncoding = Encoding.UTF8 ;

			Helper h = new Helper() ;
			DateTime start = DateTime.Now;

			h.Message("[CODEGEN START]");
			Program program = new Program(args);

			try
			{
				program.ValidateParameters();
				program.Init();

				if ( program._performAll || program._performReferentialIntegrity )
					 program.DoReferentialIntegrity();

				DatabaseGenerator dbg = new DatabaseGenerator() ;
				dbg.DoDatabase( program );

				if ( program._performAll || program._performTables )
				{
				    TableGenerator tg = new TableGenerator() ;
				    tg.DoTables( program );
				}

				if ( program._performAll || program._performViews )
				{
				    ViewGenerator vg = new ViewGenerator() ;
				    vg.DoViews( program );
				}

				if ( program._performAll || program._performQueries )
				{
				    QueryGenerator qg = new QueryGenerator() ;
				    qg.DoQueries( program ) ;
				}

				if ( program._performAll || program._performStoredProcs )
				     program.DoStoredProcs( program );

				if ( program._performAll || program._performUnitTests )
				{
				    UnitTestGenerator utg = new UnitTestGenerator() ;
				    utg.DoUnitTest( program ) ;
				}
			}
			catch( Exception ex )
			{
				rc = 1 ;
				program.DumpException(ex);
				program.DumpUsage() ;
			}
			finally
			{}

			DateTime finish = DateTime.Now;
			TimeSpan ts = finish - start ;
			h.Message( "[CODEGEN FINISH] [{0}] [{1} secs]", rc, Math.Round( ts.TotalSeconds, 2 ) ) ;
			return rc;
		}

		protected void DumpException( Exception ex )
		{
			Helper h = new Helper() ;

			h.Message("[CODEGEN EXCEPTION]");
			h.Message(ex.Message);
			h.Message(ex.StackTrace);
		}

		protected void DumpUsage()
		{
			Helper h = new Helper() ;

			h.Message("[USAGE]");
			h.Message("alby.codegen.generator.exe [codegen.xml] [--ri --unit-tests --queries --tables --views --storedProcs --verbose]");
		}

		#region state

		// common stuff
		public string[]						_args;
		public string						_codegenFile ;
		public XmlDocument					_codegen = new XmlDocument() ;
		public string						_connectionString ;
		public SqlConnection				_connection ;
		public string						_directory ;
		public string						_namespace;
		public string						_resourceNamespace;
		public string						_concurrencyColumn;
        public string						_databaseName ;
		public List<string>					_prefixObjectsWithSchema ;

		// unit test config
		public string						_unitTestNamespace ;
		public string						_unitTestDirectory ;
		public string						_unitTestTableNamespace ;
		public string						_unitTestTableNamespacePrefix ;

		// query gen stuff
		public string						_querySubDirectory ;
		public XmlNodeList					_queries ;

		// view gen stuff
		public string						_viewSubDirectory;

		// table gen stuff
		public string						_tableSubDirectory;

		// database gen stuff
		public string						_databaseSubDirectory;

		// sp gen stuff
		public string						_storedProcsSubDirectory;

		// referentail integrity stuff
		public ReferentialIntegrityHelper	_rihelper = new ReferentialIntegrityHelper();

		//database information
		public DatabaseInfo					_di = new DatabaseInfo() ;

		// parameters
		public bool							_verbose						= false ;
		public int							_threads						= 1 ;
		public bool							_performAll						= true  ;
		public bool							_performReferentialIntegrity	= false ;
		public bool							_performUnitTests				= false ;
		public bool							_performQueries					= false ;
		public bool							_performTables					= false ;
		public bool							_performViews					= false ;
		public bool							_performStoredProcs				= false ;

		#endregion

		protected Program(string[] args)
		{
			_args = args;
		}

		protected void Init()
		{
			Helper h = new Helper() ;
			Settings settings = new Settings() ;

			_codegenFile = _args[0] ;
			h.MessageVerbose( "Config file [{0}]", _codegenFile ) ;

			// load the xml configuration file
			_codegen.Load( _codegenFile ) ;

			// basic codegen info
			_namespace = _codegen.SelectSingleNode("/CodeGen/Namespace").InnerText;
			h.MessageVerbose("Namespace [{0}]", _namespace);

			_resourceNamespace = _codegen.SelectSingleNode("/CodeGen/ResourceNamespace").InnerText;
			h.MessageVerbose("ResourceNamespace [{0}]", _resourceNamespace);

			_directory = _codegen.SelectSingleNode("/CodeGen/Directory").InnerText;
			h.MessageVerbose("Directory [{0}]", _directory);

			_connectionString = _codegen.SelectSingleNode("/CodeGen/ConnectionString").InnerText ;
			h.MessageVerbose("ConnectionString [{0}]", _connectionString );

			_concurrencyColumn = _codegen.SelectSingleNode("/CodeGen/ConcurrencyColumn").InnerText;
			h.MessageVerbose("ConcurrencyColumn [{0}]", _concurrencyColumn);

			string prefixes = _codegen.SelectSingleNode("/CodeGen/PrefixObjectsWithSchema").InnerText;
			h.MessageVerbose("PrefixObjectsWithSchema [{0}]", prefixes);
			_prefixObjectsWithSchema = new List<string>( prefixes.ToUpper().Split( ',' ) ) ;

			// items related to auto codegened unit test
			_unitTestNamespace = _codegen.SelectSingleNode("/CodeGen/UnitTest/Namespace").InnerText;
			h.MessageVerbose("Unit test namespace [{0}]", _unitTestNamespace);

			_unitTestDirectory = _codegen.SelectSingleNode("/CodeGen/UnitTest/Directory").InnerText;
			h.MessageVerbose("Unit test directory [{0}]", _unitTestDirectory);

			_unitTestTableNamespace = _codegen.SelectSingleNode("/CodeGen/UnitTest/TableNamespace").InnerText;
			h.MessageVerbose("Unit test table namespace [{0}]", _unitTestTableNamespace);

			_unitTestTableNamespacePrefix = _codegen.SelectSingleNode("/CodeGen/UnitTest/TableNamespacePrefix" ).InnerText;
			h.MessageVerbose("Unit test table namespace prefix [{0}]", _unitTestTableNamespacePrefix );

			_threads = settings.Threads ;
			h.MessageVerbose("Threads [{0}]", _threads );

			_tableSubDirectory = _codegen.SelectSingleNode( "/CodeGen/Tables/@SubDirectory"  ).Value;
			h.MessageVerbose("Table subdirectory [{0}]", _tableSubDirectory );

			_viewSubDirectory = _codegen.SelectSingleNode( "/CodeGen/Views/@SubDirectory"   ).Value;
			h.MessageVerbose("View subdirectory [{0}]", _viewSubDirectory );

			_querySubDirectory = _codegen.SelectSingleNode( "/CodeGen/Queries/@SubDirectory" ).Value;
			h.MessageVerbose("Query subdirectory [{0}]", _querySubDirectory );

			_queries = _codegen.SelectNodes( "/CodeGen/Queries/Query" ) ;

			// connect to the database so we can do some code jen !
			_connection = new SqlConnection( _connectionString );
			_connection.Open();

			// get all the database metadata that we may need !
			_di.CreateDatabaseInfo( _connection ) ;

            _databaseName = _di.GetDatabaseName() ;
			h.MessageVerbose("DatabaseName [{0}]", _databaseName );

			DataSetHelper dsh = new DataSetHelper( _di.GetDatabaseInfo() ) ;
			h.MessageVerbose("Database information:\n\n{0}", dsh.ToString() );

			ColumnInfo ci = new ColumnInfo() ;
			ci.CreateColumnInfo( _connection, _di.Tables.Get(), _di.Views.Get(), _directory, _querySubDirectory, _queries ) ;
			h.MessageVerbose("Table, view and query column information:\n\n{0}", ci.ToString() ) ;

			StoredProcedureParameterInfo sppi = new StoredProcedureParameterInfo() ;
			sppi.CreateStoredProcedureInfo( _di ) ;

			StoredProcedureResultsetInfo sprsi = new StoredProcedureResultsetInfo() ;
			sprsi.CreateStoredProcedureInfo( _connection, _di, _codegen, sppi ) ;
			h.MessageVerbose("Stored procedure resultset information:\n\n{0}", sprsi.ToString() ) ;
		}

		protected void ValidateParameters()
		{
			int i = 0;
			foreach (string arg in _args)
			{
				if ( i == 0 )
				{
				    ; // skip xml file name
				}
				else
				if (arg == "--verbose")
				{
					_verbose = true ;
					Helper.__verbose = _verbose ;
				}
				else
				if (arg == "--ri")
				{
				    _performReferentialIntegrity = true ;
				    _performAll					 = false ;
				}
				else
				if (arg == "--unit-tests")
				{
				    _performUnitTests	= true ;
				    _performAll			= false;
				}
				else
				if (arg == "--queries" )
				{
				    _performQueries = true ;
				    _performAll		= false;
				}
				else
				if (arg == "--tables")
				{
				    _performTables	= true ;
				    _performAll		= false;
				}
				else
				if (arg == "--views" )
				{
				    _performViews	= true ;
				    _performAll		= false;
				}
				else
				if (arg == "--storedProcs" )
				{
				    _performStoredProcs	= true ;
				    _performAll			= false;
				}
				else
				    throw new ApplicationException(string.Format("[{0}] unknown parameter.", arg));

				i++ ;
			}

			// unit tests need ri
			if ( _performUnitTests )
				_performReferentialIntegrity = true;
		}

		protected void DoReferentialIntegrity()
		{
			Helper h = new Helper() ;

			h.MessageVerbose("### Determining referential integrity dependancies ###");

			try
			{
				_rihelper.DetermineReferentialIntegrityOrder( _di ) ;
			}
			catch( Exception )
			{
				throw ;
			}
			finally
			{
				_rihelper.DumpInfo();
			}

			h.MessageVerbose("### Determining referential integrity dependancies - done ###");
		}

	}
}


text:
const config = require('../config');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf } = format;

const loggerFormat = printf(info => {
    return `${info.timestamp} | ${info.level}: ${info.message}`;
});

const logger = createLogger({
    level: config.loggerLevel,
    format: combine(
        format.colorize(),
        timestamp(),
        loggerFormat
    ),
    transports: [
        new transports.Console()
    ]
    });

module.exports = logger;

redpajama_set_name: RedPajamaGithub


text:
<md-dialog parse-attr definition>
    <template>

[[header]]

            [[action]]

            <content></content>

    </template>
</md-dialog>


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Histone Demethylases/genetics on My bits</title>
    <link>http://lpantano.github.io/tags/histone-demethylases-genetics/</link>
    <description>Recent content in Histone Demethylases/genetics on My bits</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2018</copyright>
    <lastBuildDate>Fri, 01 Jan 2016 00:00:00 -0500</lastBuildDate>

	<atom:link href="http://lpantano.github.io/tags/histone-demethylases-genetics/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Genomic analyses identify molecular subtypes of pancreatic cancer</title>
      <link>http://lpantano.github.io/publication/bailey-2016/</link>
      <pubDate>Fri, 01 Jan 2016 00:00:00 -0500</pubDate>

      <guid>http://lpantano.github.io/publication/bailey-2016/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
tags: AES OpenSSL encryption C tutorials
date: 2012-08-25 13:30:00
title: How to encrypt a file using AES in 256-bit CBC/CTR mode using OpenSSL in C
---

I've been using [OpenSSL](http://www.openssl.org/docs/crypto/crypto.html) a _LOT_ for work lately and I've learned some interesting stuff.
Here's a quick guide on how to encrypt and decrypt files using [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) in [CBC](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29) or [CTR](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29) mode using 256 bit keys and 128 bits IVs.
To do this, I used the EVP API in OpenSSL, which allows you to easily encrypt a file using any cipher of your liking.

I am assuming some crypto knowledge here, such as block ciphers, modes of operation, keys, IVs, plaintexts, ciphertexts, etc.
There's a great course on Coursera.org on [cryptography](https://www.coursera.org/course/crypto) if you want to learn more about these things.

So, let's get to it! :) Encrypting or decrypting a file using the EVP API in OpenSSL can be done as follows in C:

```c
int aes_encrypt_file(const char * infile, const char * outfile, const void * key, const void * iv, const EVP_CIPHER * cipher, int enc)
{
  assert(cipher != NULL);

  int rc = -1;
  int cipher_block_size = EVP_CIPHER_block_size(cipher);

  assert(cipher_block_size <= BUF_SIZE);

  // The output buffer size needs to be bigger to accomodate incomplete blocks
  // See EVP_EncryptUpdate documentation for explanation:
  //    http://lmgtfy.com/?q=EVP_EncryptUpdate
  int insize = BUF_SIZE;
  int outsize = insize + (cipher_block_size - 1);

  unsigned char inbuf[insize], outbuf[outsize];
  int ofh = -1, ifh = -1;
  int u_len = 0, f_len = 0;

  EVP_CIPHER_CTX ctx;
  EVP_CIPHER_CTX_init(&ctx);

  // Open the input and output files
  rc = AES_ERR_FILE_OPEN;
  if((ifh = open(infile, O_RDONLY)) == -1) {
    fprintf(stderr, "ERROR: Could not open input file %s, errno = %s\n", infile, strerror(errno));
    goto cleanup;
  }

  if((ofh = open(outfile, O_CREAT | O_TRUNC | O_WRONLY, 0644)) == -1) {
    fprintf(stderr, "ERROR: Could not open output file %s, errno = %s\n", outfile, strerror(errno));
    goto cleanup;
  }

  // Initialize the AES cipher for enc/dec
  rc = AES_ERR_CIPHER_INIT;
  if(EVP_CipherInit_ex(&ctx, cipher, NULL, key, iv, enc) == 0) {
    fprintf(stderr, "ERROR: EVP_CipherInit_ex failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
    goto cleanup;
  }

  // Read, pass through the cipher, write.
  int read_size, len;
  while((read_size = read(ifh, inbuf, BUF_SIZE)) > 0)
  {
    dbg("Read %d bytes, passing through CipherUpdate...\n", read_size);
    if(EVP_CipherUpdate(&ctx, outbuf, &len, inbuf, read_size) == 0) {
      rc = AES_ERR_CIPHER_UPDATE;
      fprintf(stderr, "ERROR: EVP_CipherUpdate failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
      goto cleanup;
    }
    dbg("\tGot back %d bytes from CipherUpdate...\n", len);

    dbg("Writing %d bytes to %s...\n", len, outfile);
    if(write(ofh, outbuf, len) != len) {
      rc = AES_ERR_IO;
      fprintf(stderr, "ERROR: Writing to the file %s failed. errno = %s\n", outfile, strerror(errno));
      goto cleanup;
    }
    dbg("\tWrote %d bytes\n", len);

    u_len += len;
  }

  // Check last read succeeded
  if(read_size == -1) {
    rc = AES_ERR_IO;
    fprintf(stderr, "ERROR: Reading from the file %s failed. errno = %s\n", infile, strerror(errno));
    goto cleanup;
  }

  // Finalize encryption/decryption
  rc = AES_ERR_CIPHER_FINAL;
  if(EVP_CipherFinal_ex(&ctx, outbuf, &f_len) == 0) {
    fprintf(stderr, "ERROR: EVP_CipherFinal_ex failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
    goto cleanup;
  }

  dbg("u_len = %d, f_len = %d\n", u_len, f_len);

  // Write the final block, if any
  if(f_len) {
    dbg("Writing final %d bytes to %s...\n", f_len, outfile);
    if(write(ofh, outbuf, f_len) != f_len) {
      rc = AES_ERR_IO;
      fprintf(stderr, "ERROR: Final write to the file %s failed. errno = %s\n", outfile, strerror(errno));
      goto cleanup;
    }
    dbg("\tWrote last %d bytes\n", f_len);
  }

  rc = u_len + f_len;

 cleanup:
  EVP_CIPHER_CTX_cleanup(&ctx);
  if(ifh != -1) close(ifh);
  if(ofh != -1) close(ofh);

  return rc;
}
```

This code is part of a little tool I wrote for fun, while waiting for my laundry in Brooklyn, called CryptoManiac. It depends on a couple of things like:

```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>

#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#define AES_ERR_FILE_OPEN -1
#define AES_ERR_CIPHER_INIT -2
#define AES_ERR_CIPHER_UPDATE -3
#define AES_ERR_CIPHER_FINAL -4
#define AES_ERR_IO -5

#define BUF_SIZE (1024*1024)

#ifdef DEBUG
#define dbg(...) { fprintf(stderr, "   %s: ", __FUNCTION__); \
  fprintf(stderr, __VA_ARGS__); fflush(stderr); }
#else
#define dbg(...)
#endif
```

You can download the full C source code from [Github](https://github.com/alinush/cryptomaniac).

Enjoy!

 > This post used to be at `http://alinush.org/2012/08/25/encrypting-a-file-using-aes-in-256-bit-cbcctr-mode-using-the-openssl-library/`.


text:
'use strict';

const mage = require('../mage');
const logger = mage.core.logger.context('archivist');
const vaultValueLib = require('./vaultValue');
const VaultValue = vaultValueLib.VaultValue;
const configuration = require('./configuration');
const createTrueName = require('rumplestiltskin').trueName;
const async = require('async');
const sizeof = require('object-sizeof');
const memoizee = require('memoizee');

const EventEmitter = require('events').EventEmitter;

const testAggressively = mage.isDevelopmentMode('archivistInspection');

exports = module.exports = new EventEmitter();

exports.VaultValue = VaultValue;

exports.setup = function (cb) {
	vaultValueLib.setup(logger);

	configuration.setup(logger, cb);
};

exports.openVaults = function (cb) {
	configuration.openVaults(logger, cb);
};

exports.listPeerDependencies = function () {
	return {
		'Archivist Couchbase vault': ['couchbase'],
		'Archivist MySQL vault': ['mysql'],
		'Archivist Redis vault': ['redis']
	};
};

// proxy methods

exports.getPersistentVaults = function () {
	return configuration.getPersistentVaults();
};

exports.assertTopicAbilities = function (topic, index, operations) {
	configuration.assertTopicAbilities(topic, index, operations);
};

exports.closeVaults = function () {
	configuration.closeVaults();
};

exports.topicExists = function (topic) {
	return configuration.topicExists(topic);
};

exports.getTopics = function () {
	return configuration.getTopics();
};

exports.getTopicApi = function (topic, vaultName) {
	return configuration.getTopicApi(topic, vaultName);
};

exports.migrateToVersion = function (targetVersion, cb) {
	require('./migration').migrateToVersion(targetVersion, cb);
};

// vault access helpers for the Archivist class
// --------------------------------------------

function attemptListIndexesFromVault(state, vault, topic, partialIndex, options, cb) {
	// 0-length array response indicates non-existence in this vault
	// this may be totally acceptable for volatile caches

	if (!vault.archive.list) {
		return state.error(null, 'List-operations not supported on vault ' + vault.name, cb);
	}

	var topicApi = configuration.getTopicApi(topic, vault.name);
	if (!topicApi) {
		// no API available for this topic on this vault

		logger.verbose('No API available for topic', topic, 'on vault', vault.name);
		return cb();
	}

	// check if there even is an index

	if (!topicApi.index) {
		return state.error(null, 'Cannot list indexes on a topic without an index signature', cb);
	}

	// attempt to get from the vault

	logger.verbose('Attempting to list indexes for topic', topic, 'on vault', vault.name);

	var startTime = process.hrtime();

	vault.archive.list(topicApi, topic, partialIndex, options, function (error, indexes) {
		if (error) {
			exports.emit('vaultError', vault.name, 'list');

			// alert the error and mark state as erroneous
			var context = {
				index: partialIndex,
				operation: 'list',
				topic: topic,
				vault: vault.name
			};

			logger.alert.data(context).log(error);

			return state.error(null, null, cb);
		}

		exports.emit('operation', vault.name, 'list', process.hrtime(startTime));

		// value should be undefined to indicate a valid case of non-existing value

		logger.verbose('Found', indexes.length, 'indexes in vault', vault.name);

		cb(null, indexes);
	});
}

function attemptReadFromVault(state, vault, value, cb) {
	// undefined response indicates non-existence in this vault
	// this may be totally acceptable for volatile caches

	if (!vault.archive.get) {
		return state.error(null, 'Get-operations not supported on vault ' + vault.name, cb);
	}

	var topicApi = configuration.getTopicApi(value.topic, vault.name);
	if (!topicApi) {
		// no API available for this topic on this vault

		logger.verbose('No API available for topic', value.topic, 'on vault', vault.name);
		return cb();
	}

	// attempt to get from the vault

	logger.verbose('Attempting to get', value.topic, 'value from vault', vault.name);

	var startTime = process.hrtime();

	vault.archive.get(topicApi, value, function (error) {
		if (error) {
			exports.emit('vaultError', vault.name, 'get');

			// alert the error and mark state as erroneous
			var context = {
				index: value.index,
				operation: 'get',
				topic: value.topic,
				vault: vault.name
			};

			logger.alert.data(context).log(error);

			return state.error(null, null, cb);
		}

		exports.emit('operation', vault.name, 'get', process.hrtime(startTime));

		// value should be undefined to indicate a valid case of non-existing value

		if (value.data === undefined) {
			logger.verbose(
				'No data found in vault', vault.name, 'for topic', value.topic,
				'with index', value.index
			);

			value.registerReadMiss(vault);

			return cb();
		}

		logger.verbose('MediaType', value.mediaType, 'value found in vault', vault.name);

		cb();
	});
}

function getTopicExpirationTime(topic) {
	const config = configuration.getTopicConfig(topic);
	if (config && config.ttl) {
		return Math.ceil(Date.now() / 1000 + config.ttl);
	}

	return null;
}

// Archivist instances manage access to vaults
// -------------------------------------------

function Archivist(state) {
	this.state = state;
	this.loaded = {};
	this.privateVaults = {};
}

exports.Archivist = Archivist;

Archivist.prototype.reset = function () {
	this.loaded = {};
};

Archivist.prototype.clearCache = function () {
	const keys = Object.keys(this.loaded);

	for (const key of keys) {
		const entry = this.loaded[key];

		if (entry.operation === null) {
			delete this.loaded[key];
		}
	}
};

// createVault allows you to add a vault for just this instance of Archivist

Archivist.prototype.createVault = function (vaultName, vaultType, vaultConfig, cb) {
	var privateVaults = this.privateVaults;

	configuration.createVault(vaultName, vaultType, vaultConfig, function (error, vault) {
		if (error) {
			return cb(error);
		}

		privateVaults[vaultName] = vault;

		cb();
	});
};

Archivist.prototype.getTopicApi = function (topic, vaultName) {
	return configuration.getTopicApi(topic, vaultName);
};

// vault accessors

Archivist.prototype.getPrivateVault = function (name) {
	return this.privateVaults[name];
};

Archivist.prototype.getListVault = function (name) {
	var listOrder = configuration.getListOrder();
	if (listOrder.indexOf(name) !== -1) {
		return this.privateVaults[name] || configuration.getPersistentVault(name);
	}
};

Archivist.prototype.getListVaults = function () {
	var listOrder = configuration.getListOrder();
	var result = [];

	for (var i = 0; i < listOrder.length; i++) {
		var name = listOrder[i];
		var vault = this.privateVaults[name] || configuration.getPersistentVault(name);

		if (vault) {
			result.push(vault);
		}
	}

	return result;
};

Archivist.prototype.getReadVault = function (name) {
	var readOrder = configuration.getReadOrder();
	if (readOrder.indexOf(name) !== -1) {
		return this.privateVaults[name] || configuration.getPersistentVault(name);
	}
};

Archivist.prototype.getReadVaults = function () {
	var readOrder = configuration.getReadOrder();
	var result = [];

	for (var i = 0; i < readOrder.length; i++) {
		var name = readOrder[i];
		var vault = this.privateVaults[name] || configuration.getPersistentVault(name);

		if (vault) {
			result.push(vault);
		}
	}

	return result;
};

Archivist.prototype.getWriteVault = function (name) {
	var writeOrder = configuration.getWriteOrder();
	if (writeOrder.indexOf(name) !== -1) {
		return this.privateVaults[name] || configuration.getPersistentVault(name);
	}
};

Archivist.prototype.getWriteVaults = function () {
	var writeOrder = configuration.getWriteOrder();
	var result = [];

	for (var i = 0; i < writeOrder.length; i++) {
		var name = writeOrder[i];
		var vault = this.privateVaults[name] || configuration.getPersistentVault(name);

		if (vault) {
			result.push(vault);
		}
	}

	return result;
};

// loaded value access

Archivist.prototype._requestVaultValue = function (topic, index) {
	// creates a value if not yet existing in the loaded map

	var trueName = createTrueName(index || {}, topic);
	var value = this.loaded[trueName];

	if (!value) {
		value = new VaultValue(topic, index);

		if (testAggressively) {
			configuration.assertTopicAbilities(value.topic, Object.keys(value.index));
		}

		this.loaded[trueName] = value;
	}

	return value;
};

function applyReadOptions(options, value) {
	logger.verbose(
		'Applying read options', options, 'to value of topic', value.topic, 'and index', value.index
	);

	// if the value was not optional, yet none is set, fail

	if (value.data === undefined) {
		if (options.optional) {
			// there are no options to apply to a non-existing value
			return;
		}

		throw new Error(
			'Value (topic: ' + value.topic + ', index: ' + JSON.stringify(value.index) + ') ' +
			'could not be read and was not optional'
		);
	}

	// make sure the mediaType is what it should be

	if (options.mediaTypes) {
		value.setMediaType(options.mediaTypes);
	}

	// make sure the encoding is what is should be

	if (options.encodings) {
		value.setEncoding(options.encodings);
	}
}

// OPERATION: Exists

Archivist.prototype.exists = function (topic, index, cb) {
	var options = { encodings: null, optional: true };

	this.getValue(topic, index, options, function (error, value) {
		if (error) {
			return cb(error);
		}

		cb(null, value.didExist);
	});
};

// OPERATION: Get

Archivist.prototype.get = function (topic, index, options, cb) {
	if (typeof options === 'function') {
		cb = options;
		options = undefined;
	}

	this.getValue(topic, index, options, function (error, value) {
		if (error) {
			return cb(error);
		}

		cb(null, value.data);
	});
};

// OPERATION: Get (special case: returns a VaultValue)
// Archivist#get depends on this method

Archivist.prototype.getValue = function (topic, index, options, cb) {
	// parameter cleanup

	if (typeof options === 'function') {
		cb = options;
		options = undefined;
	}

	var that = this;
	var state = this.state;
	var value;

	function requestValue() {
		value = that._requestVaultValue(topic, index);
	}

	function load(callback) {
		if (value.didExist !== undefined || value.willExist !== undefined) {
			return setImmediate(callback);
		}

		// load the value from a vault

		var vaults = that.getReadVaults();

		if (vaults.length === 0) {
			var message = `No read vaults found for topic "${topic}"`;
			logger.error
				.details('Make sure to configure the vault backend for this topic, and that')
				.details('this vault backend is listed under "archivist.vault.readOrder"')
				.details('in your configuration')
				.log(message);

			return cb(new Error(message));
		}

		var readOrder = configuration.getReadOrder();
		var vaultNum = 0;

		logger.debug('Getting topic', value.topic, 'from read-vaults:', readOrder);

		return async.whilst(
			function () {
				// while there is a vault to query and data has not been read

				return vaults[vaultNum] && !value.didExist;
			},
			function (callback) {
				attemptReadFromVault(state, vaults[vaultNum++], value, callback);
			},
			function () {
				if (!value.didExist) {
					value.didNotExist();
				}

				return callback();
			}
		);
	}

	function postProcess() {
		applyReadOptions(configuration.getReadOptions(value.topic, options), value);
	}

	function afterLoadHook(callback) {
		var topicConfig = configuration.getTopicConfig(value.topic);

		// check for an afterLoad hook

		if (!topicConfig.afterLoad) {
			return callback();
		}

		// if there's a afterLoad hook, run it now

		logger.debug('Applying afterLoad logic to', value.topic);

		return topicConfig.afterLoad(state, value, callback);
	}

	// request the value

	try {
		requestValue();
	} catch (error) {
		logger.emergency(error);
		return state.error(null, null, cb);
	}

	// load the data (if we don't know whether it exists)

	load(function () {
		// analyze and process the load-result

		try {
			postProcess();
		} catch (error) {
			return state.error(null, error, cb);
		}

		// run after-load hook

		afterLoadHook(function (error, newValue) {
			if (error) {
				return state.error(error.message || error, error, cb);
			}

			// valdidate the new value

			if (newValue) {
				try {
					applyReadOptions(configuration.getReadOptions(newValue.topic, options), newValue);
				} catch (error) {
					return state.error(null, error, cb);
				}
			}

			return cb(null, newValue || value);
		});
	});
};

// multiget helper function

function mgetAggregate(queries, options, retriever, cb) {
	// queries: [{ topic: 'foo', index: { id: 1 } }, { topic: 'bar', index: { id: 'abc' } }]
	//   OR:
	// queries: { uniqueID: { topic: 'foo', index: { id: 1 } }, uniqueID2: { etc }

	const getQueryOptions = (query) => Object.assign({}, options, query.options);

	const arrayQuery = () => async.mapSeries(queries, (query, callback) => {
		retriever(query, getQueryOptions(query), callback);
	}, cb);

	function objectQuery() {
		const queryIds = Object.keys(queries);
		const result = {};

		async.forEachSeries(
			queryIds,
			(queryId, callback) => {
				const query = queries[queryId];

				retriever(query, getQueryOptions(query), function (error, data) {
					result[queryId] = data;
					callback(error);
				});
			},
			(error) => cb(error, error ? null : result)
		);
	}

	if (Array.isArray(queries)) {
		arrayQuery();
	} else if (queries && typeof queries === 'object') {
		objectQuery();
	} else {
		cb(new TypeError('mget queries must be an Array or an Object'));
	}
}

// OPERATION: Multiget

Archivist.prototype.mget = function (queries, options, cb) {
	if (typeof options === 'function') {
		cb = options;
		options = undefined;
	}

	const retriever = (query, queryOptions, callback) => {
		this.get(query.topic, query.index, queryOptions, callback);
	};

	mgetAggregate(queries, options, retriever, cb);
};

// OPERATION: Multiget (special case: returns VaultValues)

Archivist.prototype.mgetValues = function (queries, options, cb) {
	if (typeof options === 'function') {
		cb = options;
		options = undefined;
	}

	const retriever = (query, queryOptions, callback) => {
		this.getValue(query.topic, query.index, queryOptions, callback);
	};

	mgetAggregate(queries, options, retriever, cb);
};

// OPERATION: List

Archivist.prototype.list = function (topic, partialIndex, options, cb) {
	// parameter cleanup

	if (typeof options === 'function') {
		cb = options;
		options = {};
	} else {
		options = options || {};
	}

	var state = this.state;

	try {
		topic = vaultValueLib.parseTopic(topic);
		partialIndex = vaultValueLib.parseIndex(partialIndex);

		if (testAggressively) {
			configuration.assertTopicAbilities(topic, Object.keys(partialIndex), ['list'], true);
		}
	} catch (error) {
		return state.error(null, error, cb);
	}

	// load the indexes from a vault

	var vaults = this.getListVaults();
	var listOrder = configuration.getListOrder();

	logger.debug(
		'Listing', topic, 'indexes with partial index', partialIndex, 'on list-vaults:', listOrder
	);

	var vaultNum = 0;
	var indexes;

	return async.whilst(
		function () {
			// while there is a vault to query and we have not received a response yet

			return vaults[vaultNum] && indexes === undefined;
		},
		function (callback) {
			var vault = vaults[vaultNum++];
			var index = partialIndex;

			attemptListIndexesFromVault(state, vault, topic, index, options, function (error, result) {
				if (error) {
					return callback(error);
				}

				if (result) {
					indexes = result;
				}

				callback();
			});
		},
		function (error) {
			if (error) {
				return cb(error);
			}

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

// OPERATION: scan

Archivist.prototype.scan = function (topic, partialIndex, options, cb) {
	if (!cb) {
		cb = options;
		options = null;
	}

	this.list(topic, partialIndex, options, (error, indexes) => {
		if (error) {
			return cb(error);
		}

		const queries = indexes.map((index) => ({ topic, index }));
		this.mget(queries, options, (error, data) => {
			if (error) {
				return cb(error);
			}

			// Add index to data
			// Eg. [ [{ userId: 1 }, { name: "foo" }], [{ userId: 2 }, { name: "bar" }] ]
			const indexedData = indexes.map((index, i) => {
				return [index, data[i]];
			});

			cb(null, indexedData);
		});
	});
};

// OPERATION: AddToCache

Archivist.prototype.addToCache = function (topic, index, data, mediaType, encoding) {
	// noop value injection
	var value = this._requestVaultValue(topic, index);
	value.setData(mediaType, data, encoding);
	return value;
};

// Topic size tracking
const getSizeConfiguration = memoizee(() => {
	var maxSizes = configuration.getConfiguration().size || {};

	// Default warning of 1Mb

	maxSizes.warning = (maxSizes.warning || 1024) * 1024;

	// No errors by default

	maxSizes.error = maxSizes.error * 1024 || false;

	return maxSizes;
});

function trackSize(topic, index, value) {
	const maxSizes = getSizeConfiguration();

	if (!maxSizes.error && !maxSizes.warning) {
		return;
	}

	const size = sizeof(value.data);

	if (maxSizes.error && size >= maxSizes.error) {
		const message = `${topic} with index ${JSON.stringify(index)} exceeds maximum size of ${maxSizes.error}`;
		throw new Error(message);
	}

	if (maxSizes.warning && size >= maxSizes.warning) {
		logger.warning.data({
			topic: topic,
			index: index,
			byteSize: size,
			maxAllowed: maxSizes.warning
		}).log('Topic value size warning');
	}
}

// OPERATION: Set

Archivist.prototype.set = function (topic, index, data, mediaType, encoding, expirationTime) {
	// both mediaType and encoding are optional, and can be detected

	const value = this._requestVaultValue(topic, index);

	trackSize(topic, index, value);

	value.set(mediaType, data, encoding);

	if (!expirationTime) {
		expirationTime = getTopicExpirationTime(topic);
	}

	value.touch(expirationTime);
};

// OPERATION: Del

Archivist.prototype.del = function (topic, index) {
	this._requestVaultValue(topic, index).del();
};

// OPERATION: Touch

Archivist.prototype.touch = function (topic, index, expirationTime) {
	if (!expirationTime) {
		expirationTime = getTopicExpirationTime(topic);
	}

	this._requestVaultValue(topic, index).touch(expirationTime);
};

// distributing mutations
// ----------------------

function createValueOperator(vault, value) {
	// figure out what operation we should be doing for this vault

	var operation = value.getOperationForVault(vault);
	if (!operation) {
		return;
	}

	// check if this value can be stored in this vault, by pulling out the API for this topic

	var topicApi = configuration.getTopicApi(value.topic, vault.name);
	if (!topicApi) {
		logger.verbose('No topic API for topic', value.topic, 'on vault', vault.name);
		return;
	}

	// get the function that will execute this operation on this vault

	if (typeof vault.archive[operation] !== 'function') {
		throw new Error('Operation ' + operation + ' not supported on vault ' + vault.name);
	}

	// create a function that will execute this operation

	return function (cb) {
		logger.verbose('Running operation', operation, 'for topic', value.topic, 'on vault', vault.name);

		// errors are passed into the 2nd argument of the callback, because mutation operations are best-effort, and an
		// error case should never prevent other mutations from happening.

		try {
			var startTime = process.hrtime();

			vault.archive[operation](topicApi, value, function (error) {
				if (error) {
					var context = {
						index: value.index,
						operation: operation,
						topic: value.topic,
						vault: vault.name
					};

					logger.alert.data(context).log(error);

					exports.emit('vaultError', vault.name, operation);
				} else {
					exports.emit('operation', vault.name, operation, process.hrtime(startTime));
				}

				cb(null, error);
			});
		} catch (error) {
			var context = {
				index: value.index,
				operation: operation,
				topic: value.topic,
				vault: vault.name
			};

			logger.alert.data(context).log(error);

			setImmediate(cb, null, error);
		}
	};
}

function getOperations(vaults, values) {
	var operations = [];
	var trueNames = Object.keys(values);

	for (var i = 0; i < vaults.length; i += 1) {
		for (var j = 0; j < trueNames.length; j += 1) {
			var value = values[trueNames[j]];
			var operation = createValueOperator(vaults[i], value); // throws

			if (operation) {
				operations.push(operation);
			}
		}
	}

	return operations;
}

function preDistribute(state, values, cb) {
	logger.debug('Running beforeDistribute hooks for all value changes');

	var errors = [];
	var syncHooks = [];
	var asyncHooks = [];
	var i, value, topicConfig;

	// split all beforeDistribute hooks into synchronous and asynchronous versions

	var trueNames = Object.keys(values);
	for (i = 0; i < trueNames.length; i += 1) {
		value = values[trueNames[i]];
		if (!value.hasOperation()) {
			continue;
		}

		topicConfig = configuration.getTopicConfig(value.topic);
		if (!topicConfig || typeof topicConfig.beforeDistribute !== 'function') {
			continue;
		}

		switch (topicConfig.beforeDistribute.length) {
		case 2:
			syncHooks.push({ value: value, topicConfig: topicConfig });
			break;
		case 3:
			asyncHooks.push({ value: value, topicConfig: topicConfig });
			break;
		}
	}

	// run all synchronous beforeDistribute hooks and collect errors

	for (i = 0; i < syncHooks.length; i += 1) {
		value = syncHooks[i].value;
		topicConfig = syncHooks[i].topicConfig;

		try {
			topicConfig.beforeDistribute(state, value);
		} catch (error) {
			state.error(error.message || error, error);
			errors.push(error);
		}
	}

	if (asyncHooks.length === 0) {
		return cb(errors.length > 0 ? errors : null);
	}

	// run all asynchronous beforeDistribute hooks and collect errors

	async.eachSeries(
		asyncHooks,
		function (asyncHook, cb) {
			var value = asyncHook.value;
			var topicConfig = asyncHook.topicConfig;

			topicConfig.beforeDistribute(state, value, function (error) {
				if (error) {
					state.error(error.message || error, error);
					errors.push(error);
				}
				cb();
			});
		},
		function () {
			return cb(errors.length > 0 ? errors : null);
		}
	);
}

function distribute(vaults, values, cb) {
	logger.debug('Distributing all value changes');

	var operations;

	try {
		operations = getOperations(vaults, values);
	} catch (error) {
		return setImmediate(cb, [error]);
	}

	async.series(operations, function (_, errors) {
		// the first argument is *never* populated (hence underscored),
		// because we never want the series to abort.

		if (errors) {
			errors = errors.filter(Boolean); // remove all null/undefined entries

			if (errors.length > 0) {
				return cb(errors);
			}
		}

		return cb();
	});
}

function resetOperations(values) {
	var trueNames = Object.keys(values);
	for (var i = 0; i < trueNames.length; i += 1) {
		values[trueNames[i]].resetOperation();
	}
}

Archivist.prototype.distribute = function (options, cb) {
	if (typeof options === 'function') {
		cb = options;
		options = options || {};
	}

	if (options.beforeDistribute === undefined) {
		options.beforeDistribute = true;
	}

	var writeOrder = configuration.getWriteOrder();

	logger.debug('Preparing distribution of value changes to write-vaults:', writeOrder);

	var values = this.loaded;  // contents may change during preDistribute, but the reference cannot change
	var vaults = this.getWriteVaults();

	// preDistribute errors are passed to cb as the first argument
	// distribution errors are passed to cb as the second argument

	var state = this.state;

	async.series([
		function (callback) {
			if (!options.beforeDistribute) {
				return callback();
			}

			preDistribute(state, values, callback);
		}
	], function (errors) {
		if (errors) {
			return cb(errors);
		}

		distribute(vaults, values, function (errors) {
			if (errors) {
				return cb(null, errors);
			}

			resetOperations(values);

			return cb();
		});
	});
};


text:
def factorial(number)
  if number <= 1
    return 1
  else
    result = 1
    (1..number).each {|x| result = result * x}
    return result
  end
end

#Recursive version!

def factorial_recursive(numbers)
  return 1 if numbers <= 1
  numbers * (factorial_recursive(numbers - 1))
end

puts factorial_recursive(5)


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Nest
{
	public partial interface IPutRoleMappingRequest
	{
		[JsonProperty("run_as")]
		IEnumerable<string> RunAs { get; set; }

		[JsonProperty("metadata")]
		IDictionary<string, object> Metadata { get; set; }

		[JsonProperty("enabled")]
		bool Enabled { get; set; }

		[JsonProperty("roles")]
		IEnumerable<string> Roles { get; set; }

		[JsonProperty("rules")]
		RoleMappingRuleBase Rules { get; set; }
	}

	public partial class PutRoleMappingRequest
	{
		public IEnumerable<string> RunAs { get; set; }

		public IDictionary<string, object> Metadata { get; set; }

		public bool Enabled { get; set; }

		public IEnumerable<string> Roles { get; set; }

		public RoleMappingRuleBase Rules { get; set; }
	}

	[DescriptorFor("XpackSecurityPutRoleMapping")]
	public partial class PutRoleMappingDescriptor
	{
		IEnumerable<string> IPutRoleMappingRequest.Roles { get; set; }
		IEnumerable<string> IPutRoleMappingRequest.RunAs { get; set; }
		IDictionary<string, object> IPutRoleMappingRequest.Metadata { get; set; }
		bool IPutRoleMappingRequest.Enabled { get; set; }
		RoleMappingRuleBase IPutRoleMappingRequest.Rules { get; set; }

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Roles(RoleMappingRuleBase rules) => Assign(a => a.Rules = rules);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Roles(IEnumerable<string> roles) => Assign(a => a.Roles = roles);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Roles(params string[] roles) => Assign(a => a.Roles = roles);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Rules(Func<RoleMappingRuleDescriptor, RoleMappingRuleBase> selector) =>
			Assign(a => a.Rules = selector?.Invoke(new RoleMappingRuleDescriptor()));

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Rules(RoleMappingRuleBase rules) => Assign(a => a.Rules = rules);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor RunAs(IEnumerable<string> users) => Assign(a => a.RunAs = users);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor RunAs(params string[] users) => Assign(a => a.RunAs = users);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Enabled(bool enabled = true) => Assign(a => a.Enabled = enabled);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Metadata(IDictionary<string, object> metadata) => Assign(a => a.Metadata = metadata);

		/// <inheritdoc/>
		public PutRoleMappingDescriptor Metadata(Func<FluentDictionary<string, object>, FluentDictionary<string, object>> selector) =>
			Assign(a => a.Metadata = selector?.Invoke(new FluentDictionary<string, object>()));
	}

}


text:
import numpy as np
from numpy.testing import assert_allclose
from nose.tools import raises

from menpo.shape import PointCloud, TriMesh

from menpo.transform import TransformChain, Homogeneous, Translation, Scale
from menpo.transform.thinplatesplines import ThinPlateSplines
from menpo.transform.piecewiseaffine import PiecewiseAffine

def chain_tps_before_tps_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    tps_one = ThinPlateSplines(a, b)
    tps_two = ThinPlateSplines(b, a)
    chain = tps_one.compose_before(tps_two)
    assert(isinstance(chain, TransformChain))
    points = PointCloud(np.random.random([10, 2]))
    chain_res = chain.apply(points)
    manual_res = tps_two.apply(tps_one.apply(points))
    assert (np.all(chain_res.points == manual_res.points))

def chain_tps_after_tps_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    tps_one = ThinPlateSplines(a, b)
    tps_two = ThinPlateSplines(b, a)
    chain = tps_one.compose_after(tps_two)
    assert(isinstance(chain, TransformChain))
    points = PointCloud(np.random.random([10, 2]))
    chain_res = chain.apply(points)
    manual_res = tps_one.apply(tps_two.apply(points))
    assert (np.all(chain_res.points == manual_res.points))

def chain_pwa_before_tps_test():
    a_tm = TriMesh(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    pwa = PiecewiseAffine(a_tm, b)
    tps = ThinPlateSplines(b, a_tm)
    chain = pwa.compose_before(tps)
    assert(isinstance(chain, TransformChain))

def chain_pwa_after_tps_test():
    a_tm = TriMesh(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    pwa = PiecewiseAffine(a_tm, b)
    tps = ThinPlateSplines(b, a_tm)
    chain = pwa.compose_after(tps)
    assert(isinstance(chain, TransformChain))

def chain_tps_before_pwa_test():
    a_tm = TriMesh(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    pwa = PiecewiseAffine(a_tm, b)
    tps = ThinPlateSplines(b, a_tm)
    chain = tps.compose_before(pwa)
    assert(isinstance(chain, TransformChain))

def chain_tps_after_pwa_test():
    a_tm = TriMesh(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    pwa = PiecewiseAffine(a_tm, b)
    tps = ThinPlateSplines(b, a_tm)
    chain = tps.compose_after(pwa)
    assert(isinstance(chain, TransformChain))

def compose_tps_after_translation_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    t = Translation([3, 4])
    tps = ThinPlateSplines(a, b)
    chain = tps.compose_after(t)
    assert(isinstance(chain, TransformChain))

def manual_no_op_chain_test():
    points = PointCloud(np.random.random([10, 2]))
    t = Translation([3, 4])
    chain = TransformChain([t, t.pseudoinverse])
    points_applied = chain.apply(points)
    assert(np.allclose(points_applied.points, points.points))

def chain_compose_before_tps_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    tps = ThinPlateSplines(a, b)

    t = Translation([3, 4])
    s = Scale([4, 2])
    chain = TransformChain([t, s])
    chain_mod = chain.compose_before(tps)

    points = PointCloud(np.random.random([10, 2]))

    manual_res = tps.apply(s.apply(t.apply(points)))
    chain_res = chain_mod.apply(points)
    assert(np.all(manual_res.points == chain_res.points))

def chain_compose_after_tps_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    tps = ThinPlateSplines(a, b)

    t = Translation([3, 4])
    s = Scale([4, 2])
    chain = TransformChain([t, s])
    chain_mod = chain.compose_after(tps)

    points = PointCloud(np.random.random([10, 2]))

    manual_res = s.apply(t.apply(tps.apply(points)))
    chain_res = chain_mod.apply(points)
    assert(np.all(manual_res.points == chain_res.points))

def chain_compose_before_inplace_tps_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    tps = ThinPlateSplines(a, b)

    t = Translation([3, 4])
    s = Scale([4, 2])
    chain = TransformChain([t, s])
    chain.compose_before_inplace(tps)

    points = PointCloud(np.random.random([10, 2]))

    manual_res = tps.apply(s.apply(t.apply(points)))
    chain_res = chain.apply(points)
    assert(np.all(manual_res.points == chain_res.points))

def chain_compose_after_inplace_tps_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))
    tps = ThinPlateSplines(a, b)

    t = Translation([3, 4])
    s = Scale([4, 2])
    chain = TransformChain([t, s])
    chain.compose_after_inplace(tps)

    points = PointCloud(np.random.random([10, 2]))

    manual_res = s.apply(t.apply(tps.apply(points)))
    chain_res = chain.apply(points)
    assert(np.all(manual_res.points == chain_res.points))

def chain_compose_after_inplace_chain_test():
    a = PointCloud(np.random.random([10, 2]))
    b = PointCloud(np.random.random([10, 2]))

    t = Translation([3, 4])
    s = Scale([4, 2])
    chain_1 = TransformChain([t, s])
    chain_2 = TransformChain([s.pseudoinverse, t.pseudoinverse])
    chain_1.compose_before_inplace(chain_2)

    points = PointCloud(np.random.random([10, 2]))
    chain_res = chain_1.apply(points)
    assert(np.allclose(points.points, chain_res.points))


text:
{% extends "sentry/layout.html" %}

{% load i18n %}
{% load sentry_helpers %}

{% block title %}{{ project.name }} | {{ block.super }}{% endblock %}

{% block bodyclass %}{% endblock %}

{% block main %}

{% trans "Getting Started" %}

		{% client_help request.user project %}

{% endblock %}


text:
function ctf_write_headshape(HeadShape,mri,file)

% ctf_write_headshape - write a CTF .shape file
%
% ctf_write_headshape(HeadShape,mri,file)
%
% - HeadShape is Nx3 list of coordinates in the CTF head shape coordinates.
% - mri is a struct returned by ctf_read_mri; if it is empty, this function
% will prompt with a file browser and read in the file identified.  The mri
% struct contains the mri.file field, which is used to define the name of
% the .shape and the .shape_info output files (unless the optional 'file'
% input is given).  Also, the fiducials and other information in this
% struct are required to output the .shape_info file.  The .shape and
% .shape_info files are required to import the data into CTF's MRIViewer.
%
% The *.shape file is an ascii text file in the following format:
%
% Number of Points
% x1 y1 z1
% x2 y2 z2
% .
% .
% .
% xn yn zn
%
% These vertex coordinates are contained in the input HeadShape
% matrix (Nx3).  The coordinate values must be in centimeters in
% either the voxel MRI coordinate system or the MEG Head Coordinate
% System (see ctf_read_mri for more about the coordinate system).
%
% This function assumes the MEG head coordinate system is required.
% The values in the input HeadShape matrix (Nx3) should be in
% centimeteres, with the column values representing X, Y, Z, such
% that +X is toward the nasion, +Y is left preauricular and +Z is
% superior.  The values are given with respect to the origin, which
% lies half way between the left and right preauricular fiducials.  It is
% essential that the fiducials are defined and saved in the .mri file for
% this function to operate correctly.
%
% see also ctf_write_mrishape ctf_read_mri ctf_mri2head ctf_head2mri
%

% $Revision: 1.1 $ $Date: 2009-01-30 03:49:27 $

% Copyright (C) 2004  Darren L. Weber
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

% History:  02/2004, Darren.Weber_at_radiology.ucsf.edu
%                    - adapted from an appendex to CTF document
%                    MRIViewer.pdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ver = '[$Revision: 1.1 $]';
fprintf('CTF_WRITE_HEADSHAPE [v%s]\n',ver(12:16));  tic;

%--------------------------------------------------
% check the mri input variable

if exist('mri','var'),
  if isfield(mri,'file'),
    % great!
  else
    fprintf('...cannot find mri.file\n');
    [fileName, filePath] = uigetfile('*.mri', 'Pick a CTF .mri file');
    mri.file = fullfile(filePath,fileName);
    mri = ctf_read_mri(mri.file);
  end
else
  [fileName, filePath] = uigetfile('*.mri', 'Pick a CTF .mri file');
  mri.file = fullfile(filePath,fileName);
  mri = ctf_read_mri(mri.file);
end

if exist('file','var'),
    shapeFile = file;
else
    shapeFile = [mri.file,'.head.shape'];
end
shapeInfoFile = [shapeFile,'_info'];

%--------------------------------------------------
% output the .shape file

fid = fopen(shapeFile,'w');

if isequal(fid,-1),
    S=sprintf('Could not open file: "%s"',shapeFile);
    error(S);
else

    fprintf('...writing to file:\n   %s\n',shapeFile);
    fprintf('...writing CTF .shape file, with head coordinates\n');
    tic;

    % Write vertices
    Nvertices = size(HeadShape,1);
    fprintf(fid,'%d\n',Nvertices);

    for v = 1:Nvertices,
      fprintf(fid,'%6.3f %6.3f %6.3f\n',HeadShape(v,1),HeadShape(v,2),HeadShape(v,3));
    end

    fclose(fid);

    t = toc;
    fprintf('...done (%6.2f sec).\n',t);

end

%--------------------------------------------------
% output the .shape_info file

fid = fopen(shapeInfoFile,'w');

if isequal(fid,-1),
    S=sprintf('Could not open file: "%s"',shapeInfoFile);
    error(S);
else

  fprintf('...writing to file:\n   %s\n',shapeInfoFile);
  fprintf('...writing CTF .shape_info file, with head coordinates\n');
  tic;

  [mriFilePath,mriFileName,mriFileExt] = fileparts(mri.file);

  nasion = [ mri.hdr.HeadModel_Info.Nasion_Sag,   mri.hdr.HeadModel_Info.Nasion_Cor,   mri.hdr.HeadModel_Info.Nasion_Axi ];
  left   = [ mri.hdr.HeadModel_Info.LeftEar_Sag,  mri.hdr.HeadModel_Info.LeftEar_Cor,  mri.hdr.HeadModel_Info.LeftEar_Axi ];
  right  = [ mri.hdr.HeadModel_Info.RightEar_Sag, mri.hdr.HeadModel_Info.RightEar_Cor, mri.hdr.HeadModel_Info.RightEar_Axi ];

  fprintf(fid,'// *************************************\n');
  fprintf(fid,'// 	 Headshape File Information \n');
  fprintf(fid,'// *************************************\n');
  fprintf(fid,'\n');
  fprintf(fid,'MRI_Info\n');
  fprintf(fid,'{\n');
  fprintf(fid,'	VERSION:	1.00\n');
  fprintf(fid,'\n');
  fprintf(fid,'	FILENAME:	%s\n',[mriFileName,mriFileExt]);
  fprintf(fid,'\n');
  fprintf(fid,'	// Fid. Points	Sag	Cor	Axi\n');
  fprintf(fid,'	NASION:\t\t\t%5.1f %5.1f %5.1f\n',nasion(1),nasion(2),nasion(3));
  fprintf(fid,'	LEFT_EAR:\t\t%5.1f %5.1f %5.1f\n',left(1),left(2),left(3));
  fprintf(fid,'	RIGHT_EAR:\t%5.1f %5.1f %5.1f\n',right(1),right(2),right(3));
  fprintf(fid,'\n');
  fprintf(fid,'	MM_PER_VOXEL_SAGITTAL:\t\t%10.8f\n', mri.hdr.mmPerPixel_sagittal);
  fprintf(fid,'	MM_PER_VOXEL_CORONAL:\t\t%10.8f\n',  mri.hdr.mmPerPixel_coronal);
  fprintf(fid,'	MM_PER_VOXEL_AXIAL:\t\t\t%10.8f\n',  mri.hdr.mmPerPixel_axial);
  fprintf(fid,'\n');
  fprintf(fid,'	COORDINATES:	HEAD\n');
  fprintf(fid,'\n');
  fprintf(fid,'}\n');

  fclose(fid);

  t = toc;
  fprintf('...done (%6.2f sec).\n\n',t);

end

return

%// *************************************
%//       Headshape File Information
%// *************************************
%
%MRI_Info
%{
%        VERSION:        1.00
%
%        FILENAME:       ucsf_mh_orig_axial_las2ctf.mri
%
%        // Fid. Points          Sag     Cor     Axi
%        NASION:                 128.0   35.0    130.0
%        LEFT_EAR:               53.0    123.0   152.0
%        RIGHT_EAR:              207.0   123.0   152.0
%
%        MM_PER_VOXEL_SAGITTAL:          1.00000000
%        MM_PER_VOXEL_CORONAL:           1.00000000
%        MM_PER_VOXEL_AXIAL:             1.00000000
%
%        COORDINATES:    MRI
%
%}


text:
PanelConfig::PanelConfig()
{
	name = "Configuration";
	active = true;

	//Load Hardware and software info
	///Dummy importers to get the version number
	TextureImporter dummy_tex;
	MeshImporter dummy_mesh;

	dummy_mesh.GetAssimpVersion(assimp_major, assimp_minor, assimp_revision);
	devil_version = dummy_tex.GetDevilVersion();

	cpu_cores = SDL_GetCPUCount();
	cpu_cache_size = SDL_GetCPUCacheLineSize();
	ram = ((float)SDL_GetSystemRAM() / 1024.0f);
	has_3Dnow = SDL_Has3DNow() == SDL_TRUE;
	has_AVX = SDL_HasAVX() == SDL_TRUE;
	has_AVX2 = SDL_HasAVX2() == SDL_TRUE;
	has_AltiVec = SDL_HasAltiVec() == SDL_TRUE;
	has_MMX = SDL_HasMMX() == SDL_TRUE;
	has_RDTSC = SDL_HasRDTSC() == SDL_TRUE;
	has_SSE = SDL_HasSSE() == SDL_TRUE;
	has_SSE2 = SDL_HasSSE2() == SDL_TRUE;
	has_SSE3 = SDL_HasSSE3() == SDL_TRUE;
	has_SSE41 = SDL_HasSSE41() == SDL_TRUE;
	has_SSE42 = SDL_HasSSE42() == SDL_TRUE;
}

PanelConfig::~PanelConfig()
{
}

void PanelConfig::Draw()
{
	ImGui::Begin("Configuration", &active, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize);
	ImGui::SetWindowPos(ImVec2((float)App->window->width - 250, (float)App->window->height * 2 / 5 + 19), 0);
	ImGui::SetWindowSize(ImVec2((float)250, (float)App->window->height * 3 / 5 - 19), 0);

	DrawAppConfig();

	module_list = App->GetModulesList();
	std::list<Module*>::const_iterator item = module_list->begin();
	while (item != module_list->end())
	{
		if (ImGui::CollapsingHeader(item._Ptr->_Myval->GetName()))
		{
			item._Ptr->_Myval->DrawConfig();
		}
		item++;
	}
	DrawHardware();
	ImGui::End();
}

void PanelConfig::DrawAppConfig()
{
	if (ImGui::CollapsingHeader("Application"))
	{
		if (ImGui::InputText("App name", str_name, (int)sizeof(str_name), ImGuiInputTextFlags_EnterReturnsTrue))
			App->window->SetTitle(str_name);

		ImGui::InputText("Organitzation", str_org, (int)sizeof(str_org));

		if (ImGui::Checkbox("Unlimited", &uncapped_fps)) App->SetFpsCap(uncapped_fps);
		if (ImGui::SliderInt("Max FPS", &App->fps, 15, 120)) App->SetFpsCap(uncapped_fps);

		ImGui::PlotHistogram("Framerate", &App->GetFPS()->front(), App->GetFPS()->size(), 0, NULL, 0.0f, 120.0f, ImVec2(0, 80));
		ImGui::PlotHistogram("Miliseconds", &App->GetMs()->front(), App->GetMs()->size(), 0, NULL, 0.0f, 50.0f, ImVec2(0, 80));

		sMStats mem_stats = m_getMemoryStatistics();
		ImGui::Text("Total Reported Mem: %u", mem_stats.totalReportedMemory);
		ImGui::Text("Total Actual Mem: %u", mem_stats.totalActualMemory);
		ImGui::Text("Peak Reported Mem: %u", mem_stats.peakReportedMemory);
		ImGui::Text("Peak Actual Mem: %u", mem_stats.peakActualMemory);
		ImGui::Text("Accumulated Reported Mem: %u", mem_stats.accumulatedReportedMemory);
		ImGui::Text("Accumulated Actual Mem: %u", mem_stats.accumulatedActualMemory);
		ImGui::Text("Accumulated Alloc Unit Count: %u", mem_stats.accumulatedAllocUnitCount);
		ImGui::Text("Total Alloc Unit Count: %u", mem_stats.totalAllocUnitCount);
		ImGui::Text("Peak Alloc Unit Count: %u", mem_stats.peakAllocUnitCount);

	}
}

void PanelConfig::DrawHardware()
{

	if (ImGui::CollapsingHeader("Hardware & software"))
	{
		ImVec4	cyan(0.0f, 1.0f, 1.0f, 1.0f);

		//SDL info--------------
		ImGui::Text("SDL version: %i.%i.%i", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL);

		//Assimp info-----------
		ImGui::Text("Assimp version: %i.%i.%i", assimp_major, assimp_minor, assimp_revision);

		//Devil info
		ImGui::Text("Devil version: %i", devil_version);

		ImGui::Separator();
		//CPU info--------------
		ImGui::Text("CPU: "); ImGui::SameLine();
		ImGui::TextColored(cyan, "%i cores", SDL_GetCPUCount());  ImGui::SameLine();
		ImGui::TextColored(cyan, "(cache: %i bytes)", SDL_GetCPUCacheLineSize());

		ImGui::Text("System RAM: "); ImGui::SameLine();
		ImGui::TextColored(cyan, "%0.1f Gb", ((float)SDL_GetSystemRAM() / 1024.0f));

		ImGui::Separator();
		//CPU info--------------
		ImGui::Text("CPU: "); ImGui::SameLine();
		ImGui::TextColored(cyan, "%i cores", SDL_GetCPUCount());  ImGui::SameLine();
		ImGui::TextColored(cyan, "(cache: %i bytes)", SDL_GetCPUCacheLineSize());
		ImGui::Text("System RAM: "); ImGui::SameLine();
		ImGui::TextColored(cyan, "%0.1f Gb", ((float)SDL_GetSystemRAM() / 1024.0f));

		ImGui::Text("Caps: "); ImGui::SameLine();
		if (has_3Dnow)		ImGui::TextColored(cyan, "3DNow!, ");	ImGui::SameLine();
		if (has_AVX)		ImGui::TextColored(cyan, "AVX, ");		ImGui::SameLine();
		if (has_AVX2)		ImGui::TextColored(cyan, "AVX2, ");		ImGui::SameLine();
		if (has_AltiVec)	ImGui::TextColored(cyan, "AltiVec, ");	ImGui::SameLine();
		if (has_MMX)		ImGui::TextColored(cyan, "MMX, ");		ImGui::SameLine();
		if (has_RDTSC)		ImGui::TextColored(cyan, "RDTSC, ");	ImGui::SameLine();
		if (has_SSE)		ImGui::TextColored(cyan, "SSE, ");		ImGui::SameLine();
		if (has_SSE2)		ImGui::TextColored(cyan, "SSE2, ");		ImGui::SameLine();
		if (has_SSE3)		ImGui::TextColored(cyan, "SSE3, ");		ImGui::SameLine();
		if (has_SSE41)		ImGui::TextColored(cyan, "SSE41, ");	ImGui::SameLine();
		if (has_SSE42)		ImGui::TextColored(cyan, "SSE42, ");	ImGui::Separator();

		//GPU info-------------
		ImGui::Text("Vendor: "); ImGui::SameLine();
		ImGui::Text((const char*)glGetString(GL_VENDOR));

		ImGui::Text("Brand: "); ImGui::SameLine();
		ImGui::Text((const char*)glGetString(GL_RENDERER));

		ImGui::Text("OpenGL Supported: "); ImGui::SameLine();
		ImGui::Text((const char*)glGetString(GL_VERSION));
	}

}


text: Detect if two integers have opposite signs


text:
package com.salama.service.core.net.http;

import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import com.salama.service.core.net.SessionWrapper;

/**
 *
 * @author XingGu Liu
 *
 */
public class HttpSessionWrapper implements SessionWrapper {
	private HttpSession _session = null;

	public HttpSessionWrapper(HttpSession session) {
		_session = session;
	}

	@Override
	  public long getCreationTime() {
		  return _session.getCreationTime();
	  }

	@Override
	  public String getId() {
		  return _session.getId();
	  }

	@Override
	  public long getLastAccessedTime() {
		  return _session.getLastAccessedTime();
	  }

	@Override
	  public ServletContext getServletContext() {
		  return _session.getServletContext();
	  }

	@Override
	  public void setMaxInactiveInterval(int interval) {
		  _session.setMaxInactiveInterval(interval);
	  }

	@Override
	  public int getMaxInactiveInterval() {
		  return _session.getMaxInactiveInterval();
	  }

	@Override
	  public Object getAttribute(String name) {
		  return _session.getAttribute(name);
	  }

	@Override
	  public Enumeration<String> getAttributeNames() {
		  return _session.getAttributeNames();
	  }

	@Override
	  public void setAttribute(String name, Object value) {
		  _session.setAttribute(name, value);
	  }

	@Override
	  public void removeAttribute(java.lang.String name) {
		  _session.removeAttribute(name);
	  }

	@Override
	  public void invalidate() {
		  _session.invalidate();
	  }

	@Override
	  public boolean isNew() {
		  return _session.isNew();
	  }

}


text:
<?php
// src/Aslan/AdminBundle/Form/Type/PageType.php
namespace Aslan\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ImageType extends AbstractType {
	public function buildForm(FormBuilder $builder, array $options) {
		$builder->add('src', 'file');
		$builder->add('href', 'url');
	}
	public function getName() {
		return 'names';
	}
}


text:
package org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.model;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.AbstractExpectedSQLSegment;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.column.ExpectedColumn;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.orderby.ExpectedOrderByClause;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.dml.SelectStatementTestCase;

import javax.xml.bind.annotation.XmlElement;
import java.util.LinkedList;
import java.util.List;

/**
 * Expected model clause.
 */
@Getter
@Setter
public final class ExpectedModelClause extends AbstractExpectedSQLSegment {

    @XmlElement(name = "reference-model-select")
    private final List<SelectStatementTestCase> referenceModelSelect = new LinkedList<>();

    @XmlElement(name = "order-by")
    private final List<ExpectedOrderByClause> orderBySegments = new LinkedList<>();

    @XmlElement(name = "cell-assignment-column")
    private final List<ExpectedColumn> cellAssignmentColumns = new LinkedList<>();

    @XmlElement(name = "cell-assignment-select")
    private final List<SelectStatementTestCase> cellAssignmentSelect = new LinkedList<>();
}


text:
package org.apache.flink.graph.library;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.Vertex;
import org.apache.flink.test.testdata.ConnectedComponentsData;
import org.apache.flink.test.util.JavaProgramTestBase;
import org.apache.flink.types.NullValue;

import java.io.BufferedReader;

/**
 * Test {@link ConnectedComponents} with a randomly generated graph.
 */
@SuppressWarnings("serial")
public class ConnectedComponentsWithRandomisedEdgesITCase extends JavaProgramTestBase {

	private static final long SEED = 9487520347802987L;

	private static final int NUM_VERTICES = 1000;

	private static final int NUM_EDGES = 10000;

	private String resultPath;

	@Override
	protected void preSubmit() throws Exception {
		resultPath = getTempFilePath("results");
	}

	@Override
	protected void testProgram() throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
		DataSet<Long> vertexIds = env.generateSequence(1, NUM_VERTICES);
		DataSet<String> edgeString = env.fromElements(ConnectedComponentsData.getRandomOddEvenEdges(NUM_EDGES, NUM_VERTICES, SEED).split("\n"));

		DataSet<Edge<Long, NullValue>> edges = edgeString.map(new EdgeParser());

		DataSet<Vertex<Long, Long>> initialVertices = vertexIds.map(new IdAssigner());

		Graph<Long, Long, NullValue> graph = Graph.fromDataSet(initialVertices, edges, env);

		DataSet<Vertex<Long, Long>> result = graph.run(new ConnectedComponents<>(100));

		result.writeAsCsv(resultPath, "\n", " ");
		env.execute();
	}

	/**
	 * A map function that takes a Long value and creates a 2-tuple out of it:
	 * <pre>(Long value) -> (value, value)</pre>.
	 */
	public static final class IdAssigner implements MapFunction<Long, Vertex<Long, Long>> {
		@Override
		public Vertex<Long, Long> map(Long value) {
			return new Vertex<>(value, value);
		}
	}

	@Override
	protected void postSubmit() throws Exception {
		for (BufferedReader reader : getResultReader(resultPath)) {
			ConnectedComponentsData.checkOddEvenResult(reader);
		}
	}

	private static final class EdgeParser extends RichMapFunction<String, Edge<Long, NullValue>> {
		public Edge<Long, NullValue> map(String value) {
			String[] nums = value.split(" ");
			return new Edge<>(Long.parseLong(nums[0]), Long.parseLong(nums[1]),
					NullValue.getInstance());
		}
	}
}


text:
import React from 'react';

export default class LabelColors extends React.Component {

  render() {
    return (

            Red
            Blue
            Green
            Yellow
            Orange
            White

    );
  }

}


text: Nearby Arts


text:
//
//  StartScene.cpp
//  flappybird_cocos2dx_2
//
//  Created by zlh on 11/28/15.
//
//

#include "StartScene.hpp"
#include "BirdSprite.hpp"

#include "Game.hpp"

bool StartScene::init()
{
    if (!BaseScene::init())
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();

    /*************initialize the game label****************/
    mGameLabel = Label::createWithTTF("Flappy Bird", "fonts/Marker_Felt.ttf", 35);
    mGameLabel->setPosition(Vec2(visibleSize.width * 0.5, visibleSize.height * 0.5));
    mGameLabel->enableOutline(Color4B::BLACK, 2);
    this->getRootLayer()->addChild(mGameLabel);
    /*************initialize the game label****************/

    /*************initialize the BirdSprite****************/
    mBirdSprite = BirdSprite::create();
    mBirdSprite->setPosition(Vec2(visibleSize.width * 0.5 - 20, visibleSize.height * 0.5 + 80));
    this->getRootLayer()->addChild(mBirdSprite);
    /*************initialize the BirdSprite****************/

    /*************initialize the menu item****************/
    mGoToPlaySceneItem =  MenuItemImage::create(
                          "assets/replay.png",
                          "assets/replay.png",
                          CC_CALLBACK_1(StartScene::goToPlaySceneCallback, this));
    mGoToPlaySceneItem->setPosition(Vec2(visibleSize.width * 0.5, visibleSize.height * 0.5 - 80));

    auto menu = Menu::create(mGoToPlaySceneItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->getRootLayer()->addChild(menu);
    /*************initialize the menu item****************/

    return true;
}

void StartScene::goToPlaySceneCallback(Ref *pSender)
{
    StartScene * scene = (StartScene *)((MenuItemImage *)pSender)->getScene();
    scene->getGame()->goToPlayScene(pSender);
}


text:
package com.test.jflyfox.db;

import com.jflyfox.autocreate.db.Column;
import com.jflyfox.autocreate.db.Table;
import com.jflyfox.autocreate.db.TableFactory;
import com.jflyfox.autocreate.util.DbUtils;

public class TestDB {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		DbUtils.init();

		TableFactory tbFactory = TableFactory.getInstance();
		// System.out.println(tbFactory.getAllTables());
		Table t = tbFactory.getTable("report_app_advert");
		System.out.println(t.toString());
		String tmp;
		for (Column col : t.getColumns()) {
			tmp = "@Column(name = \"" + col.getColumnName() + "\")";
			System.out.println(tmp);
			System.out.println("private " + col.getJavaType().replace("java.lang.", "") + " " + col.getColumnName() +";");
			System.out.println();

		}
	}

}


text:
package org.mitre.provenance.plusobject;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * A web URL with a name.
 * @author moxious
 */
public class PLUSURL extends PLUSString {
	protected URL url;
	public static final String PLUS_SUBTYPE_URL = "URL";

	public PLUSURL() {
		super();
	}

	public PLUSURL(String name, String urlLocation) {
		super(name);
		setContent(urlLocation);
		setObjectType(PLUS_TYPE_DATA);
		setObjectSubtype(PLUS_SUBTYPE_URL);
	}

	public PLUSURL(String urlLocation) {
		super(urlLocation);
		setContent(urlLocation);
		setObjectType(PLUS_TYPE_DATA);
		setObjectSubtype(PLUS_SUBTYPE_URL);
	}

	public PLUSString clone() {
		PLUSURL s = new PLUSURL();
		s.copy(this);
		return s;
	}

	public URL getURL() throws MalformedURLException {
		url = new URL(content);
		return url;
	}

	public void copy(PLUSString other) {
		super.copy(other);
		setContent(other.getContent());
		setObjectType(PLUS_TYPE_DATA);
		setObjectSubtype(PLUS_SUBTYPE_URL);
	} // End copy

	public String getContent() { return content; }
	public void setContent(String content) { this.content = content; }
} // End PLUSURL


text:
namespace Math
{
	template <typename T>
	class Line_T
	{
	public:
		typedef T value_type;

		typedef value_type*			pointer;
		typedef value_type const *	const_pointer;

		typedef value_type&			reference;
		typedef value_type const &	const_reference;

		typedef value_type*			iterator;
		typedef value_type const *	const_iterator;

		Vector3<T> origin;
		Vector3<T> dir;

		Line_T()
		{
		}

		Line_T(const Vector3<T>& origin, const Vector3<T>& dir)
			: origin(origin), dir(dir)
		{
		}

		const std::string ToString() const
		{
			std::stringstream ss;
			ss << "[";
			ss << origin << ", " << dir;
			ss << "]";
			return ss.str();
		}

		friend std::ostream & operator<<(std::ostream & os, const Line_T<T> & v)
		{
			os << v.ToString();
			return os;
		}
	};

	template <typename T>
	class Ray_T : public Line_T<T>
	{
	public:
		typedef T value_type;

		typedef value_type*			pointer;
		typedef value_type const *	const_pointer;

		typedef value_type&			reference;
		typedef value_type const &	const_reference;

		typedef value_type*			iterator;
		typedef value_type const *	const_iterator;

		using Line_T<T>::Line_T;
		Ray_T() {}

		Ray_T(const Line_T<T>& line)
			: Line_T<T>(line)
		{
		}
	};

	using Ray = Ray_T<floating_point>;
	using Line = Line_T<floating_point>;

	template <typename T>
	Ray_T<T> Transform(const Matrix<T, 4, 4>& mat, const Ray_T<T>& ray)
	{
		return Ray_T<T>(TransformCoord(mat, ray.origin), TransformDirection(mat, ray.dir));
	}

	template <typename T>
	Ray_T<T> Transform(const Quaternion_T<T>& q, const Ray_T<T>& ray)
	{
		return Ray_T<T>(Transform(q, ray.origin), Transform(q, ray));
	}
}

#endif


text:
layout: page
title: Flynn - Dennis Wedding
date: 2016-05-24
author: Frank Glenn
tags: weekly links, java
status: published
summary: Donec sollicitudin sapien ornare venenatis luctus. Proin luctus, eros.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 07/25/2017
  endDate: 07/29/2017
  ctyhocn: UNTPAHX
  groupCode: FDW
published: true
---
Aenean vel gravida enim. Nullam felis mauris, cursus vel porta non, ullamcorper sit amet justo. Donec auctor arcu sem, in aliquam dui blandit eu. Etiam auctor pellentesque tellus non auctor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas quis magna egestas, efficitur orci nec, luctus magna. Aliquam neque tortor, vehicula ut ligula vel, facilisis hendrerit magna.

* Vestibulum in nulla feugiat, sollicitudin quam eu, commodo orci
* Donec gravida mi et est auctor, in pretium quam bibendum
* Nulla et enim vestibulum nisi ullamcorper lacinia
* Pellentesque quis dolor mollis, dapibus metus a, semper leo.

Cras ut libero a justo cursus semper quis id diam. Vestibulum rhoncus nibh sit amet pharetra cursus. Nullam quis dictum dolor, eu molestie enim. Donec a volutpat elit. Nam congue vehicula risus in tristique. Aenean hendrerit leo imperdiet gravida lacinia. Etiam non ultricies nisi. Fusce eget odio vitae nisi ultricies ullamcorper. Proin sed tempus nisl, sit amet cursus ante. Cras maximus risus sed porta feugiat. Fusce fermentum neque et dictum facilisis. Nulla eget faucibus enim, in vulputate purus.
Nunc vulputate tellus quis pretium sagittis. Donec iaculis volutpat est, sit amet fringilla velit accumsan vitae. Phasellus ante diam, scelerisque non tellus nec, porta interdum est. Fusce sed pharetra velit, et pharetra nulla. Aliquam pretium tempus augue non mollis. Suspendisse eget iaculis sem, eu volutpat risus. Ut sed auctor tellus. Aenean aliquet quis nulla in congue. Maecenas nisi risus, hendrerit vitae imperdiet in, rutrum vitae nunc. Fusce bibendum velit erat, id semper ex laoreet rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed a suscipit est. Aenean vehicula orci orci, quis commodo ex laoreet sit amet.