text:
package org.dswarm.controller.resources;

import java.io.IOException;
import java.net.URI;
import java.util.List;

import javax.inject.Provider;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.dswarm.common.types.Tuple;
import org.dswarm.controller.DMPControllerException;
import org.dswarm.controller.DMPJsonException;
import org.dswarm.persistence.DMPPersistenceException;
import org.dswarm.persistence.model.DMPObject;
import org.dswarm.persistence.model.proxy.ProxyDMPObject;
import org.dswarm.persistence.model.proxy.RetrievalType;
import org.dswarm.persistence.model.types.Triple;
import org.dswarm.persistence.service.BasicJPAService;

/**
 * A generic resource (controller service), whose concrete implementations can be derived with a given implementation of
 * {@link DMPObject} and the related identifier type. This service delivers basic controller layer functionality to create a new
 * object or retrieve existing ones.<br/>
 *
 * @param <POJOCLASSPERSISTENCESERVICE> the concrete persistence service of the resource that is related to the concrete POJO
 *                                      class
 * @param <POJOCLASS>                   the concrete POJO class of the resource
 * @author tgaengler
 * @author fniederlein
 */
public abstract class BasicResource<POJOCLASSPERSISTENCESERVICE extends BasicJPAService<PROXYPOJOCLASS, POJOCLASS>, PROXYPOJOCLASS extends ProxyDMPObject<POJOCLASS>, POJOCLASS extends DMPObject> extends AbstractBaseResource {

	private static final Logger LOG = LoggerFactory.getLogger(BasicResource.class);

	protected final Class<POJOCLASS> pojoClass;

	protected final String pojoClassName;

	protected final Provider<POJOCLASSPERSISTENCESERVICE> persistenceServiceProvider;

	protected final Provider<ObjectMapper> objectMapperProvider;

	/**
	 * Creates a new resource (controller service) for the given concrete POJO class with the provider of the concrete persistence
	 * service and metrics registry.
	 *
	 * @param pojoClassArg
	 * @param persistenceServiceProviderArg
	 * @param objectMapperProviderArg
	 */
	protected BasicResource(final Class<POJOCLASS> pojoClassArg, final Provider<POJOCLASSPERSISTENCESERVICE> persistenceServiceProviderArg,
			final Provider<ObjectMapper> objectMapperProviderArg) {

		pojoClass = pojoClassArg;
		pojoClassName = pojoClass.getSimpleName();
		persistenceServiceProvider = persistenceServiceProviderArg;
		objectMapperProvider = objectMapperProviderArg;
	}

	/**
	 * Gets the concrete POJO class of this resource (controller service).
	 *
	 * @return the concrete POJO class
	 */
	public Class<POJOCLASS> getClasz() {

		return pojoClass;
	}

	/**
	 * This endpoint returns an object of the type of the POJO class as JSON representation for the provided object uuid.
	 *
	 * @param uuid an object uuid
	 * @return a JSON representation of an object of the type of the POJO class
	 */
	// @GET
	// @Path("/{uuid}")
	// @Produces(MediaType.APPLICATION_JSON)
	@Timed
	public Response getObject(/* @PathParam("uuid") */final String uuid) throws DMPControllerException {

		BasicResource.LOG.debug("try to get {} with uuid '{}'", pojoClassName, uuid);

		final POJOCLASSPERSISTENCESERVICE persistenceService = persistenceServiceProvider.get();
		final POJOCLASS object = persistenceService.getObject(uuid);

		if (object == null) {

			BasicResource.LOG.debug("couldn't find {} '{}'", pojoClassName, uuid);

			return Response.status(Status.NOT_FOUND).build();
		}
		BasicResource.LOG.debug("got {} with uuid '{}'", pojoClassName, uuid);
		BasicResource.LOG.trace(" = '{}'", ToStringBuilder.reflectionToString(object));

		final String objectJSON = serializeObject(object);

		BasicResource.LOG.debug("return {} with uuid '{}'", pojoClassName, uuid);
		BasicResource.LOG.trace(" = '{}'", objectJSON);

		return buildResponse(objectJSON);
	}

	/**
	 * This endpoint consumes an object of the type of the POJO class as JSON representation and persists this object in the
	 * database.
	 *
	 * @param jsonObjectString a JSON representation of one object of the type of the POJO class
	 * @return the persisted object as JSON representation
	 * @throws DMPControllerException
	 */
	// @POST
	// @Consumes(MediaType.APPLICATION_JSON)
	// @Produces(MediaType.APPLICATION_JSON)
	@Timed
	public Response createObject(final String jsonObjectString) throws DMPControllerException {

		BasicResource.LOG.debug("try to create new {}", pojoClassName);

		final PROXYPOJOCLASS proxyObject = addObject(jsonObjectString);

		if (proxyObject == null) {

			BasicResource.LOG.debug("couldn't add {}", pojoClassName);
			throw new DMPControllerException("couldn't add " + pojoClassName);
		}

		final POJOCLASS object = proxyObject.getObject();

		if (object == null) {

			BasicResource.LOG.debug("couldn't add {}", pojoClassName);
			throw new DMPControllerException("couldn't add " + pojoClassName);
		}

		BasicResource.LOG.debug("added new {} with id = '{}' ", pojoClassName, object.getUuid());
		BasicResource.LOG.trace(" = '{}'", ToStringBuilder.reflectionToString(object));

		final String objectJSON = serializeObject(object);

		final URI objectURI = createObjectURI(object);

		if (objectURI == null) {

			BasicResource.LOG.debug("something went wrong, while minting the URL of the new {}", pojoClassName);
			throw new DMPControllerException("something went wrong, while minting the URL of the new " + pojoClassName);
		}

		BasicResource.LOG.debug("return new {} at '{}'", pojoClassName, objectURI);
		BasicResource.LOG.trace("with content '{}'", objectJSON);

		final ResponseBuilder responseBuilder;
		final RetrievalType type = proxyObject.getType();

		switch (type) {

			case CREATED:

				responseBuilder = Response.created(objectURI);

				break;
			case RETRIEVED:

				responseBuilder = Response.ok().contentLocation(objectURI);

				break;
			default:

				BasicResource.LOG.debug("something went wrong, while evaluating the retrieval type of the {}", pojoClassName);
				throw new DMPControllerException("something went wrong, while evaluating the retrieval type of the "
						+ pojoClassName);
		}

		return responseBuilder.entity(objectJSON).build();
	}

	/**
	 * This endpoint consumes an object of the type of the POJO class as JSON representation and update this object in the
	 * database.
	 *
	 * @param jsonObjectString a JSON representation of one object of the type of the POJO class
	 * @param uuid             an object uuid
	 * @return the persisted object as JSON representation
	 * @throws DMPControllerException
	 */
	// @PUT
	// @Path("/{uuid}")
	// @Consumes(MediaType.APPLICATION_JSON)
	// @Produces(MediaType.APPLICATION_JSON)
	@Timed
	public Response updateObject(final String jsonObjectString, /* @PathParam("uuid") */final String uuid) throws DMPControllerException {

		BasicResource.LOG.debug("try to update {} '{}'", pojoClassName, uuid);

		final POJOCLASS objectFromDB = retrieveObject(uuid, jsonObjectString);

		if (objectFromDB == null) {

			return Response.status(Status.NOT_FOUND).build();
		}

		final Triple<PROXYPOJOCLASS, POJOCLASS, String> updateResult = updateObjectInternal(jsonObjectString, uuid, objectFromDB);

		return createUpdateResponse(updateResult.v1(), updateResult.v2(), updateResult.v3());
	}

	/**
	 * This endpoint returns a list of all objects of the type of the POJO class as JSON representation.
	 *
	 * @return a list of all objects of the type of the POJO class as JSON representation
	 * @throws DMPControllerException
	 */
	// @ApiOperation(value = "get all objects ", notes = "Returns a list objects.")
	// @GET
	// @Produces(MediaType.APPLICATION_JSON)
	@Timed
	public Response getObjects() throws DMPControllerException {

		BasicResource.LOG.debug("try to get all {}s", pojoClassName);

		final POJOCLASSPERSISTENCESERVICE persistenceService = persistenceServiceProvider.get();

		final List<POJOCLASS> objects = persistenceService.getObjects();

		if (objects == null) {

			BasicResource.LOG.debug("couldn't find {}s", pojoClassName);
			return Response.status(Status.NOT_FOUND).build();
		}

		if (objects.isEmpty()) {

			BasicResource.LOG.debug("there are no {}s", pojoClassName);
			return Response.status(Status.NOT_FOUND).build();
		}

		BasicResource.LOG.debug("got all {}s ", pojoClassName);
		BasicResource.LOG.trace(" = '{}'", ToStringBuilder.reflectionToString(objects));

		final String objectsJSON = serializeObject(objects);

		BasicResource.LOG.debug("return all {}s ", pojoClassName);
		BasicResource.LOG.trace("'{}'", objectsJSON);
		return buildResponse(objectsJSON);
	}

	/**
	 * This endpoint deletes an object identified by the uuid.
	 *
	 * @param uuid an object uuid
	 * @return status 204 if removal was successful, 404 if uuid not found, 409 if it couldn't be removed, or 500 if something else
	 * went wrong
	 * @throws DMPControllerException
	 */
	// @ApiOperation(value = "delete an object by uuid ", notes = "Returns a status.")
	// @DELETE
	// @Path("/{uuid}")
	@Timed
	public Response deleteObject(/* @PathParam("uuid") */final String uuid) throws DMPControllerException {

		BasicResource.LOG.debug("try to delete {} with uuid '{}'", pojoClassName, uuid);

		final POJOCLASSPERSISTENCESERVICE persistenceService = persistenceServiceProvider.get();
		POJOCLASS object = persistenceService.getObject(uuid);

		if (object == null) {

			BasicResource.LOG.debug("couldn't find {} '{}'", pojoClassName, uuid);
			return Response.status(Status.NOT_FOUND).build();
		}
		BasicResource.LOG.debug("got {} with uuid '{}' ", pojoClassName, uuid);
		BasicResource.LOG.trace(" = '{}'", ToStringBuilder.reflectionToString(object));

		persistenceService.deleteObject(uuid);

		object = persistenceService.getObject(uuid);

		if (object != null) {

			BasicResource.LOG.debug("couldn't delete {} '{}'", pojoClassName, uuid);
			return Response.status(Status.CONFLICT).build();
		}

		BasicResource.LOG.debug("deletion of {} with uuid '{} was successful", pojoClassName, uuid);
		return Response.status(Status.NO_CONTENT).build();
	}

	/**
	 * Creates the resource URI for the given object.
	 *
	 * @param object an object
	 * @return the resource URI for the given object
	 */
	protected URI createObjectURI(final POJOCLASS object) {
		return createObjectURI(object.getUuid());
	}

	/**
	 * Prepares a given object with information from an object that was received via an API request.
	 *
	 * @param objectFromJSON an object that was received via an API request
	 * @param object         the given object
	 * @return the updated object
	 */
	protected abstract POJOCLASS prepareObjectForUpdate(final POJOCLASS objectFromJSON, final POJOCLASS object);

	/**
	 * Persists a new object that was received via an API request into the database.
	 *
	 * @param objectJSONString
	 * @return
	 * @throws DMPControllerException
	 */
	protected PROXYPOJOCLASS addObject(final String objectJSONString) throws DMPControllerException {

		// get the deserialisised object from the object JSON string

		final POJOCLASS objectFromJSON = deserializeObjectJSONString(objectJSONString);

		// create a new persistent object

		final POJOCLASSPERSISTENCESERVICE persistenceService = persistenceServiceProvider.get();
		final PROXYPOJOCLASS proxyObject;

		try {

			proxyObject = createObject(objectFromJSON, persistenceService);
		} catch (final DMPPersistenceException e) {

			BasicResource.LOG.debug("something went wrong while {} creation", pojoClassName);

			throw new DMPControllerException("something went wrong while " + pojoClassName + " creation\n" + e.getMessage());
		}

		if (proxyObject == null) {

			throw new DMPControllerException("fresh " + pojoClassName + " shouldn't be null");
		}

		final POJOCLASS object = proxyObject.getObject();

		if (object == null) {

			throw new DMPControllerException("fresh " + pojoClassName + " shouldn't be null");
		}

		return proxyObject;
	}

	/**
	 * Persists an existing object that was received via an API request into the database.
	 *
	 * @param objectJSONString
	 * @param uuid
	 * @return
	 * @throws DMPControllerException
	 */
	protected PROXYPOJOCLASS refreshObject(final String objectJSONString, final POJOCLASS object, final String uuid)
			throws DMPControllerException {

		// get the deserialisised object from the object JSON string

		final POJOCLASS objectFromJSON = deserializeObjectJSONString(objectJSONString);

		final POJOCLASS preparedObject = prepareObjectForUpdate(objectFromJSON, object);

		return updateObject(preparedObject, uuid);
	}

	protected POJOCLASS retrieveObject(final String uuid, final String jsonObjectString) throws DMPControllerException {

		// get persistent object per uuid

		final POJOCLASSPERSISTENCESERVICE persistenceService = persistenceServiceProvider.get();
		final POJOCLASS object = persistenceService.getObject(uuid);

		if (object == null) {

			BasicResource.LOG.debug("{} for uuid '{}' does not exist, i.e., it cannot be updated", pojoClassName, uuid);

			return null;
		}

		BasicResource.LOG.debug("got {} with uuid '{}' ", pojoClassName, uuid);

		if (BasicResource.LOG.isTraceEnabled()) {

			BasicResource.LOG.trace("= '{}'", ToStringBuilder.reflectionToString(object));
		}

		return object;

	}

	protected PROXYPOJOCLASS updateObject(final POJOCLASS preparedObject, final String uuid) throws DMPControllerException {

		// update the persistent object in the DB

		final POJOCLASSPERSISTENCESERVICE persistenceService = persistenceServiceProvider.get();

		try {

			return persistenceService.updateObjectTransactional(preparedObject);
		} catch (final DMPPersistenceException e) {

			BasicResource.LOG.debug("something went wrong while updating {}  for uuid '{}'", pojoClassName, uuid);

			throw new DMPControllerException("something went wrong while updating" + pojoClassName + "  for uuid '" + uuid
					+ "'\n" + e.getMessage());
		}
	}

	protected POJOCLASS deserializeObjectJSONString(final String objectJSONString) throws DMPControllerException {

		POJOCLASS objectFromJSON = null;

		try {

			objectFromJSON = objectMapperProvider.get().readValue(objectJSONString, pojoClass);
		} catch (final JsonMappingException je) {

			throw new DMPJsonException("something went wrong while deserializing the " + pojoClassName + " JSON string", je);
		} catch (final IOException e) {

			BasicResource.LOG.debug("something went wrong while deserializing the {} JSON string", pojoClassName);

			throw new DMPControllerException("something went wrong while deserializing the " + pojoClassName + " JSON string.\n" + e.getMessage());
		}

		if (objectFromJSON == null) {

			throw new DMPControllerException("deserialized " + pojoClassName + " is null");
		}

		return objectFromJSON;
	}

	protected String serializeObject(final Object object) throws DMPControllerException {

		String objectJSONString = null;

		try {

			objectJSONString = objectMapperProvider.get().writeValueAsString(object);
		} catch (final JsonProcessingException e) {

			BasicResource.LOG.debug("couldn't serialize enhanced {} JSON.", pojoClassName);

			throw new DMPControllerException("couldn't serialize enhanced " + pojoClassName + " JSON.", e);
		}

		if (objectJSONString == null) {

			BasicResource.LOG.debug("couldn't serialize enhanced {} JSON correctly.", pojoClassName);

			throw new DMPControllerException("couldn't serialize enhanced " + pojoClassName + " JSON correctly.");
		}

		return objectJSONString;
	}

	/**
	 * Creates and persists a new object into the database.
	 *
	 * @param objectFromJSON     the new object
	 * @param persistenceService the related persistence service
	 * @return the persisted object
	 * @throws DMPPersistenceException
	 */
	protected PROXYPOJOCLASS createObject(final POJOCLASS objectFromJSON, final POJOCLASSPERSISTENCESERVICE persistenceService)
			throws DMPPersistenceException {

		return persistenceService.createObjectTransactional(objectFromJSON);
	}

	protected Triple<PROXYPOJOCLASS, POJOCLASS, String> updateObjectInternal(final String jsonObjectString, final String uuid,
			final POJOCLASS objectFromDB)
			throws DMPControllerException {

		final Tuple<PROXYPOJOCLASS, POJOCLASS> updateResult = updateObjectInternal2(jsonObjectString, uuid, objectFromDB);

		final POJOCLASS object = updateResult.v2();

		final String objectJSON = serializeObject(object);

		BasicResource.LOG.debug("return updated {} with uuid '{}'", pojoClassName, object.getUuid());

		if (BasicResource.LOG.isTraceEnabled()) {

			BasicResource.LOG.trace(" = '" + objectJSON + "'");
		}

		return Triple.triple(updateResult.v1(), object, objectJSON);
	}

	protected Tuple<PROXYPOJOCLASS, POJOCLASS> updateObjectInternal2(final String jsonObjectString, final String uuid,
			final POJOCLASS objectFromDB) throws DMPControllerException {

		final PROXYPOJOCLASS proxyObject = refreshObject(jsonObjectString, objectFromDB, uuid);

		if (proxyObject == null) {

			BasicResource.LOG.debug("couldn't update {} '{}'", pojoClassName, uuid);

			throw new DMPControllerException("couldn't update " + pojoClassName + " '" + uuid + "'");
		}

		final POJOCLASS object = proxyObject.getObject();

		if (object == null) {

			BasicResource.LOG.debug("couldn't update {} '{}'", pojoClassName, uuid);

			throw new DMPControllerException("couldn't update " + pojoClassName + " '" + uuid + "'");
		}

		BasicResource.LOG.debug("updated {} '{}'", pojoClassName, uuid);

		if (BasicResource.LOG.isTraceEnabled()) {

			BasicResource.LOG.trace(" = '" + ToStringBuilder.reflectionToString(object) + "'");
		}

		return Tuple.tuple(proxyObject, object);
	}

	protected Response createUpdateResponse(final PROXYPOJOCLASS proxyObject, final POJOCLASS object, final String objectJSON)
			throws DMPControllerException {

		final URI objectURI = createObjectURI(object);
		final ResponseBuilder responseBuilder;
		final RetrievalType type = proxyObject.getType();

		switch (type) {

			case CREATED:

				responseBuilder = Response.created(objectURI);

				break;
			case UPDATED:
			case RETRIEVED:

				responseBuilder = Response.ok().contentLocation(objectURI);

				break;
			default:

				BasicResource.LOG.debug("something went wrong, while evaluating the retrieval type of the {}", pojoClassName);

				throw new DMPControllerException("something went wrong, while evaluating the retrieval type of the "
						+ pojoClassName);
		}

		return responseBuilder.entity(objectJSON).build();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package sim.topology;

import java.util.Random;

import sim.Config;
import sim.graphs.Construction;

public class DegenTorus {

	private static int _k;
	private static int _n;

	/*
	 * For each node and each dimension, make the left and right connections,
	 * except on edges where posInDim==0 or k-1
	 *
	 * Dimension i: (L) <-- (N) --> (R)
	 */
	public static Construction create(int k, int n, double faults) {

		_k = k;
		_n = n;

		int numNodes = (int) Math.pow(_k, _n);
		Construction graph = new Construction(numNodes);

        for(int node=0; node<numNodes; node++) {

			for(int dim = 0; dim < n; dim++) {

				//System.out.println("Dimension "+dim);

			    int leftNode  = getLeftNode(node, dim);
			    int rightNode = getRightNode(node, dim);

			    if(leftNode != -1) {
			    	graph.addEdge(node, leftNode);
			    }

			    if(rightNode != -1) {
			    	graph.addEdge(node, rightNode);
			    }
		    }

		}

        // Remove links as faults
        Random rand = new Random(Config.graphSeed());
        int numLinkFaults = (int)((double)graph.vertexSet().size() * faults);
        int faultCount = 0;

        while(faultCount < numLinkFaults) {
        	if(graph.removeRandomEdge(rand)) {
        		faultCount++;
        	} else {
        		System.err.println("Error: cannot remove any links without disconnecting graph");
        	}
        }

        //graph.writeDot("degen_mesh.dot");
		//Visualise.createDotImage("degen_mesh.dot", "degen_mesh.ps");

		System.out.println("Created degenerated torus topology with "+(100.0*faults)+"% ("+faultCount+") faults");
		return graph;
	}

	private static int getLeftNode(int node, int dim) {

	  int kToDim = (int) Math.pow(_k, dim);
	  int posInDim = (node / kToDim) % _k;

	  // if at the left edge of the dimension, wrap-around
	  return posInDim == 0 ? (node + (_k-1)*kToDim) : (node - kToDim);
	}

	private static int getRightNode(int node, int dim) {

	  int kToDim = (int) Math.pow(_k, dim);
	  int posInDim = (node / kToDim) % _k;

	  // if at the right edge of the dimension, wrap-around
	  return posInDim == _k-1 ? (node - (_k-1)*kToDim) : (node + kToDim);
	}

}


text:
/* $Id$ */

/*
 *  Copyright (c) 2006-2009 Axel Andersson
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>

#include <wired/wi-assert.h>
#include <wired/wi-dictionary.h>
#include <wired/wi-lock.h>
#include <wired/wi-log.h>
#include <wired/wi-pool.h>
#include <wired/wi-private.h>
#include <wired/wi-string.h>
#include <wired/wi-system.h>
#include <wired/wi-thread.h>

#define _WI_POOL_ARRAY_SIZE \
	((4096 - sizeof(wi_uinteger_t) - sizeof(void *)) / sizeof(void *))

#define _WI_POOL_STACK_INITIAL_SIZE		4
#define _WI_POOL_STACKS_INITIAL_SIZE	4
#define _WI_POOL_STACKS_BUCKETS			64

struct _wi_pool_array {
	wi_runtime_instance_t				*instances[_WI_POOL_ARRAY_SIZE];
	wi_uinteger_t						length;

	struct _wi_pool_array				*next;
};
typedef struct _wi_pool_array			_wi_pool_array_t;

struct _wi_pool_stack {
	wi_pool_t							**pools;
	wi_uinteger_t						capacity;
	wi_uinteger_t						length;
};
typedef struct _wi_pool_stack			_wi_pool_stack_t;

struct _wi_pool {
	wi_runtime_base_t					base;

	wi_uinteger_t						count;
	_wi_pool_array_t					*array;

	wi_string_t							*context;
	wi_mutable_dictionary_t				*locations;
};

static void								_wi_pool_dealloc(wi_runtime_instance_t *);

static void								_wi_pool_add_pool(wi_pool_t *);
static wi_pool_t *						_wi_pool_pool(void);
static void								_wi_pool_drain_pool(wi_pool_t *);
static void								_wi_pool_remove_pool(wi_pool_t *);
static void								_wi_pool_invalid_abort(wi_pool_t *, wi_runtime_instance_t *);

wi_boolean_t							wi_pool_debug = false;

static wi_runtime_id_t					_wi_pool_runtime_id = WI_RUNTIME_ID_NULL;
static wi_runtime_class_t				_wi_pool_runtime_class = {
	"wi_pool_t",
	_wi_pool_dealloc,
	NULL,
	NULL,
	NULL,
	NULL
};

void wi_pool_register(void) {
	_wi_pool_runtime_id = wi_runtime_register_class(&_wi_pool_runtime_class);
}

void wi_pool_initialize(void) {
	char	*env;

	env = getenv("wi_pool_debug");

	if(env) {
		wi_pool_debug = (strcmp(env, "0") != 0);

		printf("*** wi_pool_initialize(): wi_pool_debug = %u\n", wi_pool_debug);
	}
}

#pragma mark -

wi_runtime_id_t wi_pool_runtime_id(void) {
	return _wi_pool_runtime_id;
}

#pragma mark -

wi_pool_t * wi_pool_alloc(void) {
	return wi_runtime_create_instance(_wi_pool_runtime_id, sizeof(wi_pool_t));
}

wi_pool_t * wi_pool_init(wi_pool_t *pool) {
	return wi_pool_init_with_debug(pool, true);
}

wi_pool_t * wi_pool_init_with_debug(wi_pool_t *pool, wi_boolean_t debug) {
	_wi_pool_add_pool(pool);

	if(wi_pool_debug && debug) {
		pool->locations = wi_dictionary_init_with_capacity_and_callbacks(wi_mutable_dictionary_alloc(),
			200, wi_dictionary_null_key_callbacks, wi_dictionary_default_value_callbacks);
	}

	return pool;
}

static void _wi_pool_dealloc(wi_runtime_instance_t *instance) {
	wi_pool_t		*pool = instance;

	_wi_pool_drain_pool(pool);
	_wi_pool_remove_pool(pool);

	wi_release(pool->context);
	wi_release(pool->locations);
}

#pragma mark -

static void _wi_pool_add_pool(wi_pool_t *pool) {
	wi_thread_t				*thread;
	_wi_pool_stack_t		*stack;

	thread	= wi_thread_current_thread();
	stack	= wi_thread_poolstack(thread);

	if(!stack) {
		stack = wi_malloc(sizeof(_wi_pool_stack_t));
		wi_thread_set_poolstack(thread, stack);
	}

	if(stack->length >= stack->capacity) {
		stack->capacity += stack->capacity;

		if(stack->capacity < _WI_POOL_STACK_INITIAL_SIZE)
			stack->capacity = _WI_POOL_STACK_INITIAL_SIZE;

		stack->pools = wi_realloc(stack->pools, stack->capacity * sizeof(wi_pool_t *));
	}

	stack->pools[stack->length] = pool;
	stack->length++;
}

static wi_pool_t * _wi_pool_pool(void) {
	_wi_pool_stack_t		*stack;

	stack = wi_thread_poolstack(wi_thread_current_thread());

	if(!stack)
		return NULL;

	return stack->pools[stack->length - 1];
}

static void _wi_pool_drain_pool(wi_pool_t *pool) {
	wi_runtime_instance_t		**instances, *instance;
	_wi_pool_array_t			*array, *next_array;
	wi_uinteger_t				i, length;

	for(array = pool->array; array; array = next_array) {
		next_array	= array->next;
		length		= array->length;
		instances	= array->instances;

		for(i = 0; i < length; i++) {
			instance = *instances++;

			if(WI_RUNTIME_BASE(instance)->magic != WI_RUNTIME_MAGIC)
				_wi_pool_invalid_abort(pool, instance);

			wi_release(instance);
		}

		wi_free(array);
	}

	pool->count = 0;
	pool->array = NULL;

	if(pool->locations)
		wi_mutable_dictionary_remove_all_data(pool->locations);
}

static void _wi_pool_remove_pool(wi_pool_t *pool) {
	wi_thread_t				*thread;
	_wi_pool_stack_t		*stack;

	thread	= wi_thread_current_thread();
	stack	= wi_thread_poolstack(thread);

	if(!stack) {
		WI_ASSERT(0, "Orphaned pool in thread %@", thread);

		return;
	}

	if(pool != stack->pools[stack->length - 1]) {
		WI_ASSERT(0, "Removing pool that is not on top of stack in thread %@", thread);

		return;
	}

	stack->pools[stack->length - 1] = NULL;
	stack->length--;

	if(stack->length == 0) {
		if(stack->pools)
			wi_free(stack->pools);

		wi_free(stack);

		wi_thread_set_poolstack(thread, NULL);
	}
}

static void _wi_pool_invalid_abort(wi_pool_t *pool, wi_runtime_instance_t *instance) {
	if(pool->locations) {
		WI_ASSERT(0, "%p is not a valid instance: magic = 0x%x, id = %u, context = %@, autoreleased at %@",
				  instance,
				  WI_RUNTIME_BASE(instance)->magic,
				  WI_RUNTIME_BASE(instance)->id,
				  pool->context,
				  wi_dictionary_data_for_key(pool->locations, instance));
	} else {
		WI_ASSERT(0, "%p is not a valid instance: magic = 0x%x, id = %u, context = %@",
				  instance,
				  WI_RUNTIME_BASE(instance)->magic,
				  WI_RUNTIME_BASE(instance)->id,
				  pool->context);
	}
}

#pragma mark -

void wi_pool_drain(wi_pool_t *pool) {
	_wi_pool_drain_pool(pool);
}

wi_uinteger_t wi_pool_count(wi_pool_t *pool) {
	return pool->count;
}

#pragma mark -

void wi_pool_set_context(wi_pool_t *pool, wi_string_t *context) {
	wi_retain(context);
	wi_release(pool->context);

	pool->context = context;
}

#pragma mark -

wi_runtime_instance_t * _wi_autorelease(wi_runtime_instance_t *instance, const char *file, wi_uinteger_t line) {
	wi_pool_t				*pool;
	wi_mutable_string_t		*location;
	_wi_pool_array_t		*array, *new_array;

	if(!instance)
		return NULL;

	pool = _wi_pool_pool();

	if(!pool) {
		pool = wi_pool_init(wi_pool_alloc());
		WI_ASSERT(0, "Instance %p %@ autoreleased with no pool in place - just leaking", instance, instance);
		wi_release(pool);

		return instance;
	}

	if(!pool->array)
		pool->array = wi_malloc(sizeof(_wi_pool_array_t));

	array = pool->array;

	if(array->length >= _WI_POOL_ARRAY_SIZE) {
		new_array = wi_malloc(sizeof(_wi_pool_array_t));
		new_array->next = array;

		array = new_array;
		pool->array = array;
	}

	array->instances[array->length] = instance;
	array->length++;
	pool->count++;

	if(pool->locations) {
		location = wi_dictionary_data_for_key(pool->locations, instance);

		if(location) {
			wi_mutable_string_append_format(location, WI_STR(", %s:%u"), file, line);
		} else {
			location = wi_string_init_with_format(wi_mutable_string_alloc(), WI_STR("%s:%u"), file, line);
			wi_mutable_dictionary_set_data_for_key(pool->locations, location, instance);
			wi_release(location);
		}
	}

	return instance;
}


text:
'use strict';

describe('Service: fieldService', function () {

  // load the service's module
  beforeEach(module('uixApp'));

  // instantiate service
  var fieldService;
  beforeEach(inject(function (_fieldService_) {
    fieldService = _fieldService_;
  }));

  it('should do something', function () {
    expect(!!fieldService).toBe(true);
  });

});


text:
.. automodule:: insights.parsers.lssap
    :members:
    :show-inheritance:


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*=============================================================================
**
**
**
** Purpose: Container for assemblies.
**
**
=============================================================================*/
namespace System
{
//This class contains only static members and does not need to be serializable
   [AttributeUsage (AttributeTargets.Parameter, Inherited=true, AllowMultiple=false)]
[System.Runtime.InteropServices.ComVisible(true)]
   public sealed class ParamArrayAttribute : Attribute
   {
      public ParamArrayAttribute () {}
   }
}


text:
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
import { catchError, retry } from "rxjs/operators";

import { MetadataSettingsResponse } from "@app-interfaces/metadata";

import { HttpService } from '@app-services/http/http.service';

@Injectable({
  providedIn: 'root'
})
export class SoftwareLibraryService extends HttpService {

  getUploadUrl(): Observable<MetadataSettingsResponse> {
    return this.http.get<MetadataSettingsResponse>(this.apiURL + '/metadata/settings', this.httpOptions)
      .pipe(
        retry(1),
        catchError(this.handleError)
      )
  }
}


text:
class MEDIA_EXPORT AudioOutputStream {
 public:
  // Audio sources must implement AudioSourceCallback. This interface will be
  // called in a random thread which very likely is a high priority thread. Do
  // not rely on using this thread TLS or make calls that alter the thread
  // itself such as creating Windows or initializing COM.
  class MEDIA_EXPORT AudioSourceCallback {
   public:
    virtual ~AudioSourceCallback() {}

    // Provide more data by filling |dest| up to |max_size| bytes. The provided
    // buffer size is determined by the |samples_per_packet| specified in
    // AudioParameters when the stream is created. The source will return
    // the number of bytes it filled. The expected structure of |dest| is
    // platform and format specific.
    // |buffers_state| contains current state of the buffers, and can be used
    // by the source to calculate delay.
    virtual uint32 OnMoreData(
        AudioOutputStream* stream, uint8* dest, uint32 max_size,
        AudioBuffersState buffers_state) = 0;

    // There was an error while playing a buffer. Audio source cannot be
    // destroyed yet. No direct action needed by the AudioStream, but it is
    // a good place to stop accumulating sound data since is is likely that
    // playback will not continue. |code| is an error code that is platform
    // specific.
    virtual void OnError(AudioOutputStream* stream, int code) = 0;

    // Waits till data becomes available. Used when buffering data starting
    // new audio stream.
    // Polling is not the best approach, but incorporating messaging loop
    // with delayed tasks into guts of complex code is even worse, as it is
    // very error-prone. We cannot easily add synchronization, interface is
    // already cut in stone because of need of backward compatibility with
    // plugins. In any case, data is usually immediately available,
    // so there would be no delay.
    virtual void WaitTillDataReady() {}
  };

  virtual ~AudioOutputStream() {}

  // Open the stream. false is returned if the stream cannot be opened.
  virtual bool Open() = 0;

  // Starts playing audio and generating AudioSourceCallback::OnMoreData().
  // Since implementor of AudioOutputStream may have internal buffers, right
  // after calling this method initial buffers are fetched.
  //
  // The output stream does not take ownership of this callback.
  virtual void Start(AudioSourceCallback* callback) = 0;

  // Stops playing audio. Effect might not be instantaneous as the hardware
  // might have locked audio data that is processing.
  virtual void Stop() = 0;

  // Sets the relative volume, with range [0.0, 1.0] inclusive.
  virtual void SetVolume(double volume) = 0;

  // Gets the relative volume, with range [0.0, 1.0] inclusive.
  virtual void GetVolume(double* volume) = 0;

  // Close the stream. This also generates AudioSourceCallback::OnClose().
  // After calling this method, the object should not be used anymore.
  virtual void Close() = 0;
};

// Models an audio sink receiving recorded audio from the audio driver.
class MEDIA_EXPORT AudioInputStream {
 public:
  class MEDIA_EXPORT AudioInputCallback {
   public:
    virtual ~AudioInputCallback() {}

    // Called by the audio recorder when a full packet of audio data is
    // available. This is called from a special audio thread and the
    // implementation should return as soon as possible.
    virtual void OnData(AudioInputStream* stream, const uint8* src,
                        uint32 size, uint32 hardware_delay_bytes,
                        double volume) = 0;

    // The stream is done with this callback, the last call received by this
    // audio sink.
    virtual void OnClose(AudioInputStream* stream) = 0;

    // There was an error while recording audio. The audio sink cannot be
    // destroyed yet. No direct action needed by the AudioInputStream, but it
    // is a good place to stop accumulating sound data since is is likely that
    // recording will not continue. |code| is an error code that is platform
    // specific.
    virtual void OnError(AudioInputStream* stream, int code) = 0;
  };

  virtual ~AudioInputStream() {}

  // Open the stream and prepares it for recording. Call Start() to actually
  // begin recording.
  virtual bool Open() = 0;

  // Starts recording audio and generating AudioInputCallback::OnData().
  // The input stream does not take ownership of this callback.
  virtual void Start(AudioInputCallback* callback) = 0;

  // Stops recording audio. Effect might not be instantaneous as there could be
  // pending audio callbacks in the queue which will be issued first before
  // recording stops.
  virtual void Stop() = 0;

  // Close the stream. This also generates AudioInputCallback::OnClose(). This
  // should be the last call made on this object.
  virtual void Close() = 0;

  // Returns the maximum microphone analog volume or 0.0 if device does not
  // have volume control.
  virtual double GetMaxVolume() = 0;

  // Sets the microphone analog volume, with range [0, max_volume] inclusive.
  virtual void SetVolume(double volume) = 0;

  // Returns the microphone analog volume, with range [0, max_volume] inclusive.
  virtual double GetVolume() = 0;

  // Sets the Automatic Gain Control (AGC) state.
  virtual void SetAutomaticGainControl(bool enabled) = 0;

  // Returns the Automatic Gain Control (AGC) state.
  virtual bool GetAutomaticGainControl() = 0;
};

#endif  // MEDIA_AUDIO_AUDIO_IO_H_


text:
var glob = require('glob'),
    path = require('path'),
    fs = require('fs'),
    uglify = require('uglify-js'),
    CleanCSS = require('clean-css'),
    less = require('less'),
    EventEmitter = require('events').EventEmitter,
    url = require('url'),
    util = require('util'),
    crypto = require('crypto'),
    staticRoot = process.argv[2],
    siteRoot = process.argv[3]; // for resolving css url()'s that start with /

if (!staticRoot) {
  console.log('Usage: node capn-crunch folder');
  process.exit(-1);
}

if (!siteRoot) {
  siteRoot = root;
}

var events = new EventEmitter();

var rootStat = fs.statSync(staticRoot);
if (!(rootStat && rootStat.isDirectory())) {
  console.log(root + " is not a directory");
  process.exit(-1);
}

var filesGlob = "**/*.{less,css,js}";
var exclude = /(\.min\.(css|js)$)|(^_(.+?)\.less$)/;

function processLess(file, source, done) {
  var dirname = path.dirname(file);
  var options = {paths:[dirname], compress:true};
  less.render(source, options, function(e, css) {
    if (e) fileError(file, e);
    css = cacheBreakCss(file, css);
    done(null, css);
  });
}

var cleaner = new CleanCSS();
function processCss(file, source, done) {
  var minCss = cleaner.minify(source);
  minCss = cacheBreakCss(file, minCss);
  done(null, minCss);
}

function getHash(file) {
  var sha = crypto.createHash('sha1');
  sha.setEncoding('hex');
  var contents = fs.readFileSync(file);
  sha.write(contents);
  sha.end();
  return sha.read();
}

var cacheBreakers = {};
function getCacheBreaker(file) {
  if(typeof cacheBreakers[file] === 'undefined') {
    cacheBreakers[file] = getHash(file);
  }

  return cacheBreakers[file];
}

function isSiteLocalImagePath(file) {
  if(/^\/\//.test(file)) {
    return false;
  }
  if(/^http/.test(file)) {
    return false;
  }
  if(/^data:/.test(file)) {
    return false;
  }
  return true;
}

function cacheBreakCss(file, css) {
  return css.replace(/url\((['"]?)(.+?)\1\)/g, function(match, quote, p1) {
    // anything else isn't a file ref on the web site
    if(!isSiteLocalImagePath(p1)) {
      return match;
    }
    // Local or absolute
    var startFrom = file[0] == '/' ? siteRoot : path.dirname(file);
    var urlpath = path.normalize(path.join(startFrom, p1));
    var hash;
    try {
      hash = getCacheBreaker(urlpath);
    } catch (e) {
      fileError(file, 'error cache-breaking rule ' + match + '\n' + e.toString());
    }
    var broken = 'url(' + quote + p1 + '?v=' + hash.substr(0,12) + quote + ')';
    // console.log(' -> broke ' + broken);
    return broken;
  });
}

var compressor = uglify.Compressor({warnings:false});
function processJs(file, source, done) {
  var ast = uglify.parse(source);
  ast.figure_out_scope();
  ast = ast.transform(compressor);
  ast.figure_out_scope();
  ast.compute_char_frequency();
  ast.mangle_names();
  var code = ast.print_to_string();
  done(null, code);
}

var transformers = {
  'less' : {
    name : function (name) { return name.replace(/\.less$/, '.min.css'); },
    code : processLess
  },
  'css'  : {
    name : function (name) { return name.replace(/\.css$/, '.min.css'); },
    code : processCss,
    // Only process if the less file is also not present
    condition: function(name) { return !fs.existsSync(name.replace(/\.css$/, '.less')); }
  },
  'js'   : {
    name : function (name) { return name.replace(/\.js/, '.min.js'); },
    code : processJs
  }
};

function fileError(filename, e) {
  if (e.constructor !== Error) {
    throw new Error('error [' + filename + ']: ' + e);
  }
  throw e;
}

function getExtension(filename) {
  return filename.match(/\.([^\.]+)$/)[1];
}

function getOutputName(filename) {
  return transformers[getExtension(filename)].name(filename);
}

function shouldRead(filename) {
  var check = transformers[getExtension(filename)].condition;
  return !check || check(filename);
}

function readFile(filename) {
  fs.readFile(filename, {encoding:'utf-8'}, function(e, contents) {
    if (e) fileError(filename,e);
    events.emit('file-read', filename, contents);
  });
}

function processFile(filename, contents) {
  var transformer = transformers[getExtension(filename)].code;
  if (!transformer) throw new Error('Unknown file format: ' + filename);
  transformer(filename, contents, function(e, output) {
    if (e) fileError(filename,e);
    events.emit('file-processed', filename, output);
  });
};

function writeOutputFile(filename, output) {
  var outfilename = getOutputName(filename);
  fs.writeFile(outfilename, output, {encoding:'utf-8'}, function(e) {
    if (e) fileError(filename,e);
    events.emit('file-saved', filename, outfilename);
  });
};

function findFiles(root) {
  glob(filesGlob, {cwd:root}, function(e, files) {
    if (e) fileError(filename,e);
    // Convert to abs path
    files = files.map(function(f) { return path.join(root, f); });
    // Global Exclude
    files = files.filter(function(f) { return !exclude.test(path.basename(f)); });
    // Conditial check
    files = files.filter(shouldRead);

    // sort
    var ordering = ['less', 'css', 'js'];
    files.sort(function(a,b) {
      var ax = getExtension(a);
      var bx = getExtension(b);
      return ax != bx
        ? (ordering.indexOf(ax) - ordering.indexOf(bx))
        : a.localeCompare(b);
    });

    events.emit('files-found', files);

    // This essentially processes files sequentially
    // Done this way so that we get output on the console
    // as files are processed.
    //
    // If you don't care about that, the following is probably
    // much simpler:
    //
    //     files.forEach(function(file){ events.emit('file-found', file); });
    //

    var pump = function() {
      if(files.length > 0) {
        var file = files.shift();
        events.emit('file-found', file);
      } else {
        events.removeListener('file-saved', pump);
      }
    };

    events.on('file-saved', pump)
    pump();
  });
};

var processedCount = 0;
var totalToProcess = 0;

events.on('begin', function() { console.time('crunch'); })
      .on('begin', findFiles)
      .on('files-found', function(files) {
        totalToProcess = files.length;
        console.log('found ' + totalToProcess + ' files');
      })
      .on('file-found', readFile)
      .on('file-read', processFile)
      .on('file-processed', writeOutputFile)
      .on('file-saved', function(oldname, newname) {
        console.log('compiled [' + getExtension(oldname) + ']: ' + newname);
        if(++processedCount === totalToProcess)
          events.emit('done');
      })
      .on('done', function() { console.timeEnd('crunch'); })
      .emit('begin', staticRoot);

process.on('uncaughtException', function(e) {
  if(e.stack) {
    console.log(e.stack);
  } else {
    console.log(e);
  }
  process.exit(-1);
});


text:
package server;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Classe Java pour sendMessageResponse complex type.
 *
 *
Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
 *
 *

 * <complexType name="sendMessageResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sendMessageResponse")
public class SendMessageResponse {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.mobeta.android.dslv.DragSortListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:dslv="http://schemas.android.com/apk/res/com.example.PebbleKitExample"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="3dp"
    android:choiceMode="multipleChoice"
    android:dividerHeight="1px"
    android:padding="3dp"
    dslv:click_remove_id="@id/click_remove"
    dslv:collapsed_height="1px"
    dslv:drag_enabled="true"
    dslv:drag_handle_id="@id/drag_handle"
    dslv:drag_scroll_start="0.33"
    dslv:drag_start_mode="onDown"
    dslv:float_alpha="0.6"
    dslv:remove_enabled="true"
    dslv:remove_mode="clickRemove"
    dslv:slide_shuffle_speed="0.3" />


text:
package breeze.stats.distributions

import org.scalatest._;
import org.scalatest.junit._;
import org.scalatest.prop._;
import org.scalacheck._;
import org.junit.runner.RunWith

import breeze.stats.DescriptiveStats._
import org.apache.commons.math3.random.MersenneTwister

@RunWith(classOf[JUnitRunner])
class GeometricTest extends FunSuite with Checkers with MomentsTestBase[Int] with ExpFamTest[Geometric,Int] {
  import Arbitrary.arbitrary

  val expFam = Geometric

  override val numSamples = 10000

  override val VARIANCE_TOLERANCE: Double = 1E-1

  def paramsClose(p: Double, q: Double) = {
     (p - q).abs / (p.abs / 2 + q.abs / 2+ 1)  < 1E-1
  }

  implicit def arbParameter = Arbitrary {
    for(p <- arbitrary[Double].map{m => (math.abs(m) % 1.0) + 1E-3}) yield p
  }

  implicit def arbDistr = Arbitrary {
    for(p <- arbitrary[Double].map{m => (math.abs(m) % 1.0) + 1E-3}) yield new Geometric(p)(RandBasis.mt0)
  }

  def asDouble(x: Int) = x.toDouble
  def fromDouble(x: Double) = x.toInt
}


text:
class StrategiesTest < Test::Unit::TestCase

  def setup
    @c = Cohabit::Configuration.new
  end

  def test_define_strategy
    @c.strategy(:frankel) do
      model_eval do
        puts "do this in the model! hurah."
      end
    end
    assert(@c.strategies.one?)
  end

  def test_define_strategy_with_config
    @c.load do
      strategy :frankel do
        model_eval do
          puts "do this in the model! hurah."
        end
      end
    end
    assert(@c.strategies.one?)
  end

  def test_cant_add_same_named_strategies
    assert_raise(Cohabit::StrategyNameExistsError) do
      @c.load do
        strategy :frankel
        strategy :frankel # eh-uhhh, no can do.
      end
    end
  end

  def test_strategy_inherits_correct_settings
    # strategy block defaults > strategy arg defaults

    # should take on strategy default settings when passed in
    @c.load do
      strategy :frankel, { scope_validations: true }
    end
    assert_equal(true, @c.strategies.first.settings[:scope_validations])

    # should take on strategy default settings when set in block
    # overriding any defaults passed as arguments
    setup
    @c.load do
      strategy :frankel, { scope_validations: "henry cecil" } do
        set :scope_validations, true
      end
    end
    assert_equal(true, @c.strategies.first.settings[:scope_validations])
  end

  def test_nested_strategy
    @c.load do
      strategy :jim
      strategy :frankel, { association: :client } do
        include_strategy :jim
      end
    end
    assert_equal([:jim], @c.find_strategy_by_name(:frankel).strategies)
  end

end


text:
package org.apache.wicket.core.request.handler;

import org.apache.wicket.Component;
import org.apache.wicket.RequestListenerInterface;
import org.apache.wicket.behavior.Behavior;

/**
 * Thrown when a listener invocation is attempted on a component or behavior that does not allow it.
 * For example, somehow the user attempted to invoke link's onclick method on a disabled link.
 *
 * @author igor
 */
public class ListenerInvocationNotAllowedException extends RuntimeException
{
	private static final long serialVersionUID = 1L;

	private final Component component;
	private final Behavior behavior;

	/**
	 * Constructor
	 *
	 * @param iface
	 * @param component
	 * @param behavior
	 * @param message
	 */
	public ListenerInvocationNotAllowedException(RequestListenerInterface iface,
		Component component, Behavior behavior, String message)
	{
		super(message + detail(iface, component, behavior));
		this.component = component;
		this.behavior = behavior;
	}

	private static String detail(RequestListenerInterface iface, Component component,
		Behavior behavior)
	{
		StringBuilder detail = new StringBuilder("Component: ").append(component.toString(false));
		if (behavior != null)
		{
			detail.append(" Behavior: ").append(behavior.toString());
		}
		detail.append(" Listener: ").append(iface.toString());
		return detail.toString();
	}

	/**
	 * @return component that was the target of invocation or hosted the behavior that was
	 */
	public Component getComponent()
	{
		return component;
	}

	/**
	 * @return behavior that was the target of invocation or {@code null}
	 */
	public Behavior getBehavior()
	{
		return behavior;
	}

}


text:
namespace DAVA
{
class SceneFileV2;
class Camera;

class Light : public BaseObject
{
public:
    enum eType
    {
        TYPE_DIRECTIONAL = 0,
        TYPE_SPOT,
        TYPE_POINT,
        TYPE_SKY,
        TYPE_AMBIENT,

        TYPE_COUNT
    };

    enum eFlags
    {
        IS_DYNAMIC = 1 << 0,
        CAST_SHADOW = 1 << 1,
    };

protected:
    virtual ~Light();

public:
    Light();

    virtual BaseObject* Clone(BaseObject* dstNode = NULL);

    void SetType(eType _type);
    void SetAmbientColor(const Color& _color);
    void SetDiffuseColor(const Color& _color);
    void SetIntensity(float32 intensity);

    eType GetType() const;
    const Color& GetAmbientColor() const;
    const Color& GetDiffuseColor() const;
    float32 GetIntensity() const;

    const Vector3& GetPosition() const;
    const Vector3& GetDirection() const;

    void SetPosition(const Vector3& position);
    void SetDirection(const Vector3& direction);

    void SetPositionDirectionFromMatrix(const Matrix4& worldTransform);

    const Vector4& CalculatePositionDirectionBindVector(Camera* camera);

    //virtual void Update(float32 timeElapsed);
    //virtual void Draw();

    virtual void Save(KeyedArchive* archive, SerializationContext* serializationContext);
    virtual void Load(KeyedArchive* archive, SerializationContext* serializationContext);

    bool IsDynamic();
    void SetDynamic(const bool& isDynamic);
    void AddFlag(uint32 flag);
    void RemoveFlag(uint32 flag);
    uint32 GetFlags();

    //void SetRenderSystem

protected:
    uint32 flags;
    Camera* camera;
    uint32 lastUpdatedFrame;
    uint32 type;
    Vector3 position;
    Vector3 direction;
    Vector4 resultPositionDirection;

    Color ambientColor;
    Color diffuseColor;
    float32 intensity;

    DAVA_VIRTUAL_REFLECTION(Light, BaseObject);
};
};


text:
Sign in

    <button aria-label="Close" data-dismiss="modal" class="close" type="button" (click)="activeModal.dismiss('closed')">x
    </button>

                Failed to sign in! Please check your credentials and try again.

            <form class="form" role="form" (ngSubmit)="login()">

                    Login
                    <input type="text" class="form-control" name="username" id="username" placeholder="Your username"
                    [(ngModel)]="username">

                    Password
                    <input type="password" class="form-control" name="password" id="password" placeholder="Your password"
                           [(ngModel)]="password">

                        <input class="form-check-input" type="checkbox" name="rememberMe" id="rememberMe" [(ngModel)]="rememberMe" checked>
                        Remember me

                <button type="submit" class="btn btn-primary">Sign in</button>
            </form>

                Did you forget your password?

                You don't have an account yet?
                Register a new account


text:
    <title>Mark Calculator</title>
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic" rel="stylesheet" type="text/css">
    <link href="../css/creative.min.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">

          Amalnnath Parameswaran

Home

Resume

Projects

Mark Calculator

HTML | CSS | JAVASCRIPT

Weight: <input id="weight1" type="number" min="0" max="100" onchange="">

Mark: <input id="mark1" type="number" min="0" max="100" onchange="computeMark()">

Weight	Mark


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <json-c/json.h>
#include <libudev.h>

#include <argp.h>
#include <error.h>

#include <mraa/uart.h>
#include <mraa/gpio.h>
#include <mraa/i2c.h>
#include <mraa/pwm.h>

#include <mraa_internal.h>

void
imraa_write_lockfile(const char* lock_file_location, const char* serialport)
{
    FILE* fh;
    char str[10];
    json_object* platform1 = json_object_new_object();
    snprintf(str, 10, "%d", MRAA_NULL_PLATFORM);
    json_object_object_add(platform1, "id", json_object_new_string(str));

    json_object* platform2 = json_object_new_object();
    snprintf(str, 10, "%d", MRAA_GENERIC_FIRMATA);
    json_object_object_add(platform2, "id", json_object_new_string(str));
    json_object_object_add(platform2, "uart", json_object_new_string(serialport));

    json_object* platfroms = json_object_new_array();
    json_object_array_add(platfroms, platform1);
    json_object_array_add(platfroms, platform2);
    json_object* lock_file = json_object_new_object();
    json_object_object_add(lock_file, "Platform", platfroms);
    fh = fopen(lock_file_location, "w");
    if (fh != NULL) {
        fputs(json_object_to_json_string_ext(lock_file, JSON_C_TO_STRING_PRETTY), fh);
        fclose(fh);
    } else {
        fprintf(stderr, "can't write to lock file\n");
    }
    json_object_put(lock_file);
}


text:
package docs.home.pubsub;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lightbend.lagom.javadsl.immutable.ImmutableStyle;
import com.lightbend.lagom.serialization.Jsonable;
import org.immutables.value.Value;

@Value.Immutable
@ImmutableStyle
@JsonDeserialize(as = Temperature.class)
public interface AbstractTemperature extends Jsonable {

  @Value.Parameter
  double getValue();

  @Value.Parameter
  TemeratureUnit getUnit();
}


text:
package org.apache.struts.beanaction.httpmap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * Map to wrap session scope attributes.
 *

 *

 *

 * Date: Mar 11, 2004 10:35:42 PM
 *
 * @author Clinton Begin
 */
public class SessionMap extends BaseHttpMap {
  private HttpSession session;

  public SessionMap(HttpServletRequest request) {
    this.session = request.getSession();
  }

  protected Enumeration getNames() {
    return session.getAttributeNames();
  }

  protected Object getValue(Object key) {
    return session.getAttribute(String.valueOf(key));
  }

  protected void putValue(Object key, Object value) {
    session.setAttribute(String.valueOf(key), value);
  }

  protected void removeValue(Object key) {
    session.removeAttribute(String.valueOf(key));
  }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.steps.steps.GroupActivity" >

 	<item android:id="@+id/refresh"
          android:icon="@drawable/ic_action_refresh"
          android:title="@string/refresh"
          android:showAsAction="ifRoom"
          android:onClick="refresh"/>

 	<item
        android:id="@+id/add_task"
        android:orderInCategory="100"
        android:title="@string/add_task"
        android:icon="@drawable/ic_action_new_attachment"
        android:showAsAction="ifRoom"
        android:onClick="addTask" />

    <item
        android:id="@+id/members"
        android:orderInCategory="100"
        android:title="@string/members"
        android:icon="@drawable/ic_action_group"
        android:showAsAction="ifRoom"
        android:onClick="getMembers"/>

    <item
        android:id="@+id/add_member"
        android:orderInCategory="100"
        android:title="@string/add_member"
        android:icon="@drawable/ic_action_add_person"
        android:showAsAction="ifRoom"
        android:onClick="addMember" />

	<item
        android:id="@+id/leave_group"
        android:orderInCategory="100"
        android:title="@string/leave_group"
        android:showAsAction="never"
        android:onClick="leaveGroup" />

</menu>


text:
from __future__ import print_function

import os
import sys
import six
import time
import json
import signal
import shutil
import inspect
import requests
import unittest2 as unittest

from pyspider import run
from pyspider.libs import utils
from tests import data_sample_handler

class TestRun(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        shutil.rmtree('./data/tests', ignore_errors=True)
        os.makedirs('./data/tests')

        import tests.data_test_webpage
        import httpbin
        self.httpbin_thread = utils.run_in_subprocess(httpbin.app.run, port=14887)
        self.httpbin = 'http://127.0.0.1:14887'

    @classmethod
    def tearDownClass(self):
        self.httpbin_thread.terminate()
        self.httpbin_thread.join()

        shutil.rmtree('./data/tests', ignore_errors=True)

    def test_10_cli(self):
        ctx = run.cli.make_context('test', [], None, obj=dict(testing_mode=True))
        ctx = run.cli.invoke(ctx)
        self.assertEqual(ctx.obj.debug, False)
        for db in ('taskdb', 'projectdb', 'resultdb'):
            self.assertIsNotNone(getattr(ctx.obj, db))
        for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher',
                     'fetcher2processor', 'processor2result'):
            self.assertIsNotNone(getattr(ctx.obj, name))
        self.assertEqual(len(ctx.obj.instances), 0)

    def test_20_cli_config(self):
        with open('./data/tests/config.json', 'w') as fp:
            json.dump({
                'debug': True,
                'taskdb': 'mysql+taskdb://localhost:23456/taskdb',
                'amqp-url': 'amqp://guest:guest@localhost:23456/%%2F'
            }, fp)
        ctx = run.cli.make_context('test',
                                   ['--config', './data/tests/config.json'],
                                   None, obj=dict(testing_mode=True))
        ctx = run.cli.invoke(ctx)
        self.assertEqual(ctx.obj.debug, True)

        import mysql.connector
        with self.assertRaises(mysql.connector.InterfaceError):
            ctx.obj.taskdb

        with self.assertRaisesRegexp(Exception, 'Connection refused'):
            ctx.obj.newtask_queue

    def test_30_cli_command_line(self):
        ctx = run.cli.make_context(
            'test',
            ['--projectdb', 'mongodb+projectdb://localhost:23456/projectdb'],
            None,
            obj=dict(testing_mode=True)
        )
        ctx = run.cli.invoke(ctx)

        from pymongo.errors import ConnectionFailure
        with self.assertRaises(ConnectionFailure):
            ctx.obj.projectdb

    def test_40_cli_env(self):
        try:
            os.environ['RESULTDB'] = 'sqlite+resultdb://'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)

            from pyspider.database.sqlite import resultdb
            self.assertIsInstance(ctx.obj.resultdb, resultdb.ResultDB)
        finally:
            del os.environ['RESULTDB']

    @unittest.skipIf(os.environ.get('IGNORE_RABBITMQ'), 'no rabbitmq server for test.')
    def test_50_docker_rabbitmq(self):
        try:
            os.environ['RABBITMQ_NAME'] = 'rabbitmq'
            os.environ['RABBITMQ_PORT_5672_TCP_ADDR'] = 'localhost'
            os.environ['RABBITMQ_PORT_5672_TCP_PORT'] = '5672'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            queue = ctx.obj.newtask_queue
            queue.put('abc')
            queue.delete()
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['RABBITMQ_NAME']
            del os.environ['RABBITMQ_PORT_5672_TCP_ADDR']
            del os.environ['RABBITMQ_PORT_5672_TCP_PORT']

    @unittest.skipIf(os.environ.get('IGNORE_MONGODB'), 'no mongodb server for test.')
    def test_60_docker_mongodb(self):
        try:
            os.environ['MONGODB_NAME'] = 'mongodb'
            os.environ['MONGODB_PORT_27017_TCP_ADDR'] = 'localhost'
            os.environ['MONGODB_PORT_27017_TCP_PORT'] = '27017'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            ctx.obj.resultdb
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['MONGODB_NAME']
            del os.environ['MONGODB_PORT_27017_TCP_ADDR']
            del os.environ['MONGODB_PORT_27017_TCP_PORT']

    @unittest.skipIf(os.environ.get('IGNORE_MYSQL'), 'no mysql server for test.')
    def test_70_docker_mysql(self):
        try:
            os.environ['MYSQL_NAME'] = 'mysql'
            os.environ['MYSQL_PORT_3306_TCP_ADDR'] = 'localhost'
            os.environ['MYSQL_PORT_3306_TCP_PORT'] = '3306'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            ctx.obj.resultdb
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['MYSQL_NAME']
            del os.environ['MYSQL_PORT_3306_TCP_ADDR']
            del os.environ['MYSQL_PORT_3306_TCP_PORT']

    def test_80_docker_phantomjs(self):
        try:
            os.environ['PHANTOMJS_NAME'] = 'phantomjs'
            os.environ['PHANTOMJS_PORT_25555_TCP'] = 'tpc://binux:25678'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            self.assertEqual(ctx.obj.phantomjs_proxy, 'binux:25678')
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['PHANTOMJS_NAME']
            del os.environ['PHANTOMJS_PORT_25555_TCP']

    def test_90_docker_scheduler(self):
        try:
            os.environ['SCHEDULER_NAME'] = 'scheduler'
            os.environ['SCHEDULER_PORT_23333_TCP'] = 'tpc://binux:25678'
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            webui = run.cli.get_command(ctx, 'webui')
            webui_ctx = webui.make_context('webui', [], ctx)
            app = webui.invoke(webui_ctx)
            rpc = app.config['scheduler_rpc']
            self.assertEqual(rpc._ServerProxy__host, 'binux:25678')
        except Exception as e:
            self.assertIsNone(e)
        finally:
            del os.environ['SCHEDULER_NAME']
            del os.environ['SCHEDULER_PORT_23333_TCP']

    def test_a100_all(self):
        import subprocess
        #cmd = [sys.executable]
        cmd = ['coverage', 'run']
        p = subprocess.Popen(cmd+[
            inspect.getsourcefile(run),
            '--taskdb', 'sqlite+taskdb:///data/tests/all_test_task.db',
            '--resultdb', 'sqlite+resultdb:///data/tests/all_test_result.db',
            '--projectdb', 'local+projectdb://'+inspect.getsourcefile(data_sample_handler),
            'all',
        ], close_fds=True, preexec_fn=os.setsid)

        try:
            limit = 30
            while limit >= 0:
                time.sleep(3)
                # click run
                try:
                    requests.post('http://localhost:5000/run', data={
                        'project': 'data_sample_handler',
                    })
                except requests.exceptions.ConnectionError:
                    limit -= 1
                    continue
                break

            limit = 30
            data = requests.get('http://localhost:5000/counter')
            self.assertEqual(data.status_code, 200)
            while data.json().get('data_sample_handler', {}).get('5m', {}).get('success', 0) < 5:
                time.sleep(1)
                data = requests.get('http://localhost:5000/counter')
                limit -= 1
                if limit <= 0:
                    break

            self.assertGreater(limit, 0)
            rv = requests.get('http://localhost:5000/results?project=data_sample_handler')
            self.assertIn('url	', rv.text)
            self.assertIn('class=url', rv.text)
        except:
            raise
        finally:
            time.sleep(1)
            os.killpg(p.pid, signal.SIGTERM)
            p.wait()

    def test_a110_one(self):
        pid, fd = os.forkpty()
        #cmd = [sys.executable]
        cmd = ['coverage', 'run']
        cmd += [
            inspect.getsourcefile(run),
            'one',
            '-i',
            inspect.getsourcefile(data_sample_handler)
        ]

        if pid == 0:
            # child
            os.execvp(cmd[0], cmd)
        else:
            # parent
            def wait_text(timeout=1):
                import select
                text = []
                while True:
                    rl, wl, xl = select.select([fd], [], [], timeout)
                    if not rl:
                        break
                    try:
                        t = os.read(fd, 1024)
                    except OSError:
                        break
                    if not t:
                        break
                    t = utils.text(t)
                    text.append(t)
                    print(t, end='')
                return ''.join(text)

            text = wait_text(3)
            self.assertIn('new task data_sample_handler:on_start', text)
            self.assertIn('pyspider shell', text)

            os.write(fd, utils.utf8('run()\n'))
            text = wait_text()
            self.assertIn('task done data_sample_handler:on_start', text)

            os.write(fd, utils.utf8('crawl("%s/pyspider/test.html")\n' % self.httpbin))
            text = wait_text()
            self.assertIn('/robots.txt', text)

            os.write(fd, utils.utf8('crawl("%s/links/10/0")\n' % self.httpbin))
            text = wait_text()
            if '"title": "Links"' not in text:
                os.write(fd, utils.utf8('crawl("%s/links/10/1")\n' % self.httpbin))
                text = wait_text()
                self.assertIn('"title": "Links"', text)

            os.write(fd, utils.utf8('crawl("%s/404")\n' % self.httpbin))
            text = wait_text()
            self.assertIn('task retry', text)

            os.write(fd, b'quit_pyspider()\n')
            text = wait_text()
            self.assertIn('scheduler exiting...', text)
            os.close(fd)
            os.kill(pid, signal.SIGINT)

class TestSendMessage(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        shutil.rmtree('./data/tests', ignore_errors=True)
        os.makedirs('./data/tests')

        ctx = run.cli.make_context('test', [
            '--taskdb', 'sqlite+taskdb:///data/tests/task.db',
            '--projectdb', 'sqlite+projectdb:///data/tests/projectdb.db',
            '--resultdb', 'sqlite+resultdb:///data/tests/resultdb.db',
        ], None, obj=dict(testing_mode=True))
        self.ctx = run.cli.invoke(ctx)

        ctx = run.scheduler.make_context('scheduler', [], self.ctx)
        scheduler = run.scheduler.invoke(ctx)
        utils.run_in_thread(scheduler.xmlrpc_run)
        utils.run_in_thread(scheduler.run)

        time.sleep(1)

    @classmethod
    def tearDownClass(self):
        for each in self.ctx.obj.instances:
            each.quit()
        time.sleep(1)

        shutil.rmtree('./data/tests', ignore_errors=True)

    def test_10_send_message(self):
        ctx = run.send_message.make_context('send_message', [
            'test_project', 'test_message'
        ], self.ctx)
        self.assertTrue(run.send_message.invoke(ctx))
        while True:
            task = self.ctx.obj.scheduler2fetcher.get(timeout=1)
            if task['url'] == 'data:,on_message':
                break
        self.assertEqual(task['process']['callback'], '_on_message')