text:
package org.springframework.boot.cli.command.init;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import joptsimple.OptionSet;
import joptsimple.OptionSpec;

import org.springframework.boot.cli.command.Command;
import org.springframework.boot.cli.command.HelpExample;
import org.springframework.boot.cli.command.OptionParsingCommand;
import org.springframework.boot.cli.command.options.OptionHandler;
import org.springframework.boot.cli.command.status.ExitStatus;
import org.springframework.boot.cli.util.Log;
import org.springframework.util.Assert;

/**
 * {@link Command} that initializes a project using Spring initializr.
 *
 * @author Stephane Nicoll
 * @author Eddú Meléndez
 * @since 1.2.0
 */
public class InitCommand extends OptionParsingCommand {

	public InitCommand() {
		this(new InitOptionHandler(new InitializrService()));
	}

	public InitCommand(InitOptionHandler handler) {
		super("init", "Initialize a new project using Spring "
				+ "Initialzr (start.spring.io)", handler);
	}

	@Override
	public String getUsageHelp() {
		return "[options] [location]";
	}

	@Override
	public Collection<HelpExample> getExamples() {
		List<HelpExample> examples = new ArrayList<HelpExample>();
		examples.add(new HelpExample("To list all the capabilities of the service",
				"spring init --list"));
		examples.add(new HelpExample("To creates a default project", "spring init"));
		examples.add(new HelpExample("To create a web my-app.zip",
				"spring init -d=web my-app.zip"));
		examples.add(new HelpExample("To create a web/data-jpa gradle project unpacked",
				"spring init -d=web,jpa --build=gradle my-dir"));
		return examples;
	}

	static class InitOptionHandler extends OptionHandler {

		private final ServiceCapabilitiesReportGenerator serviceCapabilitiesReport;

		private final ProjectGenerator projectGenerator;

		private OptionSpec<String> target;

		private OptionSpec<Void> listCapabilities;

		private OptionSpec<String> groupId;

		private OptionSpec<String> artifactId;

		private OptionSpec<String> version;

		private OptionSpec<String> name;

		private OptionSpec<String> description;

		private OptionSpec<String> packageName;

		private OptionSpec<String> type;

		private OptionSpec<String> packaging;

		private OptionSpec<String> build;

		private OptionSpec<String> format;

		private OptionSpec<String> javaVersion;

		private OptionSpec<String> language;

		private OptionSpec<String> bootVersion;

		private OptionSpec<String> dependencies;

		private OptionSpec<Void> extract;

		private OptionSpec<Void> force;

		InitOptionHandler(InitializrService initializrService) {
			this.serviceCapabilitiesReport = new ServiceCapabilitiesReportGenerator(
					initializrService);
			this.projectGenerator = new ProjectGenerator(initializrService);

		}

		@Override
		protected void options() {
			this.target = option(Arrays.asList("target"), "URL of the service to use")
					.withRequiredArg().defaultsTo(
							ProjectGenerationRequest.DEFAULT_SERVICE_URL);
			this.listCapabilities = option(Arrays.asList("list", "l"),
					"List the capabilities of the service. Use it to discover the "
							+ "dependencies and the types that are available");
			projectGenerationOptions();
			otherOptions();
		}

		private void projectGenerationOptions() {
			this.groupId = option(Arrays.asList("groupId", "g"),
					"Project coordinates (for example 'org.test')").withRequiredArg();
			this.artifactId = option(Arrays.asList("artifactId", "a"),
					"Project coordinates; infer archive name (for example 'test')")
					.withRequiredArg();
			this.version = option(Arrays.asList("version", "v"),
					"Project version (for example '0.0.1-SNAPSHOT')").withRequiredArg();
			this.name = option(Arrays.asList("name", "n"),
					"Project name; infer application name").withRequiredArg();
			this.description = option("description", "Project description")
					.withRequiredArg();
			this.packageName = option("package-name", "Package name").withRequiredArg();
			this.type = option(
					Arrays.asList("type", "t"),
					"Project type. Not normally needed if you use --build "
							+ "and/or --format. Check the capabilities of the service "
							+ "(--list) for more details").withRequiredArg();
			this.packaging = option(Arrays.asList("packaging", "p"),
					"Project packaging (for example 'jar')").withRequiredArg();
			this.build = option("build",
					"Build system to use (for example 'maven' or 'gradle')")
					.withRequiredArg().defaultsTo("maven");
			this.format = option(
					"format",
					"Format of the generated content (for example 'build' for a build file, "
							+ "'project' for a project archive)").withRequiredArg()
					.defaultsTo("project");
			this.javaVersion = option(Arrays.asList("java-version", "j"),
					"Language level (for example '1.8')").withRequiredArg();
			this.language = option(Arrays.asList("language", "l"),
					"Programming language  (for example 'java')").withRequiredArg();
			this.bootVersion = option(Arrays.asList("boot-version", "b"),
					"Spring Boot version (for example '1.2.0.RELEASE')")
					.withRequiredArg();
			this.dependencies = option(
					Arrays.asList("dependencies", "d"),
					"Comma-separated list of dependency identifiers to include in the "
							+ "generated project").withRequiredArg();
		}

		private void otherOptions() {
			this.extract = option(Arrays.asList("extract", "x"),
					"Extract the project archive. Inferred if a location is specified without an extension");
			this.force = option(Arrays.asList("force", "f"),
					"Force overwrite of existing files");
		}

		@Override
		protected ExitStatus run(OptionSet options) throws Exception {
			try {
				if (options.has(this.listCapabilities)) {
					generateReport(options);
				}
				else {
					generateProject(options);
				}
				return ExitStatus.OK;
			}
			catch (ReportableException ex) {
				Log.error(ex.getMessage());
				return ExitStatus.ERROR;
			}
			catch (Exception ex) {
				Log.error(ex);
				return ExitStatus.ERROR;
			}
		}

		private void generateReport(OptionSet options) throws IOException {
			Log.info(this.serviceCapabilitiesReport.generate(options.valueOf(this.target)));
		}

		protected void generateProject(OptionSet options) throws IOException {
			ProjectGenerationRequest request = createProjectGenerationRequest(options);
			this.projectGenerator.generateProject(request, options.has(this.force));
		}

		protected ProjectGenerationRequest createProjectGenerationRequest(
				OptionSet options) {

			List<?> nonOptionArguments = new ArrayList<Object>(
					options.nonOptionArguments());
			Assert.isTrue(nonOptionArguments.size() <= 1,
					"Only the target location may be specified");

			ProjectGenerationRequest request = new ProjectGenerationRequest();
			request.setServiceUrl(options.valueOf(this.target));
			if (options.has(this.bootVersion)) {
				request.setBootVersion(options.valueOf(this.bootVersion));
			}
			if (options.has(this.dependencies)) {
				for (String dep : options.valueOf(this.dependencies).split(",")) {
					request.getDependencies().add(dep.trim());
				}
			}
			if (options.has(this.javaVersion)) {
				request.setJavaVersion(options.valueOf(this.javaVersion));
			}
			if (options.has(this.packageName)) {
				request.setPackageName(options.valueOf(this.packageName));
			}
			request.setBuild(options.valueOf(this.build));
			request.setFormat(options.valueOf(this.format));
			request.setDetectType(options.has(this.build) || options.has(this.format));
			if (options.has(this.type)) {
				request.setType(options.valueOf(this.type));
			}
			if (options.has(this.packaging)) {
				request.setPackaging(options.valueOf(this.packaging));
			}
			if (options.has(this.language)) {
				request.setLanguage(options.valueOf(this.language));
			}
			if (options.has(this.groupId)) {
				request.setGroupId(options.valueOf(this.groupId));
			}
			if (options.has(this.artifactId)) {
				request.setArtifactId(options.valueOf(this.artifactId));
			}
			if (options.has(this.name)) {
				request.setName(options.valueOf(this.name));
			}
			if (options.has(this.version)) {
				request.setVersion(options.valueOf(this.version));
			}
			if (options.has(this.description)) {
				request.setDescription(options.valueOf(this.description));
			}
			request.setExtract(options.has(this.extract));
			if (nonOptionArguments.size() == 1) {
				String output = (String) nonOptionArguments.get(0);
				request.setOutput(output);
			}
			return request;
		}

	}

}


text:
#include "system.h"
#include "input.h"
#include "info.h"
#include "errors.h"

#ifdef	__cplusplus
extern	"C" {
#endif

void TreeCCOperationFree(TreeCCOperation *oper)
{
	TreeCCParam *param, *nextParam;
	TreeCCOperationCase *operCase, *nextCase;
	TreeCCTrigger *trigger, *nextTrigger;

	/* Free the name and return type */
	free(oper->name);
	if(oper->className)
	{
		free(oper->className);
	}
	free(oper->returnType);

	/* Free the parameters */
	param = oper->params;
	while(param != 0)
	{
		nextParam = param->next;
		if(param->name)
		{
			free(param->name);
		}
		free(param->type);
		param = nextParam;
	}

	/* Free the operation cases */
	operCase = oper->firstCase;
	while(operCase != 0)
	{
		nextCase = operCase->next;
		if(operCase->code && !(operCase->nextHeader))
		{
			free(operCase->code);
		}
		trigger = operCase->triggers;
		while(trigger != 0)
		{
			nextTrigger = trigger->next;
			free(trigger);
			trigger = nextTrigger;
		}
		free(operCase);
		operCase = nextCase;
	}

	/* Free the array of sorted operation cases */
	if(oper->sortedCases)
	{
		free(oper->sortedCases);
	}

	/* Free the operation block itself */
	free(oper);
}

TreeCCOperation *TreeCCOperationCreate(TreeCCContext *context,
									   char *returnType, char *name,
									   char *className, char *defValue,
									   TreeCCParam *params, int flags,
									   int numTriggers, char *filename,
									   long linenum)
{
	TreeCCOperation *oper;
	unsigned int hash;

	/* Print debugging information if required */
	if(context->debugMode)
	{
		TreeCCParam *param;
		TreeCCDebug(linenum, "%%operation %s %s%s%s %d",
					returnType,
					(className ? className : ""),
					(className ? "::" : ""),
					name, flags);
		param = params;
		while(param != 0)
		{
			TreeCCDebug(linenum, "%%param %s %s %d",
						param->type, (param->name ? param->name : "no_name"),
						param->flags);
			param = param->next;
		}
	}

	/* Allocate the operation block */
	if((oper = (TreeCCOperation *)malloc(sizeof(TreeCCOperation))) == 0)
	{
		TreeCCOutOfMemory(context->input);
	}

	/* Initialise the operation block */
	oper->name = name;
	oper->className = className;
	oper->returnType = returnType;
	oper->defValue = defValue;
	oper->params = params;
	oper->flags = flags;
	oper->numTriggers = numTriggers;
	oper->filename = filename;
	oper->linenum = linenum;
	oper->firstCase = 0;
	oper->lastCase = 0;
	oper->sortedCases = 0;
	oper->numCases = 0;
	oper->header = context->headerStream;
	oper->source = context->sourceStream;

	/* Add the operation to the hash table */
	hash = (TreeCCHashString(name) & (TREECC_HASH_SIZE - 1));
	oper->nextHash = context->operHash[hash];
	context->operHash[hash] = oper;

	/* Done */
	return oper;
}

TreeCCOperation *TreeCCOperationFind(TreeCCContext *context, char *name)
{
	unsigned int hash = (TreeCCHashString(name) & (TREECC_HASH_SIZE - 1));
	TreeCCOperation *oper = context->operHash[hash];
	while(oper != 0)
	{
		if(!strcmp(oper->name, name))
		{
			return oper;
		}
		oper = oper->nextHash;
	}
	return 0;
}

TreeCCOperationCase *TreeCCOperationAddCase
			(TreeCCContext *context, TreeCCOperation *oper,
			 TreeCCTrigger *triggers, char *filename, long linenum)
{
	TreeCCOperationCase *operCase;

	/* Print debugging information if required */
	if(context->debugMode)
	{
		if(!triggers)
		{
			TreeCCDebug(linenum, "%%case %s", oper->name);
		}
		else
		{
			TreeCCDebug(linenum, "%%case %s %s", triggers->node->name,
						oper->name);
		}
	}

	/* Allocate the operation case block */
	if((operCase = (TreeCCOperationCase *)malloc(sizeof(TreeCCOperationCase)))
						== 0)
	{
		TreeCCOutOfMemory(context->input);
	}

	/* Initialise the operation case block */
	operCase->triggers = triggers;
	operCase->code = 0;
	operCase->oper = oper;
	operCase->number = 0;
	operCase->filename = filename;
	operCase->linenum = linenum;
	operCase->codeFilename = 0;
	operCase->codeLinenum = 0;
	operCase->next = 0;
	operCase->nextHeader = 0;

	/* Add the case to the operation's case list */
	if(oper->lastCase)
	{
		oper->lastCase->next = operCase;
	}
	else
	{
		oper->firstCase = operCase;
	}
	oper->lastCase = operCase;
	++(oper->numCases);

	/* Return the case to the caller */
	return operCase;
}

/*
 * Verify the coverage of an operation over a node hierarchy.
 */
static void VerifyHierarchy(TreeCCContext *context, TreeCCOperation *oper,
							TreeCCNode *node)
{
	if((node->flags & TREECC_NODE_MARK(0)) != 0)
	{
		return;
	}
	if((node->flags & TREECC_NODE_ABSTRACT) == 0)
	{
		TreeCCErrorOnLine(context->input, oper->filename, oper->linenum,
						  "node type `%s' is not handled in operation `%s'",
						  node->name, oper->name);
		return;
	}
	node = node->firstChild;
	while(node != 0)
	{
		VerifyHierarchy(context, oper, node);
		node = node->nextSibling;
	}
}

/*
 * Append a parameter type name to a comma-separated string.
 */
static char *AppendParam(TreeCCContext *context, char *str, const char *type)
{
	if(str)
	{
		int slen = strlen(str);
		int tlen = strlen(type);
		str = (char *)realloc(str, slen + tlen + 3);
		if(!str)
		{
			TreeCCOutOfMemory(context->input);
		}
		strcpy(str + slen, ", ");
		strcpy(str + slen + 2, type);
		return str;
	}
	else
	{
		return TreeCCDupString((char *)type);
	}
}

/*
 * Forward declaration.
 */
static void MarkMultiCase(TreeCCOperationCase **sortedCases, int base,
						  int multiplier, TreeCCParam *nextParam,
						  TreeCCOperationCase *operCase,
						  TreeCCTrigger *nextTrigger);

/*
 * Scan down a node type hierarchy to mark all covered children.
 */
static void MarkMultiScan(TreeCCOperationCase **sortedCases, int base,
						  int multiplier, TreeCCParam *nextParam,
						  TreeCCOperationCase *operCase,
						  TreeCCTrigger *nextTrigger, TreeCCNode *node)
{
	/* Go in one level for this node */
	MarkMultiCase(sortedCases, base + node->position * multiplier,
				  multiplier * nextParam->size, nextParam->next,
				  operCase, nextTrigger->next);

	/* Scan all of the children */
	node = node->firstChild;
	while(node != 0)
	{
		MarkMultiScan(sortedCases, base, multiplier, nextParam,
					  operCase, nextTrigger, node);
		node = node->nextSibling;
	}
}

/*
 * Mark all of the node types associated with an operation case.
 */
static void MarkMultiCase(TreeCCOperationCase **sortedCases, int base,
						  int multiplier, TreeCCParam *nextParam,
						  TreeCCOperationCase *operCase,
						  TreeCCTrigger *nextTrigger)
{
	/* Scan for the next trigger parameter */
	while(nextParam != 0 && (nextParam->flags & TREECC_PARAM_TRIGGER) == 0)
	{
		nextParam = nextParam->next;
	}

	/* If we are out of triggers, then we need to set the current value */
	if(!nextParam)
	{
		if(sortedCases[base] == 0)
		{
			sortedCases[base] = operCase;
		}
		return;
	}

	/* Scan down the node type hierarchy for this trigger level */
	MarkMultiScan(sortedCases, base, multiplier, nextParam,
				  operCase, nextTrigger, nextTrigger->node);
}

/*
 * Forward declaration.
 */
static void VerifyMultiCoverage(TreeCCContext *context, TreeCCOperation *oper,
								TreeCCOperationCase **sortedCases, int base,
								int multiplier, TreeCCParam *nextParam,
								TreeCCNode **nodeStack,
								TreeCCNode **nodeStackTop);

/*
 * Scan all children to verify a multi-coverage trigger.
 */
static void VerifyMultiScan(TreeCCContext *context, TreeCCOperation *oper,
							TreeCCOperationCase **sortedCases, int base,
							int multiplier, TreeCCParam *nextParam,
							TreeCCNode *node, TreeCCNode **nodeStack,
							TreeCCNode **nodeStackTop)
{
	/* Go in one level for this node */
	*nodeStackTop = node;
	VerifyMultiCoverage(context, oper, sortedCases,
						base + node->position * multiplier,
						multiplier * nextParam->size,
						nextParam->next, nodeStack, nodeStackTop + 1);

	/* Scan all of the children */
	node = node->firstChild;
	while(node != 0)
	{
		VerifyMultiScan(context, oper, sortedCases, base, multiplier,
						nextParam, node, nodeStack, nodeStackTop);
		node = node->nextSibling;
	}
}

/*
 * Verify coverage of a multi-trigger operation.
 */
static void VerifyMultiCoverage(TreeCCContext *context, TreeCCOperation *oper,
								TreeCCOperationCase **sortedCases, int base,
								int multiplier, TreeCCParam *nextParam,
								TreeCCNode **nodeStack,
								TreeCCNode **nodeStackTop)
{
	TreeCCNode *type;

	/* Scan for the next trigger */
	while(nextParam != 0 && (nextParam->flags & TREECC_PARAM_TRIGGER) == 0)
	{
		nextParam = nextParam->next;
	}

	/* If we are out of triggers, then we need to do a test */
	if(!nextParam)
	{
		if(sortedCases[base] == 0)
		{
			/* No case: report an error if none of the node types
			   that led us here are abstract */
			int posn;
			int isAbstract = 0;
			for(posn = 0; posn < oper->numTriggers; ++posn)
			{
				if((nodeStack[posn]->flags & TREECC_NODE_ABSTRACT) != 0)
				{
					isAbstract = 1;
					break;
				}
			}
			if(!isAbstract)
			{
				char *str = 0;
				for(posn = 0; posn < oper->numTriggers; ++posn)
				{
					str = AppendParam(context, str, nodeStack[posn]->name);
				}
				if(!str)
				{
					str = TreeCCDupString("?");
				}
				TreeCCErrorOnLine(context->input, oper->filename, oper->linenum,
								  "case `%s' is missing from operation `%s'",
								  str, oper->name);
				free(str);
			}
		}
		return;
	}

	/* Scan down the node type hierarchy for this parameter level */
	type = TreeCCNodeFindByType(context, nextParam->type);
	if(!type)
	{
		return;
	}
	VerifyMultiScan(context, oper, sortedCases, base,
				    multiplier, nextParam, type,
					nodeStack, nodeStackTop);
}

/*
 * Test the coverage of a multi-trigger operation.
 */
static void MultiCoverageTest(TreeCCContext *context, TreeCCOperation *oper)
{
	TreeCCParam *param;
	TreeCCParam *param2;
	TreeCCNode *type;
	TreeCCNode *type2;
	int size;
	TreeCCNode **nodeStack;
	TreeCCOperationCase *operCase;

	/* Determine the size of the "sortedCases" array, and also
	   check to make sure there are no overlaps between triggers
	   that will cause position information to be inconsistent */
	size = 1;
	param = oper->params;
	while(param != 0)
	{
		if((param->flags & TREECC_PARAM_TRIGGER) != 0)
		{
			type = TreeCCNodeFindByType(context, param->type);
			if(type)
			{
				param->size = TreeCCNodeAssignPositions(type);
				size *= param->size;
				param2 = oper->params;
				while(param2 != 0)
				{
					if((param2->flags & TREECC_PARAM_TRIGGER) != 0 &&
					   param2 != param)
					{
						type2 = TreeCCNodeFindByType(context, param2->type);
						if(type2 && type2 != type)
						{
							if(TreeCCNodeInheritsFrom(type, type2) ||
							   TreeCCNodeInheritsFrom(type2, type))
							{
								TreeCCErrorOnLine(context->input,
										  oper->filename, oper->linenum,
										  "overlap between trigger types");
								return;
							}
						}
					}
					param2 = param2->next;
				}
			}
		}
		param = param->next;
	}

	/* Create the "sortedCases" array */
	if((oper->sortedCases = (TreeCCOperationCase **)calloc
				(size, sizeof(TreeCCOperationCase *))) == 0)
	{
		TreeCCOutOfMemory(context->input);
	}

	/* Find the operation case to use for each combination of values */
	operCase = oper->firstCase;
	while(operCase != 0)
	{
		MarkMultiCase(oper->sortedCases, 0, 1, oper->params,
					  operCase, operCase->triggers);
		operCase = operCase->next;
	}

	/* Verify that every combination of values has been handled */
	nodeStack = (TreeCCNode **)calloc(oper->numTriggers, sizeof(TreeCCNode *));
	if(!nodeStack)
	{
		TreeCCOutOfMemory(context->input);
	}
	VerifyMultiCoverage(context, oper, oper->sortedCases, 0, 1,
						oper->params, nodeStack, nodeStack);
	free(nodeStack);
}

/*
 * Test that an operation covers all relevant node type cases.
 */
static void OperationTest(TreeCCContext *context, TreeCCOperation *oper)
{
	TreeCCOperationCase *operCase;
	TreeCCTrigger *trigger;
	TreeCCParam *param;
	TreeCCNode *node;

	/* Clear the marking bits */
	TreeCCNodeClearMarking(context, TREECC_NODE_MARK_BITS);

	/* Print an error if the operation has no cases at all */
	if(!(oper->firstCase))
	{
		TreeCCErrorOnLine(context->input, oper->filename, oper->linenum,
						  "operation `%s' has no cases", oper->name);
	}

	/* Single or multiple triggers? */
	if(oper->numTriggers == 1)
	{
		/* Mark the coverage of all operation cases */
		operCase = oper->firstCase;
		while(operCase != 0)
		{
			trigger = operCase->triggers;
			if(trigger != 0)
			{
				if((trigger->node->flags & TREECC_NODE_MARK(0)) != 0)
				{
					TreeCCErrorOnLine(context->input, operCase->filename,
									  operCase->linenum,
					  				  "node type `%s' is handled multiple "
									  		"times for operation `%s'",
									  trigger->node->name, oper->name);
				}
				else
				{
					trigger->node->flags |= TREECC_NODE_MARK(0);
				}
			}
			operCase = operCase->next;
		}

		/* Walk the node hierarchy to verify coverage */
		param = oper->params;
		while(param != 0)
		{
			if((param->flags & TREECC_PARAM_TRIGGER) != 0)
			{
				node = TreeCCNodeFindByType(context, param->type);
				if(node)
				{
					VerifyHierarchy(context, oper, node);
				}
			}
			param = param->next;
		}
	}
	else if(oper->numTriggers == 0)
	{
		/* Zero triggers: look for a single case definition */
		operCase = oper->firstCase;
		if(operCase && operCase->next)
		{
			do
			{
				operCase = operCase->next;
				TreeCCErrorOnLine(context->input, operCase->filename,
								  operCase->linenum,
								  "multiple definitions for operation `%s'",
								  oper->name);
			}
			while(operCase->next != 0);
			TreeCCErrorOnLine(context->input, oper->firstCase->filename,
							  oper->firstCase->linenum,
							  "first definition here");
		}
	}
	else
	{
		/* Multiple triggers need a more complex algorithm to verify */
		if(oper->firstCase != 0)
		{
			MultiCoverageTest(context, oper);
		}
	}
}

/*
 * Compare two operation cases for a sort operation.
 */
static int CaseCompare(const void *e1, const void *e2)
{
	TreeCCOperationCase *operCase1 = *((TreeCCOperationCase **)e1);
	TreeCCOperationCase *operCase2 = *((TreeCCOperationCase **)e2);
	TreeCCTrigger *trigger1 = operCase1->triggers;
	TreeCCTrigger *trigger2 = operCase2->triggers;
	TreeCCNode *ancestor1;
	TreeCCNode *ancestor2;
	while(trigger1 != 0 && trigger2 != 0)
	{
		if(trigger1->node != trigger2->node)
		{
			/* See if trigger1->node inherits from trigger2->node */
			ancestor1 = trigger1->node;
			while(ancestor1->parent != 0)
			{
				if(ancestor1->parent == trigger2->node)
				{
					return -1;
				}
				ancestor1 = ancestor1->parent;
			}

			/* See if trigger2->node inherits from trigger1->node */
			ancestor2 = trigger2->node;
			while(ancestor2->parent != 0)
			{
				if(ancestor2->parent == trigger1->node)
				{
					return 1;
				}
				ancestor2 = ancestor2->parent;
			}

			/* If the ancestors are separate, then use the node numbers
			   to order the separate trees.  Note: this is highly unlikely
			   because operation definition forces all cases to inherit
			   from a declared common type.  However, if we change this
			   requirement in the future, this code will be needed, so
			   we are being paranoid and including it now */
			if(ancestor1 != ancestor2)
			{
				if(ancestor1->number < ancestor2->number)
				{
					return -1;
				}
				else
				{
					return 1;
				}
			}

			/* This is the hard case: the two nodes are in separate
			   subtrees of the same ancestor, but we still need an
			   ordering between them.  We need to find the lowest
			   common ancestor, and the nodes just below it */
			ancestor1 = trigger1->node;
			while(ancestor1->parent != 0)
			{
				ancestor1 = ancestor1->parent;
				ancestor1->flags |= TREECC_NODE_MARK(0);
			}
			ancestor2 = trigger2->node;
			while(ancestor2->parent != 0)
			{
				if((ancestor2->parent->flags & TREECC_NODE_MARK(0)) != 0)
				{
					break;
				}
				ancestor2 = ancestor2->parent;
			}
			ancestor1 = trigger1->node;
			while(ancestor1->parent != 0)
			{
				ancestor1 = ancestor1->parent;
				ancestor1->flags &= ~(TREECC_NODE_MARK(0));
			}
			ancestor1 = trigger1->node;
			while(ancestor1->parent != ancestor2->parent)
			{
				ancestor1 = ancestor1->parent;
			}

			/* ancestor1 and ancestor2 are now one step down
			   from the common ancestor that we found.  Use
			   their node numbers to order the trees */
			if(ancestor1->number < ancestor2->number)
			{
				return -1;
			}
			else
			{
				return 1;
			}
		}
		trigger1 = trigger1->next;
		trigger2 = trigger2->next;
	}
	return 0;
}

/*
 * Sort a set of operation cases so that A precedes B
 * if A inherits directly or indirectly from B.  Operations
 * with multiple triggers sort on the first, then the second,
 * then the third, etc.
 */
static void SortCases(TreeCCContext *context, TreeCCOperation *oper)
{
	TreeCCOperationCase **caseList;
	TreeCCOperationCase *operCase;
	int num;

	/* Bail out early if there are 0 or 1 cases, or no triggers */
	if(oper->numCases < 2 || !(oper->numTriggers))
	{
		return;
	}

	/* Clear the marking bits */
	TreeCCNodeClearMarking(context, TREECC_NODE_MARK_BITS);

	/* Build an array that contains all operation cases */
	if((caseList = (TreeCCOperationCase **)malloc
				(sizeof(TreeCCOperationCase *) * oper->numCases)) == 0)
	{
		TreeCCOutOfMemory(context->input);
	}
	num = 0;
	operCase = oper->firstCase;
	while(operCase != 0)
	{
		caseList[num++] = operCase;
		operCase = operCase->next;
	}

	/* Sort the case list.  There are probably more efficient
	   ways to do this (e.g. topological sorting), but this
	   version is perhaps easier to understand and maintain */
#if HAVE_QSORT
	qsort(caseList, oper->numCases, sizeof(TreeCCOperationCase *), CaseCompare);
#else
	{
		int i, j;
		num = oper->numCases;
		for(i = 0; i < (num - 1); ++i)
		{
			for(j = (i + 1); j < num; ++j)
			{
				if(CaseCompare(&(caseList[i]), &(caseList[j])) > 0)
				{
					operCase = caseList[i];
					caseList[i] = caseList[j];
					caseList[j] = operCase;
				}
			}
		}
	}
#endif

	/* Build a new case list from the sorted array */
	oper->firstCase = caseList[0];
	for(num = 1; num < oper->numCases; ++num)
	{
		caseList[num - 1]->next = caseList[num];
	}
	oper->lastCase = caseList[oper->numCases - 1];
	caseList[oper->numCases - 1]->next = 0;
	free(caseList);
}

void TreeCCOperationValidate(TreeCCContext *context)
{
	unsigned int hash;
	TreeCCOperation *oper;
	for(hash = 0; hash < TREECC_HASH_SIZE; ++hash)
	{
		oper = context->operHash[hash];
		while(oper != 0)
		{
			if((oper->flags & TREECC_OPER_VIRTUAL) == 0)
			{
				/* Non-virtuals must be sorted for code generation,
				   and we also rely upon the sorted order to help us
				   test for operation coverage when multiple triggers
				   are used by the operation */
				SortCases(context, oper);
			}
			OperationTest(context, oper);
			oper = oper->nextHash;
		}
	}
}

TreeCCOperationCase *TreeCCOperationFindCase
		(TreeCCContext *context, TreeCCNode *node, char *name)
{
	TreeCCOperation *oper;
	TreeCCOperationCase *operCase;
	oper = TreeCCOperationFind(context, name);
	if(!oper)
	{
		return 0;
	}
	operCase = oper->firstCase;
	while(operCase != 0)
	{
		if(operCase->triggers && operCase->triggers->node == node)
		{
			return operCase;
		}
		operCase = operCase->next;
	}
	return 0;
}

void TreeCCOperationVisitAll(TreeCCContext *context,
							 TreeCCOperationVisitor visitor)
{
	unsigned int hash;
	TreeCCOperation *oper;
	for(hash = 0; hash < TREECC_HASH_SIZE; ++hash)
	{
		oper = context->operHash[hash];
		while(oper != 0)
		{
			(*visitor)(context, oper);
			oper = oper->nextHash;
		}
	}
}

#ifdef	__cplusplus
};
#endif

redpajama_set_name: RedPajamaGithub


text:
package com.medievallords.carbyne.gear.types.carbyne;

import com.medievallords.carbyne.gear.GearManager;
import com.medievallords.carbyne.gear.effects.carbyne.CarbyneEffect;
import com.medievallords.carbyne.gear.types.CarbyneGear;
import com.medievallords.carbyne.utils.*;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerItemBreakEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Getter
@Setter
public class CarbyneArmor extends CarbyneGear {

    private Color baseColor, minFadeColor, maxFadeColor;
    private int[] tickFadeColor;
    private List<String> enchantments = new ArrayList<>();
    private HashMap<PotionEffect, Double> offensivePotionEffects = new HashMap<>();
    private HashMap<PotionEffect, Double> defensivePotionEffects = new HashMap<>();
    private List<CarbyneEffect> carbyneEffects = new ArrayList<>();
    private double health = 1;

    @Override
    public boolean load(ConfigurationSection cs, String type) {
        if ((displayName = cs.getString(type + ".DisplayName")) == null) return false;
        if ((gearCode = cs.getString(type + ".GearCode")) == null) return false;
        if ((maxDurability = cs.getInt(type + ".Durability")) == -1) return false;
        if ((cost = cs.getInt(type + ".Cost")) == -1) return false;
        if ((health = cs.getDouble(type + ".Health")) == -1) return false;

        this.type = type;
        this.displayName = cs.getString(type + ".DisplayName");
        this.gearCode = cs.getString(type + ".GearCode");
        this.maxDurability = cs.getInt(type + ".Durability");
        this.lore = cs.getStringList(type + ".Lore");
        this.enchantments = cs.getStringList(type + ".Enchantments");
        this.cost = cs.getInt(type + ".Cost");
        this.hidden = cs.getBoolean(type + ".Hidden");
        this.health = cs.getDouble(type + ".Health");

        if (cs.contains(type + ".RepairMaterial")) {
            setRepairType(Material.getMaterial(cs.getString(type + ".RepairMaterial")));
        }

        if (cs.contains(type + ".RepairData")) {
            setRepairData(cs.getInt(type + ".RepairData"));
        }

        if (cs.contains(type + ".RepairCost")) {
            setRepairCost(cs.getInt(type + ".RepairCost"));
        }

        if (cs.getString(type + ".BaseColor") != null) {
            String[] split = cs.getString(type + ".BaseColor").split(",");

            if (split.length == 3)
                baseColor = Color.fromRGB(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            else
                baseColor = Color.WHITE;
        }

        if (cs.getString(type + ".MinFadeColor") != null) {
            String[] split = cs.getString(type + ".MinFadeColor").split(",");

            if (split.length == 3)
                minFadeColor = Color.fromRGB(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            else
                minFadeColor = Color.WHITE;
        }

        if (cs.getString(type + ".MaxFadeColor") != null) {
            String[] split = cs.getString(type + ".MaxFadeColor").split(",");

            if (split.length == 3)
                maxFadeColor = Color.fromRGB(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            else
                maxFadeColor = Color.WHITE;
        }

        if (cs.getString(type + ".TickFadeColor") != null) {
            String[] split = cs.getString(type + ".TickFadeColor").split(",");

            if (split.length == 3)
                tickFadeColor = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])};
            else
                tickFadeColor = new int[]{0, 0, 0};
        }

        //if (type.equalsIgnoreCase("chestplate") || type.equalsIgnoreCase("leggings")) {
        if (cs.getStringList(type + ".OffensivePotionEffects") != null) {
            for (String potion : cs.getStringList(type + ".OffensivePotionEffects")) {
                String[] split = potion.split(",");

                if (split.length == 3)
                    offensivePotionEffects.put(new PotionEffect(PotionEffectType.getByName(split[0].toUpperCase()), Integer.parseInt(split[1]), 0, false, false), Double.parseDouble(split[2]));
                else if (split.length == 4)
                    offensivePotionEffects.put(new PotionEffect(PotionEffectType.getByName(split[0].toUpperCase()), Integer.parseInt(split[2]), Integer.parseInt(split[1]), false, false), Double.parseDouble(split[3]));
            }
        }
        if (cs.getStringList(type + ".DefensivePotionEffects") != null) {
            for (String potion : cs.getStringList(type + ".DefensivePotionEffects")) {
                String[] split = potion.split(",");

                if (split.length == 3)
                    defensivePotionEffects.put(new PotionEffect(PotionEffectType.getByName(split[0].toUpperCase()), Integer.parseInt(split[1]), 0, false, false), Double.parseDouble(split[2]));
                else if (split.length == 4)
                    defensivePotionEffects.put(new PotionEffect(PotionEffectType.getByName(split[0].toUpperCase()), Integer.parseInt(split[2]), Integer.parseInt(split[1]), false, false), Double.parseDouble(split[3]));

            }
        }

        return true;
    }

    @Override
    public ItemStack getItem(boolean storeItem) {
        List<String> loreDupe = new ArrayList<>();

        HashMap<Enchantment, Integer> enchantmentHashMap = new HashMap<>();
        for (String s : enchantments) {
            String[] split = s.split(",");

            if (split.length != 2)
                continue;
            if (split[0].equalsIgnoreCase("protection"))
                enchantmentHashMap.put(Enchantment.PROTECTION_ENVIRONMENTAL, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("fireprotection"))
                enchantmentHashMap.put(Enchantment.PROTECTION_FIRE, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("featherfalling"))
                enchantmentHashMap.put(Enchantment.PROTECTION_FALL, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("blastprotection"))
                enchantmentHashMap.put(Enchantment.PROTECTION_EXPLOSIONS, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("projectileprotection"))
                enchantmentHashMap.put(Enchantment.PROTECTION_PROJECTILE, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("respiration"))
                enchantmentHashMap.put(Enchantment.OXYGEN, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("aquaaffinity"))
                enchantmentHashMap.put(Enchantment.WATER_WORKER, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("thorns"))
                enchantmentHashMap.put(Enchantment.THORNS, Integer.valueOf(split[1]));
            else if (split[0].equalsIgnoreCase("unbreaking"))
                enchantmentHashMap.put(Enchantment.DURABILITY, Integer.valueOf(split[1]));
            else
                enchantmentHashMap.put(Enchantment.getByName(split[0].toUpperCase()), Integer.parseInt(split[1]));
        }

        loreDupe.add(HiddenStringUtils.encodeString(gearCode + "," + maxDurability));
        int totalHealth = (int) health;
        if (enchantmentHashMap.containsKey(Enchantment.PROTECTION_ENVIRONMENTAL)) {
            totalHealth += (double) (enchantmentHashMap.get(Enchantment.PROTECTION_ENVIRONMENTAL) * GearManager.PROTECTION_HEALTH);
        }

        loreDupe.add("&aHealth&7: &c" + totalHealth);
        loreDupe.add("&aPolished&7: &cfalse");

        if (offensivePotionEffects.keySet().size() > 0 || defensivePotionEffects.keySet().size() > 0) {
            if (defensivePotionEffects.keySet().size() > 0) {
                loreDupe.add("");
                loreDupe.add("&aDefensive Effects&7:");

                for (PotionEffect effect : defensivePotionEffects.keySet())
                    loreDupe.add("  &7- &3" + MessageManager.getPotionTypeFriendlyName(effect.getType()) + " &b" + MessageManager.getPotionAmplifierInRomanNumerals(effect.getAmplifier() + 1) + " &6" + (effect.getDuration() / 20) + "s &c" + StringUtils.round(defensivePotionEffects.get(effect) * 100.0, 2) + "% &f(On Hit)");
            }

            if (offensivePotionEffects.keySet().size() > 0) {
                loreDupe.add("");
                loreDupe.add("&aOffensive Effects&7:");

                for (PotionEffect effect : offensivePotionEffects.keySet())
                    loreDupe.add("  &7- &3" + MessageManager.getPotionTypeFriendlyName(effect.getType()) + " &b" + MessageManager.getPotionAmplifierInRomanNumerals(effect.getAmplifier() + 1) + " &6" + (effect.getDuration() / 20) + "s &c" + StringUtils.round(offensivePotionEffects.get(effect) * 100.0, 2) + "% &f(On Hit)");
            }
        }

        if (lore != null && lore.size() > 0) {
            loreDupe.add("");
            loreDupe.addAll(lore);
        }

        ItemBuilder builder = new ItemBuilder(Material.getMaterial(("leather_" + type).toUpperCase()))
                .name(displayName)
                .addEnchantments(enchantmentHashMap)
                .color(baseColor);

        if (lore != null && lore.size() > 0)
            builder.setLore((loreDupe.size() > 0 ? loreDupe : lore));
        else if (loreDupe.size() > 0)
            builder.setLore(loreDupe);

        return builder.build();
    }

    public void applyDefensiveEffect(Player target) {
        if (Cooldowns.getCooldown(target.getUniqueId(), "DefensiveEffect") > 0L)
            return;

        for (PotionEffect effect : defensivePotionEffects.keySet()) {
            Double random = Math.random();

            if (random <= defensivePotionEffects.get(effect)) {
                boolean apply = true;

                for (PotionEffect potionEffect : target.getActivePotionEffects())
                    if (potionEffect.getType() == effect.getType())
                        if (potionEffect.getAmplifier() >= effect.getAmplifier() | potionEffect.getDuration() >= effect.getDuration())
                            apply = false;

                if (apply) {
                    target.addPotionEffect(effect);
                    String s = ChatColor.translateAlternateColorCodes('&', "&aYou have received &b" + Namer.getPotionEffectName(effect) + " &afor &b" + (effect.getDuration() / 20) + " &asec(s).");
                    JSONMessage json = JSONMessage.create(s);
                    json.actionbar(target);
                    Cooldowns.setCooldown(target.getUniqueId(), "DefensiveEffect", 3000L);
                }
            }
        }
    }

    public void applyOffensiveEffect(Player target) {
        if (Cooldowns.getCooldown(target.getUniqueId(), "OffensiveEffect") > 0L)
            return;

        for (PotionEffect effect : offensivePotionEffects.keySet()) {
            Double random = Math.random();

            if (random <= offensivePotionEffects.get(effect)) {
                boolean apply = true;

                for (PotionEffect potionEffect : target.getActivePotionEffects())
                    if (potionEffect.getType() == effect.getType())
                        if (potionEffect.getAmplifier() >= effect.getAmplifier() | potionEffect.getDuration() >= effect.getDuration())
                            apply = false;

                if (apply) {
                    target.addPotionEffect(effect);
                    String s = ChatColor.translateAlternateColorCodes('&', "&aYou have received &c" + Namer.getPotionEffectName(effect) + " &afor &b" + (effect.getDuration() / 20) + " &asec(s).");
                    JSONMessage json = JSONMessage.create(s);
                    json.actionbar(target);
                    Cooldowns.setCooldown(target.getUniqueId(), "OffensiveEffect", 3000L);
                }
            }
        }
    }

    public double getTotalHealth(ItemStack itemStack, boolean nerfed) {
        double total = health;

        if (isPolished(itemStack))
            total += 50.0;

        if (nerfed)
            total = total * GearManager.NERFED_PERCENTAGE_ARMOR;

        return total;
    }

    @Override
    public void damageItem(Player wielder, ItemStack itemStack) {
        if (isPolished(itemStack))
            if (ThreadLocalRandom.current().nextDouble(1.0) <= 0.15)
                return;

        int durability = getDurability(itemStack);

        if (durability == -1)
            return;

        double chance = 1;

        if (itemStack.containsEnchantment(Enchantment.DURABILITY)) {
            int level = itemStack.getEnchantmentLevel(Enchantment.DURABILITY);
            double calc = (100 / (level + 1));
            chance = calc / 100;
        }

        if (chance < Math.random())
            return;

        if (durability >= 1) {
            durability--;
            Namer.setLore(itemStack, HiddenStringUtils.encodeString(gearCode + "," + durability), 0);
            itemStack.setDurability((short) durabilityScale(itemStack));

            if (itemStack.getDurability() <= 0)
                itemStack.setDurability((short) 0);
            else if (itemStack.getDurability() >= itemStack.getType().getMaxDurability())
                itemStack.setDurability(itemStack.getType().getMaxDurability());
        } else {
            PlayerItemBreakEvent event = new PlayerItemBreakEvent(wielder, itemStack);
            Bukkit.getPluginManager().callEvent(event);
            wielder.getInventory().remove(itemStack);
            wielder.updateInventory();
            wielder.playSound(wielder.getLocation(), Sound.ITEM_BREAK, 1, 1);
        }
    }

    @Override
    public int getDurability(ItemStack itemStack) {
        if (itemStack == null)
            return -1;

        String line = HiddenStringUtils.extractHiddenString(itemStack.getItemMeta().getLore().get(0));
        String[] split = line.split(",");
        if (split.length != 2) {
            Namer.setLore(itemStack, HiddenStringUtils.encodeString(gearCode + "," + maxDurability), 0);
            return -1;
        }

        try {
            return Integer.valueOf(split[1]);
        } catch (Exception ez) {
            Namer.setLore(itemStack, HiddenStringUtils.encodeString(gearCode + "," + maxDurability), 0);
            return -1;
        }
    }

    @Override
    public int getRepairCost(ItemStack itemStack) {
        int maxAmount = getRepairCost();
        double per = (double) maxDurability / (double) maxAmount;
        double dura = ((double) (getDurability(itemStack)));
        for (int i = 1; i <= maxAmount; i++)
            if (dura < per * i)
                return (maxAmount + 1) - i;

        return 0;
    }

    @Override
    public void setDurability(ItemStack itemStack, int durability) {
        Namer.setLore(itemStack, HiddenStringUtils.encodeString(gearCode + "," + durability), 0);
        itemStack.setDurability((short) durabilityScale(itemStack));
    }

    public int durabilityScale(ItemStack itemStack) {
        double scale = ((double) (getDurability(itemStack))) / ((double) (getMaxDurability()));
        double durability = ((double) (itemStack.getType().getMaxDurability())) * scale;
        return itemStack.getType().getMaxDurability() - (int) Math.round(durability);
    }

    public ItemStack getPolishedItem() {
        return new ItemBuilder(getItem(false)).setLore(2, "&aPolished: &ctrue").color(getMinFadeColor()).build();
    }

    public boolean isPolished(ItemStack itemStack) {
        if (itemStack == null)
            return false;

        if (!itemStack.hasItemMeta())
            return false;

        if (!itemStack.getItemMeta().hasLore())
            return false;

        try {
            return Boolean.valueOf(ChatColor.stripColor(itemStack.getItemMeta().getLore().get(2)).replace(" ", "").split(":")[1]);
        } catch (Exception ex) {
            return false;
        }
    }
}


text:
require 'rubygems'
require 'bundler'
Bundler.setup(:default)
require 'nakamura/test'
include SlingUsers

class TC_Kern1540Test < Test::Unit::TestCase
  include SlingTest

  def test_calendar_in_user_home
    m = uniqueness()
    user = create_user("user-#{m}")
    home = user.home_path_for(@s)
    public = user.public_path_for(@s)
    @s.switch_user(user)
    calendarpath = "#{public}/testcalendar";
    res = @s.execute_post(@s.url_for("#{calendarpath}"), {
      "sling:resourceType" => "sakai/calendar"
    })
    assert_equal("201", res.code, "User should be able to create calendar")
    res = @s.execute_get(@s.url_for("#{calendarpath}.event.ics"))
    assert_equal("200", res.code, "User should find calendar")
    @log.info("Empty calendar = '#{res.body}'")
    assert(res.body.start_with?("BEGIN:VCALENDAR"), "Not ICS : ${res.body}")
    assert(!res.body.include?("BEGIN:VEVENT"), "Not empty : ${res.body}")
    res = @s.execute_post(@s.url_for("#{calendarpath}/firstevent"), {
      "sling:resourceType" => "sakai/calendar-event",
      "sakai:vcal-DTSTART" => "20110107T172000Z",
      "sakai:vcal-DTEND" => "20110107T180000Z",
      "sakai:vcal-SUMMARY" => "Big party"
    })
    assert_equal("201", res.code, "User should be able to create event")
    res = @s.execute_get(@s.url_for("#{calendarpath}.event.ics"))
    assert_equal("200", res.code, "User should find calendar")
    @log.info("Calendar with explicit selector = '#{res.body}'")
    assert(res.body.include?("BEGIN:VEVENT"), "Should have an event : ${res.body}")
    assert(res.body.include?("SUMMARY:Big party"), "Missing summary : ${res.body}")
    res = @s.execute_post(@s.url_for("#{calendarpath}/secondevent"), {
      "sling:resourceType" => "sakai/calendar-vevent",
      "sakai:vcal-DTSTART" => "20110207T172000Z",
      "sakai:vcal-DTEND" => "20110207T180000Z",
      "sakai:vcal-SUMMARY" => "Lesser party"
    })
    assert_equal("201", res.code, "User should be able to create event")
    res = @s.execute_get(@s.url_for("#{calendarpath}.ics"))
    assert_equal("200", res.code, "User should find calendar")
    @log.info("Calendar without explicit selector = '#{res.body}'")
    assert(res.body.include?("BEGIN:VEVENT"), "Should have an event : ${res.body}")
    assert(res.body.include?("SUMMARY:Lesser party"), "Missing summary : ${res.body}")
    assert(!res.body.include?("SUMMARY:Big party"), "Should only have one summary : ${res.body}")
  end

end


text:
/* This is not a banner. */
/* This isn't a banner
 * either
 */


text:
'use strict';

const _ = require('lodash');
const conditionsOverlap = require('./conditions-overlap');

exports = module.exports = (a, b, strict=false) => {
  const p1 = ['source_table', 'source_column', 'source_condition'];
  const p2 = ['target_table', 'target_column', 'target_condition'];
  const cmp = (a, b) => {
    if (_.isObject(a) && _.isObject(b)) {
      return _.isEqual(Object.keys(a), Object.keys(b));
    }

    return a === b;
  };

  const identical = p1.every(p => cmp(a[p], b[p])) && p2.every(p => cmp(a[p], b[p]));
  const reversed = p1.every((p, i) => cmp(a[p], b[p2[i]])) && p2.every((p, i) => cmp(a[p], b[p1[i]]));

  // order is important with strict: we're looking for anything in a that we
  // don't already know about
  if (identical) {
    return conditionsOverlap(a.source_condition, b.source_condition, strict) && conditionsOverlap(a.target_condition, b.target_condition, strict);
  } else if (reversed) {
    return conditionsOverlap(a.source_condition, b.target_condition, strict) && conditionsOverlap(a.target_condition, b.source_condition, strict);
  } else {
    return false;
  }
};


text:
import testtools
from testtools import testcase as tc

from tempest import config
from tempest.lib import decorators
from tempest.lib.common.utils import data_utils

from sahara_tempest_plugin.tests.api import base as dp_base

CONF = config.CONF

class DataSourceTest(dp_base.BaseDataProcessingTest):
    @classmethod
    def resource_setup(cls):
        super(DataSourceTest, cls).resource_setup()
        cls.swift_data_source_with_creds = {
            'url': 'swift://sahara-container.sahara/input-source',
            'description': 'Test data source',
            'credentials': {
                'user': cls.os_primary.credentials.username,
                'password': cls.os_primary.credentials.password
            },
            'type': 'swift'
        }
        cls.swift_data_source = cls.swift_data_source_with_creds.copy()
        del cls.swift_data_source['credentials']

        cls.s3_data_source_with_creds = {
            'url': 's3://sahara-bucket/input-source',
            'description': 'Test data source',
            'credentials': {
                'accesskey': 'username',
                'secretkey': 'key',
                'endpoint': 'localhost',
                'bucket_in_path': False,
                'ssl': False
            },
            'type': 's3'
        }
        cls.s3_data_source = cls.s3_data_source_with_creds.copy()
        del cls.s3_data_source['credentials']

        cls.local_hdfs_data_source = {
            'url': 'input-source',
            'description': 'Test data source',
            'type': 'hdfs'
        }

        cls.external_hdfs_data_source = {
            'url': 'hdfs://172.18.168.2:8020/usr/hadoop/input-source',
            'description': 'Test data source',
            'type': 'hdfs'
        }

    def _create_data_source(self, source_body, source_name=None):
        """Creates Data Source with optional name specified.

        It creates a link to input-source file (it may not exist), ensures
        source name and response body. Returns id and name of created source.
        """
        if not source_name:
            # generate random name if it's not specified
            source_name = data_utils.rand_name('sahara-data-source')

        # create data source
        resp_body = self.create_data_source(source_name, **source_body)

        # ensure that source created successfully
        self.assertEqual(source_name, resp_body['name'])
        if source_body['type'] == 'swift':
            source_body = self.swift_data_source
        elif source_body['type'] == 's3':
            source_body = self.s3_data_source
        self.assertDictContainsSubset(source_body, resp_body)

        return resp_body['id'], source_name

    def _list_data_sources(self, source_info):
        # check for data source in list
        sources = self.client.list_data_sources()['data_sources']
        sources_info = [(source['id'], source['name']) for source in sources]
        self.assertIn(source_info, sources_info)

    def _get_data_source(self, source_id, source_name, source_body):
        # check data source fetch by id
        source = self.client.get_data_source(source_id)['data_source']
        self.assertEqual(source_name, source['name'])
        self.assertDictContainsSubset(source_body, source)

    def _delete_data_source(self, source_id):
        # delete the data source by id
        self.client.delete_data_source(source_id)
        self.wait_for_resource_deletion(source_id, self.client.get_data_source)

        # assert data source does not exist anymore
        sources = self.client.list_data_sources()['data_sources']
        sources_ids = [source['id'] for source in sources]
        self.assertNotIn(source_id, sources_ids)

    def _update_data_source(self, source_id):
        new_source_name = data_utils.rand_name('sahara-data-source')
        body = {'name': new_source_name}
        updated_source = self.client.update_data_source(source_id, **body)
        source = updated_source['data_source']
        self.assertEqual(new_source_name, source['name'])

    @tc.attr('smoke')
    @decorators.idempotent_id('9e0e836d-c372-4fca-91b7-b66c3e9646c8')
    def test_swift_data_source_create(self):
        self._create_data_source(self.swift_data_source_with_creds)

    @tc.attr('smoke')
    @decorators.idempotent_id('3cb87a4a-0534-4b97-9edc-8bbc822b68a0')
    def test_swift_data_source_list(self):
        source_info = (
            self._create_data_source(self.swift_data_source_with_creds))
        self._list_data_sources(source_info)

    @tc.attr('smoke')
    @decorators.idempotent_id('fc07409b-6477-4cb3-9168-e633c46b227f')
    def test_swift_data_source_get(self):
        source_id, source_name = (
            self._create_data_source(self.swift_data_source_with_creds))
        self._get_data_source(source_id, source_name, self.swift_data_source)

    @tc.attr('smoke')
    @decorators.idempotent_id('df53669c-0cd1-4cf7-b408-4cf215d8beb8')
    def test_swift_data_source_delete(self):
        source_id, _ = (
            self._create_data_source(self.swift_data_source_with_creds))
        self._delete_data_source(source_id)

    @tc.attr('smoke')
    @decorators.idempotent_id('44398efb-c2a8-4a20-97cd-509c49b5d25a')
    def test_swift_data_source_update(self):
        source_id, _ = (
            self._create_data_source(self.swift_data_source_with_creds))
        self._update_data_source(source_id)

    @decorators.idempotent_id('54b68270-74d2-4c93-a324-09c2dccb1208')
    @testtools.skipUnless(CONF.data_processing_feature_enabled.s3,
                          'S3 not available')
    def test_s3_data_source_create(self):
        self._create_data_source(self.s3_data_source_with_creds)

    @decorators.idempotent_id('5f67a8d1-e362-4204-88ec-674630a71019')
    @testtools.skipUnless(CONF.data_processing_feature_enabled.s3,
                          'S3 not available')
    def test_s3_data_source_list(self):
        source_info = (
            self._create_data_source(self.s3_data_source_with_creds))
        self._list_data_sources(source_info)

    @decorators.idempotent_id('84017749-b9d6-4542-9d12-1c73239e03b2')
    @testtools.skipUnless(CONF.data_processing_feature_enabled.s3,
                          'S3 not available')
    def test_s3_data_source_get(self):
        source_id, source_name = (
            self._create_data_source(self.s3_data_source_with_creds))
        self._get_data_source(source_id, source_name, self.s3_data_source)

    @decorators.idempotent_id('fb8f9f44-17ea-4be9-8cec-e02f31a49bae')
    @testtools.skipUnless(CONF.data_processing_feature_enabled.s3,
                          'S3 not available')
    def test_s3_data_source_delete(self):
        source_id, _ = (
            self._create_data_source(self.s3_data_source_with_creds))
        self._delete_data_source(source_id)

    @decorators.idempotent_id('d069714a-86fb-45ce-8498-43901b065243')
    @testtools.skipUnless(CONF.data_processing_feature_enabled.s3,
                          'S3 not available')
    def test_s3_data_source_update(self):
        source_id, _ = (
            self._create_data_source(self.s3_data_source_with_creds))
        self._update_data_source(source_id)

    @tc.attr('smoke')
    @decorators.idempotent_id('88505d52-db01-4229-8f1d-a1137da5fe2d')
    def test_local_hdfs_data_source_create(self):
        self._create_data_source(self.local_hdfs_data_source)

    @tc.attr('smoke')
    @decorators.idempotent_id('81d7d42a-d7f6-4d9b-b38c-0801a4dfe3c2')
    def test_local_hdfs_data_source_list(self):
        source_info = self._create_data_source(self.local_hdfs_data_source)
        self._list_data_sources(source_info)

    @tc.attr('smoke')
    @decorators.idempotent_id('ec0144c6-db1e-4169-bb06-7abae14a8443')
    def test_local_hdfs_data_source_get(self):
        source_id, source_name = (
            self._create_data_source(self.local_hdfs_data_source))
        self._get_data_source(
            source_id, source_name, self.local_hdfs_data_source)

    @tc.attr('smoke')
    @decorators.idempotent_id('e398308b-4230-4f86-ba10-9b0b60a59c8d')
    def test_local_hdfs_data_source_delete(self):
        source_id, _ = self._create_data_source(self.local_hdfs_data_source)
        self._delete_data_source(source_id)

    @tc.attr('smoke')
    @decorators.idempotent_id('16a71f3b-0095-431c-b542-c871e1f95e1f')
    def test_local_hdfs_data_source_update(self):
        source_id, _ = self._create_data_source(self.local_hdfs_data_source)
        self._update_data_source(source_id)

    @tc.attr('smoke')
    @decorators.idempotent_id('bfd91128-e642-4d95-a973-3e536962180c')
    def test_external_hdfs_data_source_create(self):
        self._create_data_source(self.external_hdfs_data_source)

    @tc.attr('smoke')
    @decorators.idempotent_id('92e2be72-f7ab-499d-ae01-fb9943c90d8e')
    def test_external_hdfs_data_source_list(self):
        source_info = self._create_data_source(self.external_hdfs_data_source)
        self._list_data_sources(source_info)

    @tc.attr('smoke')
    @decorators.idempotent_id('a31edb1b-6bc6-4f42-871f-70cd243184ac')
    def test_external_hdfs_data_source_get(self):
        source_id, source_name = (
            self._create_data_source(self.external_hdfs_data_source))
        self._get_data_source(
            source_id, source_name, self.external_hdfs_data_source)

    @tc.attr('smoke')
    @decorators.idempotent_id('295924cd-a085-4b45-aea8-0707cdb2da7e')
    def test_external_hdfs_data_source_delete(self):
        source_id, _ = self._create_data_source(self.external_hdfs_data_source)
        self._delete_data_source(source_id)

    @tc.attr('smoke')
    @decorators.idempotent_id('9b317861-95db-44bc-9b4b-80d23feade3f')
    def test_external_hdfs_data_source_update(self):
        source_id, _ = self._create_data_source(self.external_hdfs_data_source)
        self._update_data_source(source_id)


text:
require "spec_helper"

describe "The Cranky factory" do

  describe '#factory_names' do
    it 'returns an array of names of defined factories' do
      Factory.factory_names.should eq %i(
                                        address
                                        admin_by_define
                                        admin_manually
                                        invalid_user
                                        user
                                        user_by_define
                                        user_hash
                                        user_manually
                                        users_collection
                                      )
    end
  end

  describe '#traits_for' do
    it 'returns an array of trait names defined for the given factory' do
      Factory.traits_for(:user_manually).should eq ['manager']
    end
  end

  describe '#create!' do
    context 'given invalid record' do
      let(:factory_name) { :invalid_user }

      it 'raises an error if validation failed' do
        expect { Factory.create!(factory_name) }.to raise_error('Validation failed: {:required_attr=>["can\'t be blank"]}')
      end
    end

    context 'given valid record' do
      let(:factory_name) { :user }

      it 'creates object' do
        result = nil
        expect { result = Factory.create!(factory_name) }.to_not raise_error
        result.should be_saved
      end
    end
  end

  it "is alive" do
    Factory.build(:user).class.should == User
  end

  it "does not save the item when generated via build or crank" do
    Factory.build(:user).saved?.should == false
    crank(:user).saved?.should == false
  end

  it "does save the item when generated via create or crank!" do
    Factory.create(:user).saved?.should == true
    crank!(:user).saved?.should == true
  end

  it "does save each item in the collection when generated via create or crank!" do
    Factory.create(:users_collection).select { |u| !u.saved? }.should be_empty
    crank!(:users_collection).select { |u| !u.saved? }.should be_empty
  end

  it "allows all attributes to be overriden in the call" do
    u = Factory.build(:user, :name => "Indy", :email => "indy@home.com", :role => :dog, :unique => :yep)
    u.name.should == "Indy"
    u.email.should == "indy@home.com"
    u.role.should == :dog
    u.unique.should == :yep
  end

  it "returns valid attributes rather than the model" do
    Factory.attributes_for(:user).class.should == Hash
  end

  it "clears all instance variables when reset" do
    Factory.instance_variable_set('@some_instance_variable', true)
    Factory.instance_variable_get('@some_instance_variable').should be_true
    Factory.reset
    Factory.instance_variable_get('@some_instance_variable').should be_nil
  end

  it "can create items using the define helper or manually" do
    m = Factory.build(:user_manually)
    d = Factory.build(:user_by_define)
    m.name.should ==  d.name
    m.email.should ==  d.email
    m.role.should ==  d.role
  end

  it "can build by inheriting and overriding from other methods" do
    a = Factory.build(:admin_manually)
    a.name.should == "Fred"
    a.role.should == :admin
    b = Factory.build(:admin_by_define)
    b.name.should == "Fred"
    b.role.should == :admin
  end

  it "gives top priority to attributes defined at the top level, even when inheriting" do
    a = Factory.build(:admin_manually, :role => :something_else)
    a.role.should == :something_else
    b = Factory.build(:admin_by_define, :role => :something_else)
    b.role.should == :something_else
  end

  it "creates unique values using the n method" do
    a = Factory.build(:user)
    b = Factory.build(:user)
    c = Factory.build(:user)
    a.unique.should_not == b.unique
    a.unique.should_not == c.unique
    b.unique.should_not == c.unique
  end

  describe "debugger" do

    it "raises an error if the factory produces an invalid object when enabled (rails only)" do
      expect { Factory.debug(:user, required_attr: nil) }.to raise_error(
        'Oops, the User created by the Factory has the following errors: {:required_attr=>["can\'t be blank"]}'
      )
    end

    it "debug works like build and create when there are no errors" do
      Factory.debug(:user, required_attr: true).class.should == User
      Factory.debug(:user, required_attr: true).saved?.should == false
      Factory.debug!(:user, required_attr: true).saved?.should == true
    end

  end

  it "allows arguments to be passed in the overrides hash" do
    Factory.build(:user).argument_received.should == nil
    Factory.build(:user, :argument_supplied => true).argument_received.should == true
  end

  it "allows blocks to be passed into the define method" do
    Factory.build(:user, :name => "jenny", :email => lambda{ |u| "#{u.name}@home.com" }).email.should == "jenny@home.com"
    Factory.build(:user, :name => lambda { |u| "jimmy" + " cranky" }).name.should == "jimmy cranky"
    Factory.build(:user, :name => "jenny", :email => Proc.new{ |u| "#{u.name}@home.com" }).email.should == "jenny@home.com"
    Factory.build(:user, :name => Proc.new{ |u| "jimmy" + " cranky" }).name.should == "jimmy cranky"
  end

  it "allows factories to call other factories" do
    Factory.build(:user_manually).address.city.should == "New York"
    Factory.create(:user_manually).address.city.should == "New York"
    Factory.create!(:user_manually).address.city.should == "New York"
    Factory.create(:user_manually).address.saved?.should == false
    Factory.create(:user_by_define).address.city.should == "New York"
    Factory.create(:user_by_define).address.saved?.should == true
    Factory.create(:user_by_define).email.should == 'max@home.com'
    Factory.create!(:user_by_define).email.should == 'max@home.com'
  end

  it "has its own syntax" do
    crank(:user).saved?.should == false
    crank!(:address).saved?.should == true
  end

  it "is capable of creating user hashes" do
    Factory.build(:user_hash)[:name].should == "Fred"
    Factory.build(:user_hash)[:role].should == :user
    Factory.build(:user_hash)[:class].should be_nil
  end

  it "is capable of overriding user hashes" do
    Factory.build(:user_hash, :role => :admin)[:role].should == :admin
  end

  it "is capable of using traits" do
    user = Factory.build(:user_manually, :traits => :manager)
    user.role.should == :manager
  end

  it "raises exception if trait method is undefined" do
    lambda { Factory.build(:user_by_define, :traits => :manager) }.should raise_error("Invalid trait 'manager'! No method 'apply_trait_manager_to_user_by_define' is defined.")
  end

  specify "attributes are not assigned when they have the value :skip" do
    crank(:user, :name => :skip).name.should_not be
  end

  it "returns an hash of attributes when the 1st argument is appended with _attrs" do
    crank(:user_attrs).class.should == Hash
    crank(:user_attrs, :name => "Yo")[:name].should == "Yo"
  end

  it "returns nothing extra in the attributes" do
    crank(:user_attrs).size.should == 4
  end

  specify "attributes for works with factory methods using inherit" do
    crank(:admin_by_define_attrs).class.should == Hash
  end

end


text: {{'SETTINGS_CONNECTIONS.ACTION_NEW_CONNECTION_GROUP' | translate}}


text:
I Heart Cuttlefish
==================

A little project for my Gymnasium class.


text:
var fs = require('fs');
var postcss = require('postcss');
var assert = require('assert');

var doitrigger = require('../');

var cssFixture = fs.readFileSync('test/fixtures/basic.css', 'utf8').toString();
var reportFixture = require('./fixtures/report.json');

describe('postcss-doitrigger', function () {
    it('Generates the correct report', function (done) {
        postcss()
            .use(doitrigger())
            .process(cssFixture)
            .then(function (result) {
                try {
                    assert.ok(true);
                    assert.deepEqual(result.messages[0].stats, reportFixture);
                    done();
                } catch (error) {
                    done(error);
                }
            });
    });
});


text:
namespace aura {
class WindowEventDispatcher;
}

namespace ui {
class CursorLoader;
}

namespace views {
class DesktopCursorLoaderUpdater;

namespace corewm {
class NativeCursorManagerDelegate;
}

// A NativeCursorManager that performs the desktop-specific setting of cursor
// state. Similar to AshNativeCursorManager, it also communicates these changes
// to all root windows.
class VIEWS_EXPORT DesktopNativeCursorManager
    : public views::corewm::NativeCursorManager {
 public:
  DesktopNativeCursorManager(
      scoped_ptr<DesktopCursorLoaderUpdater> cursor_loader_updater);
  virtual ~DesktopNativeCursorManager();

  // Builds a cursor and sets the internal platform representation.
  gfx::NativeCursor GetInitializedCursor(int type);

  // Adds |root_window| to the set |root_windows_|.
  void AddRootWindow(aura::WindowEventDispatcher* dispatcher);

  // Removes |root_window| from the set |root_windows_|.
  void RemoveRootWindow(aura::WindowEventDispatcher* dispatcher);

 private:
  // Overridden from views::corewm::NativeCursorManager:
  virtual void SetDisplay(
      const gfx::Display& display,
      views::corewm::NativeCursorManagerDelegate* delegate) OVERRIDE;
  virtual void SetCursor(
      gfx::NativeCursor cursor,
      views::corewm::NativeCursorManagerDelegate* delegate) OVERRIDE;
  virtual void SetVisibility(
      bool visible,
      views::corewm::NativeCursorManagerDelegate* delegate) OVERRIDE;
  virtual void SetCursorSet(
      ui::CursorSetType cursor_set,
      views::corewm::NativeCursorManagerDelegate* delegate) OVERRIDE;
  virtual void SetScale(
      float scale,
      views::corewm::NativeCursorManagerDelegate* delegate) OVERRIDE;
  virtual void SetMouseEventsEnabled(
      bool enabled,
      views::corewm::NativeCursorManagerDelegate* delegate) OVERRIDE;

  // The set of dispatchers to notify of changes in cursor state.
  typedef std::set<aura::WindowEventDispatcher*> Dispatchers;
  Dispatchers dispatchers_;

  scoped_ptr<DesktopCursorLoaderUpdater> cursor_loader_updater_;
  scoped_ptr<ui::CursorLoader> cursor_loader_;

  DISALLOW_COPY_AND_ASSIGN(DesktopNativeCursorManager);
};

}  // namespace views

#endif  // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_H_


text:
.. highlight:: python

============
VerticalLine
============

.. module:: vanilla
.. autoclass:: VerticalLine
   :inherited-members:
   :members:


text:
<!DOCTYPE service_bundle SYSTEM
"/usr/share/lib/xml/dtd/service_bundle.dtd.1">

<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<service_bundle type='manifest' name='activemq'>

<service
        name='network/activemq'
        type='service'
        version='1'>

                <create_default_instance enabled='true' />

        <single_instance/>

        <dependency
                name='activemq-multi-user-server-milestone'
                grouping='require_all'
                restart_on='none'
                type='service'>
                <service_fmri value='svc:/milestone/multi-user-server' />
        </dependency>
	<method_context>
		<method_credential user='activemq' group='other'/>
	       <method_environment>
                     <envvar name="PATH" value="/usr/wsfm/bin:/usr/sfw/bin:/usr/ccs/bin:/usr/local/bin:/usr/bin:" />
                     <envvar name="PWD" value="/home/activemq/activemq" />
                     <envvar name="HOME" value="/home/activemq" />
                     <envvar name="ACTIVEMQ_BASE" value="/home/activemq/activemq" />
                     <envvar name="ACTIVEMQ_HOME" value="/home/activemq/activemq" />
               </method_environment>
	</method_context>

        <exec_method
                type='method'
                name='start'
                exec='/home/activemq/activemq/bin/activemq start'
                timeout_seconds='60' />

        <exec_method
        type='method'
        name='stop'
        exec=':kill'
        timeout_seconds='60' />
        <stability value='Unstable' />

        <template>
                <common_name>
                        <loctext xml:lang='C'>Apache ActiveMQ
                        </loctext>
                </common_name>
		<documentation>
			<doc_link name='apache.org' uri='http://activemq.apache.org/' />
		</documentation>
        </template>
</service>

</service_bundle>


text:
//
//  FVProgressIndicatorCell.m
//  FileView
//
//  Created by Adam Maxwell on 2/15/08.

#import "FVProgressIndicatorCell.h"

@implementation FVProgressIndicatorCell

+ (CGColorRef)_newFillColor
{
    CGColorSpaceRef cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGFloat components[4];
    NSColor *nsColor = [[NSColor selectedControlColor] colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
    [nsColor getComponents:components];
    // make it slightly transparent
    components[3] = 0.8;
    CGColorRef fillColor = CGColorCreate(cspace, components);
    CGColorSpaceRelease(cspace);
    return fillColor;
}

+ (CGColorRef)_newStrokeColor
{
    CGColorSpaceRef cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGFloat components[4];
    NSColor *nsColor = [[NSColor alternateSelectedControlColor] colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
    [nsColor getComponents:components];
    CGColorRef strokeColor = CGColorCreate(cspace, components);
    CGColorSpaceRelease(cspace);
    return strokeColor;
}

- (id)init
{
    self = [super init];
    if (self) {
        _currentProgress = 0;
        _currentRotation = 0;
        _style = FVProgressIndicatorDeterminate;
        _fillColor = [[self class] _newFillColor];
        _strokeColor = [[self class] _newStrokeColor];
    }
    return self;
}

- (void)dealloc
{
    CGColorRelease(_fillColor);
    CGColorRelease(_strokeColor);
    [super dealloc];
}

- (void)setCurrentProgress:(CGFloat)progress { _currentProgress = progress; }
- (CGFloat)currentProgress { return _currentProgress; }
- (void)setStyle:(FVProgressIndicatorStyle)style { _style = style; }

- (void)drawWithFrame:(NSRect)aRect inView:(NSView *)aView
{
    CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSaveGState(context);
    CGRect progressRect = NSRectToCGRect(aRect);
    CGPoint ctr = CGPointMake(CGRectGetMidX(progressRect), CGRectGetMidY(progressRect));

    // indeterminate download length
    if (_style == FVProgressIndicatorIndeterminate) {
        // fixed value of 1/3
        _currentProgress = 0.333;
        _currentRotation += M_PI / (CGFloat)10;
        // rotate the 1/3 sector until the download is complete (see _updateProgressIndicators:)
        CGContextTranslateCTM(context, ctr.x, ctr.y);
        CGContextRotateCTM(context, _currentRotation);
        CGContextTranslateCTM(context, -ctr.x, -ctr.y);
    }

    if (0 < _currentProgress && _currentProgress < 1) {
        CGContextSetFillColorWithColor(context, _fillColor);
        CGContextSetStrokeColorWithColor(context, _strokeColor);
        CGContextBeginPath(context);
        CGFloat radius = CGRectGetWidth(progressRect) / 2;
        CGContextMoveToPoint(context, ctr.x, ctr.y);
        CGPoint arcStart = CGPointMake(CGRectGetMaxX(progressRect), CGRectGetMidY(progressRect));
        CGContextAddLineToPoint(context, arcStart.x, arcStart.y);
        CGFloat angle = 2 * M_PI * _currentProgress;
        CGContextAddArc(context, ctr.x, ctr.y, radius, 0, angle, false);
        CGContextClosePath(context);
        CGContextDrawPath(context, kCGPathFillStroke);
    }
    CGContextRestoreGState(context);
}

@end


text:
package mux

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"regexp"
	"strings"
)

// Route stores information to match a request and build URLs.
type Route struct {
	// Parent where the route was registered (a Router).
	parent parentRoute
	// Request handler for the route.
	handler http.Handler
	// List of matchers.
	matchers []matcher
	// Manager for the variables from host and path.
	regexp *routeRegexpGroup
	// If true, when the path pattern is "/path/", accessing "/path" will
	// redirect to the former and vice versa.
	strictSlash bool
	// If true, this route never matches: it is only used to build URLs.
	buildOnly bool
	// The name used to build URLs.
	name string
	// Error resulted from building a route.
	err error

	buildVarsFunc BuildVarsFunc
}

// Match matches the route against the request.
func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
	if r.buildOnly || r.err != nil {
		return false
	}
	// Match everything.
	for _, m := range r.matchers {
		if matched := m.Match(req, match); !matched {
			return false
		}
	}
	// Yay, we have a match. Let's collect some info about it.
	if match.Route == nil {
		match.Route = r
	}
	if match.Handler == nil {
		match.Handler = r.handler
	}
	if match.Vars == nil {
		match.Vars = make(map[string]string)
	}
	// Set variables.
	if r.regexp != nil {
		r.regexp.setMatch(req, match, r)
	}
	return true
}

// ----------------------------------------------------------------------------
// Route attributes
// ----------------------------------------------------------------------------

// GetError returns an error resulted from building the route, if any.
func (r *Route) GetError() error {
	return r.err
}

// BuildOnly sets the route to never match: it is only used to build URLs.
func (r *Route) BuildOnly() *Route {
	r.buildOnly = true
	return r
}

// Handler --------------------------------------------------------------------

// Handler sets a handler for the route.
func (r *Route) Handler(handler http.Handler) *Route {
	if r.err == nil {
		r.handler = handler
	}
	return r
}

// HandlerFunc sets a handler function for the route.
func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route {
	return r.Handler(http.HandlerFunc(f))
}

// GetHandler returns the handler for the route, if any.
func (r *Route) GetHandler() http.Handler {
	return r.handler
}

// Name -----------------------------------------------------------------------

// Name sets the name for the route, used to build URLs.
// If the name was registered already it will be overwritten.
func (r *Route) Name(name string) *Route {
	if r.name != "" {
		r.err = fmt.Errorf("mux: route already has name %q, can't set %q",
			r.name, name)
	}
	if r.err == nil {
		r.name = name
		r.getNamedRoutes()[name] = r
	}
	return r
}

// GetName returns the name for the route, if any.
func (r *Route) GetName() string {
	return r.name
}

// ----------------------------------------------------------------------------
// Matchers
// ----------------------------------------------------------------------------

// matcher types try to match a request.
type matcher interface {
	Match(*http.Request, *RouteMatch) bool
}

// addMatcher adds a matcher to the route.
func (r *Route) addMatcher(m matcher) *Route {
	if r.err == nil {
		r.matchers = append(r.matchers, m)
	}
	return r
}

// addRegexpMatcher adds a host or path matcher and builder to a route.
func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error {
	if r.err != nil {
		return r.err
	}
	r.regexp = r.getRegexpGroup()
	if !matchHost && !matchQuery {
		if len(tpl) == 0 || tpl[0] != '/' {
			return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
		}
		if r.regexp.path != nil {
			tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
		}
	}
	rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash)
	if err != nil {
		return err
	}
	for _, q := range r.regexp.queries {
		if err = uniqueVars(rr.varsN, q.varsN); err != nil {
			return err
		}
	}
	if matchHost {
		if r.regexp.path != nil {
			if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil {
				return err
			}
		}
		r.regexp.host = rr
	} else {
		if r.regexp.host != nil {
			if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil {
				return err
			}
		}
		if matchQuery {
			r.regexp.queries = append(r.regexp.queries, rr)
		} else {
			r.regexp.path = rr
		}
	}
	r.addMatcher(rr)
	return nil
}

// Headers --------------------------------------------------------------------

// headerMatcher matches the request against header values.
type headerMatcher map[string]string

func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
	return matchMapWithString(m, r.Header, true)
}

// Headers adds a matcher for request header values.
// It accepts a sequence of key/value pairs to be matched. For example:
//
//     r := mux.NewRouter()
//     r.Headers("Content-Type", "application/json",
//               "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both request header values match.
// If the value is an empty string, it will match any value if the key is set.
func (r *Route) Headers(pairs ...string) *Route {
	if r.err == nil {
		var headers map[string]string
		headers, r.err = mapFromPairsToString(pairs...)
		return r.addMatcher(headerMatcher(headers))
	}
	return r
}

// headerRegexMatcher matches the request against the route given a regex for the header
type headerRegexMatcher map[string]*regexp.Regexp

func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
	return matchMapWithRegex(m, r.Header, true)
}

// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex
// support. For example:
//
//     r := mux.NewRouter()
//     r.HeadersRegexp("Content-Type", "application/(text|json)",
//               "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both the request header matches both regular expressions.
// It the value is an empty string, it will match any value if the key is set.
func (r *Route) HeadersRegexp(pairs ...string) *Route {
	if r.err == nil {
		var headers map[string]*regexp.Regexp
		headers, r.err = mapFromPairsToRegex(pairs...)
		return r.addMatcher(headerRegexMatcher(headers))
	}
	return r
}

// Host -----------------------------------------------------------------------

// Host adds a matcher for the URL host.
// It accepts a template with zero or more URL variables enclosed by {}.
// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next dot.
//
// - {name:pattern} matches the given regexp pattern.
//
// For example:
//
//     r := mux.NewRouter()
//     r.Host("www.example.com")
//     r.Host("{subdomain}.domain.com")
//     r.Host("{subdomain:[a-z]+}.domain.com")
//
// Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request).
func (r *Route) Host(tpl string) *Route {
	r.err = r.addRegexpMatcher(tpl, true, false, false)
	return r
}

// MatcherFunc ----------------------------------------------------------------

// MatcherFunc is the function signature used by custom matchers.
type MatcherFunc func(*http.Request, *RouteMatch) bool

// Match returns the match for a given request.
func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool {
	return m(r, match)
}

// MatcherFunc adds a custom function to be used as request matcher.
func (r *Route) MatcherFunc(f MatcherFunc) *Route {
	return r.addMatcher(f)
}

// Methods --------------------------------------------------------------------

// methodMatcher matches the request against HTTP methods.
type methodMatcher []string

func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool {
	return matchInArray(m, r.Method)
}

// Methods adds a matcher for HTTP methods.
// It accepts a sequence of one or more methods to be matched, e.g.:
// "GET", "POST", "PUT".
func (r *Route) Methods(methods ...string) *Route {
	for k, v := range methods {
		methods[k] = strings.ToUpper(v)
	}
	return r.addMatcher(methodMatcher(methods))
}

// Path -----------------------------------------------------------------------

// Path adds a matcher for the URL path.
// It accepts a template with zero or more URL variables enclosed by {}. The
// template must start with a "/".
// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
// - {name:pattern} matches the given regexp pattern.
//
// For example:
//
//     r := mux.NewRouter()
//     r.Path("/products/").Handler(ProductsHandler)
//     r.Path("/products/{key}").Handler(ProductsHandler)
//     r.Path("/articles/{category}/{id:[0-9]+}").
//       Handler(ArticleHandler)
//
// Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request).
func (r *Route) Path(tpl string) *Route {
	r.err = r.addRegexpMatcher(tpl, false, false, false)
	return r
}

// PathPrefix -----------------------------------------------------------------

// PathPrefix adds a matcher for the URL path prefix. This matches if the given
// template is a prefix of the full URL path. See Route.Path() for details on
// the tpl argument.
//
// Note that it does not treat slashes specially ("/foobar/" will be matched by
// the prefix "/foo") so you may want to use a trailing slash here.
//
// Also note that the setting of Router.StrictSlash() has no effect on routes
// with a PathPrefix matcher.
func (r *Route) PathPrefix(tpl string) *Route {
	r.err = r.addRegexpMatcher(tpl, false, true, false)
	return r
}

// Query ----------------------------------------------------------------------

// Queries adds a matcher for URL query values.
// It accepts a sequence of key/value pairs. Values may define variables.
// For example:
//
//     r := mux.NewRouter()
//     r.Queries("foo", "bar", "id", "{id:[0-9]+}")
//
// The above route will only match if the URL contains the defined queries
// values, e.g.: ?foo=bar&id=42.
//
// It the value is an empty string, it will match any value if the key is set.
//
// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
// - {name:pattern} matches the given regexp pattern.
func (r *Route) Queries(pairs ...string) *Route {
	length := len(pairs)
	if length%2 != 0 {
		r.err = fmt.Errorf(
			"mux: number of parameters must be multiple of 2, got %v", pairs)
		return nil
	}
	for i := 0; i < length; i += 2 {
		if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil {
			return r
		}
	}

	return r
}

// Schemes --------------------------------------------------------------------

// schemeMatcher matches the request against URL schemes.
type schemeMatcher []string

func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool {
	return matchInArray(m, r.URL.Scheme)
}

// Schemes adds a matcher for URL schemes.
// It accepts a sequence of schemes to be matched, e.g.: "http", "https".
func (r *Route) Schemes(schemes ...string) *Route {
	for k, v := range schemes {
		schemes[k] = strings.ToLower(v)
	}
	return r.addMatcher(schemeMatcher(schemes))
}

// BuildVarsFunc --------------------------------------------------------------

// BuildVarsFunc is the function signature used by custom build variable
// functions (which can modify route variables before a route's URL is built).
type BuildVarsFunc func(map[string]string) map[string]string

// BuildVarsFunc adds a custom function to be used to modify build variables
// before a route's URL is built.
func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
	r.buildVarsFunc = f
	return r
}

// Subrouter ------------------------------------------------------------------

// Subrouter creates a subrouter for the route.
//
// It will test the inner routes only if the parent route matched. For example:
//
//     r := mux.NewRouter()
//     s := r.Host("www.example.com").Subrouter()
//     s.HandleFunc("/products/", ProductsHandler)
//     s.HandleFunc("/products/{key}", ProductHandler)
//     s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
//
// Here, the routes registered in the subrouter won't be tested if the host
// doesn't match.
func (r *Route) Subrouter() *Router {
	router := &Router{parent: r, strictSlash: r.strictSlash}
	r.addMatcher(router)
	return router
}

// ----------------------------------------------------------------------------
// URL building
// ----------------------------------------------------------------------------

// URL builds a URL for the route.
//
// It accepts a sequence of key/value pairs for the route variables. For
// example, given this route:
//
//     r := mux.NewRouter()
//     r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
//       Name("article")
//
// ...a URL for it can be built using:
//
//     url, err := r.Get("article").URL("category", "technology", "id", "42")
//
// ...which will return an url.URL with the following path:
//
//     "/articles/technology/42"
//
// This also works for host variables:
//
//     r := mux.NewRouter()
//     r.Host("{subdomain}.domain.com").
//       HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
//       Name("article")
//
//     // url.String() will be "http://news.domain.com/articles/technology/42"
//     url, err := r.Get("article").URL("subdomain", "news",
//                                      "category", "technology",
//                                      "id", "42")
//
// All variables defined in the route are required, and their values must
// conform to the corresponding patterns.
func (r *Route) URL(pairs ...string) (*url.URL, error) {
	if r.err != nil {
		return nil, r.err
	}
	if r.regexp == nil {
		return nil, errors.New("mux: route doesn't have a host or path")
	}
	values, err := r.prepareVars(pairs...)
	if err != nil {
		return nil, err
	}
	var scheme, host, path string
	if r.regexp.host != nil {
		// Set a default scheme.
		scheme = "http"
		if host, err = r.regexp.host.url(values); err != nil {
			return nil, err
		}
	}
	if r.regexp.path != nil {
		if path, err = r.regexp.path.url(values); err != nil {
			return nil, err
		}
	}
	return &url.URL{
		Scheme: scheme,
		Host:   host,
		Path:   path,
	}, nil
}

// URLHost builds the host part of the URL for a route. See Route.URL().
//
// The route must have a host defined.
func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
	if r.err != nil {
		return nil, r.err
	}
	if r.regexp == nil || r.regexp.host == nil {
		return nil, errors.New("mux: route doesn't have a host")
	}
	values, err := r.prepareVars(pairs...)
	if err != nil {
		return nil, err
	}
	host, err := r.regexp.host.url(values)
	if err != nil {
		return nil, err
	}
	return &url.URL{
		Scheme: "http",
		Host:   host,
	}, nil
}

// URLPath builds the path part of the URL for a route. See Route.URL().
//
// The route must have a path defined.
func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
	if r.err != nil {
		return nil, r.err
	}
	if r.regexp == nil || r.regexp.path == nil {
		return nil, errors.New("mux: route doesn't have a path")
	}
	values, err := r.prepareVars(pairs...)
	if err != nil {
		return nil, err
	}
	path, err := r.regexp.path.url(values)
	if err != nil {
		return nil, err
	}
	return &url.URL{
		Path: path,
	}, nil
}

// prepareVars converts the route variable pairs into a map. If the route has a
// BuildVarsFunc, it is invoked.
func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
	m, err := mapFromPairsToString(pairs...)
	if err != nil {
		return nil, err
	}
	return r.buildVars(m), nil
}

func (r *Route) buildVars(m map[string]string) map[string]string {
	if r.parent != nil {
		m = r.parent.buildVars(m)
	}
	if r.buildVarsFunc != nil {
		m = r.buildVarsFunc(m)
	}
	return m
}

// ----------------------------------------------------------------------------
// parentRoute
// ----------------------------------------------------------------------------

// parentRoute allows routes to know about parent host and path definitions.
type parentRoute interface {
	getNamedRoutes() map[string]*Route
	getRegexpGroup() *routeRegexpGroup
	buildVars(map[string]string) map[string]string
}

// getNamedRoutes returns the map where named routes are registered.
func (r *Route) getNamedRoutes() map[string]*Route {
	if r.parent == nil {
		// During tests router is not always set.
		r.parent = NewRouter()
	}
	return r.parent.getNamedRoutes()
}

// getRegexpGroup returns regexp definitions from this route.
func (r *Route) getRegexpGroup() *routeRegexpGroup {
	if r.regexp == nil {
		if r.parent == nil {
			// During tests router is not always set.
			r.parent = NewRouter()
		}
		regexp := r.parent.getRegexpGroup()
		if regexp == nil {
			r.regexp = new(routeRegexpGroup)
		} else {
			// Copy.
			r.regexp = &routeRegexpGroup{
				host:    regexp.host,
				path:    regexp.path,
				queries: regexp.queries,
			}
		}
	}
	return r.regexp
}


text:
[Jaanga]( http://jaanga.github.io/ ) » [Terrain 2]( http://jaanga.github.io/terrain-r2/ ) » [Viewers]( http://jaanga.github.io/terrain-r2/viewers/ ) »

[Moon Voyager Read Me]( index.html )
===

[You are now in GitHub source code view - click here to view Read Me file as a web page]( http://jaanga.github.io/terrain-r2/viewers/moon-voyager/index.html "View file as a web page." )
<input type=button value='You are now in GitHub web page view - Click here to view Read Me file as source code' onclick=window.location.href='https://github.com/jaanga/terrain-r2/tree/gh-pages/viewers/moon-voyager/'; />

####_Moon Voyager - Dev revision - Code Edit View_ /  [Fullscreen]( http://exploratoria.github.io/lib/code-edit-view/code-edit-view.html#http://jaanga.github.io/terrain-r2/viewers/moon-voyager/moon-voyager-r2.html )

[Mars Voyager Demo Full Screen - Dev]( http://jaanga.github.io/terrain-r2/viewers/moon-voyager/dev/ )

## Concept

### Issue

From earth, we 'see' the moon as a flat one-sided disk. Yet we know it is a 3D orb with a surface full of complexity.

## Mission

To provide a way of flying over the sphere of the moon in 3D and to see its craters and rills in detail
To show the usually hidden backside of the moon as easily as the front

## Things to Do

* Edit the auto rotation variable to change the speed of the spin of the moon
* Edit heighPlacard to move the location signboards up or down
* Edit the default height scale

## Features

* 1440 x 720 terrain data points with 255 heights
* 'Travel' over the moon in 3D faster than any satellite
	* Use one finger to rotate
	* Pinch with two fingers to zoom in and out
	* use three fingers to pan
* Gazetteer takes you to 97 locations
	* All locations available via a drop-down list
	* Clicking a location in the drop-down takes you to the location

* Slider to adjust vertical scale in real-time
* Camera position follows cursor keys
	* Latest camera position is used to control camera position when using cursor keys

## Road Map

* 'Zoom All' and 'Zoom In' buttons
* Toggle between short and long gazetteers
* Links to Data sources such as WikiMoon for each location
* First person control moon flyover capability
* Supports permalinks
* Click on a placard to go there
* Permalinks to set target and camera positions
* Sunlight and shadows
* Textures and materials to 3D terrain
* 3D models of lunar landers in their locations
* Locations of Apollo photographs - perhaps as geojson data

## Issues

* Text flashes annoyingly as it moves

## Sources

Many thanks to:

Gazetteer data sources:

* [Gazetteer of Planetary Nomenclature]( http://planetarynames.wr.usgs.gov/Page/MOON/target )
* [Lunar 100]( http://the-moon.wikispaces.com/Lunar+100 )

Lunar height data source:

[Lunar Reconnaissance Orbiter Camera]( http://wms.lroc.asu.edu/lroc/view_rdr/WAC_GLD100 )


text:
function p=lin2pcma(x,m,s)
%LIN2PCMA Convert linear PCM to A-law P=(X,M,S)
%	pcma = lin2pcma(lin) where lin contains a vector
%	or matrix of signal values.
%	The input values will be converted to integer
%	A-law pcm vlues in the range 0 to 255 and the XORed with m
%	(default m=85).
%
%	Input values are multiplied by the scale factor s:
%
%		   s		Input Range
%
%		   1		+-4096
%		2017.396342	+-2.03033976 (default)
%		4096		+-1
%
%	Input values outside the selected range will be clipped.
%
%	The default value of the scale factor is 2017.396342 which equals
%	sqrt((1120^2 + 2624^2)/2). This factor follows ITU standard G.711 and
%	the sine wave with PCM-A values [225 244 244 225 97 116 116 97]
%	has a mean square value of unity corresponding to 0 dBm0.
%
%	See also PCMA2LIN, LIN2PCMA, LIN2PCMU

%      Copyright (C) Mike Brookes 1998
%      Version: $Id: lin2pcma.m 713 2011-10-16 14:45:43Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin<3
  s=2017.396342;
  if nargin<2 m=85; end
end

y=x*pow2(s,-6);
y=(abs(y+63)-abs(y-63))/2;
q=floor((y+64)/64);
[a,e]=log2(abs(y));
d = (e+abs(e))/2;
p=128*q+16*d+floor(pow2(a,e-d+5));
if m p=bitxor(p,m); end;


text:
namespace annealing {

    using std::cout;

    using origami::molarity_to_chempot;

    AnnealingGCMCSimulation::AnnealingGCMCSimulation(
            OrigamiSystem& origami_system,
            SystemOrderParams& ops,
            SystemBiases& biases,
            InputParameters& params) :
            GCMCSimulation(origami_system, ops, biases, params),
            m_max_temp {params.m_max_temp},
            m_min_temp {params.m_min_temp},
            m_temp_interval {params.m_temp_interval},
            m_steps_per_temp {params.m_steps_per_temp},
            m_staple_M {params.m_staple_M},
            m_constant_staple_M {params.m_constant_staple_M} {

        if (fmod(m_max_temp - m_min_temp, m_temp_interval) != 0) {
            cout << "Bad temperature interval";
        }
        m_logging_stream = &cout;
        m_output_files = simulation::setup_output_files(params,
                params.m_output_filebase,
                m_origami_system, m_ops, m_biases);
    }

    void AnnealingGCMCSimulation::run() {
        double temp {m_max_temp};
        double staple_u {molarity_to_chempot(m_staple_M, temp)};
        long long int step {0};
        while (temp >= m_min_temp) {
            m_origami_system.update_temp(temp);
            if (m_constant_staple_M) {
                staple_u = molarity_to_chempot(m_staple_M, temp);
                m_origami_system.update_staple_u(staple_u);
            }
            step += simulate(m_steps_per_temp, step);
            temp -= m_temp_interval;
        }
    }
}


text:
git config --global alias.root 'rev-parse --show-toplevel'
REPO_ROOT=$(git root)

[ -f "$REPO_ROOT"/conf/master.conf ] || { echo "master conf not found!"; exit 1; }
[ -f "$REPO_ROOT"/conf/jaas.conf ] || { echo "Jaas conf not found!"; exit 1; }
[ -f "$REPO_ROOT"/conf/krb5.conf ] || { echo "Kerberos conf not found!" ; exit 1; }
[ -f "$REPO_ROOT"/build/master.jar ] || { echo "Jar file not found, run compile.sh!" ; exit 1; }

cd $REPO_ROOT/bin

java -jar -Dconfig.file=../conf/master.conf -Djava.security.auth.login.config=../conf/jaas.conf -Djava.security.krb5.conf=../conf/krb5.conf ../build/master.jar