text:
cmake_minimum_required(VERSION 3.0)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)

redpajama_set_name: RedPajamaGithub


text:
package client.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import client.configure.DruidConfiguration;

/**
 * TODO
 *
 * @author huxian
 * @version V1.0
 * @since 2017-12-21 16:12
 */
@Service
public class DataSourceService implements InitializingBean{

    @Autowired
    private DruidConfiguration druidConfiguration;

    @Override
    public void afterPropertiesSet() throws Exception {
        if(null!=druidConfiguration.getDruidDataSource()){
            DruidDataSource dataSource=druidConfiguration.getDruidDataSource();
            System.out.println("initialSize:"+dataSource.getInitialSize());
            System.out.println("minIdle:"+dataSource.getMinIdle());
            System.out.println("maxActive:"+dataSource.getMaxActive());
            System.out.println("maxWait:"+dataSource.getMaxWait());
        }
    }
}


text:
EXCLUDED_URL_PREFIXES = %w(demo
                           dev developer developers lab api
                           login signin signup logout
                           www download ftp
                           stats
                           status
                           pro
                           git
                           ssl payment secure
                           mail smtp pop imap at
                           assets files photos
                           admin
                           facebook twitter linkedin path instagram wordpress tumblr flickr
                           official contentbird cbird
                           support sites profile user)


text:
namespace Codecov.Yaml
{
    internal interface IYaml
    {
        string FileName { get; }
    }
}


text:
Ribs [![Build Status](https://travis-ci.org/quid/ribs.png?branch=master)](https://travis-ci.org/quid/ribs)
====

Ribs can be used to make beautiful things, like functional list widgets and,
according to a large number of people,
[women](http://en.wikipedia.org/wiki/Eve#Creation).

The meat and bones of Ribs is the `Ribs.List` - an extention to Backbone view
which renders models from a collection and allows an intuitive way to define
actions to run against selected models.

Example application
-------------------

A good way to learn how to use Ribs is to look at the
[annotated source of our demo application](http://quid.github.com/ribs/docs/todos.html).

You can see the application in action [here](http://quid.github.com/ribs/demo).

Annotated Source
----------------

+ [list.coffee](http://quid.github.com/ribs/docs/list.html)

Dependencies
------------

+ [jquery.js](http://jquery.com)
+ [underscore.js](http://underscorejs.org)
+ [backbone.js](http://backbonejs.org)

Downloads
---------

+ [Ribs compiled to JavaScript](http://quid.github.com/ribs/ribs.js)
+ [Ribs compiled to minfied JavaScript](http://quid.github.com/ribs/ribs.min.js)
+ [CSS which might make your widgets more palatable](http://quid.github.com/ribs/ribs.css)

Keyboard Utilities
------------------

Support for keyboard shortcuts is one of the more useful features of Ribs.

Ribs lists can have jumpkeys. Jumpkeys are prefixed by 'g' and will put keyboard
focus on the first item in the Ribs list when triggered by the user.

Actions can have hotkeys. Pressing a hotkey will trigger the action. Input to
actions is a list of all selected items in the focussed Ribs list.

Both Jumpkeys and Hotkeys can be discovered by the user by hitting the global
hotkey `?`. Calling `Ribs.getKeyboardManager().showKeyboardBindings()` will do the same.

Work in Progress
----------------

Ribs is a work in progress. It seems to work well in the lastest Chrome, Firefox
and Safari. Please let us know if something is wrong by [filing an issue on
GitHub](https://github.com/quid/ribs/issues).


text:
#include "postgres.h"

#include <dirent.h>
#include <fcntl.h>
#include <locale.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

#include "access/transam.h"
#include "access/tuptoaster.h"
#include "access/multixact.h"
#include "access/xlog_internal.h"
#include "catalog/catversion.h"
#include "catalog/pg_control.h"

extern int	optind;
extern char *optarg;

static ControlFileData ControlFile;		/* pg_control values */
static uint32 newXlogId,
			newXlogSeg;			/* ID/Segment of new XLOG segment */
static bool guessed = false;	/* T if we had to guess at any values */
static const char *progname;

static bool ReadControlFile(void);
static void GuessControlValues(void);
static void PrintControlValues(bool guessed);
static void RewriteControlFile(void);
static void FindEndOfXLOG(void);
static void KillExistingXLOG(void);
static void KillExistingArchiveStatus(void);
static void WriteEmptyXLOG(void);
static void usage(void);

int
main(int argc, char *argv[])
{
	int			c;
	bool		force = false;
	bool		noupdate = false;
	uint32		set_xid_epoch = (uint32) -1;
	TransactionId set_xid = 0;
	Oid			set_oid = 0;
	MultiXactId set_mxid = 0;
	MultiXactOffset set_mxoff = (MultiXactOffset) -1;
	uint32		minXlogTli = 0,
				minXlogId = 0,
				minXlogSeg = 0;
	char	   *endptr;
	char	   *endptr2;
	char	   *endptr3;
	char	   *DataDir;
	int			fd;
	char		path[MAXPGPATH];

	set_pglocale_pgservice(argv[0], "pg_resetxlog");

	progname = get_progname(argv[0]);

	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			usage();
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("pg_resetxlog (PostgreSQL) " PG_VERSION);
			exit(0);
		}
	}

	while ((c = getopt(argc, argv, "fl:m:no:O:x:e:")) != -1)
	{
		switch (c)
		{
			case 'f':
				force = true;
				break;

			case 'n':
				noupdate = true;
				break;

			case 'e':
				set_xid_epoch = strtoul(optarg, &endptr, 0);
				if (endptr == optarg || *endptr != '\0')
				{
					fprintf(stderr, _("%s: invalid argument for option -e\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				if (set_xid_epoch == -1)
				{
					fprintf(stderr, _("%s: transaction ID epoch (-e) must not be -1\n"), progname);
					exit(1);
				}
				break;

			case 'x':
				set_xid = strtoul(optarg, &endptr, 0);
				if (endptr == optarg || *endptr != '\0')
				{
					fprintf(stderr, _("%s: invalid argument for option -x\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				if (set_xid == 0)
				{
					fprintf(stderr, _("%s: transaction ID (-x) must not be 0\n"), progname);
					exit(1);
				}
				break;

			case 'o':
				set_oid = strtoul(optarg, &endptr, 0);
				if (endptr == optarg || *endptr != '\0')
				{
					fprintf(stderr, _("%s: invalid argument for option -o\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				if (set_oid == 0)
				{
					fprintf(stderr, _("%s: OID (-o) must not be 0\n"), progname);
					exit(1);
				}
				break;

			case 'm':
				set_mxid = strtoul(optarg, &endptr, 0);
				if (endptr == optarg || *endptr != '\0')
				{
					fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				if (set_mxid == 0)
				{
					fprintf(stderr, _("%s: multitransaction ID (-m) must not be 0\n"), progname);
					exit(1);
				}
				break;

			case 'O':
				set_mxoff = strtoul(optarg, &endptr, 0);
				if (endptr == optarg || *endptr != '\0')
				{
					fprintf(stderr, _("%s: invalid argument for option -O\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				if (set_mxoff == -1)
				{
					fprintf(stderr, _("%s: multitransaction offset (-O) must not be -1\n"), progname);
					exit(1);
				}
				break;

			case 'l':
				minXlogTli = strtoul(optarg, &endptr, 0);
				if (endptr == optarg || *endptr != ',')
				{
					fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				minXlogId = strtoul(endptr + 1, &endptr2, 0);
				if (endptr2 == endptr + 1 || *endptr2 != ',')
				{
					fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				minXlogSeg = strtoul(endptr2 + 1, &endptr3, 0);
				if (endptr3 == endptr2 + 1 || *endptr3 != '\0')
				{
					fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
					fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
					exit(1);
				}
				break;

			default:
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
				exit(1);
		}
	}

	if (optind == argc)
	{
		fprintf(stderr, _("%s: no data directory specified\n"), progname);
		fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
		exit(1);
	}

	/*
	 * Don't allow pg_resetxlog to be run as root, to avoid overwriting the
	 * ownership of files in the data directory. We need only check for root
	 * -- any other user won't have sufficient permissions to modify files in
	 * the data directory.
	 */
#ifndef WIN32
	if (geteuid() == 0)
	{
		fprintf(stderr, _("%s: cannot be executed by \"root\"\n"),
				progname);
		fprintf(stderr, _("You must run %s as the PostgreSQL superuser.\n"),
				progname);
		exit(1);
	}
#endif

	DataDir = argv[optind];

	if (chdir(DataDir) < 0)
	{
		fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"),
				progname, DataDir, strerror(errno));
		exit(1);
	}

	/*
	 * Check for a postmaster lock file --- if there is one, refuse to
	 * proceed, on grounds we might be interfering with a live installation.
	 */
	snprintf(path, MAXPGPATH, "%s/postmaster.pid", DataDir);

	if ((fd = open(path, O_RDONLY, 0)) < 0)
	{
		if (errno != ENOENT)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"), progname, path, strerror(errno));
			exit(1);
		}
	}
	else
	{
		fprintf(stderr, _("%s: lock file \"%s\" exists\n"
						  "Is a server running?  If not, delete the lock file and try again.\n"),
				progname, path);
		exit(1);
	}

	/*
	 * Attempt to read the existing pg_control file
	 */
	if (!ReadControlFile())
		GuessControlValues();

	/*
	 * Also look at existing segment files to set up newXlogId/newXlogSeg
	 */
	FindEndOfXLOG();

	/*
	 * Adjust fields if required by switches.  (Do this now so that printout,
	 * if any, includes these values.)
	 */
	if (set_xid_epoch != -1)
		ControlFile.checkPointCopy.nextXidEpoch = set_xid_epoch;

	if (set_xid != 0)
		ControlFile.checkPointCopy.nextXid = set_xid;

	if (set_oid != 0)
		ControlFile.checkPointCopy.nextOid = set_oid;

	if (set_mxid != 0)
		ControlFile.checkPointCopy.nextMulti = set_mxid;

	if (set_mxoff != -1)
		ControlFile.checkPointCopy.nextMultiOffset = set_mxoff;

	if (minXlogTli > ControlFile.checkPointCopy.ThisTimeLineID)
		ControlFile.checkPointCopy.ThisTimeLineID = minXlogTli;

	if (minXlogId > newXlogId ||
		(minXlogId == newXlogId &&
		 minXlogSeg > newXlogSeg))
	{
		newXlogId = minXlogId;
		newXlogSeg = minXlogSeg;
	}

	/*
	 * If we had to guess anything, and -f was not given, just print the
	 * guessed values and exit.  Also print if -n is given.
	 */
	if ((guessed && !force) || noupdate)
	{
		PrintControlValues(guessed);
		if (!noupdate)
		{
			printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
			exit(1);
		}
		else
			exit(0);
	}

	/*
	 * Don't reset from a dirty pg_control without -f, either.
	 */
	if (ControlFile.state != DB_SHUTDOWNED && !force)
	{
		printf(_("The database server was not shut down cleanly.\n"
			   "Resetting the transaction log might cause data to be lost.\n"
				 "If you want to proceed anyway, use -f to force reset.\n"));
		exit(1);
	}

	/*
	 * Else, do the dirty deed.
	 */
	RewriteControlFile();
	KillExistingXLOG();
	KillExistingArchiveStatus();
	WriteEmptyXLOG();

	printf(_("Transaction log reset\n"));
	return 0;
}

/*
 * Try to read the existing pg_control file.
 *
 * This routine is also responsible for updating old pg_control versions
 * to the current format.  (Currently we don't do anything of the sort.)
 */
static bool
ReadControlFile(void)
{
	int			fd;
	int			len;
	char	   *buffer;
	pg_crc32	crc;

	if ((fd = open(XLOG_CONTROL_FILE, O_RDONLY | PG_BINARY, 0)) < 0)
	{
		/*
		 * If pg_control is not there at all, or we can't read it, the odds
		 * are we've been handed a bad DataDir path, so give up. User can do
		 * "touch pg_control" to force us to proceed.
		 */
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, XLOG_CONTROL_FILE, strerror(errno));
		if (errno == ENOENT)
			fprintf(stderr, _("If you are sure the data directory path is correct, execute\n"
							  "  touch %s\n"
							  "and try again.\n"),
					XLOG_CONTROL_FILE);
		exit(1);
	}

	/* Use malloc to ensure we have a maxaligned buffer */
	buffer = (char *) malloc(PG_CONTROL_SIZE);

	len = read(fd, buffer, PG_CONTROL_SIZE);
	if (len < 0)
	{
		fprintf(stderr, _("%s: could not read file \"%s\": %s\n"),
				progname, XLOG_CONTROL_FILE, strerror(errno));
		exit(1);
	}
	close(fd);

	if (len >= sizeof(ControlFileData) &&
	  ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
	{
		/* Check the CRC. */
		INIT_CRC32(crc);
		COMP_CRC32(crc,
				   buffer,
				   offsetof(ControlFileData, crc));
		FIN_CRC32(crc);

		if (EQ_CRC32(crc, ((ControlFileData *) buffer)->crc))
		{
			/* Valid data... */
			memcpy(&ControlFile, buffer, sizeof(ControlFile));
			return true;
		}

		fprintf(stderr, _("%s: pg_control exists but has invalid CRC; proceed with caution\n"),
				progname);
		/* We will use the data anyway, but treat it as guessed. */
		memcpy(&ControlFile, buffer, sizeof(ControlFile));
		guessed = true;
		return true;
	}

	/* Looks like it's a mess. */
	fprintf(stderr, _("%s: pg_control exists but is broken or unknown version; ignoring it\n"),
			progname);
	return false;
}

/*
 * Guess at pg_control values when we can't read the old ones.
 */
static void
GuessControlValues(void)
{
	uint64		sysidentifier;
	struct timeval tv;
	char	   *localeptr;

	/*
	 * Set up a completely default set of pg_control values.
	 */
	guessed = true;
	memset(&ControlFile, 0, sizeof(ControlFile));

	ControlFile.pg_control_version = PG_CONTROL_VERSION;
	ControlFile.catalog_version_no = CATALOG_VERSION_NO;

	/*
	 * Create a new unique installation identifier, since we can no longer use
	 * any old XLOG records.  See notes in xlog.c about the algorithm.
	 */
	gettimeofday(&tv, NULL);
	sysidentifier = ((uint64) tv.tv_sec) << 32;
	sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);

	ControlFile.system_identifier = sysidentifier;

	ControlFile.checkPointCopy.redo.xlogid = 0;
	ControlFile.checkPointCopy.redo.xrecoff = SizeOfXLogLongPHD;
	ControlFile.checkPointCopy.ThisTimeLineID = 1;
	ControlFile.checkPointCopy.nextXidEpoch = 0;
	ControlFile.checkPointCopy.nextXid = (TransactionId) 514;	/* XXX */
	ControlFile.checkPointCopy.nextOid = FirstBootstrapObjectId;
	ControlFile.checkPointCopy.nextMulti = FirstMultiXactId;
	ControlFile.checkPointCopy.nextMultiOffset = 0;
	ControlFile.checkPointCopy.time = time(NULL);

	ControlFile.state = DB_SHUTDOWNED;
	ControlFile.time = time(NULL);
	ControlFile.checkPoint = ControlFile.checkPointCopy.redo;

	ControlFile.maxAlign = MAXIMUM_ALIGNOF;
	ControlFile.floatFormat = FLOATFORMAT_VALUE;
	ControlFile.blcksz = BLCKSZ;
	ControlFile.relseg_size = RELSEG_SIZE;
	ControlFile.xlog_blcksz = XLOG_BLCKSZ;
	ControlFile.xlog_seg_size = XLOG_SEG_SIZE;
	ControlFile.nameDataLen = NAMEDATALEN;
	ControlFile.indexMaxKeys = INDEX_MAX_KEYS;
	ControlFile.toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
#ifdef HAVE_INT64_TIMESTAMP
	ControlFile.enableIntTimes = TRUE;
#else
	ControlFile.enableIntTimes = FALSE;
#endif
	ControlFile.localeBuflen = LOCALE_NAME_BUFLEN;

	localeptr = setlocale(LC_COLLATE, "");
	if (!localeptr)
	{
		fprintf(stderr, _("%s: invalid LC_COLLATE setting\n"), progname);
		exit(1);
	}
	strlcpy(ControlFile.lc_collate, localeptr, sizeof(ControlFile.lc_collate));
	localeptr = setlocale(LC_CTYPE, "");
	if (!localeptr)
	{
		fprintf(stderr, _("%s: invalid LC_CTYPE setting\n"), progname);
		exit(1);
	}
	strlcpy(ControlFile.lc_ctype, localeptr, sizeof(ControlFile.lc_ctype));

	/*
	 * XXX eventually, should try to grovel through old XLOG to develop more
	 * accurate values for TimeLineID, nextXID, etc.
	 */
}

/*
 * Print the guessed pg_control values when we had to guess.
 *
 * NB: this display should be just those fields that will not be
 * reset by RewriteControlFile().
 */
static void
PrintControlValues(bool guessed)
{
	char		sysident_str[32];

	if (guessed)
		printf(_("Guessed pg_control values:\n\n"));
	else
		printf(_("pg_control values:\n\n"));

	/*
	 * Format system_identifier separately to keep platform-dependent format
	 * code out of the translatable message string.
	 */
	snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
			 ControlFile.system_identifier);

	printf(_("First log file ID after reset:        %u\n"),
		   newXlogId);
	printf(_("First log file segment after reset:   %u\n"),
		   newXlogSeg);
	printf(_("pg_control version number:            %u\n"),
		   ControlFile.pg_control_version);
	printf(_("Catalog version number:               %u\n"),
		   ControlFile.catalog_version_no);
	printf(_("Database system identifier:           %s\n"),
		   sysident_str);
	printf(_("Latest checkpoint's TimeLineID:       %u\n"),
		   ControlFile.checkPointCopy.ThisTimeLineID);
	printf(_("Latest checkpoint's NextXID:          %u/%u\n"),
		   ControlFile.checkPointCopy.nextXidEpoch,
		   ControlFile.checkPointCopy.nextXid);
	printf(_("Latest checkpoint's NextOID:          %u\n"),
		   ControlFile.checkPointCopy.nextOid);
	printf(_("Latest checkpoint's NextMultiXactId:  %u\n"),
		   ControlFile.checkPointCopy.nextMulti);
	printf(_("Latest checkpoint's NextMultiOffset:  %u\n"),
		   ControlFile.checkPointCopy.nextMultiOffset);
	printf(_("Maximum data alignment:               %u\n"),
		   ControlFile.maxAlign);
	/* we don't print floatFormat since can't say much useful about it */
	printf(_("Database block size:                  %u\n"),
		   ControlFile.blcksz);
	printf(_("Blocks per segment of large relation: %u\n"),
		   ControlFile.relseg_size);
	printf(_("WAL block size:                       %u\n"),
		   ControlFile.xlog_blcksz);
	printf(_("Bytes per WAL segment:                %u\n"),
		   ControlFile.xlog_seg_size);
	printf(_("Maximum length of identifiers:        %u\n"),
		   ControlFile.nameDataLen);
	printf(_("Maximum columns in an index:          %u\n"),
		   ControlFile.indexMaxKeys);
	printf(_("Maximum size of a TOAST chunk:        %u\n"),
		   ControlFile.toast_max_chunk_size);
	printf(_("Date/time type storage:               %s\n"),
		   (ControlFile.enableIntTimes ? _("64-bit integers") : _("floating-point numbers")));
	printf(_("Maximum length of locale name:        %u\n"),
		   ControlFile.localeBuflen);
	printf(_("LC_COLLATE:                           %s\n"),
		   ControlFile.lc_collate);
	printf(_("LC_CTYPE:                             %s\n"),
		   ControlFile.lc_ctype);
}

/*
 * Write out the new pg_control file.
 */
static void
RewriteControlFile(void)
{
	int			fd;
	char		buffer[PG_CONTROL_SIZE];		/* need not be aligned */

	/*
	 * Adjust fields as needed to force an empty XLOG starting at
	 * newXlogId/newXlogSeg.
	 */
	ControlFile.checkPointCopy.redo.xlogid = newXlogId;
	ControlFile.checkPointCopy.redo.xrecoff =
		newXlogSeg * XLogSegSize + SizeOfXLogLongPHD;
	ControlFile.checkPointCopy.time = time(NULL);

	ControlFile.state = DB_SHUTDOWNED;
	ControlFile.time = time(NULL);
	ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
	ControlFile.prevCheckPoint.xlogid = 0;
	ControlFile.prevCheckPoint.xrecoff = 0;
	ControlFile.minRecoveryPoint.xlogid = 0;
	ControlFile.minRecoveryPoint.xrecoff = 0;

	/* Now we can force the recorded xlog seg size to the right thing. */
	ControlFile.xlog_seg_size = XLogSegSize;

	/* Contents are protected with a CRC */
	INIT_CRC32(ControlFile.crc);
	COMP_CRC32(ControlFile.crc,
			   (char *) &ControlFile,
			   offsetof(ControlFileData, crc));
	FIN_CRC32(ControlFile.crc);

	/*
	 * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
	 * excess over sizeof(ControlFileData).  This reduces the odds of
	 * premature-EOF errors when reading pg_control.  We'll still fail when we
	 * check the contents of the file, but hopefully with a more specific
	 * error than "couldn't read pg_control".
	 */
	if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
	{
		fprintf(stderr,
				_("%s: internal error -- sizeof(ControlFileData) is too large ... fix PG_CONTROL_SIZE\n"),
				progname);
		exit(1);
	}

	memset(buffer, 0, PG_CONTROL_SIZE);
	memcpy(buffer, &ControlFile, sizeof(ControlFileData));

	unlink(XLOG_CONTROL_FILE);

	fd = open(XLOG_CONTROL_FILE,
			  O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
			  S_IRUSR | S_IWUSR);
	if (fd < 0)
	{
		fprintf(stderr, _("%s: could not create pg_control file: %s\n"),
				progname, strerror(errno));
		exit(1);
	}

	errno = 0;
	if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
		fprintf(stderr, _("%s: could not write pg_control file: %s\n"),
				progname, strerror(errno));
		exit(1);
	}

	if (fsync(fd) != 0)
	{
		fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
		exit(1);
	}

	close(fd);
}

/*
 * Scan existing XLOG files and determine the highest existing WAL address
 *
 * On entry, ControlFile.checkPointCopy.redo and ControlFile.xlog_seg_size
 * are assumed valid (note that we allow the old xlog seg size to differ
 * from what we're using).  On exit, newXlogId and newXlogSeg are set to
 * suitable values for the beginning of replacement WAL (in our seg size).
 */
static void
FindEndOfXLOG(void)
{
	DIR		   *xldir;
	struct dirent *xlde;

	/*
	 * Initialize the max() computation using the last checkpoint address from
	 * old pg_control.	Note that for the moment we are working with segment
	 * numbering according to the old xlog seg size.
	 */
	newXlogId = ControlFile.checkPointCopy.redo.xlogid;
	newXlogSeg = ControlFile.checkPointCopy.redo.xrecoff / ControlFile.xlog_seg_size;

	/*
	 * Scan the pg_xlog directory to find existing WAL segment files. We
	 * assume any present have been used; in most scenarios this should be
	 * conservative, because of xlog.c's attempts to pre-create files.
	 */
	xldir = opendir(XLOGDIR);
	if (xldir == NULL)
	{
		fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
				progname, XLOGDIR, strerror(errno));
		exit(1);
	}

	errno = 0;
	while ((xlde = readdir(xldir)) != NULL)
	{
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24)
		{
			unsigned int tli,
						log,
						seg;

			sscanf(xlde->d_name, "%08X%08X%08X", &tli, &log, &seg);

			/*
			 * Note: we take the max of all files found, regardless of their
			 * timelines.  Another possibility would be to ignore files of
			 * timelines other than the target TLI, but this seems safer.
			 * Better too large a result than too small...
			 */
			if (log > newXlogId ||
				(log == newXlogId && seg > newXlogSeg))
			{
				newXlogId = log;
				newXlogSeg = seg;
			}
		}
		errno = 0;
	}
#ifdef WIN32

	/*
	 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
	 * released version
	 */
	if (GetLastError() == ERROR_NO_MORE_FILES)
		errno = 0;
#endif

	if (errno)
	{
		fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
				progname, XLOGDIR, strerror(errno));
		exit(1);
	}
	closedir(xldir);

	/*
	 * Finally, convert to new xlog seg size, and advance by one to ensure we
	 * are in virgin territory.
	 */
	newXlogSeg *= ControlFile.xlog_seg_size;
	newXlogSeg = (newXlogSeg + XLogSegSize - 1) / XLogSegSize;

	/* be sure we wrap around correctly at end of a logfile */
	NextLogSeg(newXlogId, newXlogSeg);
}

/*
 * Remove existing XLOG files
 */
static void
KillExistingXLOG(void)
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];

	xldir = opendir(XLOGDIR);
	if (xldir == NULL)
	{
		fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
				progname, XLOGDIR, strerror(errno));
		exit(1);
	}

	errno = 0;
	while ((xlde = readdir(xldir)) != NULL)
	{
		if (strlen(xlde->d_name) == 24 &&
			strspn(xlde->d_name, "0123456789ABCDEF") == 24)
		{
			snprintf(path, MAXPGPATH, "%s/%s", XLOGDIR, xlde->d_name);
			if (unlink(path) < 0)
			{
				fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
						progname, path, strerror(errno));
				exit(1);
			}
		}
		errno = 0;
	}
#ifdef WIN32

	/*
	 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
	 * released version
	 */
	if (GetLastError() == ERROR_NO_MORE_FILES)
		errno = 0;
#endif

	if (errno)
	{
		fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
				progname, XLOGDIR, strerror(errno));
		exit(1);
	}
	closedir(xldir);
}

/*
 * Remove existing archive status files
 */
static void
KillExistingArchiveStatus(void)
{
	DIR		   *xldir;
	struct dirent *xlde;
	char		path[MAXPGPATH];

#define ARCHSTATDIR	XLOGDIR "/archive_status"

	xldir = opendir(ARCHSTATDIR);
	if (xldir == NULL)
	{
		fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
				progname, ARCHSTATDIR, strerror(errno));
		exit(1);
	}

	errno = 0;
	while ((xlde = readdir(xldir)) != NULL)
	{
		if (strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
			(strcmp(xlde->d_name + 24, ".ready") == 0 ||
			 strcmp(xlde->d_name + 24, ".done")  == 0))
		{
			snprintf(path, MAXPGPATH, "%s/%s", ARCHSTATDIR, xlde->d_name);
			if (unlink(path) < 0)
			{
				fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
						progname, path, strerror(errno));
				exit(1);
			}
		}
		errno = 0;
	}
#ifdef WIN32

	/*
	 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
	 * released version
	 */
	if (GetLastError() == ERROR_NO_MORE_FILES)
		errno = 0;
#endif

	if (errno)
	{
		fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
				progname, ARCHSTATDIR, strerror(errno));
		exit(1);
	}
	closedir(xldir);
}

/*
 * Write an empty XLOG file, containing only the checkpoint record
 * already set up in ControlFile.
 */
static void
WriteEmptyXLOG(void)
{
	char	   *buffer;
	XLogPageHeader page;
	XLogLongPageHeader longpage;
	XLogRecord *record;
	pg_crc32	crc;
	char		path[MAXPGPATH];
	int			fd;
	int			nbytes;

	/* Use malloc() to ensure buffer is MAXALIGNED */
	buffer = (char *) malloc(XLOG_BLCKSZ);
	page = (XLogPageHeader) buffer;
	memset(buffer, 0, XLOG_BLCKSZ);

	/* Set up the XLOG page header */
	page->xlp_magic = XLOG_PAGE_MAGIC;
	page->xlp_info = XLP_LONG_HEADER;
	page->xlp_tli = ControlFile.checkPointCopy.ThisTimeLineID;
	page->xlp_pageaddr.xlogid =
		ControlFile.checkPointCopy.redo.xlogid;
	page->xlp_pageaddr.xrecoff =
		ControlFile.checkPointCopy.redo.xrecoff - SizeOfXLogLongPHD;
	longpage = (XLogLongPageHeader) page;
	longpage->xlp_sysid = ControlFile.system_identifier;
	longpage->xlp_seg_size = XLogSegSize;
	longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;

	/* Insert the initial checkpoint record */
	record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
	record->xl_prev.xlogid = 0;
	record->xl_prev.xrecoff = 0;
	record->xl_xid = InvalidTransactionId;
	record->xl_tot_len = SizeOfXLogRecord + sizeof(CheckPoint);
	record->xl_len = sizeof(CheckPoint);
	record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
	record->xl_rmid = RM_XLOG_ID;
	memcpy(XLogRecGetData(record), &ControlFile.checkPointCopy,
		   sizeof(CheckPoint));

	INIT_CRC32(crc);
	COMP_CRC32(crc, &ControlFile.checkPointCopy, sizeof(CheckPoint));
	COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
			   SizeOfXLogRecord - sizeof(pg_crc32));
	FIN_CRC32(crc);
	record->xl_crc = crc;

	/* Write the first page */
	XLogFilePath(path, ControlFile.checkPointCopy.ThisTimeLineID,
				 newXlogId, newXlogSeg);

	unlink(path);

	fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
			  S_IRUSR | S_IWUSR);
	if (fd < 0)
	{
		fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
				progname, path, strerror(errno));
		exit(1);
	}

	errno = 0;
	if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
		fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
				progname, path, strerror(errno));
		exit(1);
	}

	/* Fill the rest of the file with zeroes */
	memset(buffer, 0, XLOG_BLCKSZ);
	for (nbytes = XLOG_BLCKSZ; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
	{
		errno = 0;
		if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
		{
			if (errno == 0)
				errno = ENOSPC;
			fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
					progname, path, strerror(errno));
			exit(1);
		}
	}

	if (fsync(fd) != 0)
	{
		fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
		exit(1);
	}

	close(fd);
}

static void
usage(void)
{
	printf(_("%s resets the PostgreSQL transaction log.\n\n"), progname);
	printf(_("Usage:\n  %s [OPTION]... DATADIR\n\n"), progname);
	printf(_("Options:\n"));
	printf(_("  -f              force update to be done\n"));
	printf(_("  -l TLI,FILE,SEG force minimum WAL starting location for new transaction log\n"));
	printf(_("  -m XID          set next multitransaction ID\n"));
	printf(_("  -n              no update, just show extracted control values (for testing)\n"));
	printf(_("  -o OID          set next OID\n"));
	printf(_("  -O OFFSET       set next multitransaction offset\n"));
	printf(_("  -x XID          set next transaction ID\n"));
	printf(_("  -e XIDEPOCH     set next transaction ID epoch\n"));
	printf(_("  --help          show this help, then exit\n"));
	printf(_("  --version       output version information, then exit\n"));
	printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
}


text:
package org.glowroot.agent.weaving;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.objectweb.asm.ConstantDynamic;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;

// copied and modified from org.objectweb.asm.commons.AdviceAdapter
// modifications include
// * tracking stack frames for all methods (not just constructors)
// * tracking double words on the stack via SECOND_WORD
// * field "stackFrameTracking" to allow subclass to temporarily suppress stack frame tracking
// * fix in visitFieldInsn switch case PUTFIELD
// (reported fix at http://forge.ow2.org/tracker/?group_id=23&atid=100023&func=detail&aid=317604)
// * clearing stackFrame on GOTO
abstract class AdviceAdapter extends GeneratorAdapter implements Opcodes {

    /** The "uninitialized this" value. */
    static final Object UNINITIALIZED_THIS = new Object();

    protected static final Object SECOND_WORD = new Object();

    /** Any value other than "uninitialized this". */
    private static final Object OTHER = new Object();

    /** Prefix of the error message when invalid opcodes are found. */
    private static final String INVALID_OPCODE = "Invalid opcode ";

    /** The access flags of the visited method. */
    protected int methodAccess;

    /** The descriptor of the visited method. */
    protected String methodDesc;

    /** Whether the visited method is a constructor. */
    private final boolean isConstructor;

    /**
     * Whether the super class constructor has been called (if the visited method is a constructor),
     * at the current instruction. There can be multiple call sites to the super constructor (e.g.
     * for Java code such as {@code super(expr ? value1 : value2);}), in different branches. When
     * scanning the bytecode linearly, we can move from one branch where the super constructor has
     * been called to another where it has not been called yet. Therefore, this value can change
     * from false to true, and vice-versa.
     */
    private boolean superClassConstructorCalled;

    /**
     * The values on the current execution stack frame (long and double are represented by two
     * elements). Each value is either {@link #UNINITIALIZED_THIS} (for the uninitialized this
     * value), or {@link #OTHER} (for any other value). This field is only maintained for
     * constructors, in branches where the super class constructor has not been called yet.
     */
    protected List<Object> stackFrame = new ArrayList<>();

    /**
     * The stack map frames corresponding to the labels of the forward jumps made *before* the super
     * class constructor has been called (note that the Java Virtual Machine forbids backward jumps
     * before the super class constructor is called). Note that by definition (cf. the 'before'),
     * when we reach a label from this map, {@link #superClassConstructorCalled} must be reset to
     * false. This field is only maintained for constructors.
     */
    private Map<Label, List<Object>> forwardJumpStackFrames = new HashMap<>();

    protected boolean stackFrameTracking = true;

    /**
     * Constructs a new {@link AdviceAdapter}.
     *
     * @param api
     *            the ASM API version implemented by this visitor. Must be one of
     *            {@link Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or
     *            {@link Opcodes#ASM9}.
     * @param methodVisitor
     *            the method visitor to which this adapter delegates calls.
     * @param access
     *            the method's access flags (see {@link Opcodes}).
     * @param name
     *            the method's name.
     * @param descriptor
     *            the method's descriptor (see {@link Type Type}).
     */
    protected AdviceAdapter(final int api, final MethodVisitor methodVisitor, final int access,
            final String name, final String descriptor) {
        super(api, methodVisitor, access, name, descriptor);
        methodAccess = access;
        methodDesc = descriptor;
        isConstructor = "<init>".equals(name);
    }

    @Override
    public void visitCode() {
        super.visitCode();
        onMethodPreEnter();
        if (!isConstructor) {
            superClassConstructorCalled = true;
            onMethodEnter();
        }
    }

    @Override
    public void visitLabel(final Label label) {
        super.visitLabel(label);
        if (stackFrameTracking && forwardJumpStackFrames != null) {
            List<Object> labelStackFrame = forwardJumpStackFrames.get(label);
            if (labelStackFrame != null) {
                stackFrame = labelStackFrame;
                superClassConstructorCalled = false;
                forwardJumpStackFrames.remove(label);
            }
        }
    }

    @Override
    public void visitInsn(final int opcode) {
        if (stackFrameTracking) {
            int stackSize;
            switch (opcode) {
                case IRETURN:
                case FRETURN:
                case ARETURN:
                    popValue();
                    onMethodExit(opcode);
                    break;
                case LRETURN:
                case DRETURN:
                    popValue();
                    popValue();
                    onMethodExit(opcode);
                    break;
                case RETURN: // empty stack
                    onMethodExit(opcode);
                    endConstructorBasicBlockWithoutSuccessor();
                    break;
                case ATHROW: // 1 before n/a after
                    popValue();
                    onMethodExit(opcode);
                    endConstructorBasicBlockWithoutSuccessor();
                    break;
                case NOP:
                case LALOAD: // remove 2 add 2
                case DALOAD: // remove 2 add 2
                case LNEG:
                case DNEG:
                case FNEG:
                case INEG:
                case L2D:
                case D2L:
                case F2I:
                case I2B:
                case I2C:
                case I2S:
                case I2F:
                case ARRAYLENGTH:
                    break;
                case ACONST_NULL:
                case ICONST_M1:
                case ICONST_0:
                case ICONST_1:
                case ICONST_2:
                case ICONST_3:
                case ICONST_4:
                case ICONST_5:
                case FCONST_0:
                case FCONST_1:
                case FCONST_2:
                case F2L: // 1 before 2 after
                case F2D:
                case I2L:
                case I2D:
                    pushValue(OTHER);
                    break;
                case LCONST_0:
                case LCONST_1:
                case DCONST_0:
                case DCONST_1:
                    pushValue(OTHER);
                    pushValue(SECOND_WORD);
                    break;
                case IALOAD: // remove 2 add 1
                case FALOAD: // remove 2 add 1
                case AALOAD: // remove 2 add 1
                case BALOAD: // remove 2 add 1
                case CALOAD: // remove 2 add 1
                case SALOAD: // remove 2 add 1
                case POP:
                case IADD:
                case FADD:
                case ISUB:
                case LSHL: // 3 before 2 after
                case LSHR: // 3 before 2 after
                case LUSHR: // 3 before 2 after
                case L2I: // 2 before 1 after
                case L2F: // 2 before 1 after
                case D2I: // 2 before 1 after
                case D2F: // 2 before 1 after
                case FSUB:
                case FMUL:
                case FDIV:
                case FREM:
                case FCMPL: // 2 before 1 after
                case FCMPG: // 2 before 1 after
                case IMUL:
                case IDIV:
                case IREM:
                case ISHL:
                case ISHR:
                case IUSHR:
                case IAND:
                case IOR:
                case IXOR:
                case MONITORENTER:
                case MONITOREXIT:
                    popValue();
                    break;
                case POP2:
                case LSUB:
                case LMUL:
                case LDIV:
                case LREM:
                case LADD:
                case LAND:
                case LOR:
                case LXOR:
                case DADD:
                case DMUL:
                case DSUB:
                case DDIV:
                case DREM:
                    popValue();
                    popValue();
                    break;
                case IASTORE:
                case FASTORE:
                case AASTORE:
                case BASTORE:
                case CASTORE:
                case SASTORE:
                case LCMP: // 4 before 1 after
                case DCMPL:
                case DCMPG:
                    popValue();
                    popValue();
                    popValue();
                    break;
                case LASTORE:
                case DASTORE:
                    popValue();
                    popValue();
                    popValue();
                    popValue();
                    break;
                case DUP:
                    pushValue(peekValue());
                    break;
                case DUP_X1:
                    stackSize = stackFrame.size();
                    stackFrame.add(stackSize - 2, stackFrame.get(stackSize - 1));
                    break;
                case DUP_X2:
                    stackSize = stackFrame.size();
                    stackFrame.add(stackSize - 3, stackFrame.get(stackSize - 1));
                    break;
                case DUP2:
                    stackSize = stackFrame.size();
                    stackFrame.add(stackSize - 2, stackFrame.get(stackSize - 1));
                    stackFrame.add(stackSize - 2, stackFrame.get(stackSize - 1));
                    break;
                case DUP2_X1:
                    stackSize = stackFrame.size();
                    stackFrame.add(stackSize - 3, stackFrame.get(stackSize - 1));
                    stackFrame.add(stackSize - 3, stackFrame.get(stackSize - 1));
                    break;
                case DUP2_X2:
                    stackSize = stackFrame.size();
                    stackFrame.add(stackSize - 4, stackFrame.get(stackSize - 1));
                    stackFrame.add(stackSize - 4, stackFrame.get(stackSize - 1));
                    break;
                case SWAP:
                    stackSize = stackFrame.size();
                    stackFrame.add(stackSize - 2, stackFrame.get(stackSize - 1));
                    stackFrame.remove(stackSize);
                    break;
                case RET:
                    endConstructorBasicBlockWithoutSuccessor();
                    break;
                default:
                    throw new IllegalArgumentException(INVALID_OPCODE + opcode);
            }
        } else {
            switch (opcode) {
                case RETURN:
                case IRETURN:
                case FRETURN:
                case ARETURN:
                case LRETURN:
                case DRETURN:
                case ATHROW:
                    onMethodExit(opcode);
                    break;
                default:
                    break;
            }
        }
        super.visitInsn(opcode);
    }

    @Override
    public void visitVarInsn(final int opcode, final int var) {
        super.visitVarInsn(opcode, var);
        if (stackFrameTracking) {
            switch (opcode) {
                case ILOAD:
                case FLOAD:
                    pushValue(OTHER);
                    break;
                case LLOAD:
                case DLOAD:
                    pushValue(OTHER);
                    pushValue(SECOND_WORD);
                    break;
                case ALOAD:
                    pushValue(var == 0 ? UNINITIALIZED_THIS : OTHER);
                    break;
                case ASTORE:
                case ISTORE:
                case FSTORE:
                    popValue();
                    break;
                case LSTORE:
                case DSTORE:
                    popValue();
                    popValue();
                    break;
                default:
                    throw new IllegalArgumentException(INVALID_OPCODE + opcode);
            }
        }
    }

    @Override
    public void visitFieldInsn(final int opcode, final String owner, final String name,
            final String descriptor) {
        super.visitFieldInsn(opcode, owner, name, descriptor);
        if (stackFrameTracking) {
            char firstDescriptorChar = descriptor.charAt(0);
            boolean longOrDouble = firstDescriptorChar == 'J' || firstDescriptorChar == 'D';
            switch (opcode) {
                case GETSTATIC:
                    pushValue(OTHER);
                    if (longOrDouble) {
                        pushValue(SECOND_WORD);
                    }
                    break;
                case PUTSTATIC:
                    popValue();
                    if (longOrDouble) {
                        popValue();
                    }
                    break;
                case PUTFIELD:
                    popValue();
                    popValue();
                    if (longOrDouble) {
                        popValue();
                    }
                    break;
                case GETFIELD:
                    if (longOrDouble) {
                        pushValue(SECOND_WORD);
                    }
                    break;
                default:
                    throw new IllegalArgumentException(INVALID_OPCODE + opcode);
            }
        }
    }

    @Override
    public void visitIntInsn(final int opcode, final int operand) {
        super.visitIntInsn(opcode, operand);
        if (stackFrameTracking && opcode != NEWARRAY) {
            pushValue(OTHER);
        }
    }

    @Override
    public void visitLdcInsn(final Object value) {
        super.visitLdcInsn(value);
        if (stackFrameTracking) {
            pushValue(OTHER);
            if (value instanceof Double || value instanceof Long
                    || (value instanceof ConstantDynamic
                            && ((ConstantDynamic) value).getSize() == 2)) {
                pushValue(SECOND_WORD);
            }
        }
    }

    @Override
    public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
        super.visitMultiANewArrayInsn(descriptor, numDimensions);
        if (stackFrameTracking) {
            for (int i = 0; i < numDimensions; i++) {
                popValue();
            }
            pushValue(OTHER);
        }
    }

    @Override
    public void visitTypeInsn(final int opcode, final String type) {
        super.visitTypeInsn(opcode, type);
        // ANEWARRAY, CHECKCAST or INSTANCEOF don't change stack.
        if (stackFrameTracking && opcode == NEW) {
            pushValue(OTHER);
        }
    }

    @Override
    public void visitMethodInsn(final int opcodeAndSource, final String owner, final String name,
            final String descriptor, final boolean isInterface) {
        if (api < Opcodes.ASM5 && (opcodeAndSource & Opcodes.SOURCE_DEPRECATED) == 0) {
            // Redirect the call to the deprecated version of this method.
            super.visitMethodInsn(opcodeAndSource, owner, name, descriptor, isInterface);
            return;
        }
        super.visitMethodInsn(opcodeAndSource, owner, name, descriptor, isInterface);
        int opcode = opcodeAndSource & ~Opcodes.SOURCE_MASK;

        doVisitMethodInsn(opcode, name, descriptor);
    }

    private void doVisitMethodInsn(final int opcode, final String name, final String descriptor) {
        if (stackFrameTracking) {
            for (Type argumentType : Type.getArgumentTypes(descriptor)) {
                popValue();
                if (argumentType.getSize() == 2) {
                    popValue();
                }
            }
            switch (opcode) {
                case INVOKEINTERFACE:
                case INVOKEVIRTUAL:
                    popValue();
                    break;
                case INVOKESPECIAL:
                    Object value = popValue();
                    if (value == UNINITIALIZED_THIS
                            && !superClassConstructorCalled
                            && name.equals("<init>")) {
                        superClassConstructorCalled = true;
                        onMethodEnter();
                    }
                    break;
                default:
                    break;
            }

            Type returnType = Type.getReturnType(descriptor);
            if (returnType != Type.VOID_TYPE) {
                pushValue(OTHER);
                if (returnType.getSize() == 2) {
                    pushValue(SECOND_WORD);
                }
            }
        }
    }

    @Override
    public void visitInvokeDynamicInsn(final String name, final String descriptor,
            final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {
        super.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle,
                bootstrapMethodArguments);
        doVisitMethodInsn(Opcodes.INVOKEDYNAMIC, name, descriptor);
    }

    @Override
    public void visitJumpInsn(final int opcode, final Label label) {
        super.visitJumpInsn(opcode, label);
        if (stackFrameTracking) {
            switch (opcode) {
                case IFEQ:
                case IFNE:
                case IFLT:
                case IFGE:
                case IFGT:
                case IFLE:
                case IFNULL:
                case IFNONNULL:
                    popValue();
                    break;
                case IF_ICMPEQ:
                case IF_ICMPNE:
                case IF_ICMPLT:
                case IF_ICMPGE:
                case IF_ICMPGT:
                case IF_ICMPLE:
                case IF_ACMPEQ:
                case IF_ACMPNE:
                    popValue();
                    popValue();
                    break;
                case JSR:
                    pushValue(OTHER);
                    break;
                case GOTO:
                    endConstructorBasicBlockWithoutSuccessor();
                    break;
                default:
                    break;
            }
            addForwardJump(label);
            if (opcode == GOTO) {
                stackFrame = new ArrayList<>();
            }
        }
    }

    @Override
    public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
        super.visitLookupSwitchInsn(dflt, keys, labels);
        if (stackFrameTracking) {
            popValue();
            addForwardJumps(dflt, labels);
            endConstructorBasicBlockWithoutSuccessor();
        }
    }

    @Override
    public void visitTableSwitchInsn(final int min, final int max, final Label dflt,
            final Label... labels) {
        super.visitTableSwitchInsn(min, max, dflt, labels);
        if (stackFrameTracking) {
            popValue();
            addForwardJumps(dflt, labels);
            endConstructorBasicBlockWithoutSuccessor();
        }
    }

    @Override
    public void visitTryCatchBlock(final Label start, final Label end, final Label handler,
            final String type) {
        super.visitTryCatchBlock(start, end, handler, type);
        // By definition of 'forwardJumpStackFrames', 'handler' should be pushed only if there is an
        // instruction between 'start' and 'end' at which the super class constructor is not yet
        // called. Unfortunately, try catch blocks must be visited before their labels, so we have
        // no
        // way to know this at this point. Instead, we suppose that the super class constructor has
        // not
        // been called at the start of *any* exception handler. If this is wrong, normally there
        // should
        // not be a second super class constructor call in the exception handler (an object can't be
        // initialized twice), so this is not issue (in the sense that there is no risk to emit a
        // wrong
        // 'onMethodEnter').
        if (stackFrameTracking && !forwardJumpStackFrames.containsKey(handler)) {
            List<Object> handlerStackFrame = new ArrayList<>();
            handlerStackFrame.add(OTHER);
            forwardJumpStackFrames.put(handler, handlerStackFrame);
        }
    }

    private void addForwardJumps(final Label dflt, final Label[] labels) {
        addForwardJump(dflt);
        for (Label label : labels) {
            addForwardJump(label);
        }
    }

    private void addForwardJump(final Label label) {
        if (forwardJumpStackFrames.containsKey(label)) {
            return;
        }
        forwardJumpStackFrames.put(label, new ArrayList<>(stackFrame));
    }

    private void endConstructorBasicBlockWithoutSuccessor() {
        // The next instruction is not reachable from this instruction. If it is dead code, we
        // should not try to simulate stack operations, and there is no need to insert advices
        // here. If it is reachable with a backward jump, the only possible case is that the super
        // class constructor has already been called (backward jumps are forbidden before it is
        // called). If it is reachable with a forward jump, there are two sub-cases. Either the
        // super class constructor has already been called when reaching the next instruction, or
        // it has not been called. But in this case there must be a forwardJumpStackFrames entry
        // for a Label designating the next instruction, and superClassConstructorCalled will be
        // reset to false there. We can therefore always reset this field to true here.
        superClassConstructorCalled = true;
    }

    private Object popValue() {
        if (stackFrame.isEmpty()) {
            // this is to handle less-than-perfect bytecode, see
            // WeaverTest.shouldExecuteAdviceOnMoreNotPerfectBytecode()
            return OTHER;
        }
        return stackFrame.remove(stackFrame.size() - 1);
    }

    private Object peekValue() {
        if (stackFrame.isEmpty()) {
            // this is to handle less-than-perfect bytecode, see
            // WeaverTest.shouldExecuteAdviceOnMoreNotPerfectBytecode()
            return OTHER;
        }
        return stackFrame.get(stackFrame.size() - 1);
    }

    private void pushValue(final Object value) {
        stackFrame.add(value);
    }

    protected void onMethodPreEnter() {}

    /**
     * Generates the "before" advice for the visited method. The default implementation of this
     * method does nothing. Subclasses can use or change all the local variables, but should not
     * change state of the stack. This method is called at the beginning of the method or after
     * super class constructor has been called (in constructors).
     */
    protected void onMethodEnter() {}

    /**
     * Generates the "after" advice for the visited method. The default implementation of this
     * method does nothing. Subclasses can use or change all the local variables, but should not
     * change state of the stack. This method is called at the end of the method, just before return
     * and athrow instructions. The top element on the stack contains the return value or the
     * exception instance. For example:
     *
     * <pre>
     * public void onMethodExit(final int opcode) {
     *   if (opcode == RETURN) {
     *     visitInsn(ACONST_NULL);
     *   } else if (opcode == ARETURN || opcode == ATHROW) {
     *     dup();
     *   } else {
     *     if (opcode == LRETURN || opcode == DRETURN) {
     *       dup2();
     *     } else {
     *       dup();
     *     }
     *     box(Type.getReturnType(this.methodDesc));
     *   }
     *   visitIntInsn(SIPUSH, opcode);
     *   visitMethodInsn(INVOKESTATIC, owner, "onExit", "(Ljava/lang/Object;I)V");
     * }
     *
     * // An actual call back method.
     * public static void onExit(final Object exitValue, final int opcode) {
     *   ...
     * }
     * </pre>
     *
     * @param opcode
     *            one of {@link Opcodes#RETURN}, {@link Opcodes#IRETURN}, {@link Opcodes#FRETURN},
     *            {@link Opcodes#ARETURN}, {@link Opcodes#LRETURN}, {@link Opcodes#DRETURN} or
     *            {@link Opcodes#ATHROW}.
     */
    protected void onMethodExit(final int opcode) {}
}


text:
@import AudioToolbox;

#import "YRAudioConverter.h"

static UInt32 const kBufferSize32KB = 32 * 1024;
static OSStatus const kOutOfDataError = 'oofd';

typedef struct {
    // Queue on which callbacks will be performed.
    dispatch_queue_t __unsafe_unretained targetQueue;

    // === Converter-related === //
    AudioStreamBasicDescription sourceASBD;
    AudioStreamBasicDescription destinationASBD;
    AudioConverterRef rawConverter;

    // === Converter metadata per convert call. === //
    UInt32 currentPacketIndex;
    UInt32 totalPackets;
    UInt32 totalBytes;
    const AudioStreamPacketDescription *packetDescriptions;
    const void *rawStreamData;

    BOOL isCancelled;
} AudioConverterSettings;

@implementation YRAudioConverter {
    AudioConverterSettings *_converterSettings;

    dispatch_queue_t _convertingQueue;

    // Hold references to the queue/blocks.
    dispatch_queue_t _targetQueue;
    ConvertCallback _convertCallback;
    FailureCallback _failureCallback;
}

#pragma mark - Lifecycle

- (instancetype)initWithSourceASBD:(AudioStreamBasicDescription)sourceASBD
                   destinationASBD:(AudioStreamBasicDescription)destinationASBD
                       targetQueue:(dispatch_queue_t)targetQueue {
    if (self = [super init]) {
        AudioConverterRef rawConverter = NULL;
        BOOL didCreateConverter = NO;

        NSError *__autoreleasing converterError = nil;

        didCreateConverter = [self createConverterWithSourceASBD:sourceASBD
                                                 destinationASBD:destinationASBD
                                                           error:&converterError
                                                    outConverter:&rawConverter];

        if (didCreateConverter) {
            _convertingQueue = dispatch_queue_create("com.YRAudioConverter.ConverterProcessingQueue", DISPATCH_QUEUE_SERIAL);

            _converterSettings = calloc(1, sizeof(AudioConverterSettings));
            _converterSettings->sourceASBD = sourceASBD;
            _converterSettings->destinationASBD = destinationASBD;
            _converterSettings->rawConverter = rawConverter;

//            _converterSettings->convertCallback = convertCallback;
//            _converterSettings->failureCallback = failureCallback;
            _converterSettings->targetQueue = targetQueue ? _targetQueue : dispatch_get_main_queue();

            // Store strong refrences
//            _convertCallback = convertCallback;
//            _failureCallback = failureCallback;
            _targetQueue = _converterSettings->targetQueue;
        } else {
            return nil;
        }
    }

    return self;
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);

    if (_converterSettings) {
        // Cleanup everything.
        AudioConverterDispose(_converterSettings->rawConverter);

        free(_converterSettings);
    }
}

#pragma mark - Public

- (void)convertAudioStreamPackets:(const void *)streamPacketData
               packetDescriptions:(const AudioStreamPacketDescription *)aspd
                     totalPackets:(UInt32)packetsCount
                       totalBytes:(UInt32)bytesInStream
                  convertCallback:(ConvertCallback)convertCallback
                  failureCallback:(FailureCallback)failureCallback {

    dispatch_async(_convertingQueue, ^{
        // Prepare our data for processing.
        _converterSettings->currentPacketIndex = 0;
        _converterSettings->totalPackets = packetsCount;
        _converterSettings->packetDescriptions = aspd;
        _converterSettings->totalBytes = bytesInStream;

        // We are in bg, so loop in while.
        while (_converterSettings->currentPacketIndex < _converterSettings->totalPackets &&
               !_converterSettings->isCancelled) {

            // Determine how buffer size and how much packets we can receive.
            UInt32 bufferSize = 0;
            UInt32 packetsToReceive = 0;

            // TODO: Check for error.
            calculateBufferSizeAndPacketsForConverter(_converterSettings,
                                                      &bufferSize,
                                                      &packetsToReceive,
                                                      NO);

            // Allocate data for receiving packets.
            AudioBufferList bufferList = {0};
            UInt32 receivedPackets = packetsToReceive;
            AudioStreamPacketDescription *packetDescriptions = NULL;
            BOOL shouldReceivePacketDescriptions = NO;

            if (isVBR(_converterSettings->destinationASBD)) {
                packetDescriptions = calloc(packetsToReceive, sizeof(AudioStreamPacketDescription));
                shouldReceivePacketDescriptions = YES;
            }

            // Don't see any benefit of using several buffers.
            bufferList.mNumberBuffers = 1;
            bufferList.mBuffers[0].mNumberChannels = _converterSettings->destinationASBD.mChannelsPerFrame;
            bufferList.mBuffers[0].mDataByteSize = bufferSize;
            bufferList.mBuffers[0].mData = malloc(bufferSize);

            // Start converting whole stream data.
            OSStatus convertError = AudioConverterFillComplexBuffer(_converterSettings->rawConverter,
                                                                    converterProc,
                                                                    &_converterSettings,
                                                                    &receivedPackets,
                                                                    &bufferList,
                                                                    packetDescriptions);
            // Here are what can happen here:
            // 1. Conversion was performed successfully and received packets.
            // 2. Want to deliver packets to target queue, but converting was cancelled.
            // 3. Conversion was performed successfully, but didn't receive any packets.
            // 4. Conversion wasn't performed successfuly.
            if (convertError != noErr || convertError == kOutOfDataError) {
                // Converted with success (or at least everything that was provided by user).
                if (receivedPackets > 0) {
                    // Even got packets!
                    dispatch_async(_targetQueue, ^{
                        // Callback on target queue
                        if (!_converterSettings->isCancelled) {
                            // Conversion wasn't cancelled, so give away packets!
                            UInt32 receivedPacketDescriptions = shouldReceivePacketDescriptions ? receivedPackets : 0;

                            !convertCallback ? : convertCallback(bufferList,
                                                                 packetDescriptions,
                                                                 receivedPacketDescriptions);

                            // Cleanup resources.
                            free(bufferList.mBuffers[0].mData);
                            if (shouldReceivePacketDescriptions) {
                                free(packetDescriptions);
                            }
                        } else {
                            // Cleanup resources.
                            free(bufferList.mBuffers[0].mData);
                            if (shouldReceivePacketDescriptions) {
                                free(packetDescriptions);
                            }
                        }
                    });
                } else {
                    // Didn't receive any packets...
                    // Cleanup resources.
                    free(bufferList.mBuffers[0].mData);
                    if (shouldReceivePacketDescriptions) {
                        free(packetDescriptions);
                    }
                    break;
                }
            } else {
                // Conversion failed, notify and stop.
                // TODO: Notify
                // Cleanup resources.
                free(bufferList.mBuffers[0].mData);
                if (shouldReceivePacketDescriptions) {
                    free(packetDescriptions);
                }

                break;
            }
        }
    });
}

- (void)cancelConverting {
    _converterSettings->isCancelled = YES;

    dispatch_async(_convertingQueue, ^{
        // Let all task finish on converting queue and set cancel flag to NO.
        // This is used to make new convert calls.
        _converterSettings->isCancelled = NO;
    });
}

#pragma mark - Private

- (BOOL)createConverterWithSourceASBD:(AudioStreamBasicDescription)sourceASBD
                      destinationASBD:(AudioStreamBasicDescription)destinationASBD
                                error:(NSError **)error
                         outConverter:(AudioConverterRef *)converter {
    if (converter) {
        OSStatus status = AudioConverterNew(&sourceASBD,
                                            &destinationASBD,
                                            converter);

        if (status == kAudioConverterErr_FormatNotSupported && error) {
            *error = [NSError errorWithDomain:NSCocoaErrorDomain
                                         code:0
                                     userInfo:@{NSLocalizedDescriptionKey : @"Given format(input/output) is not supported by converter"}];
        } else {
            // TODO: Return error if any.
        }

        return status == noErr;
    } else {
        // TODO: Return error.
        return NO;
    }
}

static inline
BOOL isVBR (AudioStreamBasicDescription asbd) {
    return asbd.mBytesPerFrame == 0 || asbd.mFramesPerPacket == 0 || asbd.mBytesPerPacket == 0;
}

static inline
OSStatus calculateBufferSizeAndPacketsForConverter(AudioConverterSettings *converterSettings,
                                                   UInt32 *outBufferSize,
                                                   UInt32 *outPacketsCount,
                                                   BOOL isInput) {
    OSStatus resultingStatus = noErr;

    UInt32 bufferSize = kBufferSize32KB;
    UInt32 packetsToReceive = 0;

    AudioStreamBasicDescription asbd = isInput ? converterSettings->sourceASBD :
                                                 converterSettings->destinationASBD;

    if (asbd.mBytesPerPacket) {
        // We have CBR. Good.
        // At least hold 1 packet if buffer < that packet.
        bufferSize = MAX(bufferSize, asbd.mBytesPerPacket);

        packetsToReceive = bufferSize / asbd.mBytesPerPacket;
    } else {
        if (asbd.mFramesPerPacket &&
            asbd.mBytesPerFrame) {
            // At least hold 1 packet if buffer < that packet.
            bufferSize = MAX(bufferSize, asbd.mChannelsPerFrame);

            packetsToReceive = bufferSize / asbd.mBytesPerFrame;

        } else {
            // We have VBR format. Get output packet size from converter
            UInt32 maxOutputPacketSize = 0;

            AudioConverterPropertyID packetSizeProp = isInput ? kAudioConverterPropertyMaximumInputPacketSize :
                                                                kAudioConverterPropertyMaximumOutputPacketSize;

            resultingStatus = AudioConverterGetProperty(converterSettings->rawConverter,
                                                        packetSizeProp,
                                                        &(UInt32){sizeof(UInt32)},
                                                        &maxOutputPacketSize);
            // TODO:
            // HALT IF ERROR.

            bufferSize = MAX(bufferSize, maxOutputPacketSize);

            packetsToReceive = bufferSize / maxOutputPacketSize;
        }
    }

    if (outBufferSize) {
        *outBufferSize = bufferSize;
    }

    if (outPacketsCount) {
        *outPacketsCount = packetsToReceive;
    }

    return resultingStatus;
}

#pragma mark - AudioConverterProcedures

static inline
OSStatus converterProc (AudioConverterRef inAudioConverter,
                        UInt32 *ioNumberDataPackets,
                        AudioBufferList *ioData,
                        AudioStreamPacketDescription **outDataPacketDescription,
                        void *context) {
    // We passed 1 buffer - callback should return 1 buffer to us.
    assert(ioData->mNumberBuffers == 1);

    // Cleanup
    ioData->mBuffers[0].mDataByteSize = 0;
    ioData->mBuffers[0].mData = NULL;

    AudioConverterSettings *converterSettings = (AudioConverterSettings *)context;

    if (converterSettings->currentPacketIndex + *ioNumberDataPackets > converterSettings->totalPackets) {
        *ioNumberDataPackets = converterSettings->totalPackets - converterSettings->currentPacketIndex;
    }

    if (*ioNumberDataPackets == 0) {
        return kOutOfDataError;
    }

    // Give bytes.
    ioData->mBuffers[0].mDataByteSize = converterSettings->totalBytes;
    ioData->mBuffers[0].mData = (void *)converterSettings->rawStreamData;

    // Give packet description.
    // It's ok that above we gave WHOLE data.
    // Packet descriptions contain offset in buffer to deliver packets to codec.
    if (outDataPacketDescription) {
        *outDataPacketDescription = (AudioStreamPacketDescription *)&converterSettings->packetDescriptions[converterSettings->currentPacketIndex];
    }

    converterSettings->currentPacketIndex += *ioNumberDataPackets;

    return noErr;
}

@end


text:
'''

'''
from __future__ import absolute_import

class DocumentChangedEvent(object):
    '''

    '''

    def __init__(self, document, setter=None):
        '''

        '''
        self.document = document
        self.setter = setter

    def dispatch(self, receiver):
        '''

        '''
        if hasattr(receiver, '_document_changed'):
            receiver._document_changed(self)

class DocumentPatchedEvent(DocumentChangedEvent):
    '''

    '''

    def dispatch(self, receiver):
        '''

        '''
        super(DocumentPatchedEvent, self).dispatch(receiver)
        if hasattr(receiver, '_document_patched'):
            receiver._document_patched(self)

class ModelChangedEvent(DocumentPatchedEvent):
    '''

    '''

    def __init__(self, document, model, attr, old, new, serializable_new, hint=None, setter=None):
        '''

        '''
        if setter is None and isinstance(hint, (ColumnsStreamedEvent, ColumnsPatchedEvent)):
            setter = hint.setter
        super(ModelChangedEvent, self).__init__(document, setter)
        self.model = model
        self.attr = attr
        self.old = old
        self.new = new
        self.serializable_new = serializable_new
        self.hint = hint

    def dispatch(self, receiver):
        '''

        '''
        super(ModelChangedEvent, self).dispatch(receiver)
        if hasattr(receiver, '_document_model_changed'):
            receiver._document_model_changed(self)

class ColumnsStreamedEvent(DocumentPatchedEvent):
    '''

    '''

    def __init__(self, document, column_source, data, rollover, setter=None):
        '''

        '''
        super(ColumnsStreamedEvent, self).__init__(document, setter)
        self.column_source = column_source
        self.data = data
        self.rollover = rollover

    def dispatch(self, receiver):
        '''

        '''
        super(ModelChangedEvent, self).dispatch(receiver)
        if hasattr(receiver, '_columns_streamed'):
            receiver._columns_streamed(self)

class ColumnsPatchedEvent(DocumentPatchedEvent):
    '''

    '''

    def __init__(self, document, column_source, patches, setter=None):
        '''

        '''
        super(ColumnsPatchedEvent, self).__init__(document, setter)
        self.column_source = column_source
        self.patches = patches

    def dispatch(self, receiver):
        '''

        '''
        super(ModelChangedEvent, self).dispatch(receiver)
        if hasattr(receiver, '_columns_patched'):
            receiver._columns_patched(self)

class TitleChangedEvent(DocumentPatchedEvent):
    '''

    '''

    def __init__(self, document, title, setter=None):
        '''

        '''
        super(TitleChangedEvent, self).__init__(document, setter)
        self.title = title

class RootAddedEvent(DocumentPatchedEvent):
    '''

    '''

    def __init__(self, document, model, setter=None):
        '''

        '''
        super(RootAddedEvent, self).__init__(document, setter)
        self.model = model

class RootRemovedEvent(DocumentPatchedEvent):
    '''

    '''

    def __init__(self, document, model, setter=None):
        '''

        '''
        super(RootRemovedEvent, self).__init__(document, setter)
        self.model = model

class SessionCallbackAdded(DocumentChangedEvent):
    '''

    '''

    def __init__(self, document, callback):
        '''

        '''
        super(SessionCallbackAdded, self).__init__(document)
        self.callback = callback

    def dispatch(self, receiver):
        '''

        '''
        super(SessionCallbackAdded, self).dispatch(receiver)
        if hasattr(receiver, '_session_callback_added'):
            receiver._session_callback_added(self)

class SessionCallbackRemoved(DocumentChangedEvent):
    '''

    '''

    def __init__(self, document, callback):
        '''

        '''
        super(SessionCallbackRemoved, self).__init__(document)
        self.callback = callback

    def dispatch(self, receiver):
        '''

        '''
        super(SessionCallbackRemoved, self).dispatch(receiver)
        if hasattr(receiver, '_session_callback_removed'):
            receiver._session_callback_removed(self)


text:
package org.jasig.cas.authentication.handler;

/**
 * Strategy pattern component for transforming principal names in the authentication pipeline.
 *
 * @author Howard Gilbert
 * @since 3.3.6
 */
public interface PrincipalNameTransformer {

    /**
     * Transform the string typed into the login form into a tentative Principal Name to be
     * validated by a specific type of Authentication Handler.
     *
     * <p>The Principal Name eventually assigned by the PrincipalResolver may
     * be unqualified ("AENewman"). However, validation of the Principal name against a
     * particular backend source represented by a particular Authentication Handler may
     * require transformation to a temporary fully qualified format such as
     * AENewman@MAD.DCCOMICS.COM or MAD\AENewman. After validation, this form of the
     * Principal name is discarded in favor of the choice made by the Resolver.
     *
     * @param formUserId The raw userid typed into the login form
     * @return the string that the Authentication Handler should lookup in the backend system
     */
    String transform(String formUserId);
}


text:
mpache is a simple linux static web server code by c.
base on the 《Linux C程序设计 王者归来》part 26.3 .
miku remove the code about cgi file (bug) and add the support for http post request.

# how to start
make
./mpache

# gcc info
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.0.0
Thread model: posix

# next to do
完善GET与POST请求的参数处理
尝试与PHP做整合


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver;
using SCNDISC.Server.Application.Services.Partners;
using SCNDISC.Server.Domain.Aggregates.Partners;
using SCNDISC.Server.Infrastructure.Imaging;
using SCNDISC.Server.Infrastructure.Persistence.Commands.Partners;
using SCNDISC.Server.Infrastructure.Persistence.Queries.Partners;

namespace SCNDISC.Server.Application.Tests.Services.Partners
{
    [TestClass]
    public class PartnerApplicationServiceTests : BaseApplicationServiceTests
    {
        [TestMethod]
        public async Task ShouldGetPartnerDetailsAsync()
        {
            var branches = await CreateHierachyAsync(_collectionProvider.GetCollection<Branch>(), 3, 3, 3, 2, 2);
            var partner = branches.First(b => b.Id == b.PartnerId);
            var service = CreateService();
            var partnerDetails = await service.GetPartnerDetailsAsync(partner.Id);
            Assert.AreEqual(4, partnerDetails.Count());
            Assert.IsTrue(partnerDetails.All(b => b.PartnerId == partner.Id));
        }

        [TestMethod]
        public async Task ShouldGetBranchToolTipAsync()
        {
            var branches = await CreateHierachyAsync(_collectionProvider.GetCollection<Branch>(), 3, 3, 3, 2, 2);
            var branch = branches.First(b => b.Id != b.PartnerId);
            var partner = branches.First(b => b.Id == branch.PartnerId);
            var service = CreateService();
            var toolTip = await service.GetBranchToolTipAsync(branch.PartnerId, branch.Id);
            Assert.AreEqual(branch.Id, toolTip.Id);
            Assert.AreEqual(branch.PartnerId, toolTip.PartnerId);
            Assert.IsTrue(AreEntityCollectionsEqual(branch.Discounts, toolTip.Discounts));
            Assert.IsTrue(AreLocalizableTextPropertiesEqual(partner.Name, toolTip.Name));
            Assert.IsTrue(AreLocalizableTextPropertiesEqual(branch.Name, toolTip.Description));
        }

        protected IPartnerApplicationService CreateService()
        {
            return new PartnerApplicationService(
	            CreateCommandQuery<PartnerDetailsQuery, Branch>(),
	            CreateCommandQuery<BranchToolTipQuery, Branch>(),
                CreateCommandQuery<ActivePartnerIdsQuery, Branch>(),
                CreateCommandQuery<UpsertBranchCommand, Branch>(),
	            CreateCommandQuery<DeleteBranchCommand, Branch>(),
	            CreateCommandQuery<UpsertPartnerCommand, Branch>(),
	            CreateCommandQuery<DeletePartnerCommand, Branch>()
	            );
        }

        //[TestMethod]
        [Ignore]
        public async Task GenerateDb()
        {
            await CreateHierachyAsync(_collectionProvider.GetCollection<Branch>(), 1, 1, 1, 1, 1);
        }

        // !Important!: to use this method on real DB you had better comment out the line of the code with
        // deleting all Branches during initialization of BaseApplicationServiceTest in Initialize method,
        // set up desired db to processing in Settings
        // and then execute only the below method to do images reprocessing
        //[TestMethod]
        [Ignore]
        public async Task ImagesProcessing()
        {
            var collection = _collectionProvider.GetCollection<Branch>();
            var filter = new FilterDefinitionBuilder<Branch>().Where(b => b.IsDeleted == false);
            var imageConverter = new ImageConverter();
            var sortDefinition = new SortDefinitionBuilder<Branch>().Ascending(b => b.Modified);
            var counter = 0;

            using (var cursor = await collection.FindAsync(filter, new FindOptions<Branch>() { Sort = sortDefinition }))
            {
                using (var logWriter = System.IO.File.AppendText($"imageProcessing-{DateTime.UtcNow.ToFileTimeUtc()}.txt"))
                {
                    try
                    {
                        logWriter.WriteLine($"Image processing started at {DateTime.UtcNow}:");

                        while (await cursor.MoveNextAsync())
                        {
                            var branches = cursor.Current;
                            foreach (Branch branch in branches)
                            {
                                UpdateDefinition<Branch> updateBranch = null;
                                string processedIcon = null;
                                string processedImage = null;

                                if (branch.Id != branch.PartnerId)
                                {
                                    // branch
                                    if (!string.IsNullOrEmpty(branch.Image) || !string.IsNullOrEmpty(branch.Icon))
                                    {
                                        updateBranch = Builders<Branch>.
                                        Update.
                                        Set(x => x.Icon, null).
                                        Set(x => x.Image, null);
                                        counter++;
                                    }
                                }
                                else if (branch.Id == branch.PartnerId)
                                {
                                    // partner
                                    processedIcon = branch.Icon == null ? null : Convert.ToBase64String(imageConverter.Convert(Convert.FromBase64String(branch.Icon), ImageOptions.Icon));
                                    processedImage = branch.Image == null ? null : Convert.ToBase64String(imageConverter.Convert(Convert.FromBase64String(branch.Image), ImageOptions.Image));

                                    if (branch.Icon?.Length != processedIcon?.Length || branch.Image?.Length != processedImage?.Length)
                                    {
                                        updateBranch = Builders<Branch>.
                                        Update.
                                        Set(x => x.Modified, DateTime.UtcNow).
                                        Set(x => x.Icon, processedIcon).
                                        Set(x => x.Image, processedImage);
                                        counter++;
                                    }
                                }

                                if (updateBranch != null)
                                {
                                    var filterBranch = new FilterDefinitionBuilder<Branch>().Where(b => b.Id == branch.Id);
                                    var resultOfProcessing = await collection.UpdateOneAsync(filterBranch, updateBranch);
                                    Assert.IsTrue(resultOfProcessing.ModifiedCount == 1);

                                    logWriter.WriteLine($"____________________________________________{counter}______________________________________________");
                                    logWriter.WriteLine($"Image processing for BranchId = {branch.Id} with partnerId = {branch.PartnerId}");
                                    logWriter.WriteLine($"Icon and (or) Image were processed for branch with Id = {branch.Id}");
                                    logWriter.WriteLine($"Icon original size: {branch.Icon?.Length}, after processing: {processedIcon?.Length}");
                                    logWriter.WriteLine($"Image original size: {branch.Image?.Length}, after processing: {processedImage?.Length}");
                                    logWriter.WriteLine("____________________________________________________________________________________________________");
                                }
                            }
                        }
                        logWriter.WriteLine($"Image processing finished at {DateTime.UtcNow}");
                    }
                    catch (Exception ex)
                    {
                        logWriter.WriteLine(ex);
                        logWriter.Dispose();
                    }
                }
            }
        }
    }
}


text:
import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-progressbar-texttypes',
  templateUrl: './progressbar-texttypes.html'
})
export class NgbdProgressbarTextTypes {
}


text:
package foam.dao.index;

import foam.core.FObject;
import foam.core.PropertyInfo;
import foam.dao.Sink;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Binary;
import foam.mlang.predicate.False;
import foam.mlang.predicate.Gt;
import foam.mlang.predicate.Gte;
import foam.mlang.predicate.Lt;
import foam.mlang.predicate.Lte;
import foam.mlang.predicate.Predicate;
import foam.mlang.sink.Count;
import java.util.Arrays;

public class TreeIndex implements Index {
  protected Index tail_;
  protected PropertyInfo prop_;
  protected long selectCount_;

  public TreeIndex(PropertyInfo prop) {
    this(prop, ValueIndex.instance());
  }

  public TreeIndex(PropertyInfo prop, Index tail) {
    prop_ = prop;
    selectCount_ = 0;
    tail_ = tail;
  }

  public Object bulkLoad(FObject[] a) {
    Arrays.sort(a);
    return TreeNode.getNullNode().bulkLoad(tail_, prop_, 0, a.length-1, a);
  }

  protected Binary isExprMatch(Predicate predicate, Class model) {
    if ( predicate != null && prop_ != null && model != null ) {
      if ( predicate instanceof Binary &&
           model.equals(predicate.getClass()) &&
           ((Binary) predicate).getArg1().equals(prop_) ) {

        Binary b = new Binary() {};
        b.setArg2(((Binary) predicate).getArg2());
        return b;
      }
    }
    return null;
  }

  public Object put(Object state, FObject value) {
    if ( state == null ) {
      state = TreeNode.getNullNode();
    }
    return ((TreeNode) state).putKeyValue((TreeNode)state,
      prop_, prop_.f(value), value, tail_);
  }

  public Object remove(Object state, FObject value) {
    return ((TreeNode) state).removeKeyValue((TreeNode) state, prop_, prop_.f(value), value, tail_);
  }

  public Object removeAll() {
    return TreeNode.getNullNode();
  }

  //TODO
  public FindPlan planFind(Object state, Object key) {
    return new TreeLookupFindPlan(prop_, (state != null ? ((TreeNode) state).size : 0) );
  }

  //TODO
  public SelectPlan planSelect(Object state, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
    if ( predicate == null && sink instanceof Count ) {
      return new CountPlan(((TreeNode) state).size);
    }

    if ( predicate != null && predicate instanceof False ) {
      return NotFoundPlan.instance();
    }

//    Binary expr = isExprMatch(predicate, In.class);
//    Binary expr = isExprMatch(predicate, Eq.class);
//
//    if ( expr != null ) {
//      Object key = expr.getArg2().f(expr);
//      Object result = this.get(key);
//      if ( result == null) {
//        return NotFoundPlan.instance();
//      }
//      Plan[] subPlans = { planSelect(result, sink, skip, limit, order, predicate) };
//      return new AltPlan(subPlans,this.prop);
//    }
    TreeNode subTree = ((TreeNode) state);

    Binary expr = isExprMatch(predicate, Gt.class);
    if ( expr != null ) subTree = subTree.gt(subTree, expr.getArg2().f(expr), prop_);

    expr = isExprMatch(predicate, Gte.class);
    if ( expr != null ) subTree = subTree.gte(subTree, expr.getArg2().f(expr), prop_);

    expr = isExprMatch(predicate, Lt.class);
    if ( expr != null ) subTree = subTree.lt(subTree, expr.getArg2().f(expr), prop_);

    expr = isExprMatch(predicate, Lte.class);
    if ( expr != null ) subTree = subTree.lte(subTree, expr.getArg2().f(expr), prop_);

    long cost = subTree.size;

//    return CustomPlan;

    return (SelectPlan) ValuePlan.instance();
  }

  public long size(Object state) {
    return ((TreeNode) state).size;
  }

  public void onAdd(Sink sink) {
  }

}


text:
import FLOAT32_ABS_MASK = require( './index' );

// TESTS //

// The export is a number...
{
	// tslint:disable-next-line:no-unused-expression
	FLOAT32_ABS_MASK; // $ExpectType number
}


text:
{{{
  "title": "Getting Started with AppFog's Command Line",
  "date": "1-25-2015",
  "author": "Originally Posted On AppFog",
  "attachments": [],
  "contentIsHTML": false
}}}

[AppFog](http://www.ctl.io/appfog) provides a cloud-based hosting service for your favorite web application stack. You can get servers setup and ready for your code in under a minute using our command line tools or our web console–the choice is yours. Today, we're going to walk through deploying a WordPress app using af, the command line interface to AppFog.

To get started, you're going to need a beta account and af. If we haven't already let you into our private beta, add your email to our list at [appfog](http://www.ctl.io) and we'll add you in no time!

af is based on vmc, the [CloudFoundry](http://cloudfoundry.org/index.html) command line tool and is distributed as a RubyGem. To install af, you will need [Ruby](https://www.ruby-lang.org/en/) and [RubyGems](https://rubygems.org/). If these are available, then run

$ gem install af

Now you're ready to login!

$ af login
Email: jeremy@appfog.com
Password: *********
Successfully logged into [https://api.appfog.com]

Next, you're going to need some code to deploy. Luckily, we have prepared a CloudFoundry-ready WordPress sample at [https://github.com/phpfog/af-sample-wordpress](https://github.com/phpfog/af-sample-wordpress). If git is available on your system, then run

$ git clone https://github.com/phpfog/af-sample-wordpress.git
$ cd af-sample-wordpress

If you'd rather not use git, you can download a zip archive from [https://github.com/phpfog/af-sample-wordpress/](https://github.com/phpfog/af-sample-wordpress/).

Now let's push our code to AppFog, name it my-first-app and give it a MySQL database. First, we need to call af push to create our app and upload our code.

$ af push my-first-app --url my-first-app.aws.af.cm
Creating Application: OK
Uploading Application:
  Checking for available resources: OK
  Processing resources: OK
  Packing application: OK
  Uploading (127K): OK
Push Status: OK
Staging Application: OK
Starting Application: OK

af detected that we are pushing PHP code and staged and deployed it using Apache 2, but it still needs to connect to a database so let's ask af to create a MySQL database and bind it to our app.

$ af create-service mysql --bind my-first-app
Creating Service [mysql-cff71]: OK
Binding Service: OK
Stopping Application: OK
Staging Application: OK
Starting Application: OK
And you're done! You can now visit your new WP app at http://my-first-app.aws.af.cm/ (or whichever url you chose).

That's all for now. You can learn more about af by running af help or asking a question at [support.appfog.com](support.appfog.com).


text:
odoo.testing = {};

odoo.testing.start_services = function () {
    var factories = odoo.__DEBUG__.factories;
    var jobs = _.map(factories, function (factory, name) {
        return {
            name: name,
            factory: factory,
            deps: factory.deps,
        };
    });
    var services = Object.create({
        qweb: new QWeb2.Engine(),
        $: $,
        _: _,
    });
  return odoo.process_jobs(jobs, services);
};

odoo.testing.MockRPC = function (session) {
    this.responses = {};
};

odoo.testing.MockRPC.prototype.clear = function () {
    this.responses = {};
};

odoo.testing.MockRPC.prototype.interceptRPC = function (session) {
    session.rpc = this.rpc.bind(this);
};

odoo.testing.MockRPC.prototype.add = function (spec, handler, no_override) {
    if (no_override && (spec in this.responses)) {
        return;
    }
    this.responses[spec] = handler;
};

odoo.testing.MockRPC.prototype.rpc =  function (url, rparams, options) {
    if (_.isString(url)) {
        url = {url: url};
    }
    var fn, params;
    var needle = rparams.model + ':' + rparams.method;
    if (url.url.substr(0, 20) === '/web/dataset/call_kw' && needle in this.responses) {
        fn = this.responses[needle];
        params = [
            rparams.args || [],
            rparams.kwargs || {}
        ];
    } else {
        fn = this.responses[url.url];
        params = [{params: rparams}];
    }

    if (!fn) {
        return $.Deferred().reject({}, 'failed',
            _.str.sprintf("Url %s not found in mock responses, with arguments %s",
                          url.url, JSON.stringify(rparams))
        ).promise();
    }
    try {
        return $.when(fn.apply(null, params)).then(function (result) {
            // Wrap for RPC layer unwrapper thingy
            return result;
        });
    } catch (e) {
        // not sure why this looks like that
        return $.Deferred().reject({}, 'failed', String(e));
    }
};

odoo.testing.noop = function () {};

odoo.define_section = function (name, section_deps) {
    var section_body, options, mock;

    if (typeof arguments[2] === 'function') {
        options = {};
        section_body = arguments[2];
    } else {
        options = arguments[2];
        section_body = arguments[3];
    }

    QUnit.module(name, options);

    function test () {
        var name = arguments[0],
            dep_names = arguments[1] instanceof Array ? arguments[1] : [],
            body = arguments[arguments.length - 1];

        QUnit.test(name, function (assert) {
            var services = odoo.testing.start_services();
            var deps = _.map(section_deps.concat(dep_names), function (name) { return services[name]; });
            services.qweb.add_template(odoo.testing.templates);
            mock.clear();
            mock.interceptRPC(services['web.session']);
            var info = {
                assert: assert,
                mock: mock,
                deps: _.pick.apply(null, [services].concat(section_deps).concat(dep_names)),
            }
            return body.apply(info, [assert].concat(deps));
        });
    }

    var mock = new odoo.testing.MockRPC();
    section_body(test, mock);
};

QUnit.done(function(result) {
    if (result.failed === 0) {
        console.log('ok');
    } else {
        console.log('error');
    }
});

QUnit.log(function(result) {
    if (!result.result) {
        console.log(result.name, 'in section', result.module, 'failed:', result.message);
    }
});

(new QWeb2.Engine()).load_xml("/web/webclient/qweb", function (err, xDoc) {
    odoo.testing.templates = xDoc;
    QUnit.start();
});

QUnit.config.autostart = false;

localStorage.clear();
QUnit.config.testTimeout = 1 * 60 * 1000;
QUnit.moduleDone(function(result) {
    if (!result.failed) {
        console.log(result.name, "passed", result.total, "tests.");
    } else {
        console.log(result.name, "failed:", result.failed, "tests out of", result.total, ".");
    }

});


text:
namespace content {

namespace {

gpu::GpuDiskCacheFactory* factory_instance = nullptr;

void CreateFactoryInstance() {
  DCHECK(!factory_instance);
  // Setup static reserved handles and their mapping to specific paths.
  gpu::GpuDiskCacheFactory::HandleToPathMap handle_to_path_map;
  if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableGpuShaderDiskCache)) {
    base::FilePath compositor_cache_dir =
        GetContentClient()->browser()->GetShaderDiskCacheDirectory();
    if (!compositor_cache_dir.empty()) {
      handle_to_path_map.emplace(gpu::kDisplayCompositorGpuDiskCacheHandle,
                                 compositor_cache_dir);
    }
    base::FilePath gr_cache_dir =
        GetContentClient()->browser()->GetGrShaderDiskCacheDirectory();
    if (!gr_cache_dir.empty()) {
      handle_to_path_map.emplace(gpu::kGrShaderGpuDiskCacheHandle,
                                 gr_cache_dir);
    }
  }

  factory_instance = new gpu::GpuDiskCacheFactory(handle_to_path_map);
}

}  // namespace

void InitGpuDiskCacheFactorySingleton() {
  CreateFactoryInstance();
}

gpu::GpuDiskCacheFactory* GetGpuDiskCacheFactorySingleton() {
  return factory_instance;
}

}  // namespace content


text:
package me.magicall.game.map;

import me.magicall.game.Game;
import me.magicall.game.unit.UnitsHolder;

public interface GamingMap extends GameMap, UnitsHolder {

	Game getGame();
}


text:
<?php

namespace KoolKode\Database\Migration;

class MigrationConfig
{
	protected $migrations = [];

	public function addMigration(AbstractMigration $migration)
	{
		$this->migrations[$migration->getVersion()] = $migration;

		ksort($this->migrations);
	}

	public function loadMigrationsFromDirectory($dir)
	{
		foreach(glob($dir . DIRECTORY_SEPARATOR . '*.php') as $file)
		{
			$file = new \SplFileInfo($file);

			$m = NULL;

			if($file->isFile() && preg_match("'^(Version([0-9]{14}))\\.php$'i", $file->getFilename(), $m))
			{
				$this->migrations[$m[2]] = realpath($file->getPathname());
			}
		}

		ksort($this->migrations);
	}

	public function getMigrations()
	{
		return $this->migrations;
	}
}


text:
/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');

const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'admin', 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      use: {
        loader: 'babel',
        options: {
          "presets": options.babelPresets,
          "env": {
            "production": {
              "only": [
                "src",
              ],
              "plugins": [
                require.resolve('babel-plugin-transform-react-remove-prop-types'),
                require.resolve('babel-plugin-transform-react-constant-elements'),
                require.resolve('babel-plugin-transform-react-inline-elements'),
              ],
            },
            "test": {
              "plugins": [
                "istanbul",
              ],
            },
          },
        }
      },
      include: [
        path.join(process.cwd(), 'admin', 'src'),
        // Add the `strapi-helper-plugin` folders watched by babel
        path.join(process.cwd(), 'node_modules', 'strapi-helper-plugin', 'lib', 'src'),
      ],
    }, {
      // Transform our own .scss files
      test: /\.scss$/,
      exclude: /node_modules/,
      // loader: 'null-loader'
      use: options.cssLoaders,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader',
    }, {
      test: /\.(jpg|png|gif)$/,
      loaders: [
        'file-loader',
        'image-webpack?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}',
      ],
    }, {
      test: /\.json$/,
      loader: 'json-loader',
    }, {
      test: /\.(mp4|webm)$/,
      loader: 'url-loader?limit=10000',
    }],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports?self.fetch!whatwg-fetch',
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new webpack.NamedModulesPlugin(),
  ]),
  resolve: {
    modules: [
      'admin/src',
      'node_modules/strapi-helper-plugin/lib/src',
      'node_modules/strapi-helper-plugin/node_modules',
      'node_modules',
    ],
    symlinks: false,
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },

  resolveLoader: {
    modules: [
      path.join(__dirname, '..', '..', '..', 'node_modules'),
      path.join(process.cwd(), 'node_modules'),
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
});