text:
package org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto;
import org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties;
import org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DBRetriever implements ArtifactRetriever {

    private static final Log log = LogFactory.getLog(DBRetriever.class);
    protected EventHubConfigurationDto eventHubConfigurationDto = ServiceReferenceHolder.getInstance()
            .getAPIManagerConfigurationService().getAPIManagerConfiguration().getEventHubConfigurationDto();
    protected GatewayArtifactSynchronizerProperties gatewayArtifactSynchronizerProperties =
            ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration()
                    .getGatewayArtifactSynchronizerProperties();
    private String baseURL = eventHubConfigurationDto.getServiceUrl() + APIConstants.INTERNAL_WEB_APP_EP;

    @Override
    public void init() throws ArtifactSynchronizerException {
        //not required
    }

    @Override
    public String retrieveArtifact(String apiId, String gatewayLabel)
            throws ArtifactSynchronizerException {

        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        try {
            Thread.sleep(gatewayArtifactSynchronizerProperties.getEventWaitingTime());
        } catch (InterruptedException e) {
            log.error("Error occurred while waiting to retrieve artifacts from event hub");
        }
        try {
            String encodedGatewayLabel = URLEncoder.encode(gatewayLabel, APIConstants.DigestAuthConstants.CHARSET);
            encodedGatewayLabel = encodedGatewayLabel.replace("\\+", "%20");
            String path = APIConstants.GatewayArtifactSynchronizer.GATEAY_SYNAPSE_ARTIFACTS + "?apiId=" + apiId +
                    "&gatewayLabel=" + encodedGatewayLabel + "&type=Synapse";
            String endpoint = baseURL + path;
            try (CloseableHttpResponse httpResponse = invokeService(endpoint, tenantDomain)) {
                JSONArray jsonArray = retrieveArtifact(httpResponse);
                if (jsonArray != null && jsonArray.length() > 0) {
                    return jsonArray.getString(0);
                }
            }
        } catch (IOException e) {
            String msg = "Error while executing the http client";
            log.error(msg, e);
            throw new ArtifactSynchronizerException(msg, e);
        }
        return null;
    }

    private JSONArray retrieveArtifact(CloseableHttpResponse httpResponse)
            throws IOException, ArtifactSynchronizerException {

        String gatewayRuntimeArtifact;
        if (httpResponse.getStatusLine().getStatusCode() == 404) {
            log.debug("No artifacts available to deploy");
            return new JSONArray();
        } else if (httpResponse.getStatusLine().getStatusCode() == 200) {
            if (httpResponse.getEntity() != null) {
                gatewayRuntimeArtifact = EntityUtils.toString(httpResponse.getEntity(),
                        APIConstants.DigestAuthConstants.CHARSET);
                JSONObject artifactObject = new JSONObject(gatewayRuntimeArtifact);
                return (JSONArray) artifactObject.get("list");
            } else {
                throw new ArtifactSynchronizerException("HTTP response is empty");
            }
        } else {
            String errorMessage = EntityUtils.toString(httpResponse.getEntity(),
                    APIConstants.DigestAuthConstants.CHARSET);
            throw new ArtifactSynchronizerException(errorMessage + "Event-Hub status code is : "
                    + httpResponse.getStatusLine().getStatusCode());
        }
    }

    @Override
    public List<String> retrieveAllArtifacts(String label, String tenantDomain) throws ArtifactSynchronizerException {
        List<String> gatewayRuntimeArtifactsArray = new ArrayList<>();
        try {
            String endcodedgatewayLabel = URLEncoder.encode(label, APIConstants.DigestAuthConstants.CHARSET);
            String path = APIConstants.GatewayArtifactSynchronizer.GATEAY_SYNAPSE_ARTIFACTS
                    + "?gatewayLabel=" + endcodedgatewayLabel + "&type=Synapse";
            String endpoint = baseURL + path;
            try (CloseableHttpResponse httpResponse = invokeService(endpoint,tenantDomain)) {
                JSONArray jsonArray = retrieveArtifact(httpResponse);
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        gatewayRuntimeArtifactsArray.add(jsonArray.getString(i));
                    }
                }

            }
            return gatewayRuntimeArtifactsArray;
        } catch (IOException e) {
            String msg = "Error while executing the http client";
            log.error(msg, e);
            throw new ArtifactSynchronizerException(msg, e);
        }
    }

    @Override
    public Map<String, String> retrieveAttributes(String apiName, String version, String tenantDomain)
            throws ArtifactSynchronizerException {

        CloseableHttpResponse httpResponse = null;
        try {
            String endcodedVersion = URLEncoder.encode(version, APIConstants.DigestAuthConstants.CHARSET);
            String path = APIConstants.GatewayArtifactSynchronizer.SYNAPSE_ATTRIBUTES + "?apiName=" + apiName +
                    "&tenantDomain=" + tenantDomain + "&version=" + endcodedVersion;
            String endpoint = baseURL + path;
            httpResponse = invokeService(endpoint, tenantDomain);
            String responseString;
            if (httpResponse.getEntity() != null) {
                responseString = EntityUtils.toString(httpResponse.getEntity(),
                        APIConstants.DigestAuthConstants.CHARSET);
                httpResponse.close();
            } else {
                throw new ArtifactSynchronizerException("HTTP response is empty");
            }
            Map<String, String> apiAttribute = new HashMap<>();

            JSONObject artifactObject = new JSONObject(responseString);
            String label = null;
            String apiId = null;
            try {
                apiId = (String) artifactObject.get(APIConstants.GatewayArtifactSynchronizer.API_ID);
                String labelsStr = artifactObject.get(APIConstants.GatewayArtifactSynchronizer.LABELS).toString();

                Set<String> labelsSet = new Gson().fromJson(labelsStr, new TypeToken<HashSet<String>>() {
                }.getType());
                Set<String> gatewaySubscribedLabel = gatewayArtifactSynchronizerProperties.getGatewayLabels();
                if (!labelsSet.isEmpty() || !gatewaySubscribedLabel.isEmpty()) {
                    labelsSet.retainAll(gatewaySubscribedLabel);
                    if (!labelsSet.isEmpty()) {
                        label = labelsSet.iterator().next();
                    }
                }
            } catch (ClassCastException e) {
                log.error("Unexpected response received from the storage." + e.getMessage());
            }

            apiAttribute.put(APIConstants.GatewayArtifactSynchronizer.API_ID, apiId);
            apiAttribute.put(APIConstants.GatewayArtifactSynchronizer.LABEL, label);
            return apiAttribute;
        } catch (IOException e) {
            String msg = "Error while executing the http client";
            log.error(msg, e);
            throw new ArtifactSynchronizerException(msg, e);
        }
    }

    private CloseableHttpResponse invokeService(String endpoint,String tenantDomain) throws IOException,
            ArtifactSynchronizerException {

        HttpGet method = new HttpGet(endpoint);
        URL url = new URL(endpoint);
        String username = eventHubConfigurationDto.getUsername();
        String password = eventHubConfigurationDto.getPassword();
        byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password).
                getBytes(APIConstants.DigestAuthConstants.CHARSET));
        int port = url.getPort();
        String protocol = url.getProtocol();
        method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC
                + new String(credentials, APIConstants.DigestAuthConstants.CHARSET));
        if (tenantDomain != null) {
            method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
        }

        HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
        try {
            return APIUtil.executeHTTPRequest(method, httpClient);
        } catch (APIManagementException e) {
            throw new ArtifactSynchronizerException(e);
        }
    }

    @Override
    public void disconnect() {
        //not required
    }

    @Override
    public String getName() {

        return APIConstants.GatewayArtifactSynchronizer.DB_RETRIEVER_NAME;
    }
}


text:
using System.Data.Entity.Migrations;

namespace WebTextEditor.DAL.Sql.Migrations
{
    public partial class Initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Document",
                c => new
                    {
                        Id = c.String(nullable: false, maxLength: 128),
                        Name = c.String(),
                        Text = c.String(),
                        UserId = c.String(maxLength: 128),
                        Created = c.DateTime(nullable: false),
                        Modified = c.DateTime(nullable: false),
                    })
                .PrimaryKey(t => t.Id)
                .Index(t => t.UserId);

        }

        public override void Down()
        {
            DropIndex("dbo.Document", new[] { "UserId" });
            DropTable("dbo.Document");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.openengsb.core.api.model;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * Representation of a unique identification of context instances.
 *
 * A context instance is identified by a String-identifier
 *
 */
@XmlRootElement
public class ContextId {

    public static final String META_KEY_ID = "id";

    private String id;

    public ContextId(String id) {
        this.id = id;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /**
     * returns a map-representation of the ID for use with
     * {@link org.openengsb.core.api.persistence.ConfigPersistenceService}
     */
    public Map<String, String> toMetaData() {
        Map<String, String> metaData = new HashMap<String, String>();
        metaData.put(META_KEY_ID, id);
        return metaData;
    }

    /**
     * parses a ContextId object from a Map-representation used in
     * {@link org.openengsb.core.api.persistence.ConfigPersistenceService}
     */
    public static ContextId fromMetaData(Map<String, String> metaData) {
        return new ContextId(metaData.get(META_KEY_ID));
    }

    @Override
    public String toString() {
        return "Context: " + getId();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + this.id.hashCode();
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() == obj.getClass()) {
            ContextId other = (ContextId) obj;
            return equals(other);
        }
        if (Map.class.isInstance(obj)) {
            Map<?, ?> metadata = (Map<?, ?>) obj;
            return toMetaData().equals(metadata);
        }
        if (obj instanceof String) {
            return toString().equals(obj);
        }
        return false;
    }

    private boolean equals(ContextId other) {
        if (this.id == null && other.id != null) {
            return false;
        }
        if (!this.id.equals(other.id)) {
            return false;
        }
        return true;
    }

    /***
     * An empty map is treated as a wildcard for Context IDs in queries.
     * This means that (where applicable), queries return all contexts in scope when provided with an empty map.
     */
    public static Map<String, String> getContextIdWildCard() {
        return Collections.emptyMap();
    }

}


text:
package controllers

import (
	"code.google.com/p/go.crypto/bcrypt"
	"github.com/jgraham909/revmgo"
	"github.com/revel/revel"
	"labix.org/v2/mgo/bson"
)

type Admin struct {
	*revel.Controller
	revmgo.MongoController
}

func (c Admin) Index() revel.Result {
	return c.Render()
}

func (c Admin) Password() revel.Result {
	return c.Render()
}

func (c Admin) UpdatePassword(password, verify string) revel.Result {
	var isSuccess bool
	isPost := true

	if password == verify {

		hashedPass, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
		info, err := c.MongoSession.DB("gocasts").C("id").Upsert(bson.M{"email": "admin@gocasts.net"}, bson.M{"$set": bson.M{"password": hashedPass, "email": "admin@gocasts.net"}})

		if err == nil {
			if info.Updated >= 0 {
				isSuccess = true
			}
		}
	} else {
		isSuccess = false
	}
	c.RenderArgs["isPost"] = isPost
	c.RenderArgs["isSuccess"] = isSuccess

	return c.RenderTemplate("admin/Password.html")
}


text:
package com.orange.opengl.util;

import java.nio.ByteBuffer;

import com.orange.util.debug.Debug;
import com.orange.util.system.SystemUtils;

import android.os.Build;

/**
 * (c) OrangeGame 2012
 *
 * @author OrangeGame <OGEngine@orangegame.cn>
 * @see http://code.google.com/p/android/issues/detail?id=11078
 * @see http://code.google.com/p/android/issues/detail?id=16941
 */
public class BufferUtils {
	// ===========================================================
	// Constants
	// ===========================================================

	private static final boolean NATIVE_LIB_LOADED;

	/** Android issue 16941. */
	private static final boolean WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY;
	/** Android issue 16941. */
	private static final boolean WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT;

	static {
		boolean loadLibrarySuccess;
		try {
			System.loadLibrary("andengine");
			loadLibrarySuccess = true;
		} catch (final UnsatisfiedLinkError pUnsatisfiedLinkError) {
			loadLibrarySuccess = false;
		}
		NATIVE_LIB_LOADED = loadLibrarySuccess;

		if(BufferUtils.NATIVE_LIB_LOADED) {
			if(SystemUtils.isAndroidVersion(Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR2)) {
				WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT = true;
			} else {
				WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT = false;
			}

			if(SystemUtils.isAndroidVersionOrLower(Build.VERSION_CODES.FROYO)) {
				WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY = true;
			} else {
				WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY = false;
			}
		} else {
			WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT = false;
			if(SystemUtils.isAndroidVersion(Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR2)) {
				Debug.w("Creating a " + ByteBuffer.class.getSimpleName() + " will actually allocate 4x the memory than requested!");
			}

			WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY = false;
		}
	}

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	/**
	 * @param pCapacity the capacity of the returned {@link ByteBuffer} in bytes.
	 * @return
	 */
	public static ByteBuffer allocateDirectByteBuffer(final int pCapacity) {
		if(BufferUtils.WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT) {
			return BufferUtils.jniAllocateDirect(pCapacity);
		} else {
			return ByteBuffer.allocateDirect(pCapacity);
		}
	}

	public static void freeDirectByteBuffer(final ByteBuffer pByteBuffer) {
		if(BufferUtils.WORKAROUND_BYTEBUFFER_ALLOCATE_DIRECT) {
			BufferUtils.jniFreeDirect(pByteBuffer);
		}
	}

	private native static ByteBuffer jniAllocateDirect(final int pCapacity);
	private native static void jniFreeDirect(final ByteBuffer pByteBuffer);

	/**
	 * @param pByteBuffer must be a direct Buffer.
	 * @param pSource
	 * @param pLength to copy in pSource.
	 * @param pOffset in pSource.
	 */
	public static void put(final ByteBuffer pByteBuffer, final float[] pSource, final int pLength, final int pOffset) {
		if(BufferUtils.WORKAROUND_BYTEBUFFER_PUT_FLOATARRAY) {
			BufferUtils.jniPut(pByteBuffer, pSource, pLength, pOffset);
		} else {
			for(int i = pOffset; i < (pOffset + pLength); i++) {
				pByteBuffer.putFloat(pSource[i]);
			}
		}
		pByteBuffer.position(0);
		pByteBuffer.limit(pLength << 2);
	}

	private native static void jniPut(final ByteBuffer pByteBuffer, final float[] pSource, final int pLength, final int pOffset);

	public static short getUnsignedByte(final ByteBuffer pByteBuffer) {
		return (short) (pByteBuffer.get() & 0xFF);
	}

	public static void putUnsignedByte(final ByteBuffer pByteBuffer, final int pValue) {
		pByteBuffer.put((byte) (pValue & 0xFF));
	}

	public static short getUnsignedByte(final ByteBuffer pByteBuffer, final int pPosition) {
		return (short) (pByteBuffer.get(pPosition) & (short) 0xFF);
	}

	public static void putUnsignedByte(final ByteBuffer pByteBuffer, final int pPosition, final int pValue) {
		pByteBuffer.put(pPosition, (byte) (pValue & 0xFF));
	}

	public static int getUnsignedShort(final ByteBuffer pByteBuffer) {
		return pByteBuffer.getShort() & 0xFFFF;
	}

	public static void putUnsignedShort(final ByteBuffer pByteBuffer, final int pValue) {
		pByteBuffer.putShort((short) (pValue & 0xFFFF));
	}

	public static int getUnsignedShort(final ByteBuffer pByteBuffer, final int pPosition) {
		return pByteBuffer.getShort(pPosition) & 0xFFFF;
	}

	public static void putUnsignedShort(final ByteBuffer pByteBuffer, final int pPosition, final int pValue) {
		pByteBuffer.putShort(pPosition, (short) (pValue & 0xFFFF));
	}

	public static long getUnsignedInt(final ByteBuffer pByteBuffer) {
		return pByteBuffer.getInt() & 0xFFFFFFFFL;
	}

	public static void putUnsignedInt(final ByteBuffer pByteBuffer, final long pValue) {
		pByteBuffer.putInt((int) (pValue & 0xFFFFFFFFL));
	}

	public static long getUnsignedInt(final ByteBuffer pByteBuffer, final int pPosition) {
		return pByteBuffer.getInt(pPosition) & 0xFFFFFFFFL;
	}

	public static void putUnsignedInt(final ByteBuffer pByteBuffer, final int pPosition, final long pValue) {
		pByteBuffer.putInt(pPosition, (short) (pValue & 0xFFFFFFFFL));
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>itobot ~ respect for Mr.Ito~</title>
<meta charset="utf-8">
<meta name="description" content="I am Ito!hoooo!!">
<meta name="author" content="ito">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="">
<?php echo $css ?>

    <?php //echo $js ?>


text:
'''This module provides random data generation and database population.

   When this module is run directly for purposes of database population, the default is
   to use a fixed seed for randomization. The result should be that the generated random
   data is the same regardless of when or where the execution is done.

'''

from datetime import datetime, timedelta
from decimal import Decimal as PyDecimal
from logging import basicConfig, getLogger
from random import choice, randint, random, seed, uniform

from tests.comparison.db_connector import (
    DbConnector,
    HIVE,
    IMPALA,
    MYSQL,
    ORACLE,
    POSTGRESQL)
from tests.comparison.common import Column, Table
from tests.comparison.types import (
    Boolean,
    Char,
    Decimal,
    EXACT_TYPES,
    Float,
    get_char_class,
    get_decimal_class,
    get_varchar_class,
    Int,
    String,
    Timestamp,
    TYPES,
    VarChar)

LOG = getLogger(__name__)

class RandomValGenerator(object):
  '''This class will generate random data of various data types.'''

  def __init__(self,
      min_number=-1000,
      max_number=1000,
      min_date=datetime(1990, 1, 1),
      max_date=datetime(2030, 1, 1),
      null_val_percentage=0.1,
      max_decimal_fractional_digits=2):
    if type(min_number) != int or type(max_number) != int:
      raise Exception("min_number and max_number must be integers but were %s and %s"
          % (type(min_number), type(max_number)))
    self.min_number = min_number
    self.max_number = max_number
    self.min_date = min_date
    self.max_date = max_date
    self.null_val_percentage = null_val_percentage
    self.max_decimal_fractional_digits = max_decimal_fractional_digits

  def generate_val(self, val_type):
    '''Generate and return a single random val. Use the val_type parameter to
       specify the type of val to generate. See types.py for valid val_type
       options.

       Ex:
         generator = RandomValGenerator(min_number=1, max_number=5)
         val = generator.generate_val(model.Int)
         assert 1 <= val and val <= 5
    '''
    if issubclass(val_type, Char):
      val = self.generate_val(Int)
      return None if val is None else str(val)[:val_type.MAX]
    if random() < self.null_val_percentage:
      return None
    if issubclass(val_type, Int):
      return randint(
          max(self.min_number, val_type.MIN), min(val_type.MAX, self.max_number))
    if issubclass(val_type, Decimal):
      # Create an int within the maximum length of the Decimal, then shift the decimal
      # point as needed.
      if val_type.MAX_FRACTIONAL_DIGITS > self.max_decimal_fractional_digits:
        max_digits = val_type.MAX_DIGITS \
            - (val_type.MAX_FRACTIONAL_DIGITS - self.max_decimal_fractional_digits)
        fractal_digits = self.max_decimal_fractional_digits
      else:
        max_digits = val_type.MAX_DIGITS
        fractal_digits = val_type.MAX_FRACTIONAL_DIGITS
      max_type_val = 10 ** max_digits
      decimal_point_shift = 10 ** fractal_digits
      max_val = min(self.max_number * decimal_point_shift, max_type_val)
      min_val = max(self.min_number * decimal_point_shift, -1 * max_type_val)
      return PyDecimal(randint(min_val + 1, max_val - 1)) / decimal_point_shift
    if issubclass(val_type, Float):
      return uniform(self.min_number, self.max_number)
    if issubclass(val_type, Timestamp):
      delta = self.max_date - self.min_date
      delta_in_seconds = delta.days * 24 * 60 * 60 + delta.seconds
      offset_in_seconds = randint(0, delta_in_seconds)
      val = self.min_date + timedelta(0, offset_in_seconds)
      return datetime(val.year, val.month, val.day)
    if issubclass(val_type, Boolean):
      return randint(0, 1) == 1
    raise Exception('Unsupported type %s' % val_type.__name__)

class DatabasePopulator(object):
  '''This class will populate a database with randomly generated data. The population
     includes table creation and data generation. Table names are hard coded as
     table_<table number>.

  '''

  def __init__(self):
    self.val_generator = RandomValGenerator()

  def populate_db_with_random_data(self,
      db_name,
      db_connectors,
      min_number_of_tables,
      max_number_of_tables,
      min_number_of_cols,
      max_number_of_cols,
      min_number_of_rows,
      max_number_of_rows,
      allowed_storage_formats,
      create_files):
    '''Create tables with a random number of cols.

       The given db_name must have already been created.
    '''
    connections = list()
    hive_connection = None
    for connector in db_connectors:
      connection = connector.create_connection(db_name=db_name)
      connections.append(connection)
      if connector.db_type == IMPALA:
        # The Impala table creator needs help from Hive for some storage formats.
        # Eventually Impala should be able to write in all formats and this can be
        # removed.
        hive_connection = DbConnector(HIVE).create_connection(db_name=db_name)
        connection.hive_connection = hive_connection
    for table_idx in xrange(randint(min_number_of_tables, max_number_of_tables)):
      table = self.create_random_table(
          'table_%s' % (table_idx + 1),
          min_number_of_cols,
          max_number_of_cols,
          allowed_storage_formats)

      for connection in connections:
        connection.bulk_load_data_file = open(
            "/tmp/%s_%s.data" % (table.name, connection.db_type.lower()), "w")
        connection.begin_bulk_load_table(table)

      row_count = randint(min_number_of_rows, max_number_of_rows)
      LOG.info('Inserting %s rows into %s', row_count, table.name)
      while row_count:
        batch_size = min(1000, row_count)
        rows = self.generate_table_data(table, number_of_rows=batch_size)
        row_count -= batch_size
        for connection in connections:
          connection.handle_bulk_load_table_data(rows)

      for connection in connections:
        connection.end_bulk_load_table()

    self.index_tables_in_database(connections)

    for connection in connections:
      connection.close()
    if hive_connection:
      hive_connection.close()

  def migrate_database(self,
      db_name,
      source_db_connector,
      destination_db_connectors,
      include_table_names=None):
    '''Read table metadata and data from the source database and create a replica in
       the destination databases. For example, the Impala functional test database could
       be copied into Postgresql.

       source_db_connector and items in destination_db_connectors should be
       of type db_connector.DbConnector. destination_db_connectors and
       include_table_names should be iterables.
    '''
    source_connection = source_db_connector.create_connection(db_name)

    cursors = [connector.create_connection(db_name=db_name).create_cursor()
               for connector in destination_db_connectors]

    for table_name in source_connection.list_table_names():
      if include_table_names and table_name not in include_table_names:
        continue
      try:
        table = source_connection.describe_table(table_name)
      except Exception as e:
        LOG.warn('Error fetching metadata for %s: %s', table_name, e)
        continue
      for destination_cursor in cursors:
        sql = destination_cursor.connection.make_create_table_sql(table)
        destination_cursor.execute(sql)
      with source_connection.open_cursor() as source_cursor:
        try:
          source_cursor.execute('SELECT * FROM ' + table_name)
          while True:
            rows = source_cursor.fetchmany(size=100)
            if not rows:
              break
            for destination_cursor in cursors:
              sql = destination_cursor.connection.make_insert_sql_from_data(table, rows)
              destination_cursor.execute(sql)
        except Exception as e:
          LOG.error('Error fetching data for %s: %s', table_name, e)
          continue

    self.index_tables_in_database([cursor.connection for cursor in cursors])

    for cursor in cursors:
      cursor.close()
      cursor.connection.close()

  def create_random_table(self,
      table_name,
      min_number_of_cols,
      max_number_of_cols,
      allowed_storage_formats):
    '''Create and return a Table with a random number of cols.'''
    col_count = randint(min_number_of_cols, max_number_of_cols)
    storage_format = choice(allowed_storage_formats)
    table = Table(table_name)
    table.storage_format = storage_format
    for col_idx in xrange(col_count):
      col_type = choice(TYPES)
      col_type = choice(filter(lambda type_: issubclass(type_, col_type), EXACT_TYPES))
      if issubclass(col_type, VarChar) and not issubclass(col_type, String):
        col_type = get_varchar_class(randint(1, VarChar.MAX))
      elif issubclass(col_type, Char) and not issubclass(col_type, String):
        col_type = get_char_class(randint(1, Char.MAX))
      elif issubclass(col_type, Decimal):
        max_digits = randint(1, Decimal.MAX_DIGITS)
        col_type = get_decimal_class(max_digits, randint(1, max_digits))
      col = Column(
          table,
          '%s_col_%s' % (col_type.__name__.lower(), col_idx + 1),
          col_type)
      table.cols.append(col)
    return table

  def generate_table_data(self, table, number_of_rows=100):
      rows = list()
      for row_idx in xrange(number_of_rows):
        row = list()
        for col in table.cols:
          row.append(self.val_generator.generate_val(col.exact_type))
        rows.append(row)
      return rows

  def drop_and_create_database(self, db_name, db_connectors):
    for connector in db_connectors:
      with connector.open_connection() as connection:
        connection.drop_db_if_exists(db_name)
        connection.create_database(db_name)

  def index_tables_in_database(self, connections):
    for connection in connections:
      if connection.supports_index_creation:
        for table_name in connection.list_table_names():
          LOG.info('Indexing %s on %s' % (table_name, connection.db_type))
          connection.index_table(table_name)

if __name__ == '__main__':
  import logging
  from optparse import NO_DEFAULT, OptionGroup, OptionParser

  import tests.comparison.cli_options as cli_options

  parser = OptionParser(
      usage='usage: \n'
            '  %prog [options] [populate]\n\n'
            '     Create and populate database(s). The Impala database will always be \n'
            '     included, the other database types are optional.\n\n'
            '  %prog [options] migrate\n\n'
            '     Migrate an Impala database to another database type. The destination \n'
            '     database will be dropped and recreated.')
  cli_options.add_logging_options(parser)
  cli_options.add_db_name_option(parser)
  cli_options.add_connection_option_groups(parser)

  group = OptionGroup(parser, 'Database Population Options')
  group.add_option('--randomization-seed', default=1, type='int',
      help='The randomization will be initialized with this seed. Using the same seed '
          'will produce the same results across runs.')
  storage_formats = ['avro', 'parquet', 'rcfile', 'sequencefile', 'textfile']
  group.add_option('--storage-file-formats', default=','.join(storage_formats),
      help='A comma separated list of storage formats to choose from.')
  group.add_option('--create-data-files', default=False, action='store_true',
      help='Create files that can be used to repopulate the databases elsewhere.')
  group.add_option('--min-table-count', default=10, type='int',
      help='The minimum number of tables to generate.')
  group.add_option('--max-table-count', default=100, type='int',
      help='The maximum number of tables to generate.')
  group.add_option('--min-column-count', default=10, type='int',
      help='The minimum number of columns to generate per table.')
  group.add_option('--max-column-count', default=100, type='int',
      help='The maximum number of columns to generate per table.')
  group.add_option('--min-row-count', default=(10 ** 3), type='int',
      help='The minimum number of rows to generate per table.')
  group.add_option('--max-row-count', default=(10 ** 6), type='int',
      help='The maximum number of rows to generate per table.')
  parser.add_option_group(group)

  group = OptionGroup(parser, 'Database Migration Options')
  group.add_option('--migrate-table-names',
      help='Table names should be separated with commas. The default is to migrate all '
          'tables.')
  parser.add_option_group(group)

  for group in parser.option_groups + [parser]:
    for option in group.option_list:
      if option.default != NO_DEFAULT:
        option.help += ' [default: %default]'

  options, args = parser.parse_args()
  command = args[0] if args else 'populate'
  if len(args) > 1 or command not in ['populate', 'migrate']:
    raise Exception('Command must either be "populate" or "migrate" but was "%s"' %
        ' '.join(args))
  if command == 'migrate' and \
      not any((options.use_mysql, options.use_postgresql, options.use_oracle)):
    raise Exception('At least one destination database must be chosen with '
          '--use-<database type>')

  basicConfig(level=getattr(logging, options.log_level))

  seed(options.randomization_seed)

  impala_connector = DbConnector(IMPALA)
  db_connectors = []
  if options.use_postgresql:
    db_connectors.append(DbConnector(POSTGRESQL,
      user_name=options.postgresql_user,
      password=options.postgresql_password,
      host_name=options.postgresql_host,
      port=options.postgresql_port))
  if options.use_oracle:
    db_connectors.append(DbConnector(ORACLE,
      user_name=options.oracle_user,
      password=options.oracle_password,
      host_name=options.oracle_host,
      port=options.oracle_port))
  if options.use_mysql:
    db_connectors.append(DbConnector(MYSQL,
      user_name=options.mysql_user,
      password=options.mysql_password,
      host_name=options.mysql_host,
      port=options.mysql_port))

  populator = DatabasePopulator()
  if command == 'populate':
    db_connectors.append(impala_connector)
    populator.drop_and_create_database(options.db_name, db_connectors)
    populator.populate_db_with_random_data(
        options.db_name,
        db_connectors,
        options.min_table_count,
        options.max_table_count,
        options.min_column_count,
        options.max_column_count,
        options.min_row_count,
        options.max_row_count,
        options.storage_file_formats.split(','),
        options.create_data_files)
  else:
    populator.drop_and_create_database(options.db_name, db_connectors)
    if options.migrate_table_names:
      table_names = options.migrate_table_names.split(',')
    else:
      table_names = None
    populator.migrate_database(
        options.db_name,
        impala_connector,
        db_connectors,
        include_table_names=table_names)


text:
package controllers

import helpers.{TestWithApplication, UnitSpec}
import helpers.changekeeper.CookieFactoryForUnitSpecs
import models.CompleteAndConfirmFormModel.AllowGoingToCompleteAndConfirmPageCacheKey
import models.DateOfSaleFormModel
import models.DateOfSaleFormModel.DateOfSaleCacheKey
import models.DateOfSaleFormModel.Form.{DateOfSaleId, MileageId}
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, LocalDate}
import pages.changekeeper.DateOfSalePage.{DayDateOfSaleValid, MileageValid, MonthDateOfSaleValid, YearDateOfSaleValid, ValidDateOfSale}
import pages.changekeeper.{CompleteAndConfirmPage, NewKeeperChooseYourAddressPage, NewKeeperEnterAddressManuallyPage}
import play.api.test.FakeRequest
import play.api.test.Helpers.{BAD_REQUEST, LOCATION, contentAsString, defaultAwaitTimeout}
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.CookieImplicits.RichCookies
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.{ClearTextClientSideSessionFactory, NoCookieFlags}
import uk.gov.dvla.vehicles.presentation.common.mappings.Date.{DayId, MonthId, YearId}
import uk.gov.dvla.vehicles.presentation.common.testhelpers.CookieHelper

class DateOfSaleUnitSpec extends UnitSpec {
  implicit private final val sessionFactory = new ClearTextClientSideSessionFactory()(new NoCookieFlags)

  "submit" should {
    "replace numeric mileage error message for with standard error message" in new TestWithApplication {
      val request = buildCorrectlyPopulatedRequest(mileage = "$$")
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.privateKeeperDetailsModel())

      val result = dateOfSale.submitWithDateCheck(request)
      val replacementMileageErrorMessage = "You must enter a valid mileage between 0 and 999999"
      replacementMileageErrorMessage.r.findAllIn(contentAsString(result)).length should equal(2)
    }

    "return a bad request if date of sale is not entered" in new TestWithApplication {
      val request = buildCorrectlyPopulatedRequest(dayDateOfSale = "", monthDateOfSale = "", yearDateOfSale = "")
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel())

      val result = dateOfSale.submitWithDateCheck(request)
      whenReady(result) { r =>
        r.header.status should equal(BAD_REQUEST)
      }
    }

    "redirect to next page when mandatory fields are complete for new keeper " +
      "and neither the date of disposal or the change date are present" in new TestWithApplication {
      val request = buildCorrectlyPopulatedRequest()
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitWithDateCheck(request)
      whenReady(result) { r =>
        r.header.headers.get(LOCATION) should equal(Some(CompleteAndConfirmPage.address))

        CookieHelper.fetchCookiesFromHeaders(r).getModel[DateOfSaleFormModel] shouldEqual
          Some(DateOfSaleFormModel(
            Some(MileageValid.toInt),
            new LocalDate(YearDateOfSaleValid.toInt, MonthDateOfSaleValid.toInt, DayDateOfSaleValid.toInt)
          ))

        CookieHelper.fetchCookiesFromHeaders(r).find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) orElse
          fail(s"Did not add cookie for th: $DateOfSaleCacheKey ")
      }
    }

    "not go to the next page when the date of sale is before the date of disposal " +
      "and return a bad request" in new TestWithApplication {
      val disposalDate = ValidDateOfSale.plusDays(1)

      val request = buildCorrectlyPopulatedRequest()
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel(keeperEndDate = Some(disposalDate)))
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitWithDateCheck(request)
      whenReady(result) { r =>
        r.header.status should equal(BAD_REQUEST)
        val resultCookies = CookieHelper.fetchCookiesFromHeaders(r)
        resultCookies.getModel[DateOfSaleFormModel] shouldEqual None
        resultCookies.find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) shouldEqual None
      }
    }

    "not go to the next page when the date of sale is before the keeper change date " +
      "and return a bad request" in new TestWithApplication {
      val changeKeeperDate = ValidDateOfSale.plusDays(1)

      val request = buildCorrectlyPopulatedRequest()
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel(keeperChangeDate = Some(changeKeeperDate)))
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitWithDateCheck(request)
      whenReady(result) { r =>
        r.header.status should equal(BAD_REQUEST)
        val resultCookies = CookieHelper.fetchCookiesFromHeaders(r)
        resultCookies.getModel[DateOfSaleFormModel] shouldEqual None
        resultCookies.find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) shouldEqual None
      }
    }

    "not go to the next page when the date of sale is over 12 months" in new TestWithApplication {
      val invalidDateOfSale = ValidDateOfSale.minusYears(1)

      val request = buildCorrectlyPopulatedRequest(
        dayDateOfSale = invalidDateOfSale.toString("dd"),
        monthDateOfSale = invalidDateOfSale.toString("MM"),
        yearDateOfSale = invalidDateOfSale.getYear.toString
      )
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitWithDateCheck(request)
      whenReady(result) { r =>
        r.header.status should equal(BAD_REQUEST)
        val resultCookies = CookieHelper.fetchCookiesFromHeaders(r)
        resultCookies.getModel[DateOfSaleFormModel] shouldEqual None
        resultCookies.find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) shouldEqual None
      }
    }

    "go to the next page when the date of sale is the same as the date of disposal" in new TestWithApplication {
      val disposalDate = ValidDateOfSale

      val request = buildCorrectlyPopulatedRequest()
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel(keeperEndDate = Some(disposalDate)))
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitWithDateCheck(request)
      whenReady(result) { r =>
        r.header.headers.get(LOCATION) should equal(Some(CompleteAndConfirmPage.address))
        val resultCookies = CookieHelper.fetchCookiesFromHeaders(r)
        resultCookies.getModel[DateOfSaleFormModel] shouldEqual
          Some(DateOfSaleFormModel(
            Some(MileageValid.toInt),
            new LocalDate(YearDateOfSaleValid.toInt, MonthDateOfSaleValid.toInt, DayDateOfSaleValid.toInt)
          ))

        resultCookies.find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) orElse
          fail(s"Did not add cookie for th: $DateOfSaleCacheKey ")
      }
    }

    "go to the next page when the date of sale is the same as the keeper change date" in new TestWithApplication {
      //    The date of sale is 19-10-${saleYear}
      val changeDate = ValidDateOfSale

      val request = buildCorrectlyPopulatedRequest()
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel(keeperChangeDate = Some(changeDate)))
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitNoDateCheck(request)
      whenReady(result) { r =>
        r.header.headers.get(LOCATION) should equal(Some(CompleteAndConfirmPage.address))

        val resultCookies = CookieHelper.fetchCookiesFromHeaders(r)
        resultCookies.getModel[DateOfSaleFormModel] shouldEqual
          Some(DateOfSaleFormModel(
            Some(MileageValid.toInt),
            new LocalDate(YearDateOfSaleValid.toInt, MonthDateOfSaleValid.toInt, DayDateOfSaleValid.toInt)
          ))

        resultCookies.find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) orElse
          fail(s"Did not add cookie for th: $DateOfSaleCacheKey ")
      }
    }

    "call the micro service when both the date of disposal and the change date are present " +
      "and redirect to the next page" in new TestWithApplication {
      val disposalDate = ValidDateOfSale
      val changeDate = ValidDateOfSale

      val request = buildCorrectlyPopulatedRequest()
        .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleLookupFormModel())
        .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel(
          keeperEndDate = Some(disposalDate),
          keeperChangeDate = Some(changeDate)
        ))
        .withCookies(CookieFactoryForUnitSpecs.sellerEmailModel())

      val result = dateOfSale.submitNoDateCheck(request)
      whenReady(result) { r =>
        r.header.headers.get(LOCATION) should equal(Some(CompleteAndConfirmPage.address))

        CookieHelper.fetchCookiesFromHeaders(r).getModel[DateOfSaleFormModel] shouldEqual
          Some(DateOfSaleFormModel(
            Some(MileageValid.toInt),
            new LocalDate(YearDateOfSaleValid.toInt, MonthDateOfSaleValid.toInt, DayDateOfSaleValid.toInt)
          ))

        CookieHelper.fetchCookiesFromHeaders(r).find(_.name == AllowGoingToCompleteAndConfirmPageCacheKey) orElse
          fail(s"Did not add cookie for th: $DateOfSaleCacheKey ")
      }
    }
  }

  "back" should {
    "go back to the NewKeeperEnterAddressManually if manual input was chosen" in new TestWithApplication {
      val request = FakeRequest().withCookies(CookieFactoryForUnitSpecs.newKeeperEnterAddressManually())
      val result = dateOfSale.back(request)
      whenReady(result) { r =>
        r.header.headers.get(LOCATION) should equal(Some(NewKeeperEnterAddressManuallyPage.address))
      }
    }

    "go back to the NewKeeperEnterAddress if no manual input was chosen" in new TestWithApplication {
      val request = FakeRequest()
      val result = dateOfSale.back(request)
      whenReady(result) { r =>
        r.header.headers.get(LOCATION) should equal(Some(NewKeeperChooseYourAddressPage.address))
      }
    }
  }

  private def buildCorrectlyPopulatedRequest(mileage: String = MileageValid,
                                              dayDateOfSale: String = DayDateOfSaleValid,
                                              monthDateOfSale: String = MonthDateOfSaleValid,
                                              yearDateOfSale: String = YearDateOfSaleValid) = {
    FakeRequest().withFormUrlEncodedBody(
      MileageId -> mileage,
      s"$DateOfSaleId.$DayId" -> dayDateOfSale,
      s"$DateOfSaleId.$MonthId" -> monthDateOfSale,
      s"$DateOfSaleId.$YearId" -> yearDateOfSale
    ).withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
     .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel())
  }

  private def dateOfSale = injector.getInstance(classOf[DateOfSale])

  private lazy val present =
    dateOfSale.present(FakeRequest()
      .withCookies(CookieFactoryForUnitSpecs.newKeeperDetailsModel())
      .withCookies(CookieFactoryForUnitSpecs.vehicleAndKeeperDetailsModel())
    )
}


text:
package info.ganglia.jmxetric;

/**
 * MXBean definition used for testing
 * @author humphrej
 *
 */
public interface TestExampleMXBean {

	final int INT_VALUE=1234 ;
	final long LONG_VALUE=43210L ;
	final double DOUBLE_VALUE=123.45D ;
	final float FLOAT_VALUE=543.21F ;
	final String STRING_VALUE="STRING" ;

	int getInt() ;
	long getLong() ;
	String getString() ;
	double getDouble() ;
	float getFloat() ;
	ExampleComposite getComposite();
	int getCounter() ;
}


text:
package org.gradschoolsearch.db

import org.gradschoolsearch.db.Tables._

import scala.slick.driver.MySQLDriver.simple._
import scala.slick.jdbc.JdbcBackend.Database.dynamicSession

/*class DbUtil {
  val db:Database

  def getUserFromId(email: String) = {
    db withDynSession {
      val userOpt = users.filter(_.email === email).firstOption
    }
  }
}*/


text:
/******************************************************************************
 *
 * HelloMantis.c
 * Author: Andrew Ferg
 *
 * Sample code that connects to a V2 system that manages an unknown number
 * of Mantis camera systems.
 *
 *****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mantis/MantisAPI.h"

/**
 * \brief Function that handles new ACOS_CAMERA objects
 **/
void newCameraCallback(ACOS_CAMERA cam, void* data)
{
    static int cameraCounter = 0;
    ACOS_CAMERA* camList = (ACOS_CAMERA*) data;
    camList[cameraCounter++] = cam;
}

/**
 * \brief prints the command line options
 **/
void printHelp()
{
   printf("HelloMantis Demo Application\n");
   printf("Usage:\n");
   printf("\t-ip <address> IP Address connect to (default localhost)\n");
   printf("\t-port <port> port connect to (default 9999)\n\n");
}

/**
 * \brief Main function
 **/
int main(int argc, char * argv[])
{
    /* IP and port of the V2 instance managing the cameras */
    char ip[24] = "localhost";
    int port = 9999;

    /* Parse command line inputs to determine IP address
     * or port if provided from the command line */
    for( int i = 1; i < argc; i++ ){
       if( !strcmp(argv[i],"-ip") ){
          if( ++i >= argc ){
             printHelp();
             return 0;
          }
          int length = strlen(argv[i]);
          if( length < 24 ){
             strncpy(ip, argv[i], length);
             ip[length] = 0;
          }
       } else if( !strcmp(argv[i],"-port") ){
          if( ++i >= argc ){
             printHelp();
             return 0;
          }
          int length = strlen(argv[i]);
          port = atoi(argv[i]);
       } else{
          printHelp();
          return 0;
       }
    }

    /* connect to the V2 instance */
    connectToCameraServer(ip, port);

    /* get the number of cameras and create some data structure to hold them */
    int numCameras = getNumberOfCameras();
    printf("API reported that there are %d cameras available\n", numCameras);
    ACOS_CAMERA cameraList[numCameras];

    /* create a new camera callback struct */
    NEW_CAMERA_CALLBACK camCB;
    camCB.f = newCameraCallback;
    camCB.data = cameraList;

    /* call setNewCameraCallback; this function sets a callback that is
     * triggered each time a new Mantis system is discovered by the API,
     * and also calls the callback function for each Mantis camera that
     * has already been discovered at the time of setting the callback */
    setNewCameraCallback(camCB);

    /* now if we check our camera list, we should see a populated list
     * of ACOS_CAMERA objects */
    for( int i = 0; i < numCameras; i++ ){
        printf("Found camera with ID %u and %d microcameras\n",
                cameraList[i].camID,
                cameraList[i].mcamList.numMCams);
    }

    /* If these cameras report 0 microcameras, this means that they have
     * never been connected to their physical camera systems and do not
     * know how many microcameras they contain. We can check the current
     * connection status and create a connection using the following code */
    for( int i = 0; i < numCameras; i++ ){
        printf("\nChecking the connection status of camera %u\n",
               cameraList[i].camID);

        /* This function checks the current connection status */
        AQ_SYSTEM_STATE connected = isCameraConnected(cameraList[i]);
        printf("Camera %u is%s connected to its physical camera system\n",
               cameraList[i].camID,
               (connected == AQ_CAMERA_CONNECTED ? "" : " not"));

        /* If not connected, we can toggle the connection with the
         * following function. The last parameter is a timeout in
         * milliseconds that waits for the command to complete
         * before returning the current state of the connection */
        if( connected != AQ_CAMERA_CONNECTED ){
            if( setCameraConnection(cameraList[i], true, 15) != AQ_SUCCESS ){
                printf("Failed to establish connection for camera %u!\n",
                       cameraList[i].camID);
                return 0;
            } else{
                printf("Camera %u is now connected to its physical camera system\n",
                       cameraList[i].camID);
            }
        }

        /* Now if we re-query the number of microcameras in the camera system,
         * we should see the correct number instead of a 0 */
        uint32_t numMCams = getCameraNumberOfMCams(cameraList[i]);
        printf("Camera system %u contains %u microcameras\n",
               cameraList[i].camID,
               numMCams);

        /* If we want, we can correct the 0 in the ACOS_CAMERA struct.
         * This is not needed for use as input to the API functions, but may
         * be useful if we are saving the structs for our own use. */
        cameraList[i].mcamList.numMCams = numMCams;
    }

    /* Disconnect the cameras to prevent issues when another program
     * tries to connect */
    for( int i = 0; i < numCameras; i++ ){
        disconnectCamera(cameraList[i]);
    }

    exit(1);
}


text:
sudo apt-get update
sudo apt-get install -y build-essential libncurses-dev git libgmp3c2 libgmp3-dev zlib1g-dev libedit2 libedit-dev freeglut3-dev libglu1-mesa-dev libglib2.0-dev libcairo2-dev libpango1.0-dev libgtk2.0-dev zip
wget http://www.haskell.org/ghc/dist/7.4.2/ghc-7.4.2-x86_64-unknown-linux.tar.bz2
tar jxfv ghc-7.4.2-x86_64-unknown-linux.tar.bz2
cd ghc-7.4.2
./configure --prefix=/opt/ghc-7.4.2
sudo make install
echo 'export PATH=/opt/ghc-7.4.2/bin:~/.cabal/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
cd ..
wget http://hackage.haskell.org/packages/archive/cabal-install/1.16.0.2/cabal-install-1.16.0.2.tar.gz
tar zxfv cabal-install-1.16.0.2.tar.gz
cd cabal-install-1.16.0.2/
bash bootstrap.sh
cd ..
git clone --recursive https://github.com/fpco/stackage
cd stackage
cabal update
cabal install

# Temporary hack for cairo:
cabal install alex happy
cabal install gtk2hs-buildtools

stackage build


text:
package com.github.tojo.session.cookies;

public class TimeoutStrategyDefaultImpl implements TimeoutStrategy {

	@Override
	public void issue(SessionData sessionData, CookieValue cookieValue) {
		// noop
	}

	@Override
	public void advance(CookieValue cookieValue) {
		// noop
	}

	@Override
	public void expire(CookieValue cookieValue) {
		// noop
	}
}


text:
#include "config.h"
#include "DFGCompilationKey.h"

#include "CodeBlock.h"

namespace JSC { namespace DFG {

void CompilationKey::dump(PrintStream& out) const
{
    if (!*this) {
        out.print("<empty>");
        return;
    }
    out.print("(Compile of ", *m_profiledBlock, " with ", m_mode, ")");
}

} } // namespace JSC::DFG


text:
/**
 * @fileoverview Object representing a code comment.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Comment');

/**
 * Class for a comment.
 * @param {!Blockly.Block} block The block associated with this comment.
 * @constructor
 */
Blockly.Comment = function(block) {
  this.block_ = block;
  this.createIcon_();
};

/**
 * Radius of the comment icon.
 */
Blockly.Comment.ICON_RADIUS = 8;

/**
 * Bubble UI (if visible).
 * @type {Blockly.Bubble}
 * @private
 */
Blockly.Comment.prototype.bubble_ = null;

/**
 * Comment text (if bubble is not visible).
 * @private
 */
Blockly.Comment.prototype.text_ = '';

/**
 * Absolute X coordinate of icon's center.
 * @private
 */
Blockly.Comment.prototype.iconX_ = 0;

/**
 * Absolute Y coordinate of icon's centre.
 * @private
 */
Blockly.Comment.prototype.iconY_ = 0;

/**
 * Width of bubble.
 * @private
 */
Blockly.Comment.prototype.width_ = 160;

/**
 * Height of bubble.
 * @private
 */
Blockly.Comment.prototype.height_ = 80;

/**
 * Create the icon on the block.
 * @private
 */
Blockly.Comment.prototype.createIcon_ = function() {
  /* Here's the markup that will be generated:
  <g class="blocklyIconGroup">
    <circle class="blocklyIconShield" r="8" cx="8" cy="8"/>
    <text class="blocklyIconMark" x="8" y="13">?</text>
  </g>
  */
  this.iconGroup_ = Blockly.createSvgElement('g', {}, null);
  if (!this.block_.isInFlyout) {
    this.iconGroup_.setAttribute('class', 'blocklyIconGroup');
  }
  var iconShield = Blockly.createSvgElement('circle',
      {'class': 'blocklyIconShield',
       'r': Blockly.Comment.ICON_RADIUS,
       'cx': Blockly.Comment.ICON_RADIUS,
       'cy': Blockly.Comment.ICON_RADIUS}, this.iconGroup_);
  this.iconMark_ = Blockly.createSvgElement('text',
      {'class': 'blocklyIconMark',
       'x': Blockly.Comment.ICON_RADIUS,
       'y': 2 * Blockly.Comment.ICON_RADIUS - 3}, this.iconGroup_);
  this.iconMark_.appendChild(document.createTextNode('?'));
  this.block_.getSvgRoot().appendChild(this.iconGroup_);
  if (this.block_.editable && !this.block_.isInFlyout) {
    Blockly.bindEvent_(this.iconGroup_, 'mouseup', this, this.iconClick_);
  }
};

/**
 * Create the editor for the comment's bubble.
 * @return {!Element} The top-level node of the editor.
 * @private
 */
Blockly.Comment.prototype.createEditor_ = function() {
  /* Create the editor.  Here's the markup that will be generated:
    <foreignObject x="8" y="8" width="164" height="164">
      <body xmlns="http://www.w3.org/1999/xhtml" class="blocklyMinimalBody">
        <textarea xmlns="http://www.w3.org/1999/xhtml"
            class="blocklyCommentTextarea"
            style="height: 164px; width: 164px;"></textarea>
      </body>
    </foreignObject>
  */
  this.foreignObject_ = Blockly.createSvgElement('foreignObject',
      {'x': Blockly.Bubble.BORDER_WIDTH, 'y': Blockly.Bubble.BORDER_WIDTH},
      null);
  var body = document.createElementNS(Blockly.HTML_NS, 'body');
  body.setAttribute('xmlns', Blockly.HTML_NS);
  body.className = 'blocklyMinimalBody';
  this.textarea_ = document.createElementNS(Blockly.HTML_NS, 'textarea');
  this.textarea_.className = 'blocklyCommentTextarea';
  this.textarea_.setAttribute('dir', Blockly.RTL ? 'RTL' : 'LTR');
  body.appendChild(this.textarea_);
  this.foreignObject_.appendChild(body);
  Blockly.bindEvent_(this.textarea_, 'mouseup', this, this.textareaFocus_);
  return this.foreignObject_;
};

/**
 * Callback function triggered when the bubble has resized.
 * Resize the text area accordingly.
 * @private
 */
Blockly.Comment.prototype.resizeBubble_ = function() {
  var size = this.bubble_.getBubbleSize();
  var doubleBorderWidth = 2 * Blockly.Bubble.BORDER_WIDTH;
  this.foreignObject_.setAttribute('width', size.width - doubleBorderWidth);
  this.foreignObject_.setAttribute('height', size.height - doubleBorderWidth);
  this.textarea_.style.width = (size.width - doubleBorderWidth - 4) + 'px';
  this.textarea_.style.height = (size.height - doubleBorderWidth - 4) + 'px';
};

/**
 * Is the comment bubble visible?
 * @return {boolean} True if the bubble is visible.
 */
Blockly.Comment.prototype.isVisible = function() {
  return !!this.bubble_;
};

/**
 * Show or hide the comment bubble.
 * @param {boolean} visible True if the bubble should be visible.
 */
Blockly.Comment.prototype.setVisible = function(visible) {
  if (visible == this.isVisible()) {
    // No change.
    return;
  }
  // Save the bubble stats before the visibility switch.
  var text = this.getText();
  var size = this.getBubbleSize();
  if (visible) {
    // Create the bubble.
    this.bubble_ = new Blockly.Bubble(
        /** @type {!Blockly.Workspace} */ (this.block_.workspace),
        this.createEditor_(), this.block_.svg_.svgGroup_,
        this.iconX_, this.iconY_,
        this.width_, this.height_);
    this.bubble_.registerResizeEvent(this, this.resizeBubble_);
    this.updateColour();
    this.text_ = null;
  } else {
    // Dispose of the bubble.
    this.bubble_.dispose();
    this.bubble_ = null;
    this.textarea_ = null;
    this.foreignObject_ = null;
  }
  // Restore the bubble stats after the visibility switch.
  this.setText(text);
  this.setBubbleSize(size.width, size.height);
};

/**
 * Clicking on the icon toggles if the bubble is visible.
 * @param {!Event} e Mouse click event.
 * @private
 */
Blockly.Comment.prototype.iconClick_ = function(e) {
  this.setVisible(!this.isVisible());
};

/**
 * Bring the comment to the top of the stack when clicked on.
 * @param {!Event} e Mouse up event.
 * @private
 */
Blockly.Comment.prototype.textareaFocus_ = function(e) {
  // Ideally this would be hooked to the focus event for the comment.
  // However doing so in Firefox swallows the cursor for unknown reasons.
  // So this is hooked to mouseup instead.  No big deal.
  this.bubble_.promote_();
  // Since the act of moving this node within the DOM causes a loss of focus,
  // we need to reapply the focus.
  this.textarea_.focus();
};

/**
 * Get the dimensions of this comment's bubble.
 * @return {!Object} Object with width and height properties.
 */
Blockly.Comment.prototype.getBubbleSize = function() {
  if (this.isVisible()) {
    return this.bubble_.getBubbleSize();
  } else {
    return {width: this.width_, height: this.height_};
  }
};

/**
 * Size this comment's bubble.
 * @param {number} width Width of the bubble.
 * @param {number} height Height of the bubble.
 */
Blockly.Comment.prototype.setBubbleSize = function(width, height) {
  if (this.isVisible()) {
    this.bubble_.setBubbleSize(width, height);
  } else {
    this.width_ = width;
    this.height_ = height;
  }
};

/**
 * Returns this comment's text.
 * @return {string} Comment text.
 */
Blockly.Comment.prototype.getText = function() {
  return this.isVisible() ? this.textarea_.value : this.text_;
};

/**
 * Set this comment's text.
 * @param {string} text Comment text.
 */
Blockly.Comment.prototype.setText = function(text) {
  if (this.isVisible()) {
    this.textarea_.value = text;
  } else {
    this.text_ = text;
  }
};

/**
 * Change the colour of a comment to match its block.
 */
Blockly.Comment.prototype.updateColour = function() {
  if (this.isVisible()) {
    var hexColour = Blockly.makeColour(this.block_.getColour());
    this.bubble_.setColour(hexColour);
  }
};

/**
 * Dispose of this comment.
 */
Blockly.Comment.prototype.dispose = function() {
  // Dispose of and unlink the icon.
  goog.dom.removeNode(this.iconGroup_);
  this.iconGroup_ = null;
  // Dispose of and unlink the bubble.
  this.setVisible(false);
  // Disconnect links between the block and the comment.
  this.block_.comment = null;
  this.block_ = null;
};

/**
 * Render the icon for this comment.
 * @param {number} cursorX Horizontal offset at which to position the icon.
 * @return {number} Horizontal offset for next item to draw.
 */
Blockly.Comment.prototype.renderIcon = function(cursorX) {
  if (this.block_.collapsed) {
    this.iconGroup_.setAttribute('display', 'none');
    return cursorX;
  }
  this.iconGroup_.setAttribute('display', 'block');

  var TOP_MARGIN = 5;
  var diameter = 2 * Blockly.Comment.ICON_RADIUS;
  if (Blockly.RTL) {
    cursorX -= diameter;
  }
  this.iconGroup_.setAttribute('transform',
      'translate(' + cursorX + ', ' + TOP_MARGIN + ')');
  this.computeIconLocation();
  if (Blockly.RTL) {
    cursorX -= Blockly.BlockSvg.SEP_SPACE_X;
  } else {
    cursorX += diameter + Blockly.BlockSvg.SEP_SPACE_X;
  }
  return cursorX;
};

/**
 * Notification that the icon has moved.  Update the arrow accordingly.
 * @param {number} x Absolute horizontal location.
 * @param {number} y Absolute vertical location.
 */
Blockly.Comment.prototype.setIconLocation = function(x, y) {
  this.iconX_ = x;
  this.iconY_ = y;
  if (this.isVisible()) {
    this.bubble_.setAnchorLocation(x, y);
  }
};

/**
 * Notification that the icon has moved, but we don't really know where.
 * Recompute the icon's location from scratch.
 */
Blockly.Comment.prototype.computeIconLocation = function() {
  // Find coordinates for the centre of the icon and update the arrow.
  var blockXY = this.block_.getRelativeToSurfaceXY();
  var iconXY = Blockly.getRelativeXY_(this.iconGroup_);
  var newX = blockXY.x + iconXY.x + Blockly.Comment.ICON_RADIUS;
  var newY = blockXY.y + iconXY.y + Blockly.Comment.ICON_RADIUS;
  if (newX !== this.iconX_ || newY !== this.iconY_) {
    this.setIconLocation(newX, newY);
  }
};

/**
 * Returns the center of the block's icon relative to the surface.
 * @return {!Object} Object with x and y properties.
 */
Blockly.Comment.prototype.getIconLocation = function() {
  return {x: this.iconX_, y: this.iconY_};
};


text:
import json
from sys import exc_info
from time import time
from unittest import main, TestCase
from test.unit import FakeLogger

from swift.common import internal_client
from swift.obj import expirer
from swift.proxy.server import Application

def not_random():
    return 0.5

last_not_sleep = 0

def not_sleep(seconds):
    global last_not_sleep
    last_not_sleep = seconds

class TestObjectExpirer(TestCase):
    maxDiff = None

    def setUp(self):
        global not_sleep

        self.old_loadapp = internal_client.loadapp
        self.old_sleep = internal_client.sleep

        internal_client.loadapp = lambda x: None
        internal_client.sleep = not_sleep

    def teardown(self):
        internal_client.sleep = self.old_sleep
        internal_client.loadapp = self.loadapp

    def test_report(self):
        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()

        x.report()
        self.assertEquals(x.logger.log_dict['info'], [])

        x.logger._clear()
        x.report(final=True)
        self.assertTrue('completed' in x.logger.log_dict['info'][-1][0][0],
                        x.logger.log_dict['info'])
        self.assertTrue('so far' not in x.logger.log_dict['info'][-1][0][0],
                        x.logger.log_dict['info'])

        x.logger._clear()
        x.report_last_time = time() - x.report_interval
        x.report()
        self.assertTrue('completed' not in x.logger.log_dict['info'][-1][0][0],
                        x.logger.log_dict['info'])
        self.assertTrue('so far' in x.logger.log_dict['info'][-1][0][0],
                        x.logger.log_dict['info'])

    def test_run_once_nothing_to_do(self):
        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.swift = 'throw error because a string does not have needed methods'
        x.run_once()
        self.assertEquals(x.logger.log_dict['exception'],
                          [(("Unhandled exception",), {},
                            "'str' object has no attribute "
                            "'get_account_info'")])

    def test_run_once_calls_report(self):
        class InternalClient(object):
            def get_account_info(*a, **kw):
                return 1, 2

            def iter_containers(*a, **kw):
                return []

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.swift = InternalClient()
        x.run_once()
        self.assertEquals(
            x.logger.log_dict['info'],
            [(('Pass beginning; 1 possible containers; '
               '2 possible objects',), {}),
             (('Pass completed in 0s; 0 objects expired',), {})])

    def test_container_timestamp_break(self):
        class InternalClient(object):
            def __init__(self, containers):
                self.containers = containers

            def get_account_info(*a, **kw):
                return 1, 2

            def iter_containers(self, *a, **kw):
                return self.containers

            def iter_objects(*a, **kw):
                raise Exception('This should not have been called')

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.swift = InternalClient([{'name': str(int(time() + 86400))}])
        x.run_once()
        for exccall in x.logger.log_dict['exception']:
            self.assertTrue(
                'This should not have been called' not in exccall[0][0])
        self.assertEquals(
            x.logger.log_dict['info'],
            [(('Pass beginning; 1 possible containers; '
               '2 possible objects',), {}),
             (('Pass completed in 0s; 0 objects expired',), {})])

        # Reverse test to be sure it still would blow up the way expected.
        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.swift = InternalClient([{'name': str(int(time() - 86400))}])
        x.run_once()
        self.assertEquals(x.logger.log_dict['exception'],
            [(('Unhandled exception',), {},
              str(Exception('This should not have been called')))])

    def test_object_timestamp_break(self):
        class InternalClient(object):
            def __init__(self, containers, objects):
                self.containers = containers
                self.objects = objects

            def get_account_info(*a, **kw):
                return 1, 2

            def iter_containers(self, *a, **kw):
                return self.containers

            def delete_container(*a, **kw):
                pass

            def iter_objects(self, *a, **kw):
                return self.objects

        def should_not_be_called(*a, **kw):
            raise Exception('This should not have been called')

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.swift = InternalClient([{'name': str(int(time() - 86400))}],
            [{'name': '%d-actual-obj' % int(time() + 86400)}])
        x.run_once()
        for exccall in x.logger.log_dict['exception']:
            self.assertTrue(
                'This should not have been called' not in exccall[0][0])
        self.assertEquals(x.logger.log_dict['info'],
            [(('Pass beginning; 1 possible containers; '
               '2 possible objects',), {}),
             (('Pass completed in 0s; 0 objects expired',), {})])

        # Reverse test to be sure it still would blow up the way expected.
        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        ts = int(time() - 86400)
        x.swift = InternalClient([{'name': str(int(time() - 86400))}],
            [{'name': '%d-actual-obj' % ts}])
        x.delete_actual_object = should_not_be_called
        x.run_once()
        excswhiledeleting = []
        for exccall in x.logger.log_dict['exception']:
            if exccall[0][0].startswith('Exception while deleting '):
                excswhiledeleting.append(exccall[0][0])
        self.assertEquals(excswhiledeleting,
            ['Exception while deleting object %d %d-actual-obj '
             'This should not have been called' % (ts, ts)])

    def test_failed_delete_keeps_entry(self):
        class InternalClient(object):
            def __init__(self, containers, objects):
                self.containers = containers
                self.objects = objects

            def get_account_info(*a, **kw):
                return 1, 2

            def iter_containers(self, *a, **kw):
                return self.containers

            def delete_container(*a, **kw):
                pass

            def delete_object(*a, **kw):
                raise Exception('This should not have been called')

            def iter_objects(self, *a, **kw):
                return self.objects

        def deliberately_blow_up(actual_obj, timestamp):
            raise Exception('failed to delete actual object')

        def should_not_get_called(container, obj):
            raise Exception('This should not have been called')

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.iter_containers = lambda: [str(int(time() - 86400))]
        ts = int(time() - 86400)
        x.delete_actual_object = deliberately_blow_up
        x.swift = InternalClient([{'name': str(int(time() - 86400))}],
            [{'name': '%d-actual-obj' % ts}])
        x.run_once()
        excswhiledeleting = []
        for exccall in x.logger.log_dict['exception']:
            if exccall[0][0].startswith('Exception while deleting '):
                excswhiledeleting.append(exccall[0][0])
        self.assertEquals(excswhiledeleting,
            ['Exception while deleting object %d %d-actual-obj '
             'failed to delete actual object' % (ts, ts)])
        self.assertEquals(x.logger.log_dict['info'],
            [(('Pass beginning; 1 possible containers; '
               '2 possible objects',), {}),
             (('Pass completed in 0s; 0 objects expired',), {})])

        # Reverse test to be sure it still would blow up the way expected.
        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        ts = int(time() - 86400)
        x.delete_actual_object = lambda o, t: None
        x.swift = InternalClient([{'name': str(int(time() - 86400))}],
            [{'name': '%d-actual-obj' % ts}])
        x.run_once()
        excswhiledeleting = []
        for exccall in x.logger.log_dict['exception']:
            if exccall[0][0].startswith('Exception while deleting '):
                excswhiledeleting.append(exccall[0][0])
        self.assertEquals(excswhiledeleting,
            ['Exception while deleting object %d %d-actual-obj This should '
             'not have been called' % (ts, ts)])

    def test_success_gets_counted(self):
        class InternalClient(object):
            def __init__(self, containers, objects):
                self.containers = containers
                self.objects = objects

            def get_account_info(*a, **kw):
                return 1, 2

            def iter_containers(self, *a, **kw):
                return self.containers

            def delete_container(*a, **kw):
                pass

            def delete_object(*a, **kw):
                pass

            def iter_objects(self, *a, **kw):
                return self.objects

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        x.delete_actual_object = lambda o, t: None
        self.assertEquals(x.report_objects, 0)
        x.swift = InternalClient([{'name': str(int(time() - 86400))}],
            [{'name': '%d-actual-obj' % int(time() - 86400)}])
        x.run_once()
        self.assertEquals(x.report_objects, 1)
        self.assertEquals(x.logger.log_dict['info'],
            [(('Pass beginning; 1 possible containers; '
               '2 possible objects',), {}),
             (('Pass completed in 0s; 1 objects expired',), {})])

    def test_failed_delete_continues_on(self):
        class InternalClient(object):
            def __init__(self, containers, objects):
                self.containers = containers
                self.objects = objects

            def get_account_info(*a, **kw):
                return 1, 2

            def iter_containers(self, *a, **kw):
                return self.containers

            def delete_container(*a, **kw):
                raise Exception('failed to delete container')

            def delete_object(*a, **kw):
                pass

            def iter_objects(self, *a, **kw):
                return self.objects

        def fail_delete_actual_object(actual_obj, timestamp):
            raise Exception('failed to delete actual object')

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()

        cts = int(time() - 86400)
        ots = int(time() - 86400)

        containers = [
            {'name': str(cts)},
            {'name': str(cts + 1)},
        ]

        objects = [
            {'name': '%d-actual-obj' % ots},
            {'name': '%d-next-obj' % ots}
        ]

        x.swift = InternalClient(containers, objects)
        x.delete_actual_object = fail_delete_actual_object
        x.run_once()
        excswhiledeleting = []
        for exccall in x.logger.log_dict['exception']:
            if exccall[0][0].startswith('Exception while deleting '):
                excswhiledeleting.append(exccall[0][0])
        self.assertEquals(excswhiledeleting, [
            'Exception while deleting object %d %d-actual-obj failed to '
            'delete actual object' % (cts, ots),
            'Exception while deleting object %d %d-next-obj failed to '
            'delete actual object' % (cts, ots),
            'Exception while deleting container %d failed to delete '
            'container' % (cts,),
            'Exception while deleting object %d %d-actual-obj failed to '
            'delete actual object' % (cts + 1, ots),
            'Exception while deleting object %d %d-next-obj failed to '
            'delete actual object' % (cts + 1, ots),
            'Exception while deleting container %d failed to delete '
            'container' % (cts + 1,)])
        self.assertEquals(x.logger.log_dict['info'],
            [(('Pass beginning; 1 possible containers; '
               '2 possible objects',), {}),
             (('Pass completed in 0s; 0 objects expired',), {})])

    def test_run_forever_initial_sleep_random(self):
        global last_not_sleep

        def raise_system_exit():
            raise SystemExit('test_run_forever')

        interval = 1234
        x = expirer.ObjectExpirer({'__file__': 'unit_test',
                                   'interval': interval})
        orig_random = expirer.random
        orig_sleep = expirer.sleep
        exc = None
        try:
            expirer.random = not_random
            expirer.sleep = not_sleep
            x.run_once = raise_system_exit
            x.run_forever()
        except SystemExit, err:
            exc = err
        finally:
            expirer.random = orig_random
            expirer.sleep = orig_sleep
        self.assertEquals(str(err), 'test_run_forever')
        self.assertEquals(last_not_sleep, 0.5 * interval)

    def test_run_forever_catches_usual_exceptions(self):
        raises = [0]

        def raise_exceptions():
            raises[0] += 1
            if raises[0] < 2:
                raise Exception('exception %d' % raises[0])
            raise SystemExit('exiting exception %d' % raises[0])

        x = expirer.ObjectExpirer({})
        x.logger = FakeLogger()
        orig_sleep = expirer.sleep
        exc = None
        try:
            expirer.sleep = not_sleep
            x.run_once = raise_exceptions
            x.run_forever()
        except SystemExit, err:
            exc = err
        finally:
            expirer.sleep = orig_sleep
        self.assertEquals(str(err), 'exiting exception 2')
        self.assertEquals(x.logger.log_dict['exception'],
                          [(('Unhandled exception',), {},
                            'exception 1')])

    def test_delete_actual_object(self):
        got_env = [None]

        def fake_app(env, start_response):
            got_env[0] = env
            start_response('204 No Content', [('Content-Length', '0')])
            return []

        internal_client.loadapp = lambda x: fake_app

        x = expirer.ObjectExpirer({})
        ts = '1234'
        x.delete_actual_object('/path/to/object', ts)
        self.assertEquals(got_env[0]['HTTP_X_IF_DELETE_AT'], ts)

    def test_delete_actual_object_handles_404(self):

        def fake_app(env, start_response):
            start_response('404 Not Found', [('Content-Length', '0')])
            return []

        internal_client.loadapp = lambda x: fake_app

        x = expirer.ObjectExpirer({})
        x.delete_actual_object('/path/to/object', '1234')

    def test_delete_actual_object_handles_412(self):

        def fake_app(env, start_response):
            start_response('412 Precondition Failed',
                           [('Content-Length', '0')])
            return []

        internal_client.loadapp = lambda x: fake_app

        x = expirer.ObjectExpirer({})
        x.delete_actual_object('/path/to/object', '1234')

    def test_delete_actual_object_does_not_handle_odd_stuff(self):

        def fake_app(env, start_response):
            start_response('503 Internal Server Error',
                [('Content-Length', '0')])
            return []

        internal_client.loadapp = lambda x: fake_app

        x = expirer.ObjectExpirer({})
        exc = None
        try:
            x.delete_actual_object('/path/to/object', '1234')
        except Exception, err:
            exc = err
        finally:
            pass
        self.assertEquals(503, exc.resp.status_int)

if __name__ == '__main__':
    main()