text:
/* irfunc.c v0.4.1 (c) 1998-99 Tom Wheeley <tomw@tsys.demon.co.uk> */
/* this code is placed under the LGPL, see www.gnu.org for info    */

/*
 * irfunc.c, infrared functions (Irman specific)
 */

#include "ir.h"

/* generic function for ir_get_code() and ir_poll_code() */
static unsigned char *ir_read_code(unsigned long timeout);

/* converts a single hex character to an integer */
static int ir_hex_to_int(unsigned char hex);

/* flag to enable use of higher level functions */
static int ir_enabled = 0;

/* output hex digits */
static char ir_hexdigit[16] =
{
	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};

/* this function is used by both ir_get_code() and ir_poll_code(),
 * the difference being in the timeout for the first piece of data.
 * we also have a short timeout whatever for the remaining five bytes,
 * in case computer and Irman get out of sync we can just raise an error
 * and get back to normal life.
 *
 * note esp. that these functions return a pointer to statically defined
 * data.  In the forseeable usage of LIBIRMAN this seems the easiest way.
 */

static unsigned char *ir_read_code(unsigned long timeout)
{
	static unsigned char codebuf[IR_MAX_CODE_LEN];
	int i, datum;

	datum = ir_read_char(timeout);
	if (datum < 0)
		return NULL;

	codebuf[0] = (unsigned char) datum;

	for (i = 1; i < ircfg.codelen; i++)
	{
		datum = ir_read_char(IR_POLL_TIMEOUT);
		if (datum < 0)
		{
			return NULL;
		}
		else
		{
			codebuf[i] = (unsigned char) datum;
		}
	}

	return codebuf;
}

unsigned char *ir_get_code(void)
{
	/* well dodgy choice of error here...! */
	if (!ir_enabled)
	{
		errno = ENXIO;
		return NULL;
	}

	return ir_read_code(IR_BLOCKING);
}

unsigned char *ir_poll_code(void)
{
	if (!ir_enabled)
	{
		errno = ENXIO;
		return NULL;
	}

	return ir_read_code(0);
}

/* checks to see if a piece of text is a valid ir code (1 = yes) */
int ir_valid_code(char *text)
{
	char *c;

	if (strlen(text) != ircfg.codelen * 2)
		return 0;

	for (c = text; *c; c++)
		if (!isxdigit(*c))
			return 0;

	return 1;
}

char *ir_code_to_text(unsigned char *code)
{
	static char text[2 * IR_MAX_CODE_LEN + 1];
	int i;
	char *j;

	j = text;
	for (i = 0; i < ircfg.codelen; i++)
	{
		*j++ = ir_hexdigit[(code[i] >> 4) & 0x0f];
		*j++ = ir_hexdigit[code[i] & 0x0f];
	}
	*j = '\0';

	return text;
}

static int ir_hex_to_int(unsigned char hex)
{
	if (hex >= '0' && hex <= '9')
		return hex - '0';

	hex = tolower(hex);
	if (hex >= 'a' && hex <= 'f')
		return hex - 'a' + 10;

	/* error! */
	return 0;
}

unsigned char *ir_text_to_code(char *text)
{
	static char code[IR_MAX_CODE_LEN];
	int i;
	char *j;

	j = text;
	for (i = 0; i < ircfg.codelen; i++)
	{
		if (!j[0] || !j[1])
		{
			break;
		}
		code[i] = (ir_hex_to_int(*j++) << 4) & 0xf0;
		code[i] += (ir_hex_to_int(*j++)) & 0x0f;
	}

	/* if string isn't long enough, pad with zeros. This is (marginally)
	 * better than the leaving in the remains of the last conversion
	 */
	for (; i < ircfg.codelen; i++)
		code[i] = '\0';

	return code;
}

/* this function should never be called, but maybe someone wants to manually
 * open the ir channel, then use the higher level functions.  If you use this
 * then you deserve any problems you get!  It is only here because I don't
 * believe in unneccesary restrictions.
 */
void ir_set_enabled(int val)
{
	ir_enabled = val;
}

/* end of irfunc.c */


text:
import java.lang.annotation.*;
import java.util.List;
import static java.lang.annotation.ElementType.*;

@Target({TYPE_USE}) @interface TA { }

class C {
  {
    Object o = null;
    @TA <caret>List<@TA String> l = (@TA List<@TA String>) o;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>

	<!-- Data source -->

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:44444/copre" />
		<property name="username" value="copre" />
		<property name="password" value="copre" />
	</bean>

	<!-- Repository Locator -->

	<bean id="repositoryLocator" class="ar.com.trimatec.copre.repositories.RepositoryLocator"
		factory-method="getInstance">
		<property name="copreRepository">
			<ref local="copreRepository" />
		</property>
		<property name="categoryRepository">
			<ref local="categoryRepository" />
		</property>
		<property name="participantRepository">
			<ref local="participantRepository" />
		</property>
		<property name="productRepository">
			<ref local="productRepository" />
		</property>
		<property name="brandRepository">
			<ref local="brandRepository" />
		</property>
		<property name="measureRepository">
			<ref local="measureRepository" />
		</property>
		<property name="itemRepository">
			<ref local="itemRepository" />
		</property>
		<property name="requirementRepository">
			<ref local="requirementRepository" />
		</property>
		<property name="workflowRepository">
			<ref local="workflowRepository" />
		</property>
		<property name="workflowNodeDescriptionRepository">
			<ref local="workflowNodeDescriptionRepository" />
		</property>
		<property name="bidRepository">
			<ref local="bidRepository" />
		</property>
		<property name="workflowNodeRepository">
			<ref local="workflowNodeRepository" />
		</property>
	</bean>

	<!-- Repositories -->

	<bean id="copreRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateCopreRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="categoryRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateCategoryRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="participantRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateParticipantRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="productRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateProductRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="brandRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateBrandRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="measureRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateMeasureRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="itemRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateItemRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="requirementRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateRequirementRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="workflowRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateWorkflowRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="workflowNodeDescriptionRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateWorkflowNodeDescriptionRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="bidRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateBidRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<bean id="workflowNodeRepository"
		class="ar.com.trimatec.copre.repositories.impl.hibernate.HibernateWorkflowNodeRepository">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<!-- Services -->

	<bean id="baseServiceImpl" class="ar.com.trimatec.copre.services.impl.BaseServiceImpl"
		abstract="true">
		<property name="copreRepository">
			<ref local="copreRepository" />
		</property>
		<property name="categoryRepository">
			<ref local="categoryRepository" />
		</property>
		<property name="participantRepository">
			<ref local="participantRepository" />
		</property>
		<property name="productRepository">
			<ref local="productRepository" />
		</property>
		<property name="brandRepository">
			<ref local="brandRepository" />
		</property>
		<property name="measureRepository">
			<ref local="measureRepository" />
		</property>
		<property name="itemRepository">
			<ref local="itemRepository" />
		</property>
		<property name="requirementRepository">
			<ref local="requirementRepository" />
		</property>
		<property name="workflowRepository">
			<ref local="workflowRepository" />
		</property>
		<property name="workflowNodeDescriptionRepository">
			<ref local="workflowNodeDescriptionRepository" />
		</property>
		<property name="bidRepository">
			<ref local="bidRepository" />
		</property>
		<property name="workflowNodeRepository">
			<ref local="workflowNodeRepository" />
		</property>
	</bean>

	<!-- Service Targets -->

	<bean id="participantServiceTarget"
		class="ar.com.trimatec.copre.services.impl.ParticipantServiceImpl"
		parent="baseServiceImpl">
	</bean>

	<bean id="catalogServiceTarget" class="ar.com.trimatec.copre.services.impl.CatalogServiceImpl"
		parent="baseServiceImpl">
	</bean>

	<bean id="requirementServiceTarget"
		class="ar.com.trimatec.copre.services.impl.RequirementServiceImpl"
		parent="baseServiceImpl">
	</bean>

	<bean id="bidServiceTarget"
		class="ar.com.trimatec.copre.services.impl.BidServiceImpl"
		parent="baseServiceImpl">
	</bean>

	<!-- Transaction Manager -->

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>

	<!-- SessionFactory -->

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="mappingResources">
			<list>
				<value>
					/ar/com/trimatec/copre/entities/maps/Copre.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Participant.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Category.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Product.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Brand.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Measure.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Item.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Requirement.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/WorkflowDescription.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/WorkflowNodeDescription.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/WorkflowLinkDescription.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/WorkflowNode.hbm.xml
				</value>
				<value>
					/ar/com/trimatec/copre/entities/maps/Bid.hbm.xml
				</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="show_sql">
					true
				</prop>
			</props>
		</property>
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
	</bean>

	<!-- Services -->

	<bean id="participantService"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager">
			<ref local="transactionManager" />
		</property>
		<property name="target">
			<ref local="participantServiceTarget" />
		</property>
		<property name="transactionAttributes">
			<props>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>

	<bean id="catalogService"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager">
			<ref local="transactionManager" />
		</property>
		<property name="target">
			<ref local="catalogServiceTarget" />
		</property>
		<property name="transactionAttributes">
			<props>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>

	<bean id="requirementService"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager">
			<ref local="transactionManager" />
		</property>
		<property name="target">
			<ref local="requirementServiceTarget" />
		</property>
		<property name="transactionAttributes">
			<props>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>

	<bean id="bidService"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager">
			<ref local="transactionManager" />
		</property>
		<property name="target">
			<ref local="bidServiceTarget" />
		</property>
		<property name="transactionAttributes">
			<props>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>

</beans>


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Network.Nanomsg.C.Transports (

  -- * Transports

  -- Transports are mechanisms by which sockets connect to one another
  -- through @bind@ and @connect@.

  Transport (..), transTCP, transIPC, transINPROC,

  ) where

import Foreign (Storable)
import Foreign.C.Types
import Network.Nanomsg.C.Syms

-- Transports
-------------

newtype Transport = Transport CInt
                  deriving (Eq, Storable)

-- | TCP transport allows for passing message over the network using
-- simple reliable one-to-one connections. TCP is the most widely used
-- transport protocol, it is virtually ubiquitous and thus the
-- transport of choice for communication over the network.
--
-- When binding a TCP socket address of the form
-- @tcp://interface:port@ should be used. Port is the TCP port number
-- to use. Interface is one of the following (optionally placed within
-- square brackets):
--
-- Asterisk character (*) meaning all local network interfaces.
--
-- * IPv4 address of a local network interface in numeric form
--   (@192.168.0.111@).
--
-- * IPv6 address of a local network interface in numeric form (@::1@).
--
-- * Interface name, as defined by operating system.
--
-- When connecting a TCP socket address of the form
-- tcp://interface;address:port should be used. Port is the TCP port
-- number to use. Interface is optional and specifies which local
-- network interface to use. If not specified, OS will select an
-- appropriate interface itself. If specified it can be one of the
-- following (optionally placed within square brackets):
--
-- * IPv4 address of a local network interface in numeric form
--   (@192.168.0.111@).
--
-- * IPv6 address of a local network interface in numeric form (@::1@).
--
-- * Interface name, as defined by operating system (@eth0@).
--
-- Finally, address specifies the remote address to connect to. It can
-- be one of the following (optionally placed within square brackets):
--
-- * IPv4 address of a remote network interface in numeric form
--   (@192.168.0.111@).
--
-- * IPv6 address of a remote network interface in numeric form (@::1@).
--
-- * The DNS name of the remote box.
transTCP :: Transport
transTCP = Transport (getSym "NN_TCP")

-- | In-process transport allows to send messages between threads or
-- modules inside a process. In-process address is an arbitrary
-- case-sensitive string preceded by @inproc://@ protocol
-- specifier. All in-process addresses are visible from any module
-- within the process. They are not visible from outside of the
-- process.
--
-- The nature of in-process transport makes it easy to pass pointers
-- between threads instead of actual data. This is, however,
-- considered a bad application design and violates the scalable
-- share-nothing architecture. If you do pass pointers among threads,
-- synchronising thread access to shared data becomes your
-- responsibility. Such design also prevents moving the thread into
-- different process or machine once the need arises. As a rule of the
-- thumb, don't pass pointers among threads unless you know what you
-- are doing.
--
-- The overall buffer size for an inproc connection is determined by
-- @NN_RCVBUF@ socket option on the receiving end of the
-- connection. @NN_SNDBUF@ socket option is ignored. In addition to
-- the buffer, one message of arbitrary size will fit into the
-- buffer. That way, even messages larger than the buffer can be
-- transfered via inproc connection.
transINPROC :: Transport
transINPROC = Transport (getSym "NN_INPROC")

-- | Inter-process transport allows for sending messages between
-- processes within a single box. The implementation uses native IPC
-- mechanism provided by the local operating system and the IPC
-- addresses are thus OS-specific.
--
-- On POSIX-compliant systems, UNIX domain sockets are used and IPC
-- addresses are file references. Note that both relative
-- (@ipc://test.ipc@) and absolute (@ipc:///tmp/test.ipc@) paths may
-- be used. Also note that access rights on the IPC files must be set
-- in such a way that the appropriate applications can actually use
-- them.
--
-- On Windows, named pipes are used for IPC. IPC address is an
-- arbitrary case-insensitive string containing any character except
-- for backslash. Internally, address @ipc://test@ means that named
-- pipe @\\.\pipe\test@ will be used.
transIPC :: Transport
transIPC = Transport (getSym "NN_IPC")

instance Show Transport where
  show p
    | p == transTCP     = "Transport {TCP}"
    | p == transINPROC  = "Transport {Inproc}"
    | p == transIPC     = "Transport {IPC}"
    | otherwise         = "Transport {unknown}"


text:
import * as Store from "../src/charts/store";
import * as Chartist from "../src/lib/chartist";

Store.addChart(Store.CHART_CONTENT.ORDERS_RATIO, Chartist.CHART_TYPES.PIE_CHART);
Store.addChart(Store.CHART_CONTENT.VIEW_OVER_ORDER_CHART, Chartist.CHART_TYPES.LINE_CHART);


text:
package com.atlassian.plugin.servlet.util;

import junit.framework.TestCase;

import java.net.URISyntaxException;

public class TestClassLoaderStack extends TestCase
{
    public void testThreadClassLoaderIsReplacedAndRestored() throws URISyntaxException
    {
        ClassLoader mainLoader = Thread.currentThread().getContextClassLoader();
        try
        {
            ClassLoader pluginLoader1 = new MockClassLoader();
            ClassLoader pluginLoader2 = new MockClassLoader();

            ClassLoaderStack.push(pluginLoader1);
            assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
            ClassLoaderStack.push(pluginLoader2);
            assertSame(pluginLoader2, Thread.currentThread().getContextClassLoader());
            ClassLoaderStack.pop();
            assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
            ClassLoaderStack.pop();
            assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
        }
        finally
        {
            Thread.currentThread().setContextClassLoader(mainLoader);
        }
    }

    public void testPopReturnsPreviousContextClassLoader() throws Exception
    {
        ClassLoader mainLoader = Thread.currentThread().getContextClassLoader();
        try
        {
            ClassLoader pluginLoader1 = new MockClassLoader();
            ClassLoader pluginLoader2 = new MockClassLoader();

            ClassLoaderStack.push(pluginLoader1);
            assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
            ClassLoaderStack.push(pluginLoader2);
            assertSame(pluginLoader2, Thread.currentThread().getContextClassLoader());
            ClassLoader previous = ClassLoaderStack.pop();
            assertSame(pluginLoader2, previous);
            assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
            previous = ClassLoaderStack.pop();
            assertSame(pluginLoader1, previous);
            assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
        }
        finally
        {
            // Clean up in case of error
            Thread.currentThread().setContextClassLoader(mainLoader);
        }
    }

    public void testPushAndPopHandleNull() throws Exception
    {
        ClassLoader mainLoader = Thread.currentThread().getContextClassLoader();
        try
        {
            // popping with empty stack should return null
            assertNull(ClassLoaderStack.pop());
            // pushing null should be a no-op
            ClassLoaderStack.push(null);
            assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
            assertNull(ClassLoaderStack.pop());
        }
        finally
        {
            // Clean up in case of error
            Thread.currentThread().setContextClassLoader(mainLoader);
        }
    }

    public static class MockClassLoader extends ClassLoader
    {
    }
}


text:
/* $Id: net.c $ */
/** @file
 *
 * VirtualBox Windows Guest Shared Folders
 *
 * File System Driver network redirector subsystem routines
 */

/*
 * Copyright (C) 2012 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#include "vbsf.h"

NTSTATUS VBoxMRxUpdateNetRootState(IN OUT PMRX_NET_ROOT pNetRoot)
{
    Log(("VBOXSF: MRxUpdateNetRootState\n"));
    return STATUS_NOT_IMPLEMENTED;
}

static void vbsfUpdateNetRoot(PMRX_NET_ROOT pNetRoot)
{
    Log(("VBOXSF: vbsfUpdateNetRoot: NetRoot = 0x%x Type = 0x%x\n",
         pNetRoot, pNetRoot->Type));

    switch (pNetRoot->Type)
    {
        case NET_ROOT_DISK:
            pNetRoot->DeviceType = RxDeviceType(DISK);
            break;
        case NET_ROOT_PIPE:
            pNetRoot->DeviceType = RxDeviceType(NAMED_PIPE);
            break;
        case NET_ROOT_COMM:
            pNetRoot->DeviceType = RxDeviceType(SERIAL_PORT);
            break;
        case NET_ROOT_PRINT:
            pNetRoot->DeviceType = RxDeviceType(PRINTER);
            break;
        case NET_ROOT_MAILSLOT:
            pNetRoot->DeviceType = RxDeviceType(MAILSLOT);
            break;
        case NET_ROOT_WILD:
            /* We get this type when for example Windows Media player opens an MP3 file.
             * This NetRoot has the same remote path (\\vboxsrv\dir) as other NetRoots,
             * which were created earlier and which were NET_ROOT_DISK.
             *
             * In the beginning of the function (UpdateNetRoot) the DDK sample sets
             * pNetRoot->Type of newly created NetRoots using a value previously
             * pstored in a NetRootExtension. One NetRootExtensions is used for a single
             * remote path and reused by a few NetRoots, if they point to the same path.
             *
             * To simplify things we just set the type to DISK here (we do not support
             * anything else anyway), and update the DeviceType correspondingly.
             */
            pNetRoot->Type = NET_ROOT_DISK;
            pNetRoot->DeviceType = RxDeviceType(DISK);
            break;
        default:
            AssertMsgFailed(("VBOXSF: vbsfUpdateNetRoot: Invalid net root type! Type = 0x%x\n",
                             pNetRoot->Type));
            break;
    }

    Log(("VBOXSF: vbsfUpdateNetRoot: leaving pNetRoot->DeviceType = 0x%x\n",
         pNetRoot->DeviceType));
}

NTSTATUS VBoxMRxCreateVNetRoot(IN PMRX_CREATENETROOT_CONTEXT pCreateNetRootContext)
{
    NTSTATUS Status;

    PMRX_V_NET_ROOT pVNetRoot = (PMRX_V_NET_ROOT)pCreateNetRootContext->pVNetRoot;

    PMRX_VBOX_DEVICE_EXTENSION pDeviceExtension = VBoxMRxGetDeviceExtension(pCreateNetRootContext->RxContext);
    PMRX_VBOX_NETROOT_EXTENSION pNetRootExtension = VBoxMRxGetNetRootExtension(pVNetRoot->pNetRoot);

    PMRX_NET_ROOT pNetRoot = pVNetRoot->pNetRoot;
    PMRX_SRV_CALL pSrvCall = pNetRoot->pSrvCall;

    BOOLEAN fInitializeNetRoot = FALSE;

    Log(("VBOXSF: MRxCreateVNetRoot: pNetRoot = %p, pNetRootExtension = %p, name = [%.*ls]\n",
         pNetRoot, pNetRootExtension, pNetRoot->pNetRootName->Length / sizeof(WCHAR), pNetRoot->pNetRootName->Buffer));

    /* IMPORTANT:
     *
     * This function must always call 'pCreateNetRootContext->Callback(pCreateNetRootContext)' before
     * returning and then return STATUS_PENDING. Otherwise Win64 will hang.
     */

    if (pNetRoot->Type == NET_ROOT_PIPE)
    {
        /* VBoxSF claims everything which starts with '\vboxsrv'.
         *
         * So sometimes the system tries to open \vboxsrv\ipc$ pipe for DFS
         * and fails the application call if an unexpected code is returned.
         *
         * According to MSDN: The Windows client returns STATUS_MORE_PROCESSING_REQUIRED to the calling
         * application to indicate that the path does not correspond to a DFS Namespace.
         */
        pVNetRoot->Context = NULL;

        if (pNetRoot->pNetRootName->Length >= 13 * sizeof (WCHAR)) /* Number of bytes in '\vboxsrv\ipc$' unicode string. */
        {
            const WCHAR *Suffix = &pNetRoot->pNetRootName->Buffer[8]; /* Number of chars in '\vboxsrv' */

            if (   Suffix[0] == L'\\'
                && (Suffix[1] == L'I' || Suffix[1] == L'i')
                && (Suffix[2] == L'P' || Suffix[2] == L'p')
                && (Suffix[3] == L'C' || Suffix[3] == L'c')
                && Suffix[4] == L'$'
               )
            {
                if (   pNetRoot->pNetRootName->Length == 13 * sizeof (WCHAR)
                    || (Suffix[5] == L'\\' || Suffix[5] == 0)
                   )
                {
                    /* It is '\vboxsrv\IPC$[\*]'. */
                    Log(("VBOXSF: MRxCreateVNetRoot: IPC$\n"));
                    Status = STATUS_MORE_PROCESSING_REQUIRED;
                    goto l_Exit;
                }
            }
        }

        /* Fail all other pipe open requests. */
        Log(("VBOXSF: MRxCreateVNetRoot: Pipe open not supported!\n"));
        Status = STATUS_NOT_SUPPORTED;
        goto l_Exit;
    }
    else if (pNetRoot->Type == NET_ROOT_MAILSLOT)
    {
        Log(("VBOXSF: MRxCreateVNetRoot: Mailslot open not supported!\n"));
        pVNetRoot->Context = NULL;
        Status = STATUS_NOT_SUPPORTED;
        goto l_Exit;
    }

    if (!pNetRoot->Context)
    {
        /* MRxNetRootSize is not zero in VBoxSF, so it is expected
         * that the Context, which is NetRootExtension, is already allocated.
         */
        Log(("VBOXSF: MRxCreateVNetRoot: NULL netroot context\n"));
        pVNetRoot->Context = NULL;
        Status = STATUS_NOT_SUPPORTED;
        goto l_Exit;
    }

    /* Detect an already initialized NetRoot.
     * pNetRootExtension is actually the pNetRoot->Context and it is not NULL.
     */
    fInitializeNetRoot = (pNetRootExtension->phgcmClient == NULL);

    Status = STATUS_SUCCESS;

    if (fInitializeNetRoot)
    {
        PWCHAR pRootName;
        ULONG RootNameLength;
        int vboxRC;
        PSHFLSTRING ParsedPath = 0;

        Log(("VBOXSF: MRxCreateVNetRoot: initialize NET_ROOT\n"));

        pNetRoot->MRxNetRootState = MRX_NET_ROOT_STATE_GOOD;

        RootNameLength = pNetRoot->pNetRootName->Length - pSrvCall->pSrvCallName->Length;
        if (RootNameLength < sizeof(WCHAR))
        {
            /* Refuse a netroot path with an empty shared folder name */
            Log(("VBOXSF: MRxCreateVNetRoot: Empty shared folder name!\n"));
            pNetRoot->MRxNetRootState = MRX_NET_ROOT_STATE_ERROR;

            Status = STATUS_BAD_NETWORK_NAME;
            goto l_Exit;
        }

        RootNameLength -= sizeof(WCHAR); /* Remove leading backslash. */
        pRootName = (PWCHAR)(pNetRoot->pNetRootName->Buffer + (pSrvCall->pSrvCallName->Length / sizeof(WCHAR)));
        pRootName++; /* Remove leading backslash. */

        /* Strip the trailing \0. Sometimes there is one, sometimes not... */
        if (   RootNameLength >= sizeof(WCHAR)
            && pRootName[RootNameLength / sizeof(WCHAR) - 1] == 0)
            RootNameLength -= sizeof(WCHAR);

        if (!pNetRootExtension->phgcmClient)
        {
            Log(("VBOXSF: MRxCreateVNetRoot: Initialize netroot length = %d, name = %.*ls\n",
                 RootNameLength, RootNameLength / sizeof(WCHAR), pRootName));

            Status = vbsfShflStringFromUnicodeAlloc(&ParsedPath, pRootName, (uint16_t)RootNameLength);
            if (Status != STATUS_SUCCESS)
            {
                goto l_Exit;
            }

            vboxRC = vboxCallMapFolder(&pDeviceExtension->hgcmClient, ParsedPath, &pNetRootExtension->map);
            vbsfFreeNonPagedMem(ParsedPath);
            if (vboxRC != VINF_SUCCESS)
            {
                Log(("VBOXSF: MRxCreateVNetRoot: vboxCallMapFolder failed with %d\n", vboxRC));
                Status = STATUS_BAD_NETWORK_NAME;
            }
            else
            {
                Status = STATUS_SUCCESS;
                pNetRootExtension->phgcmClient = &pDeviceExtension->hgcmClient;
            }
        }
    }
    else
        Log(("VBOXSF: MRxCreateVNetRoot: Creating V_NET_ROOT on existing NET_ROOT!\n"));

    vbsfUpdateNetRoot(pNetRoot);

l_Exit:
    if (Status != STATUS_PENDING)
    {
        Log(("VBOXSF: MRxCreateVNetRoot: Returning 0x%08X\n", Status));
        pCreateNetRootContext->VirtualNetRootStatus = Status;
        if (fInitializeNetRoot)
            pCreateNetRootContext->NetRootStatus = Status;
        else
            pCreateNetRootContext->NetRootStatus = STATUS_SUCCESS;

        /* Inform RDBSS. */
        pCreateNetRootContext->Callback(pCreateNetRootContext);

        /* RDBSS expects this. */
        Status = STATUS_PENDING;
    }

    Log(("VBOXSF: MRxCreateVNetRoot: Returned STATUS_PENDING\n"));
    return Status;
}

NTSTATUS VBoxMRxFinalizeVNetRoot(IN PMRX_V_NET_ROOT pVNetRoot,
                                 IN PBOOLEAN ForceDisconnect)
{
    Log(("VBOXSF: MRxFinalizeVNetRoot: V_NET_ROOT %p, NET_ROOT %p\n",
         pVNetRoot, pVNetRoot->pNetRoot));

    return STATUS_SUCCESS;
}

NTSTATUS VBoxMRxFinalizeNetRoot(IN PMRX_NET_ROOT pNetRoot,
                                IN PBOOLEAN ForceDisconnect)
{
    PMRX_VBOX_NETROOT_EXTENSION pNetRootExtension = VBoxMRxGetNetRootExtension(pNetRoot);

    Log(("VBOXSF: MRxFinalizeNetRoot: NET_ROOT %p\n", pNetRoot));

    if (pNetRootExtension->phgcmClient)
    {
        int vboxRC = vboxCallUnmapFolder(pNetRootExtension->phgcmClient, &pNetRootExtension->map);
        if (vboxRC != VINF_SUCCESS)
            Log(("VBOXSF: MRxFinalizeVNetRoot: vboxCallUnmapFolder failed with %d\n",
                 vboxRC));
        pNetRootExtension->phgcmClient = NULL;
    }

    return STATUS_SUCCESS;
}

VOID VBoxMRxExtractNetRootName(IN PUNICODE_STRING FilePathName,
                               IN PMRX_SRV_CALL SrvCall,
                               OUT PUNICODE_STRING NetRootName,
                               OUT PUNICODE_STRING RestOfName OPTIONAL)
{
    int cChars = FilePathName->Length/sizeof(WCHAR);
    int iNetRoot;
    int i;

    /* Split "\vboxsvr\share\path" to
     * NetRootName = "\share"
     * RestOfName = "\path"
     *
     * Note that SrvCall->pSrvCallName contains "\vboxsrv".
     */

    Log(("VBOXSF: MRxExtractNetRootName: [%.*ls], RestOfName %p\n",
         FilePathName->Length/sizeof(WCHAR), FilePathName->Buffer, RestOfName));

    /* Assume that the server prefix is OK.
     * iNetRoot points to the first char after server name, the delimiter.
     */
    iNetRoot = SrvCall->pSrvCallName->Length/sizeof(WCHAR);

    /* Find the NetRoot length: end of FilePathName or the next delimiter. */
    i = iNetRoot;
    while (i < cChars)
    {
        if (   FilePathName->Buffer[i] == L'\\'
            && i > iNetRoot)
        {
            break;
        }
        i++;
    }

    Log(("VBOXSF: MRxExtractNetRootName: cChars %d, iNetRoot %d, iRest %d\n",
         cChars, iNetRoot, i));

    NetRootName->Buffer = &FilePathName->Buffer[iNetRoot];
    NetRootName->Length = (USHORT)((i - iNetRoot) * sizeof(WCHAR));
    NetRootName->MaximumLength = NetRootName->Length;

    Log(("VBOXSF: MRxExtractNetRootName: Srv = %.*ls, Root = %.*ls\n",
         SrvCall->pSrvCallName->Length / sizeof(WCHAR), SrvCall->pSrvCallName->Buffer,
         NetRootName->Length / sizeof(WCHAR), NetRootName->Buffer));

    if (RestOfName)
    {
        RestOfName->Buffer = &FilePathName->Buffer[i];
        RestOfName->Length = (USHORT)((cChars - i) * sizeof(WCHAR));
        RestOfName->MaximumLength = RestOfName->Length;

        Log(("VBOXSF: MRxExtractNetRootName: Rest = %.*ls\n",
             RestOfName->Length / sizeof(WCHAR), RestOfName->Buffer));
    }
}

static VOID vbsfExecuteCreateSrvCall(PMRX_SRVCALL_CALLBACK_CONTEXT pCallbackContext)
{
    NTSTATUS Status;
    PWCHAR pSrvName = 0;
    BOOLEAN Verifier;

    PMRX_SRVCALL_CALLBACK_CONTEXT SCCBC = pCallbackContext;
    PMRX_SRVCALLDOWN_STRUCTURE SrvCalldownStructure = (PMRX_SRVCALLDOWN_STRUCTURE)(SCCBC->SrvCalldownStructure);
    PMRX_SRV_CALL pSrvCall = SrvCalldownStructure->SrvCall;

    /* Validate the server name with the test name of 'vboxsvr'. */
    Log(("VBOXSF: vbsfExecuteCreateSrvCall: Connection Name %.*ls Length: %d, pSrvCall = %p\n",
         pSrvCall->pSrvCallName->Length / sizeof(WCHAR), pSrvCall->pSrvCallName->Buffer, pSrvCall->pSrvCallName->Length, pSrvCall));

    if (pSrvCall->pPrincipalName && pSrvCall->pPrincipalName->Length)
    {
        Log(("VBOXSF: vbsfExecuteCreateSrvCall: Principal name = %.*ls\n",
             pSrvCall->pPrincipalName->Length / sizeof(WCHAR), pSrvCall->pPrincipalName->Buffer));
    }

    if (pSrvCall->pDomainName && pSrvCall->pDomainName->Length)
    {
        Log(("VBOXSF: vbsfExecuteCreateSrvCall: Domain name = %.*ls\n",
             pSrvCall->pDomainName->Length / sizeof(WCHAR), pSrvCall->pDomainName->Buffer));
    }

    if (pSrvCall->pSrvCallName->Length >= 14)
    {
        pSrvName = pSrvCall->pSrvCallName->Buffer;

        Verifier = (pSrvName[0] == L'\\');
        Verifier &= (pSrvName[1] == L'V') || (pSrvName[1] == L'v');
        Verifier &= (pSrvName[2] == L'B') || (pSrvName[2] == L'b');
        Verifier &= (pSrvName[3] == L'O') || (pSrvName[3] == L'o');
        Verifier &= (pSrvName[4] == L'X') || (pSrvName[4] == L'x');
        Verifier &= (pSrvName[5] == L'S') || (pSrvName[5] == L's');
        /* Both vboxsvr & vboxsrv are now accepted */
        if ((pSrvName[6] == L'V') || (pSrvName[6] == L'v'))
        {
            Verifier &= (pSrvName[6] == L'V') || (pSrvName[6] == L'v');
            Verifier &= (pSrvName[7] == L'R') || (pSrvName[7] == L'r');
        }
        else
        {
            Verifier &= (pSrvName[6] == L'R') || (pSrvName[6] == L'r');
            Verifier &= (pSrvName[7] == L'V') || (pSrvName[7] == L'v');
        }
        Verifier &= (pSrvName[8] == L'\\') || (pSrvName[8] == 0);
    }
    else
        Verifier = FALSE;

    if (Verifier)
    {
        Log(("VBOXSF: vbsfExecuteCreateSrvCall: Verifier succeeded!\n"));
        Status = STATUS_SUCCESS;
    }
    else
    {
        Log(("VBOXSF: vbsfExecuteCreateSrvCall: Verifier failed!\n"));
        Status = STATUS_BAD_NETWORK_PATH;
    }

    SCCBC->Status = Status;
    SrvCalldownStructure->CallBack(SCCBC);
}

NTSTATUS VBoxMRxCreateSrvCall(PMRX_SRV_CALL pSrvCall,
                              PMRX_SRVCALL_CALLBACK_CONTEXT pCallbackContext)
{
    PMRX_SRVCALLDOWN_STRUCTURE SrvCalldownStructure = (PMRX_SRVCALLDOWN_STRUCTURE)(pCallbackContext->SrvCalldownStructure);

    Log(("VBOXSF: MRxCreateSrvCall: %p.\n", pSrvCall));

    if (IoGetCurrentProcess() == RxGetRDBSSProcess())
    {
        Log(("VBOXSF: MRxCreateSrvCall: Called in context of RDBSS process\n"));

        vbsfExecuteCreateSrvCall(pCallbackContext);
    }
    else
    {
        NTSTATUS Status;

        Log(("VBOXSF: MRxCreateSrvCall: Dispatching to worker thread\n"));

        Status = RxDispatchToWorkerThread(VBoxMRxDeviceObject, DelayedWorkQueue,
                                          (PWORKER_THREAD_ROUTINE)vbsfExecuteCreateSrvCall,
                                          pCallbackContext);

        if (Status == STATUS_SUCCESS)
            Log(("VBOXSF: MRxCreateSrvCall: queued\n"));
        else
        {
            pCallbackContext->Status = Status;
            SrvCalldownStructure->CallBack(pCallbackContext);
        }
    }

    /* RDBSS expect this. */
    return STATUS_PENDING;
}

NTSTATUS VBoxMRxFinalizeSrvCall (PMRX_SRV_CALL pSrvCall,
                                 BOOLEAN Force)
{
    Log(("VBOXSF: MRxFinalizeSrvCall %p, ctx = %p.\n", pSrvCall, pSrvCall->Context));

    pSrvCall->Context = NULL;

    return STATUS_SUCCESS;
}

NTSTATUS VBoxMRxSrvCallWinnerNotify(IN PMRX_SRV_CALL pSrvCall,
                                    IN BOOLEAN ThisMinirdrIsTheWinner,
                                    IN OUT PVOID pSrvCallContext)
{
    NTSTATUS Status = STATUS_SUCCESS;

    Log(("VBOXSF: MRxSrvCallWinnerNotify: pSrvCall %p, pSrvCall->Ctx %p, winner %d, context %p\n",
         pSrvCall, pSrvCall->Context, ThisMinirdrIsTheWinner, pSrvCallContext));

    /* Set it to not NULL. */
    pSrvCall->Context = pSrvCall;

    return STATUS_SUCCESS;
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M3.1,20.9V19.25H20.9V20.9ZM3.1,4.75V3.1H20.9V4.75Z"/>
</vector>


text:
<?php

namespace spec\PHPCR\Shell\Transport\Transport;

use PhpSpec\ObjectBehavior;

class JackrabbitSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType('PHPCR\Shell\Transport\Transport\Jackrabbit');
    }
}


text:
module Roxx
  module Dsl
    class TrackCommand < Command
      def initialize track, library, logger
        @library = library
        @track = track
        @logger = logger
      end

      def sound(name, options = {})
        offset = options.delete(:offset) || 0
        duration = options.delete(:duration) || nil

        raise_argument_condition_when !options.keys.empty?,
          :and_display => "unknown options specified [#{options.keys * ','}]"

        @track.add_sound(@library.fetch(name), offset, duration)

      rescue Roxx::Library::SoundNotFound
        @logger.log "cannot find sound [#{name}] in library"
        raise
      end

      def volume level
        @track.volume = level
      end
    end
  end
end


text:
using namespace std;

const int WIDTH = 100, HEIGHT = 70;
const int INI_WIDTH = 60, INI_HEIGHT = 30;
const int LIMIT = 80;
const int SLEEP_TIME = 400 * 1000;  // 0.2 seconds in microseconds.

// If an occupied cell has zero or one neighbor, it dies of loneliness.
// If it has more than three neighbors, it dies of overcrowding.
void death(char world[][WIDTH], int height, int width, int livingNeighbors);
// If an empty cell has exactly three occupied neighbor cells,
// there is a birth of a new cell to replace the empty cell.
void birth(char world[][WIDTH], int height, int width, int livingNeighbors);

bool inRange(int height, int width, int x, int y);
bool isAlive(char world[][WIDTH], int height, int width, int x, int y);
int countLivingNeighbors(char world[][WIDTH], int height, int width);
void nextGeneration(char world[][WIDTH]);
void copyWorlds(char oldWorld[][WIDTH], char newWorld[][WIDTH]);
void printWorld(char world[][WIDTH]);
void initializeWorld(char world[][WIDTH]);

int main() {
    char world[HEIGHT][WIDTH];
    // Randomly assign life or death to the world.
    initializeWorld(world);
    printWorld(world);

    for (int i = 0; i < LIMIT; i++) {
        usleep(SLEEP_TIME);
        nextGeneration(world);
        printWorld(world);
    }

    return 0;
}

void nextGeneration(char world[][WIDTH]) {
    char newWorld[HEIGHT][WIDTH];
    for (int height = 0; height < HEIGHT; height++) {
        for (int width = 0; width < WIDTH; width++) {
            int livingNeighbors = countLivingNeighbors(world, height, width);
            if (world[height][width] == 'X') {
                // Determine if cell dies or not.
                death(newWorld, height, width, livingNeighbors);
            } else if (world[height][width] == ' ') {
                // Determine whether cell is born or not.
                birth(newWorld, height, width, livingNeighbors);
            } else {
                cerr << "There is an error in nextGeneration() \n";
            }
        }
        // cout << endl;
    }
    copyWorlds(world, newWorld);
}

bool inRange(int height, int width, int x, int y) {
    bool biggerZero = ((height + y) >= 0) && ((width + x) >= 0);
    bool smallerMax = ((height + y) < HEIGHT) && ((width + x) < WIDTH);
    return (biggerZero && smallerMax);
}

bool isAlive(char world[][WIDTH], int height, int width, int x, int y) {
    return (world[height + y][width + x] == 'X');
}

int countLivingNeighbors(char world[][WIDTH], int height, int width) {
    int livingNeighbors = 0;
    for (int x = -1; x <= 1; x++) {
        for (int y = -1; y <= 1; y++) {
            if (inRange(height, width, x, y)) {
                if (!((x == 0) && (y == 0))) {
                    if (isAlive(world, height, width, x, y)) {
                        livingNeighbors++;
                    }
                }
            }
        }
    }
    // cout << livingNeighbors;
    return livingNeighbors;
}

// If an occupied cell has zero or one neighbor, it dies of loneliness.
// If it has more than three neighbors, it dies of overcrowding.
void death(char world[][WIDTH], int height, int width, int livingNeighbors) {
    if (livingNeighbors == 0 || livingNeighbors == 1 || livingNeighbors > 3) {
        world[height][width] = ' ';
    } else {
        world[height][width] = 'X';
    }
    // cout << world[height][width];
}

// If an empty cell has exactly three occupied neighbor cells,
// there is a birth of a new cell to replace the empty cell.
void birth(char world[][WIDTH], int height, int width, int livingNeighbors) {
    if (livingNeighbors == 3) {
        world[height][width] = 'X';
    } else {
        world[height][width] = ' ';
    }
    // cout << world[height][width];
}

void printWorld(char world[][WIDTH]) {
    for (int width = -1; width <= WIDTH; width++) {
        cout << "-";
    }
    cout << endl;
    for (int i = 0; i < HEIGHT; i++) {
        cout << "|";
        for (int j = 0; j < WIDTH; j++) {
            cout << world[i][j];
        }
        cout << "|";
    cout << endl;
    }
    for (int width = -1; width <= WIDTH; width++) {
        cout << "-";
    }
    cout << "\n\n";
}
 void copyWorlds(char oldWorld[][WIDTH], char newWorld[][WIDTH]) {
    for (int height = 0; height < HEIGHT; height++) {
        for (int width = 0; width < WIDTH; width++) {
            oldWorld[height][width] = newWorld[height][width];
        }
    }
}

void initializeWorld(char world[][WIDTH]) {
    // Randomly assign life or death to the world.
    srand(time(NULL));
    for (int height = 0; height < HEIGHT; height++) {
        for (int width = 0; width < WIDTH; width++) {
            int lifeInt = 0;
            if ((height <= INI_HEIGHT) && (width <= INI_WIDTH)) {
                lifeInt = rand() % 2;
            }
            if (lifeInt == 1) {
                world[height][width] = 'X';
            } else {
                world[height][width] = ' ';
            }
        }
    }
}


text:
/*!
 * \file
 * \brief VkSwapchain Tests
 *//*--------------------------------------------------------------------*/

#include "vktWsiSwapchainTests.hpp"

#include "vktTestCaseUtil.hpp"
#include "vktTestGroupUtil.hpp"

#include "vkDefs.hpp"
#include "vkPlatform.hpp"
#include "vkStrUtil.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkDeviceUtil.hpp"
#include "vkPrograms.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkWsiPlatform.hpp"
#include "vkWsiUtil.hpp"
#include "vkAllocationCallbackUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"

#include "tcuTestLog.hpp"
#include "tcuFormatUtil.hpp"
#include "tcuPlatform.hpp"
#include "tcuResultCollector.hpp"

#include "deUniquePtr.hpp"
#include "deStringUtil.hpp"
#include "deArrayUtil.hpp"
#include "deSharedPtr.hpp"

#include <limits>

namespace vkt
{
namespace wsi
{

namespace
{

using namespace vk;
using namespace vk::wsi;

using tcu::TestLog;
using tcu::Maybe;
using tcu::UVec2;

using de::MovePtr;
using de::UniquePtr;

using std::string;
using std::vector;

typedef vector<VkExtensionProperties> Extensions;

void checkAllSupported (const Extensions& supportedExtensions, const vector<string>& requiredExtensions)
{
	for (vector<string>::const_iterator requiredExtName = requiredExtensions.begin();
		 requiredExtName != requiredExtensions.end();
		 ++requiredExtName)
	{
		if (!isExtensionSupported(supportedExtensions, RequiredExtension(*requiredExtName)))
			TCU_THROW(NotSupportedError, (*requiredExtName + " is not supported").c_str());
	}
}

Move<VkInstance> createInstanceWithWsi (const PlatformInterface&		vkp,
										deUint32						version,
										const Extensions&				supportedExtensions,
										Type							wsiType,
										const VkAllocationCallbacks*	pAllocator	= DE_NULL)
{
	vector<string>	extensions;

	extensions.push_back("VK_KHR_surface");
	extensions.push_back(getExtensionName(wsiType));

	// VK_EXT_swapchain_colorspace adds new surface formats. Driver can enumerate
	// the formats regardless of whether VK_EXT_swapchain_colorspace was enabled,
	// but using them without enabling the extension is not allowed. Thus we have
	// two options:
	//
	// 1) Filter out non-core formats to stay within valid usage.
	//
	// 2) Enable VK_EXT_swapchain colorspace if advertised by the driver.
	//
	// We opt for (2) as it provides basic coverage for the extension as a bonus.
	if (isExtensionSupported(supportedExtensions, RequiredExtension("VK_EXT_swapchain_colorspace")))
		extensions.push_back("VK_EXT_swapchain_colorspace");

	checkAllSupported(supportedExtensions, extensions);

	return createDefaultInstance(vkp, version, vector<string>(), extensions, pAllocator);
}

VkPhysicalDeviceFeatures getDeviceFeaturesForWsi (void)
{
	VkPhysicalDeviceFeatures features;
	deMemset(&features, 0, sizeof(features));
	return features;
}

Move<VkDevice> createDeviceWithWsi (const vk::PlatformInterface&	vkp,
									vk::VkInstance					instance,
									const InstanceInterface&		vki,
									VkPhysicalDevice				physicalDevice,
									const Extensions&				supportedExtensions,
									const deUint32					queueFamilyIndex,
									const VkAllocationCallbacks*	pAllocator = DE_NULL)
{
	const float						queuePriorities[]	= { 1.0f };
	const VkDeviceQueueCreateInfo	queueInfos[]		=
	{
		{
			VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
			DE_NULL,
			(VkDeviceQueueCreateFlags)0,
			queueFamilyIndex,
			DE_LENGTH_OF_ARRAY(queuePriorities),
			&queuePriorities[0]
		}
	};
	const VkPhysicalDeviceFeatures	features		= getDeviceFeaturesForWsi();
	vector<const char*>		extensions;

	if (!isExtensionSupported(supportedExtensions, RequiredExtension("VK_KHR_swapchain")))
		TCU_THROW(NotSupportedError, (string(extensions[0]) + " is not supported").c_str());
	extensions.push_back("VK_KHR_swapchain");

	if (isExtensionSupported(supportedExtensions, RequiredExtension("VK_EXT_hdr_metadata")))
		extensions.push_back("VK_EXT_hdr_metadata");

	const VkDeviceCreateInfo		deviceParams	=
	{
		VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
		DE_NULL,
		(VkDeviceCreateFlags)0,
		DE_LENGTH_OF_ARRAY(queueInfos),
		&queueInfos[0],
		0u,									// enabledLayerCount
		DE_NULL,							// ppEnabledLayerNames
		(deUint32)extensions.size(),
		extensions.empty() ? DE_NULL : &extensions[0],
		&features
	};

	return createDevice(vkp, instance, vki, physicalDevice, &deviceParams, pAllocator);
}

deUint32 getNumQueueFamilyIndices (const InstanceInterface& vki, VkPhysicalDevice physicalDevice)
{
	deUint32	numFamilies		= 0;

	vki.getPhysicalDeviceQueueFamilyProperties(physicalDevice, &numFamilies, DE_NULL);

	return numFamilies;
}

vector<deUint32> getSupportedQueueFamilyIndices (const InstanceInterface& vki, VkPhysicalDevice physicalDevice, VkSurfaceKHR surface)
{
	const deUint32		numTotalFamilyIndices	= getNumQueueFamilyIndices(vki, physicalDevice);
	vector<deUint32>	supportedFamilyIndices;

	for (deUint32 queueFamilyNdx = 0; queueFamilyNdx < numTotalFamilyIndices; ++queueFamilyNdx)
	{
		if (getPhysicalDeviceSurfaceSupport(vki, physicalDevice, queueFamilyNdx, surface) != VK_FALSE)
			supportedFamilyIndices.push_back(queueFamilyNdx);
	}

	return supportedFamilyIndices;
}

deUint32 chooseQueueFamilyIndex (const InstanceInterface& vki, VkPhysicalDevice physicalDevice, VkSurfaceKHR surface)
{
	const vector<deUint32>	supportedFamilyIndices	= getSupportedQueueFamilyIndices(vki, physicalDevice, surface);

	if (supportedFamilyIndices.empty())
		TCU_THROW(NotSupportedError, "Device doesn't support presentation");

	return supportedFamilyIndices[0];
}

struct InstanceHelper
{
	const vector<VkExtensionProperties>	supportedExtensions;
	const Unique<VkInstance>			instance;
	const InstanceDriver				vki;

	InstanceHelper (Context& context, Type wsiType, const VkAllocationCallbacks* pAllocator = DE_NULL)
		: supportedExtensions	(enumerateInstanceExtensionProperties(context.getPlatformInterface(),
																	  DE_NULL))
		, instance				(createInstanceWithWsi(context.getPlatformInterface(),
													   context.getUsedApiVersion(),
													   supportedExtensions,
													   wsiType,
													   pAllocator))
		, vki					(context.getPlatformInterface(), *instance)
	{}
};

struct DeviceHelper
{
	const VkPhysicalDevice	physicalDevice;
	const deUint32			queueFamilyIndex;
	const Unique<VkDevice>	device;
	const DeviceDriver		vkd;
	const VkQueue			queue;

	DeviceHelper (Context&						context,
				  const InstanceInterface&		vki,
				  VkInstance					instance,
				  VkSurfaceKHR					surface,
				  const VkAllocationCallbacks*	pAllocator = DE_NULL)
		: physicalDevice	(chooseDevice(vki, instance, context.getTestContext().getCommandLine()))
		, queueFamilyIndex	(chooseQueueFamilyIndex(vki, physicalDevice, surface))
		, device			(createDeviceWithWsi(context.getPlatformInterface(),
												 instance,
												 vki,
												 physicalDevice,
												 enumerateDeviceExtensionProperties(vki, physicalDevice, DE_NULL),
												 queueFamilyIndex,
												 pAllocator))
		, vkd				(context.getPlatformInterface(), instance, *device)
		, queue				(getDeviceQueue(vkd, *device, queueFamilyIndex, 0))
	{
	}
};

MovePtr<Display> createDisplay (const vk::Platform&	platform,
								const Extensions&	supportedExtensions,
								Type				wsiType)
{
	try
	{
		return MovePtr<Display>(platform.createWsiDisplay(wsiType));
	}
	catch (const tcu::NotSupportedError& e)
	{
		if (isExtensionSupported(supportedExtensions, RequiredExtension(getExtensionName(wsiType))) &&
		    platform.hasDisplay(wsiType))
		{
			// If VK_KHR_{platform}_surface was supported, vk::Platform implementation
			// must support creating native display & window for that WSI type.
			throw tcu::TestError(e.getMessage());
		}
		else
			throw;
	}
}

MovePtr<Window> createWindow (const Display& display, const Maybe<UVec2>& initialSize)
{
	try
	{
		return MovePtr<Window>(display.createWindow(initialSize));
	}
	catch (const tcu::NotSupportedError& e)
	{
		// See createDisplay - assuming that wsi::Display was supported platform port
		// should also support creating a window.
		throw tcu::TestError(e.getMessage());
	}
}

struct NativeObjects
{
	const UniquePtr<Display>	display;
	const UniquePtr<Window>		window;

	NativeObjects (Context&				context,
				   const Extensions&	supportedExtensions,
				   Type					wsiType,
				   const Maybe<UVec2>&	initialWindowSize = tcu::nothing<UVec2>())
		: display	(createDisplay(context.getTestContext().getPlatform().getVulkanPlatform(), supportedExtensions, wsiType))
		, window	(createWindow(*display, initialWindowSize))
	{}
};

enum TestDimension
{
	TEST_DIMENSION_MIN_IMAGE_COUNT = 0,	//!< Test all supported image counts
	TEST_DIMENSION_IMAGE_FORMAT,		//!< Test all supported formats
	TEST_DIMENSION_IMAGE_EXTENT,		//!< Test various (supported) extents
	TEST_DIMENSION_IMAGE_ARRAY_LAYERS,
	TEST_DIMENSION_IMAGE_USAGE,
	TEST_DIMENSION_IMAGE_SHARING_MODE,
	TEST_DIMENSION_PRE_TRANSFORM,
	TEST_DIMENSION_COMPOSITE_ALPHA,
	TEST_DIMENSION_PRESENT_MODE,
	TEST_DIMENSION_CLIPPED,

	TEST_DIMENSION_LAST
};

struct TestParameters
{
	Type			wsiType;
	TestDimension	dimension;

	TestParameters (Type wsiType_, TestDimension dimension_)
		: wsiType	(wsiType_)
		, dimension	(dimension_)
	{}

	TestParameters (void)
		: wsiType	(TYPE_LAST)
		, dimension	(TEST_DIMENSION_LAST)
	{}
};

struct GroupParameters
{
	typedef FunctionInstance1<TestParameters>::Function	Function;

	Type		wsiType;
	Function	function;

	GroupParameters (Type wsiType_, Function function_)
		: wsiType	(wsiType_)
		, function	(function_)
	{}

	GroupParameters (void)
		: wsiType	(TYPE_LAST)
		, function	((Function)DE_NULL)
	{}
};

VkSwapchainCreateInfoKHR getBasicSwapchainParameters (Type						wsiType,
													  const InstanceInterface&	vki,
													  VkPhysicalDevice			physicalDevice,
													  VkSurfaceKHR				surface,
													  VkSurfaceFormatKHR		surfaceFormat,
													  const tcu::UVec2&			desiredSize,
													  deUint32					desiredImageCount)
{
	const VkSurfaceCapabilitiesKHR		capabilities		= getPhysicalDeviceSurfaceCapabilities(vki,
																								   physicalDevice,
																								   surface);
	const PlatformProperties&			platformProperties	= getPlatformProperties(wsiType);
	const VkSurfaceTransformFlagBitsKHR transform			= (capabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) ? VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR : capabilities.currentTransform;
	const VkSwapchainCreateInfoKHR		parameters			=
	{
		VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
		DE_NULL,
		(VkSwapchainCreateFlagsKHR)0,
		surface,
		de::clamp(desiredImageCount, capabilities.minImageCount, capabilities.maxImageCount > 0 ? capabilities.maxImageCount : capabilities.minImageCount + desiredImageCount),
		surfaceFormat.format,
		surfaceFormat.colorSpace,
		(platformProperties.swapchainExtent == PlatformProperties::SWAPCHAIN_EXTENT_MUST_MATCH_WINDOW_SIZE
			? capabilities.currentExtent : vk::makeExtent2D(desiredSize.x(), desiredSize.y())),
		1u,									// imageArrayLayers
		VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
		VK_SHARING_MODE_EXCLUSIVE,
		0u,
		(const deUint32*)DE_NULL,
		transform,
		VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
		VK_PRESENT_MODE_FIFO_KHR,
		VK_FALSE,							// clipped
		(VkSwapchainKHR)0					// oldSwapchain
	};

	return parameters;
}

typedef de::SharedPtr<Unique<VkImageView> >		ImageViewSp;
typedef de::SharedPtr<Unique<VkFramebuffer> >	FramebufferSp;

class TriangleRenderer
{
public:
									TriangleRenderer	(const DeviceInterface&		vkd,
														 const VkDevice				device,
														 Allocator&					allocator,
														 const BinaryCollection&	binaryRegistry,
														 const vector<VkImage>		swapchainImages,
														 const VkFormat				framebufferFormat,
														 const UVec2&				renderSize);
									~TriangleRenderer	(void);

	void							recordFrame			(VkCommandBuffer			cmdBuffer,
														 deUint32					imageNdx,
														 deUint32					frameNdx) const;

	static void						getPrograms			(SourceCollections& dst);

private:
	static Move<VkRenderPass>		createRenderPass	(const DeviceInterface&		vkd,
														 const VkDevice				device,
														 const VkFormat				colorAttachmentFormat);
	static Move<VkPipelineLayout>	createPipelineLayout(const DeviceInterface&		vkd,
														 VkDevice					device);
	static Move<VkPipeline>			createPipeline		(const DeviceInterface&		vkd,
														 const VkDevice				device,
														 const VkRenderPass			renderPass,
														 const VkPipelineLayout		pipelineLayout,
														 const BinaryCollection&	binaryCollection,
														 const UVec2&				renderSize);

	static Move<VkImageView>		createAttachmentView(const DeviceInterface&		vkd,
														 const VkDevice				device,
														 const VkImage				image,
														 const VkFormat				format);
	static Move<VkFramebuffer>		createFramebuffer	(const DeviceInterface&		vkd,
														 const VkDevice				device,
														 const VkRenderPass			renderPass,
														 const VkImageView			colorAttachment,
														 const UVec2&				renderSize);

	static Move<VkBuffer>			createBuffer		(const DeviceInterface&		vkd,
														 VkDevice					device,
														 VkDeviceSize				size,
														 VkBufferUsageFlags			usage);

	const DeviceInterface&			m_vkd;

	const vector<VkImage>			m_swapchainImages;
	const tcu::UVec2				m_renderSize;

	const Unique<VkRenderPass>		m_renderPass;
	const Unique<VkPipelineLayout>	m_pipelineLayout;
	const Unique<VkPipeline>		m_pipeline;

	const Unique<VkBuffer>			m_vertexBuffer;
	const UniquePtr<Allocation>		m_vertexBufferMemory;

	vector<ImageViewSp>				m_attachmentViews;
	vector<FramebufferSp>			m_framebuffers;
};

Move<VkRenderPass> TriangleRenderer::createRenderPass (const DeviceInterface&	vkd,
													   const VkDevice			device,
													   const VkFormat			colorAttachmentFormat)
{
	const VkAttachmentDescription	colorAttDesc		=
	{
		(VkAttachmentDescriptionFlags)0,
		colorAttachmentFormat,
		VK_SAMPLE_COUNT_1_BIT,
		VK_ATTACHMENT_LOAD_OP_CLEAR,
		VK_ATTACHMENT_STORE_OP_STORE,
		VK_ATTACHMENT_LOAD_OP_DONT_CARE,
		VK_ATTACHMENT_STORE_OP_DONT_CARE,
		VK_IMAGE_LAYOUT_UNDEFINED,
		VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
	};
	const VkAttachmentReference		colorAttRef			=
	{
		0u,
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
	};
	const VkSubpassDescription		subpassDesc			=
	{
		(VkSubpassDescriptionFlags)0u,
		VK_PIPELINE_BIND_POINT_GRAPHICS,
		0u,							// inputAttachmentCount
		DE_NULL,					// pInputAttachments
		1u,							// colorAttachmentCount
		&colorAttRef,				// pColorAttachments
		DE_NULL,					// pResolveAttachments
		DE_NULL,					// depthStencilAttachment
		0u,							// preserveAttachmentCount
		DE_NULL,					// pPreserveAttachments
	};
	const VkSubpassDependency		dependencies[]		=
	{
		{
			VK_SUBPASS_EXTERNAL,	// srcSubpass
			0u,						// dstSubpass
			VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
			VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
			VK_ACCESS_MEMORY_READ_BIT,
			(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT|
			 VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT),
			VK_DEPENDENCY_BY_REGION_BIT
		},
		{
			0u,						// srcSubpass
			VK_SUBPASS_EXTERNAL,	// dstSubpass
			VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
			VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
			(VK_ACCESS_COLOR_ATTACHMENT_READ_BIT|
			 VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT),
			VK_ACCESS_MEMORY_READ_BIT,
			VK_DEPENDENCY_BY_REGION_BIT
		},
	};
	const VkRenderPassCreateInfo	renderPassParams	=
	{
		VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
		DE_NULL,
		(VkRenderPassCreateFlags)0,
		1u,
		&colorAttDesc,
		1u,
		&subpassDesc,
		DE_LENGTH_OF_ARRAY(dependencies),
		dependencies,
	};

	return vk::createRenderPass(vkd, device, &renderPassParams);
}

Move<VkPipelineLayout> TriangleRenderer::createPipelineLayout (const DeviceInterface&	vkd,
															   const VkDevice			device)
{
	const VkPushConstantRange						pushConstantRange		=
	{
		VK_SHADER_STAGE_VERTEX_BIT,
		0u,											// offset
		(deUint32)sizeof(deUint32),					// size
	};
	const VkPipelineLayoutCreateInfo				pipelineLayoutParams	=
	{
		VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
		DE_NULL,
		(vk::VkPipelineLayoutCreateFlags)0,
		0u,											// setLayoutCount
		DE_NULL,									// pSetLayouts
		1u,
		&pushConstantRange,
	};

	return vk::createPipelineLayout(vkd, device, &pipelineLayoutParams);
}

Move<VkPipeline> TriangleRenderer::createPipeline (const DeviceInterface&	vkd,
												   const VkDevice			device,
												   const VkRenderPass		renderPass,
												   const VkPipelineLayout	pipelineLayout,
												   const BinaryCollection&	binaryCollection,
												   const UVec2&				renderSize)
{
	// \note VkShaderModules are fully consumed by vkCreateGraphicsPipelines()
	//		 and can be deleted immediately following that call.
	const Unique<VkShaderModule>					vertShaderModule		(createShaderModule(vkd, device, binaryCollection.get("tri-vert"), 0));
	const Unique<VkShaderModule>					fragShaderModule		(createShaderModule(vkd, device, binaryCollection.get("tri-frag"), 0));
	const std::vector<VkViewport>					viewports				(1, makeViewport(renderSize));
	const std::vector<VkRect2D>						scissors				(1, makeRect2D(renderSize));

	return vk::makeGraphicsPipeline(vkd,				// const DeviceInterface&            vk
									device,				// const VkDevice                    device
									pipelineLayout,		// const VkPipelineLayout            pipelineLayout
									*vertShaderModule,	// const VkShaderModule              vertexShaderModule
									DE_NULL,			// const VkShaderModule              tessellationControlShaderModule
									DE_NULL,			// const VkShaderModule              tessellationEvalShaderModule
									DE_NULL,			// const VkShaderModule              geometryShaderModule
									*fragShaderModule,	// const VkShaderModule              fragmentShaderModule
									renderPass,			// const VkRenderPass                renderPass
									viewports,			// const std::vector<VkViewport>&    viewports
									scissors);			// const std::vector<VkRect2D>&      scissors
}

Move<VkImageView> TriangleRenderer::createAttachmentView (const DeviceInterface&	vkd,
														  const VkDevice			device,
														  const VkImage				image,
														  const VkFormat			format)
{
	const VkImageViewCreateInfo		viewParams	=
	{
		VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
		DE_NULL,
		(VkImageViewCreateFlags)0,
		image,
		VK_IMAGE_VIEW_TYPE_2D,
		format,
		vk::makeComponentMappingRGBA(),
		{
			VK_IMAGE_ASPECT_COLOR_BIT,
			0u,						// baseMipLevel
			1u,						// levelCount
			0u,						// baseArrayLayer
			1u,						// layerCount
		},
	};

	return vk::createImageView(vkd, device, &viewParams);
}

Move<VkFramebuffer> TriangleRenderer::createFramebuffer	(const DeviceInterface&		vkd,
														 const VkDevice				device,
														 const VkRenderPass			renderPass,
														 const VkImageView			colorAttachment,
														 const UVec2&				renderSize)
{
	const VkFramebufferCreateInfo	framebufferParams	=
	{
		VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
		DE_NULL,
		(VkFramebufferCreateFlags)0,
		renderPass,
		1u,
		&colorAttachment,
		renderSize.x(),
		renderSize.y(),
		1u,							// layers
	};

	return vk::createFramebuffer(vkd, device, &framebufferParams);
}

Move<VkBuffer> TriangleRenderer::createBuffer (const DeviceInterface&	vkd,
											   VkDevice					device,
											   VkDeviceSize				size,
											   VkBufferUsageFlags		usage)
{
	const VkBufferCreateInfo	bufferParams	=
	{
		VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
		DE_NULL,
		(VkBufferCreateFlags)0,
		size,
		usage,
		VK_SHARING_MODE_EXCLUSIVE,
		0,
		DE_NULL
	};

	return vk::createBuffer(vkd, device, &bufferParams);
}

TriangleRenderer::TriangleRenderer (const DeviceInterface&	vkd,
									const VkDevice			device,
									Allocator&				allocator,
									const BinaryCollection&	binaryRegistry,
									const vector<VkImage>	swapchainImages,
									const VkFormat			framebufferFormat,
									const UVec2&			renderSize)
	: m_vkd					(vkd)
	, m_swapchainImages		(swapchainImages)
	, m_renderSize			(renderSize)
	, m_renderPass			(createRenderPass(vkd, device, framebufferFormat))
	, m_pipelineLayout		(createPipelineLayout(vkd, device))
	, m_pipeline			(createPipeline(vkd, device, *m_renderPass, *m_pipelineLayout, binaryRegistry, renderSize))
	, m_vertexBuffer		(createBuffer(vkd, device, (VkDeviceSize)(sizeof(float)*4*3), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT))
	, m_vertexBufferMemory	(allocator.allocate(getBufferMemoryRequirements(vkd, device, *m_vertexBuffer),
							 MemoryRequirement::HostVisible))
{
	m_attachmentViews.resize(swapchainImages.size());
	m_framebuffers.resize(swapchainImages.size());

	for (size_t imageNdx = 0; imageNdx < swapchainImages.size(); ++imageNdx)
	{
		m_attachmentViews[imageNdx]	= ImageViewSp(new Unique<VkImageView>(createAttachmentView(vkd, device, swapchainImages[imageNdx], framebufferFormat)));
		m_framebuffers[imageNdx]	= FramebufferSp(new Unique<VkFramebuffer>(createFramebuffer(vkd, device, *m_renderPass, **m_attachmentViews[imageNdx], renderSize)));
	}

	VK_CHECK(vkd.bindBufferMemory(device, *m_vertexBuffer, m_vertexBufferMemory->getMemory(), m_vertexBufferMemory->getOffset()));

	{
		const VkMappedMemoryRange	memRange	=
		{
			VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
			DE_NULL,
			m_vertexBufferMemory->getMemory(),
			m_vertexBufferMemory->getOffset(),
			VK_WHOLE_SIZE
		};
		const tcu::Vec4				vertices[]	=
		{
			tcu::Vec4(-0.5f, -0.5f, 0.0f, 1.0f),
			tcu::Vec4(+0.5f, -0.5f, 0.0f, 1.0f),
			tcu::Vec4( 0.0f, +0.5f, 0.0f, 1.0f)
		};
		DE_STATIC_ASSERT(sizeof(vertices) == sizeof(float)*4*3);

		deMemcpy(m_vertexBufferMemory->getHostPtr(), &vertices[0], sizeof(vertices));
		VK_CHECK(vkd.flushMappedMemoryRanges(device, 1u, &memRange));
	}
}

TriangleRenderer::~TriangleRenderer (void)
{
}

void TriangleRenderer::recordFrame (VkCommandBuffer	cmdBuffer,
									deUint32		imageNdx,
									deUint32		frameNdx) const
{
	const VkFramebuffer	curFramebuffer	= **m_framebuffers[imageNdx];

	beginCommandBuffer(m_vkd, cmdBuffer, 0u);

	beginRenderPass(m_vkd, cmdBuffer, *m_renderPass, curFramebuffer, makeRect2D(0, 0, m_renderSize.x(), m_renderSize.y()), tcu::Vec4(0.125f, 0.25f, 0.75f, 1.0f));

	m_vkd.cmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_pipeline);

	{
		const VkDeviceSize bindingOffset = 0;
		m_vkd.cmdBindVertexBuffers(cmdBuffer, 0u, 1u, &m_vertexBuffer.get(), &bindingOffset);
	}

	m_vkd.cmdPushConstants(cmdBuffer, *m_pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0u, (deUint32)sizeof(deUint32), &frameNdx);
	m_vkd.cmdDraw(cmdBuffer, 3u, 1u, 0u, 0u);
	endRenderPass(m_vkd, cmdBuffer);

	endCommandBuffer(m_vkd, cmdBuffer);
}

void TriangleRenderer::getPrograms (SourceCollections& dst)
{
	dst.glslSources.add("tri-vert") << glu::VertexSource(
		"#version 310 es\n"
		"layout(location = 0) in highp vec4 a_position;\n"
		"layout(push_constant) uniform FrameData\n"
		"{\n"
		"    highp uint frameNdx;\n"
		"} frameData;\n"
		"void main (void)\n"
		"{\n"
		"    highp float angle = float(frameData.frameNdx) / 100.0;\n"
		"    highp float c     = cos(angle);\n"
		"    highp float s     = sin(angle);\n"
		"    highp mat4  t     = mat4( c, -s,  0,  0,\n"
		"                              s,  c,  0,  0,\n"
		"                              0,  0,  1,  0,\n"
		"                              0,  0,  0,  1);\n"
		"    gl_Position = t * a_position;\n"
		"}\n");
	dst.glslSources.add("tri-frag") << glu::FragmentSource(
		"#version 310 es\n"
		"layout(location = 0) out lowp vec4 o_color;\n"
		"void main (void) { o_color = vec4(1.0, 0.0, 1.0, 1.0); }\n");
}

typedef de::SharedPtr<Unique<VkCommandBuffer> >	CommandBufferSp;
typedef de::SharedPtr<Unique<VkFence> >			FenceSp;
typedef de::SharedPtr<Unique<VkSemaphore> >		SemaphoreSp;

vector<FenceSp> createFences (const DeviceInterface&	vkd,
							  const VkDevice			device,
							  size_t					numFences)
{
	vector<FenceSp> fences(numFences);

	for (size_t ndx = 0; ndx < numFences; ++ndx)
		fences[ndx] = FenceSp(new Unique<VkFence>(createFence(vkd, device)));

	return fences;
}

vector<SemaphoreSp> createSemaphores (const DeviceInterface&	vkd,
									  const VkDevice			device,
									  size_t					numSemaphores)
{
	vector<SemaphoreSp> semaphores(numSemaphores);

	for (size_t ndx = 0; ndx < numSemaphores; ++ndx)
		semaphores[ndx] = SemaphoreSp(new Unique<VkSemaphore>(createSemaphore(vkd, device)));

	return semaphores;
}

vector<CommandBufferSp> allocateCommandBuffers (const DeviceInterface&		vkd,
												const VkDevice				device,
												const VkCommandPool			commandPool,
												const VkCommandBufferLevel	level,
												const size_t				numCommandBuffers)
{
	vector<CommandBufferSp>				buffers		(numCommandBuffers);

	for (size_t ndx = 0; ndx < numCommandBuffers; ++ndx)
		buffers[ndx] = CommandBufferSp(new Unique<VkCommandBuffer>(allocateCommandBuffer(vkd, device, commandPool, level)));

	return buffers;
}

tcu::TestStatus basicExtensionTest (Context& context, Type wsiType)
{
	const tcu::UVec2				desiredSize		(256, 256);
	const InstanceHelper			instHelper		(context, wsiType);
	const NativeObjects				native			(context, instHelper.supportedExtensions, wsiType, tcu::just(desiredSize));
	const Unique<VkSurfaceKHR>		surface			(createSurface(instHelper.vki, *instHelper.instance, wsiType, *native.display, *native.window));
	const DeviceHelper				devHelper		(context, instHelper.vki, *instHelper.instance, *surface);

	if (!de::contains(context.getInstanceExtensions().begin(), context.getInstanceExtensions().end(), "VK_EXT_swapchain_colorspace"))
		TCU_THROW(NotSupportedError, "Extension VK_EXT_swapchain_colorspace not supported");

	const vector<VkSurfaceFormatKHR>	formats			= getPhysicalDeviceSurfaceFormats(instHelper.vki,
																						  devHelper.physicalDevice,
																						  *surface);

	bool found = false;
	for (vector<VkSurfaceFormatKHR>::const_iterator curFmt = formats.begin(); curFmt != formats.end(); ++curFmt)
	{
		if (curFmt->colorSpace != VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
		{
			found = true;
			break;
		}
	}
	if (!found)
	{
		TCU_THROW(NotSupportedError, "VK_EXT_swapchain_colorspace supported, but no non-SRGB_NONLINEAR_KHR surface formats found.");
	}
	return tcu::TestStatus::pass("Extension tests succeeded");
}

tcu::TestStatus surfaceFormatRenderTest (Context& context,
										 Type wsiType,
										 VkSurfaceKHR surface,
										 VkSurfaceFormatKHR curFmt,
										 deBool checkHdr = false)
{
	const tcu::UVec2					desiredSize		(256, 256);
	const InstanceHelper				instHelper		(context, wsiType);
	const DeviceHelper					devHelper		(context, instHelper.vki, *instHelper.instance, surface);
	const DeviceInterface&				vkd				= devHelper.vkd;
	const VkDevice						device			= *devHelper.device;
	SimpleAllocator						allocator		(vkd, device, getPhysicalDeviceMemoryProperties(instHelper.vki, devHelper.physicalDevice));

	const VkSwapchainCreateInfoKHR		swapchainInfo			= getBasicSwapchainParameters(wsiType, instHelper.vki, devHelper.physicalDevice, surface, curFmt, desiredSize, 2);
	const Unique<VkSwapchainKHR>		swapchain				(createSwapchainKHR(vkd, device, &swapchainInfo));
	const vector<VkImage>				swapchainImages			= getSwapchainImages(vkd, device, *swapchain);
	const vector<VkExtensionProperties>	deviceExtensions		(enumerateDeviceExtensionProperties(instHelper.vki, devHelper.physicalDevice, DE_NULL));

	if (checkHdr && !isExtensionSupported(deviceExtensions, RequiredExtension("VK_EXT_hdr_metadata")))
		TCU_THROW(NotSupportedError, "Extension VK_EXT_hdr_metadata not supported");

	const TriangleRenderer			renderer					(vkd,
																 device,
																 allocator,
																 context.getBinaryCollection(),
																 swapchainImages,
																 swapchainInfo.imageFormat,
																 tcu::UVec2(swapchainInfo.imageExtent.width, swapchainInfo.imageExtent.height));

	const Unique<VkCommandPool>		commandPool					(createCommandPool(vkd, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, devHelper.queueFamilyIndex));

	const size_t					maxQueuedFrames				= swapchainImages.size()*2;

	// We need to keep hold of fences from vkAcquireNextImageKHR to actually
	// limit number of frames we allow to be queued.
	const vector<FenceSp>			imageReadyFences			(createFences(vkd, device, maxQueuedFrames));

	// We need maxQueuedFrames+1 for imageReadySemaphores pool as we need to pass
	// the semaphore in same time as the fence we use to meter rendering.
	const vector<SemaphoreSp>		imageReadySemaphores		(createSemaphores(vkd, device, maxQueuedFrames+1));

	// For rest we simply need maxQueuedFrames as we will wait for image
	// from frameNdx-maxQueuedFrames to become available to us, guaranteeing that
	// previous uses must have completed.
	const vector<SemaphoreSp>		renderingCompleteSemaphores	(createSemaphores(vkd, device, maxQueuedFrames));
	const vector<CommandBufferSp>	commandBuffers				(allocateCommandBuffers(vkd, device, *commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, maxQueuedFrames));

	try
	{
		const deUint32	numFramesToRender	= 60;

		for (deUint32 frameNdx = 0; frameNdx < numFramesToRender; ++frameNdx)
		{
			const VkFence		imageReadyFence		= **imageReadyFences[frameNdx%imageReadyFences.size()];
			const VkSemaphore	imageReadySemaphore	= **imageReadySemaphores[frameNdx%imageReadySemaphores.size()];
			deUint32			imageNdx			= ~0u;

			if (frameNdx >= maxQueuedFrames)
				VK_CHECK(vkd.waitForFences(device, 1u, &imageReadyFence, VK_TRUE, std::numeric_limits<deUint64>::max()));

			VK_CHECK(vkd.resetFences(device, 1, &imageReadyFence));

			{
				const VkResult	acquireResult	= vkd.acquireNextImageKHR(device,
																		  *swapchain,
																		  std::numeric_limits<deUint64>::max(),
																		  imageReadySemaphore,
																		  (vk::VkFence)0,
																		  &imageNdx);

				if (acquireResult == VK_SUBOPTIMAL_KHR)
					context.getTestContext().getLog() << TestLog::Message << "Got " << acquireResult << " at frame " << frameNdx << TestLog::EndMessage;
				else
					VK_CHECK(acquireResult);
			}

			TCU_CHECK((size_t)imageNdx < swapchainImages.size());

			{
				const VkSemaphore			renderingCompleteSemaphore	= **renderingCompleteSemaphores[frameNdx%renderingCompleteSemaphores.size()];
				const VkCommandBuffer		commandBuffer				= **commandBuffers[frameNdx%commandBuffers.size()];
				const VkPipelineStageFlags	waitDstStage				= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
				const VkSubmitInfo			submitInfo					=
				{
					VK_STRUCTURE_TYPE_SUBMIT_INFO,
					DE_NULL,
					1u,
					&imageReadySemaphore,
					&waitDstStage,
					1u,
					&commandBuffer,
					1u,
					&renderingCompleteSemaphore
				};
				const VkPresentInfoKHR		presentInfo					=
				{
					VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
					DE_NULL,
					1u,
					&renderingCompleteSemaphore,
					1u,
					&*swapchain,
					&imageNdx,
					(VkResult*)DE_NULL
				};

				if (checkHdr) {
					const VkHdrMetadataEXT hdrData = {
							VK_STRUCTURE_TYPE_HDR_METADATA_EXT,
							DE_NULL,
							makeXYColorEXT(0.680f, 0.320f),
							makeXYColorEXT(0.265f, 0.690f),
							makeXYColorEXT(0.150f, 0.060f),
							makeXYColorEXT(0.3127f, 0.3290f),
							1000.0,
							0.0,
							1000.0,
							70.0
					};
					vector<VkSwapchainKHR> swapchainArray;

					swapchainArray.push_back(*swapchain);
					vkd.setHdrMetadataEXT(device, (deUint32)swapchainArray.size(), swapchainArray.data(), &hdrData);
				}

				renderer.recordFrame(commandBuffer, imageNdx, frameNdx);
				VK_CHECK(vkd.queueSubmit(devHelper.queue, 1u, &submitInfo, imageReadyFence));
				VK_CHECK(vkd.queuePresentKHR(devHelper.queue, &presentInfo));
			}
		}

		VK_CHECK(vkd.deviceWaitIdle(device));
	}
	catch (...)
	{
		// Make sure device is idle before destroying resources
		vkd.deviceWaitIdle(device);
		throw;
	}

	return tcu::TestStatus::pass("Rendering test succeeded");
}

tcu::TestStatus surfaceFormatRenderTests (Context& context, Type wsiType)
{
	const tcu::UVec2					desiredSize		(256, 256);
	const InstanceHelper				instHelper		(context, wsiType);
	const NativeObjects					native			(context, instHelper.supportedExtensions, wsiType, tcu::just(desiredSize));
	const Unique<VkSurfaceKHR>			surface			(createSurface(instHelper.vki, *instHelper.instance, wsiType, *native.display, *native.window));
	const DeviceHelper					devHelper		(context, instHelper.vki, *instHelper.instance, *surface);

	if (!de::contains(context.getInstanceExtensions().begin(), context.getInstanceExtensions().end(), "VK_EXT_swapchain_colorspace"))
		TCU_THROW(NotSupportedError, "Extension VK_EXT_swapchain_colorspace not supported");

	const vector<VkSurfaceFormatKHR>	formats			= getPhysicalDeviceSurfaceFormats(instHelper.vki,
																							 devHelper.physicalDevice,
																							 *surface);
	for (vector<VkSurfaceFormatKHR>::const_iterator curFmt = formats.begin(); curFmt != formats.end(); ++curFmt)
	{
		surfaceFormatRenderTest(context, wsiType, *surface, *curFmt);
	}
	return tcu::TestStatus::pass("Rendering tests succeeded");
}

tcu::TestStatus surfaceFormatRenderWithHdrTests (Context& context, Type wsiType)
{
	const tcu::UVec2					desiredSize		(256, 256);
	const InstanceHelper				instHelper		(context, wsiType);
	const NativeObjects					native			(context, instHelper.supportedExtensions, wsiType, tcu::just(desiredSize));
	const Unique<VkSurfaceKHR>			surface			(createSurface(instHelper.vki, *instHelper.instance, wsiType, *native.display, *native.window));
	const DeviceHelper					devHelper		(context, instHelper.vki, *instHelper.instance, *surface);

	if (!de::contains(context.getInstanceExtensions().begin(), context.getInstanceExtensions().end(), "VK_EXT_swapchain_colorspace"))
		TCU_THROW(NotSupportedError, "Extension VK_EXT_swapchain_colorspace not supported");

	const vector<VkSurfaceFormatKHR>	formats			= getPhysicalDeviceSurfaceFormats(instHelper.vki,
																						  devHelper.physicalDevice,
																						  *surface);
	for (vector<VkSurfaceFormatKHR>::const_iterator curFmt = formats.begin(); curFmt != formats.end(); ++curFmt)
	{
		surfaceFormatRenderTest(context, wsiType, *surface, *curFmt, true);
	}
	return tcu::TestStatus::pass("Rendering tests succeeded");
}

void getBasicRenderPrograms (SourceCollections& dst, Type)
{
	TriangleRenderer::getPrograms(dst);
}

} // anonymous

void createColorSpaceTests (tcu::TestCaseGroup* testGroup, vk::wsi::Type wsiType)
{
	addFunctionCase(testGroup, "extensions", "Verify Colorspace Extensions", basicExtensionTest, wsiType);
	addFunctionCaseWithPrograms(testGroup, "basic", "Basic Rendering Tests", getBasicRenderPrograms, surfaceFormatRenderTests, wsiType);
	addFunctionCaseWithPrograms(testGroup, "hdr", "Basic Rendering Tests with HDR", getBasicRenderPrograms, surfaceFormatRenderWithHdrTests, wsiType);
}

} // wsi
} // vkt


text:
class DropPolicyTables < ActiveRecord::Migration
  def up
    drop_table :edition_policy_groups
    drop_table :editioned_supporting_page_mappings
    drop_table :featured_items
    drop_table :featured_topics_and_policies_lists
    drop_table :supporting_page_redirects
  end
end


text:
use strict;
use warnings;

package Gwybodaeth::Escape;

=head1 NAME

Escape - Escape characters with XML escapes

=head1 SYNOPSIS

    use Escape;

    my $e = Escape->new();

    $e->escape($string);

=head1 DESCRIPTION

This module escapes strings in preperation for putting in XML.

=over

=cut

use Carp qw(croak);
{

=item new()
    Returns an instance of the Escape class.

=cut

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

=item escape()
    Escapes strings with XML escapes.

=cut

sub escape {
    ref(my $self = shift) or croak "instance variable needed";
    my $string = shift;

    # escape '&' chars.
    $string =~ s/&
                # an ampersand
                /\&/xg;
    $string =~ s/
                # an ampersand
                \&
                /&/xg;

    chomp($string);

    return $string;
}

}
1;
__END__

=back

=head1 AUTHOR

Iestyn Pryce, <imp25@cam.ac.uk>

=head1 ACKNOWLEDGEMENTS

I'd like to thank the Ensemble project (L<www.ensemble.ac.uk>) for funding me to work on this project in the summer of 2009.

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 Iestyn Pryce <imp25@cam.ac.uk>

This library is free software; you can redistribute it and/or modify it under
the terms of the BSD license.


text:
package pl.polidea.coverflow;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

/**
 * This class is an adapter that provides base, abstract class for images
 * adapter.
 *
 */
public abstract class AbstractCoverFlowImageAdapter extends BaseAdapter {

    /** The Constant TAG. */
    private static final String TAG = AbstractCoverFlowImageAdapter.class.getSimpleName();

    /** The width. */
    private float width = 0;

    /** The height. */
    private float height = 0;

    /** The bitmap map. */
    private final Map<Integer, WeakReference<Bitmap>> bitmapMap = new HashMap<Integer, WeakReference<Bitmap>>();

    public AbstractCoverFlowImageAdapter() {
        super();
    }

    /**
     * Set width for all pictures.
     *
     * @param width
     *            picture height
     */
    public synchronized void setWidth(final float width) {
        this.width = width;
    }

    /**
     * Set height for all pictures.
     *
     * @param height
     *            picture height
     */
    public synchronized void setHeight(final float height) {
        this.height = height;
    }

    @Override
    public final Bitmap getItem(final int position) {
        final WeakReference<Bitmap> weakBitmapReference = bitmapMap.get(position);
        if (weakBitmapReference != null) {
            final Bitmap bitmap = weakBitmapReference.get();
            if (bitmap == null) {
                Log.v(TAG, "Empty bitmap reference at position: " + position + ":" + this);
            } else {
                Log.v(TAG, "Reusing bitmap item at position: " + position + ":" + this);
                return bitmap;
            }
        }
        Log.v(TAG, "Creating item at position: " + position + ":" + this);
        final Bitmap bitmap = createBitmap(position);
        bitmapMap.put(position, new WeakReference<Bitmap>(bitmap));
        Log.v(TAG, "Created item at position: " + position + ":" + this);
        return bitmap;
    }

    /**
     * Creates new bitmap for the position specified.
     *
     * @param position
     *            position
     * @return Bitmap created
     */
    protected abstract Bitmap createBitmap(int position);

    /*
     * (non-Javadoc)
     *
     * @see android.widget.Adapter#getItemId(int)
     */
    @Override
    public final synchronized long getItemId(final int position) {
        return position;
    }

    /*
     * (non-Javadoc)
     *
     * @see android.widget.Adapter#getView(int, android.view.View,
     * android.view.ViewGroup)
     */
    @Override
    public final synchronized ImageView getView(final int position, final View convertView, final ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            final Context context = parent.getContext();
            Log.v(TAG, "Creating Image view at position: " + position + ":" + this);
            imageView = new ImageView(context);
            imageView.setLayoutParams(new CoverFlow.LayoutParams((int) width, (int) height));
        } else {
            Log.v(TAG, "Reusing view at position: " + position + ":" + this);
            imageView = (ImageView) convertView;
        }
        imageView.setImageBitmap(getItem(position));
        return imageView;
    }

}


text:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen(3000, function() {
  console.log('listening on *:3000');
});

var users = 0;

io.on('connection', function(socket) {
  var message;

  users += 1;
  console.log('a user connected');

  if (users == 1) {
    message = 'There is  1 user online';
  } else {
    message = 'There are ' + users + ' users online';
  }
  socket.emit('server', {message: 'Welcome to the chat!'});
  socket.emit('server', {message: message});

  socket.on('chat', function(message) {
    socket.broadcast.emit('chat', message);
  });

  socket.on('entered', function(user) {
    socket.broadcast.emit('server',
                          {message: user + ' user has entered the chat!'});
  });

  socket.on('disconnect', function() {
    var message;

    console.log('a user disconnected');
    users -= 1;

    if (users == 1) {
      message = 'There is 1 user online';
    } else {
      message = 'There are ' + users + ' users online';
    }
    socket.emit('server', {message: message});
  });
});


text:
package org.spongepowered.vanilla.launch.console;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;

import java.io.PrintStream;

public class LoggingPrintStream extends PrintStream {

    private final LoggingOutputStream out;

    public LoggingPrintStream(Logger logger, Level level) {
        this(new LoggingOutputStream(logger, level));
    }

    public LoggingPrintStream(LoggingOutputStream out) {
        super(out, true);
        this.out = out;
    }

    @Override
    public void write(byte[] buf, int off, int len) {
        this.out.flush = false;
        super.write(buf, off, len);
        this.out.flush = true;
    }

}


text:
package org.apache.flink.table.gateway.api.results;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.catalog.CatalogBaseTable.TableKind;
import org.apache.flink.table.catalog.CatalogTable;
import org.apache.flink.table.catalog.ObjectIdentifier;

import java.util.Objects;

/**
 * Information of the table or view.
 *
 * <p>Note: It is not equivalent to the {@link CatalogTable} that also contains {@link Schema}. The
 * invoker can get basic information for the table without to read all information in the remote
 * catalog.
 */
@PublicEvolving
public class TableInfo {
    private final ObjectIdentifier identifier;
    private final TableKind tableKind;

    public TableInfo(ObjectIdentifier identifier, TableKind tableKind) {
        this.identifier = identifier;
        this.tableKind = tableKind;
    }

    public ObjectIdentifier getIdentifier() {
        return identifier;
    }

    public TableKind getTableKind() {
        return tableKind;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof TableInfo)) {
            return false;
        }
        TableInfo that = (TableInfo) o;
        return identifier.equals(that.identifier) && tableKind == that.tableKind;
    }

    @Override
    public int hashCode() {
        return Objects.hash(identifier, tableKind);
    }

    @Override
    public String toString() {
        return "TableInfo{" + "identifier=" + identifier + ", tableKind=" + tableKind + '}';
    }
}


text:
import logging
import numpy as np
import progressbar

from mlfromscratch.utils.misc import bar_widgets
from mlfromscratch.utils import batch_iterator
from mlfromscratch.deep_learning.activation_functions import Sigmoid

sigmoid = Sigmoid()

class RBM():
    """Bernoulli Restricted Boltzmann Machine (RBM)

    Parameters:
    -----------
    n_hidden: int:
        The number of processing nodes (neurons) in the hidden layer.
    learning_rate: float
        The step length that will be used when updating the weights.
    batch_size: int
        The size of the mini-batch used to calculate each weight update.
    n_iterations: float
        The number of training iterations the algorithm will tune the weights for.

    Reference:
        A Practical Guide to Training Restricted Boltzmann Machines
        URL: https://www.cs.toronto.edu/~hinton/absps/guideTR.pdf
    """
    def __init__(self, n_hidden=128, learning_rate=0.1, batch_size=10, n_iterations=100):
        self.n_iterations = n_iterations
        self.batch_size = batch_size
        self.lr = learning_rate
        self.n_hidden = n_hidden
        self.progressbar = progressbar.ProgressBar(widgets=bar_widgets)

    def _initialize_weights(self, X):
        n_visible = X.shape[1]
        self.W = np.random.normal(scale=0.1, size=(n_visible, self.n_hidden))
        self.v0 = np.zeros(n_visible)       # Bias visible
        self.h0 = np.zeros(self.n_hidden)   # Bias hidden

    def fit(self, X, y=None):
        '''Contrastive Divergence training procedure'''

        self._initialize_weights(X)

        self.training_errors = []
        self.training_reconstructions = []
        for _ in self.progressbar(range(self.n_iterations)):
            batch_errors = []
            for batch in batch_iterator(X, batch_size=self.batch_size):
                # Positive phase
                positive_hidden = sigmoid(batch.dot(self.W) + self.h0)
                hidden_states = self._sample(positive_hidden)
                positive_associations = batch.T.dot(positive_hidden)

                # Negative phase
                negative_visible = sigmoid(hidden_states.dot(self.W.T) + self.v0)
                negative_visible = self._sample(negative_visible)
                negative_hidden = sigmoid(negative_visible.dot(self.W) + self.h0)
                negative_associations = negative_visible.T.dot(negative_hidden)

                self.W  += self.lr * (positive_associations - negative_associations)
                self.h0 += self.lr * (positive_hidden.sum(axis=0) - negative_hidden.sum(axis=0))
                self.v0 += self.lr * (batch.sum(axis=0) - negative_visible.sum(axis=0))

                batch_errors.append(np.mean((batch - negative_visible) ** 2))

            self.training_errors.append(np.mean(batch_errors))
            # Reconstruct a batch of images from the training set
            idx = np.random.choice(range(X.shape[0]), self.batch_size)
            self.training_reconstructions.append(self.reconstruct(X[idx]))

    def _sample(self, X):
        return X > np.random.random_sample(size=X.shape)

    def reconstruct(self, X):
        positive_hidden = sigmoid(X.dot(self.W) + self.h0)
        hidden_states = self._sample(positive_hidden)
        negative_visible = sigmoid(hidden_states.dot(self.W.T) + self.v0)
        return negative_visible