text:
package org.mustangproject.ZUGFeRD;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ZF2Test extends MustangReaderTestCase {
	final String TARGET_PDF = "./target/testout-ZF2new.pdf";

	@Override
	public Date getDeliveryDate() {
		return new GregorianCalendar(2017, Calendar.MAY, 7).getTime();
	}

	@Override
	public Date getDueDate() {
		return new GregorianCalendar(2017, Calendar.MAY, 30).getTime();
	}

	@Override
	public Date getIssueDate() {
		return new GregorianCalendar(2017, Calendar.MAY, 9).getTime();
	}

	@Override
	public String getNumber() {
		return "RE-20170509/505";
	}

	@Override
	public IZUGFeRDExportableTradeParty getSender() {
		return new SenderTradeParty();

	}

	@Override
	public String getOwnTaxID() {
		return "22/815/0815/4";
	}

	@Override
	public String getOwnVATID() {
		return "DE136695976";
	}

	@Override
	public String getOwnZIP() {
		return "12345";
	}

	@Override
	public IZUGFeRDExportableTradeParty getRecipient() {
		return new RecipientTradeParty();
	}

	@Override
	public String getOwnOrganisationFullPlaintextInfo() {
		return null;
	}

	@Override
	public String getCurrency() {
		return "EUR";
	}

	@Override
	public IZUGFeRDExportableItem[] getZFItems() {
		final Item[] allItems = new Item[3];
		final Product designProduct = new Product("", "Künstlerische Gestaltung (Stunde): Einer Beispielrechnung", "HUR",
				new BigDecimal("7.000000"));
		final Product balloonProduct = new Product("", "Bestellerweiterung für E&F Umbau", "C62",
				new BigDecimal("19.000000"));// test for issue 103
		final Product airProduct = new Product("", "Heiße Luft pro Liter", "LTR", new BigDecimal("19.000000"));

		allItems[0] = new Item(new BigDecimal("160"), new BigDecimal("1"), designProduct);
		allItems[1] = new Item(new BigDecimal("0.79"), new BigDecimal("400"), balloonProduct);
		allItems[2] = new Item(new BigDecimal("0.10"), new BigDecimal("200"), airProduct);
		return allItems;
	}

	@Override
	public String getPaymentTermDescription() {
		final SimpleDateFormat germanDateFormat = new SimpleDateFormat("dd.MM.yyyy");
		return "Zahlbar ohne Abzug bis zum " + germanDateFormat.format(getDueDate());
	}

	@Override
	public IZUGFeRDAllowanceCharge[] getZFAllowances() {
		return null;
	}

	@Override
	public IZUGFeRDAllowanceCharge[] getZFCharges() {
		return null;
	}

	@Override
	public IZUGFeRDAllowanceCharge[] getZFLogisticsServiceCharges() {
		return null;
	}

	@Override
	public String getReferenceNumber() {
		return "AB321";
	}

	/**
	 * Create the test case
	 *
	 * @param testName name of the test case
	 */
	public ZF2Test(String testName) {
		super(testName);
	}

	/**
	 * @return the suite of tests being tested
	 */
	public static Test suite() {
		return new TestSuite(ZF2Test.class);
	}

	// //////// TESTS
	// //////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * The exporter test bases on @{code
	 * ./src/test/MustangGnuaccountingBeispielRE-20170509_505PDFA3.pdf}, adds
	 * metadata, writes to @{code ./target/testout-*} and then imports to check the
	 * values.
	 */
	public void testExport() {

		// the writing part

		try (InputStream SOURCE_PDF = this.getClass()
				.getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505PDFA3.pdf");

			 ZUGFeRDExporterFromA3 ze = new ZUGFeRDExporterFromA3().setProducer("My Application")
						.setCreator(System.getProperty("user.name")).setZUGFeRDVersion(2).setProfile("EN16931")
						.load(SOURCE_PDF)) {

			ze.setTransaction(this);
			final String theXML = new String(ze.getProvider().getXML());
			assertTrue(theXML.contains("<rsm:CrossIndustryInvoice"));
			ze.export(TARGET_PDF);
		} catch (final IOException e) {
			fail("IOException should not be raised in testEdgeExport");
		}

		// now check the contents (like MustangReaderTest)
		final ZUGFeRDImporter zi = new ZUGFeRDImporter(TARGET_PDF);

		assertTrue(zi.getUTF8().contains("<ram:DueDateDateTime>"));

		// Reading ZUGFeRD
		assertEquals(zi.getAmount(), "571.04");
		assertEquals(zi.getInvoiceID(), "RE-20170509/505");
		assertEquals(zi.getZUGFeRDProfil(), "COMFORT");
		assertEquals(zi.getInvoiceCurrencyCode(), "EUR");
		assertEquals(zi.getIssuerAssignedID(),"");
		assertEquals(zi.getIssueDate(), "20170509");
		assertEquals(zi.getTaxPointDate(), "20170507");
		assertEquals(zi.getPaymentTerms(), "Zahlbar ohne Abzug bis zum 30.05.2017");
		assertEquals(zi.getLineTotalAmount(), "496.00");
		assertEquals(zi.getTaxBasisTotalAmount(), "496.00");
		assertEquals(zi.getTaxTotalAmount(),"75.04");
		assertEquals(zi.getRoundingAmount(), "");
		assertEquals(zi.getPaidAmount(), "0.00");
		assertEquals(zi.getBuyerTradePartyName(), "Theodor Est");
		assertEquals(zi.getBuyerTradePartyGlobalID(), "");
		assertEquals(zi.getSellerTradePartyGlobalID(), "");
		assertEquals(zi.getBuyerTradePartyID(), "DE999999999");
		assertEquals(zi.getBuyertradePartySpecifiedTaxRegistrationID(), "DE999999999");
		assertEquals(zi.getIncludedNote(), "");
		assertEquals(zi.getHolder(), getOwnOrganisationName());
		assertEquals(zi.getDocumentCode(),"380");
		assertEquals(zi.getReference(),"AB321");
		assertEquals(zi.getAmount(), "571.04");
		assertEquals(zi.getBIC(), "COBADEFFXXX");
		assertEquals(zi.getIBAN(), "DE88 2008 0000 0970 3757 00");
		assertEquals(zi.getHolder(), getOwnOrganisationName());
		assertEquals(zi.getForeignReference(), getNumber());
		assertEquals(zi.getBuyerTradePartyAddress().getPostcodeCode(), "88802");
		assertEquals(zi.getBuyerTradePartyAddress().getLineOne(), "Bahnstr. 42");
		assertEquals(zi.getBuyerTradePartyAddress().getLineTwo(), "Hinterhaus");
		assertEquals(zi.getBuyerTradePartyAddress().getLineThree(), "Zweiter Stock");
		assertEquals(zi.getBuyerTradePartyAddress().getCountrySubDivisionName(), null);
		assertEquals(zi.getBuyerTradePartyAddress().getCountryID(), "DE");
		assertEquals(zi.getBuyerTradePartyAddress().getCityName(), "Spielkreis");
		assertEquals(zi.getSellerTradePartyAddress().getPostcodeCode(), "12345");
		assertEquals(zi.getSellerTradePartyAddress().getLineOne(), "Ecke 12");
		assertEquals(zi.getSellerTradePartyAddress().getLineTwo(), null);
		assertEquals(zi.getSellerTradePartyAddress().getLineThree(), null);
		assertEquals(zi.getSellerTradePartyAddress().getCountrySubDivisionName(), null);
		assertEquals(zi.getSellerTradePartyAddress().getCountryID(), "DE");
		assertEquals(zi.getSellerTradePartyAddress().getCityName(), "Stadthausen");

		final List<org.mustangproject.Item> li = zi.getLineItemList();
		assertEquals(zi.getLineItemList().get(0).getId().toString(), "1");
		assertEquals(zi.getLineItemList().get(0).getProduct().getBuyerAssignedID(), "");
		assertEquals(zi.getLineItemList().get(0).getProduct().getSellerAssignedID(), "");
		assertEquals(zi.getLineItemList().get(0).getLineTotalAmount().toString(), "160.00");
		assertEquals(zi.getLineItemList().get(0).getQuantity().toString(), "1.0000");
		assertEquals(zi.getLineItemList().get(0).getGrossPrice().toString(), "160.0000");
		assertEquals(zi.getLineItemList().get(0).getProduct().getVATPercent().toString(), "7.00");
		assertEquals(zi.getLineItemList().get(0).getProduct().getName(), "Künstlerische Gestaltung (Stunde): Einer Beispielrechnung");
		assertEquals(zi.getLineItemList().get(0).getProduct().getDescription(), "");

		try {
			assertEquals(zi.getVersion(), 2);
		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	/**
	 * The exporter test bases on @{code
	 * ./src/test/MustangBeispiel20221026.pdf}, adds
	 * metadata, writes to @{code ./target/testout-*} and then imports to check the
	 * values.
	 */
	public void testImport() {
		// now check the contents (like MustangReaderTest)
		final ZUGFeRDImporter zi = new ZUGFeRDImporter("src/test/resources/MustangBeispiel20221026.pdf");

		// Reading ZUGFeRD
		assertEquals("963.11", zi.getAmount());
		assertEquals("RE1001", zi.getInvoiceID());
		assertEquals("COMFORT", zi.getZUGFeRDProfil());
		assertEquals("EUR", zi.getInvoiceCurrencyCode());
		assertEquals("20221026", zi.getIssueDate());
		assertEquals("20221026", zi.getTaxPointDate());
		assertEquals("Innerhalb von 30 Tagen 2% Skonto, 60 Tage ohne Abzug", zi.getPaymentTerms());
		assertEquals("804.35", zi.getLineTotalAmount());
		assertEquals("809.34", zi.getTaxBasisTotalAmount());
		assertEquals("153.77",zi.getTaxTotalAmount());
		assertEquals("", zi.getRoundingAmount());
		assertEquals("0.00", zi.getPaidAmount());
		assertEquals("Beispiel AG", zi.getBuyerTradePartyName());
		assertEquals("", zi.getBuyerTradePartyGlobalID());
		assertEquals("", zi.getSellerTradePartyGlobalID());
		assertEquals("10000", zi.getBuyerTradePartyID());
		assertEquals("\n      weclapp.com\nSomestreet 42\n08155 Some city\nDE\n    ", zi.getIncludedNote());
		assertEquals("weclapp.com", zi.getHolder());
		assertEquals("380",zi.getDocumentCode());
		assertEquals("01-95",zi.getReference());
		assertEquals("RE1001", zi.getForeignReference());
		assertEquals("54321", zi.getBuyerTradePartyAddress().getPostcodeCode());
		assertEquals("Feldstraße 34", zi.getBuyerTradePartyAddress().getLineOne());
		assertEquals(null, zi.getBuyerTradePartyAddress().getLineTwo());
		assertEquals(null, zi.getBuyerTradePartyAddress().getLineThree());
		assertEquals(null, zi.getBuyerTradePartyAddress().getCountrySubDivisionName());
		assertEquals("DE", zi.getBuyerTradePartyAddress().getCountryID());
		assertEquals("Hithausen", zi.getBuyerTradePartyAddress().getCityName());
		assertEquals("Beispiel Lager AG", zi.getDeliveryTradePartyName());
    assertEquals("54321", zi.getDeliveryTradePartyAddress().getPostcodeCode());
    assertEquals("Feldstraße 39", zi.getDeliveryTradePartyAddress().getLineOne());
    assertEquals(null, zi.getDeliveryTradePartyAddress().getLineTwo());
    assertEquals(null, zi.getDeliveryTradePartyAddress().getLineThree());
    assertEquals(null, zi.getDeliveryTradePartyAddress().getCountrySubDivisionName());
    assertEquals("DE", zi.getDeliveryTradePartyAddress().getCountryID());
    assertEquals("Hithausen", zi.getDeliveryTradePartyAddress().getCityName());
		assertEquals("08155", zi.getSellerTradePartyAddress().getPostcodeCode());
		assertEquals("Somestreet 42", zi.getSellerTradePartyAddress().getLineOne());
		assertEquals(null, zi.getSellerTradePartyAddress().getLineTwo());
		assertEquals(null, zi.getSellerTradePartyAddress().getLineThree());
		assertEquals(null, zi.getSellerTradePartyAddress().getCountrySubDivisionName());
		assertEquals("DE", zi.getSellerTradePartyAddress().getCountryID());
		assertEquals("Some city", zi.getSellerTradePartyAddress().getCityName());

		try {
			assertEquals(zi.getVersion(), 2);
		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


text:
<?php

namespace Cocorico\CoreBundle\DataFixtures\ORM;

use Cocorico\CoreBundle\Entity\ListingCharacteristic;
use Cocorico\CoreBundle\Entity\ListingCharacteristicGroup;
use Cocorico\CoreBundle\Entity\ListingCharacteristicType;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

class LoadListingCharacteristicData extends AbstractFixture implements OrderedFixtureInterface
{

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $listingCharacteristic = new ListingCharacteristic();
        $listingCharacteristic->setPosition(1);
        $listingCharacteristic->translate('en')->setName('Characteristic_1');
        $listingCharacteristic->translate('fr')->setName('Caractéristique_1');
        $listingCharacteristic->translate('en')->setDescription('Characteristic_1 description');
        $listingCharacteristic->translate('fr')->setDescription('Description de la Caractéristique_1');
        /** @var ListingCharacteristicType $listingCharacteristicType */
        $listingCharacteristicType = $manager->merge($this->getReference('characteristic_type_yes_no'));
        $listingCharacteristic->setListingCharacteristicType($listingCharacteristicType);
        /** @var ListingCharacteristicGroup $listingCharacteristicGroup */
        $listingCharacteristicGroup = $manager->merge($this->getReference('group_1'));
        $listingCharacteristic->setListingCharacteristicGroup($listingCharacteristicGroup);

        $manager->persist($listingCharacteristic);
        $listingCharacteristic->mergeNewTranslations();
        $manager->flush();
        $this->addReference('characteristic_1', $listingCharacteristic);

        $listingCharacteristic = new ListingCharacteristic();
        $listingCharacteristic->setPosition(2);
        $listingCharacteristic->translate('en')->setName('Characteristic_2');
        $listingCharacteristic->translate('fr')->setName('Caractéristique_2');
        $listingCharacteristic->translate('en')->setDescription('Characteristic_2 description');
        $listingCharacteristic->translate('fr')->setDescription('Description de la Caractéristique_2');
        $listingCharacteristicType = $manager->merge($this->getReference('characteristic_type_quantity'));
        $listingCharacteristic->setListingCharacteristicGroup($listingCharacteristicGroup);
        $listingCharacteristic->setListingCharacteristicType($listingCharacteristicType);
        $manager->persist($listingCharacteristic);
        $listingCharacteristic->mergeNewTranslations();
        $manager->flush();
        $this->addReference('characteristic_2', $listingCharacteristic);

        $listingCharacteristic = new ListingCharacteristic();
        $listingCharacteristic->setPosition(3);
        $listingCharacteristic->translate('en')->setName('Characteristic_3');
        $listingCharacteristic->translate('fr')->setName('Caractéristique_3');
        $listingCharacteristic->translate('en')->setDescription('Characteristic_3 description');
        $listingCharacteristic->translate('fr')->setDescription('Description de la Caractéristique_3');
        $listingCharacteristicType = $manager->merge($this->getReference('characteristic_type_custom_1'));
        $listingCharacteristic->setListingCharacteristicType($listingCharacteristicType);
        $listingCharacteristicGroup = $manager->merge($this->getReference('group_2'));
        $listingCharacteristic->setListingCharacteristicGroup($listingCharacteristicGroup);
        $manager->persist($listingCharacteristic);
        $listingCharacteristic->mergeNewTranslations();
        $manager->flush();
        $this->addReference('characteristic_3', $listingCharacteristic);

        $listingCharacteristic = new ListingCharacteristic();
        $listingCharacteristic->setPosition(4);
        $listingCharacteristic->translate('en')->setName('Characteristic_4');
        $listingCharacteristic->translate('fr')->setName('Caractéristique_4');
        $listingCharacteristic->translate('en')->setDescription('Characteristic_4 description');
        $listingCharacteristic->translate('fr')->setDescription('Description de la Caractéristique_4');
        $listingCharacteristicType = $manager->merge($this->getReference('characteristic_type_custom_1'));
        $listingCharacteristic->setListingCharacteristicType($listingCharacteristicType);
        $listingCharacteristicGroup = $manager->merge($this->getReference('group_2'));
        $listingCharacteristic->setListingCharacteristicGroup($listingCharacteristicGroup);
        $manager->persist($listingCharacteristic);
        $listingCharacteristic->mergeNewTranslations();
        $manager->flush();
        $this->addReference('characteristic_4', $listingCharacteristic);
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 7;
    }

}

redpajama_set_name: RedPajamaGithub


text:
.. image:: https://travis-ci.org/irothschild/stefuna.svg
   :target: https://travis-ci.org/irothschild/stefuna

===============================
stefuna
===============================

Stefuna is a simple AWS Step Function Activity server framework.
It makes it incredibly quick and easy to write workers to
process activity tasks in Python.

Install
-------

.. code-block:: bash

    $ pip install stefuna

Implementation
---------------

Stefuna uses a multiprocessing Pool of pre-forked worker processes
to run the activity tasks. There is a single instance of a Server
class in the main process and a single instance of a Worker
class in each worker process. To implement your task, simply
create a Worker subclass, override the
``run_task(self, task_token, input_data)`` method and start the
server.

The ``run_task`` method can do whatever work it requires and then
return a result as a string or dict (which is automatically JSON
stringified). It can be a long-running task but the worker process
won't be released until the method returns.

If ``run_task`` raises an exception, the task is failed
with a ``Task.Failure`` error which can be handled in the Step
Function state machine. Alternatively, a worker can call
``self.send_task_failure(error, cause)`` with a custom error
string and return value from ``run_task`` will be ignored.

Configurable heartbeats are supported for longer-running tasks.

A healthcheck port can be configured so the server listens for
HTTP GET requests on ``http://localhost:<healthcheck>/``

The Server instance in the main class can be customized by
setting a custom Server subclass in the config and overriding
the ``init`` method.

The Python multiprocessing start method for worker processes
can be set in the config. By default 'spawn' is used to ensure
a clean, safe worker process. Although potentially slower than
'forkserver' (or 'fork' which is not recommended), since new
workers are typically rarely created, this should not be an
issue.

Getting Started
---------------

See the examples folder for the files described below.

Step Function
^^^^^^^^^^^^^^

Create an AWS Step Function Activity, for example ``hello``.

Then create a Step Function State Machine, using the ARN of the activity you just created.
For example a single state ``Hello World`` State Machine:

.. code-block:: JavaScript

    {
       "Comment": "A Hello World example with a single activity",
       "StartAt": "HelloWorld",
       "States": {
          "HelloWorld": {
            "Type": "Task",
            "Resource": "arn:aws:states:us-east-1:00000000000000:activity:hello",
            "End": true
          }
       }
    }

Worker Code
^^^^^^^^^^^

Create a worker class, which is a subclass of the ``stefuna.Worker``
in the file ``hello_worker.py``:

.. code-block:: python

    import logging
    from stefuna import Worker

    logger = logging.getLogger('stefuna.example')

    class HelloWorker(Worker):

	def init(self):
	    """Initialize the single instance in a worker"""
            # self.config is the worker config
            self.logger.debug('Init worker instance')

	def run_task(self, task_token, input_data):
	    self.logger.debug('Worker in run_task')

	    # Do some work!
            # self.config is the worker config

	    # Return value can be a string or a dict/array that
	    # will be JSON stringified.
	    return {"message": "Hello World"}

Create a config file ``hello_config.py``, setting the worker class, server name, and
activity ARN:

.. code-block:: python

    #
    # Stefuna server worker config file
    #

    # [OPTIONAL] The module path of the server class
    server = 'examples.hello_server.HelloServer'

    # The module path of the worker class
    worker = 'examples.hello_worker.HelloWorker'

    # The base name of the server that will be combined with host and pid
    # and used when requesting tasks from AWS.
    name = 'HelloExample'

    # Set the ARN for the activity that this server will work on.
    activity_arn = 'arn:aws:states:us-east-1:00000000000000:activity:hello'

    # [OPTIONAL] The number of worker processes.
    # If None, it will be set to the number of cores.
    # Default is None.
    processes = None

    # [OPTIONAL] Number of seconds between heartbeats.
    # None or 0 means there is no heartbeat.
    # Default is no heartbeat.
    heartbeat = 120

    # [OPTIONAL] Maximum number of tasks for a worker to run before the worker
    # process is automatically killed and a new one created.
    # If None, workers will not be killed.
    # Default is None.
    maxtasksperchild = None

    # [OPTIONAL] The multiprocessing start method for worker processes.
    # See https://docs.python.org/3.7/library/multiprocessing.html for more info
    # The default is 'spawn' which starts a fresh python interpreter process.
    # It is rather slow compared to using fork or forkserver, but we typically
    # create workers and leave them running so the impact should be minimal.
    # Possible values are:
    # spawn - Recommended (Unix and Windows)
    # fork - Not recommended due to thread-safety issues
    # forkserver - On Unix platforms which support passing fds over Unix pipes
    # '' - Uses the python defaults. Not recommended.
    start_method = 'spawn'

    # [OPTIONAL] If set to a non-zero integer, an HTTP healthcheck handler listens on
    # the port number.
    # Healthcheck requests are GET requests to 'http://localhost:<healthcheck>/'
    # and return JSON: {"status": "ok"}
    # Default is 8080
    healthcheck = 8080

    # [OPTIONAL] The server_config is an arbitrary dictionary that is available
    # in the server instance as self.config and passed to server init()
    # Use it for server-specific configuration.
    server_config = {
        'foo': 'bar'
    }

    # [OPTIONAL] The worker_config is an arbitrary dictionary that is available
    # in the worker instance as self.config
    # Use it for worker-specific configuration.
    worker_config = {
	'foo': 'bar'
    }

Run the server:

.. code-block:: bash

    $ stefuna --config=hello_config

.. code-block:: bash

    $ stefuna --help
    usage: stefuna [-h] [--config CONFIG] [--worker WORKER]
                   [--activity-arn ACTIVITY_ARN] [--processes PROCESSES]
                   [--loglevel LOGLEVEL]

    Run a Step Function Activity server.

    optional arguments:
      -h, --help            show this help message and exit
      --config CONFIG       Module or dict of config to override defaults
      --worker WORKER       Module and class of worker in dot notation. Overrides
                            config setting.
      --activity-arn ACTIVITY_ARN
                            Step Function Activity ARN, Overrides config setting.
      --processes PROCESSES
                            Number of worker processes. Overrides config setting.
                            If 0, cpu_count is used.
      --loglevel LOGLEVEL   Loglevel (debug, info, warning, error or critical).
                            Overrides config setting.

History (Change Log)
--------------------

See `HISTORY.rst <HISTORY.rst>`_

License
-------

MIT License

See `LICENSE <LICENSE>`_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="AntConfiguration">
    <buildFile url="file://$PROJECT_DIR$/build/update.xml">
      <properties>
        <property name="work.idea.home" value="$APPLICATION_HOME_DIR$" />
      </properties>
    </buildFile>
  </component>
</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              style="@style/rootStyle"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <include layout="@layout/toolbar"/>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/swipe_refresh"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            >

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view_news_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </android.support.v4.widget.SwipeRefreshLayout>

    </android.support.design.widget.CoordinatorLayout>
</LinearLayout>


text:
/**
 * @author cramakrishnan OscPacket is the abstract superclass for the various
 *         kinds of OSC Messages. Its direct subclasses are: OscMessage,
 *         OscBundle Subclasses need to know how to produce a byte array in the
 *         format specified by the OSC spec (or SuperCollider documentation, as
 *         the case may be). This implementation is based on Markus Gaelli and
 *         Iannis Zannos' OSC implementation in Squeak:
 *         http://www.emergent.de/Goodies/
 */

package com.illposed.osc;

import com.illposed.osc.utility.OSCJavaToByteArrayConverter;

/**
 * The Class OSCPacket.
 */
public abstract class OSCPacket
{

	/** The byte array. */
	protected byte[] byteArray;

	/** The is byte array computed. */
	protected boolean isByteArrayComputed;

	/**
	 * Instantiates a new OSC packet.
	 */
	public OSCPacket()
	{
		super();
	}

	/**
	 * @return byte[]
	 */
	public byte[] getByteArray()
	{
		if (!isByteArrayComputed)
		{
			computeByteArray();
		}
		return byteArray;
	}

	/**
	 * Compute byte array.
	 */
	protected void computeByteArray()
	{
		OSCJavaToByteArrayConverter stream = new OSCJavaToByteArrayConverter();
		computeByteArray(stream);
	}

	/**
	 * @param stream
	 *            OscPacketByteArrayConverter Subclasses should implement this
	 *            method to product a byte array formatted according to the
	 *            OSC/SuperCollider specification.
	 */
	protected abstract void computeByteArray(OSCJavaToByteArrayConverter stream);

	/**
	 * Inits the.
	 */
	protected void init()
	{

	}

}


text:
"""Regenerates all the .isolated test data files.

Keep in sync with ../run_isolated_smoke_test.py.
"""

import glob
import hashlib
import json
import os
import sys

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

# Ordering is important to keep this script simple.
INCLUDES_TO_FIX = [
    ('manifest2.isolated', ['manifest1.isolated']),
    ('check_files.isolated', ['gtest_fake.isolated', 'manifest2.isolated']),
]

def sha1(filename):
  with open(filename, 'rb') as f:
    return hashlib.sha1(f.read()).hexdigest()

def load(filename):
  with open(filename, 'r') as f:
    return json.load(f)

def save(filename, data):
  """Saves data as json properly formatted.

  Strips spurious whitespace json.dump likes to add at the end of lines and add
  a trailing \n.
  """
  out = ''.join(
      '%s\n' % l.rstrip()
      for l in json.dumps(data, indent=2, sort_keys=True).splitlines())
  with open(filename, 'wb') as f:
    f.write(out)

def main():
  # Simplify our life.
  os.chdir(ROOT_DIR)

  # First, reformat all the files.
  for filename in glob.glob('*.isolated'):
    save(filename, load(filename))

  # Then update the SHA-1s.
  for manifest, includes in INCLUDES_TO_FIX:
    data = load(manifest)
    data['includes'] = [sha1(f) for f in includes]
    save(manifest, data)
  return 0

if __name__ == '__main__':
  sys.exit(main())


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
E-Index
</TITLE>

<META NAME="date" CONTENT="2014-03-17">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I L M N O P Q R S T U V W X Y

E

EndOfStackException - Exception in exceptions

EndOfStackException() -
Constructor for exception exceptions.EndOfStackException

EqualBooleanCommand - Class in commands.booleanCommands

EqualBooleanCommand() -
Constructor for class commands.booleanCommands.EqualBooleanCommand

equals(Tuple) -
Method in class util.Tuple

exceptions - package exceptions

execute(Object) -
Method in class commands.advancedCommands.AddVariableAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.DoTimesAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.ForAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.IDAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.IfAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.IfElseAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.RepeatAdvancedCommand

execute(Object) -
Method in class commands.advancedCommands.ToAdvancedCommand

execute(Object) -
Method in class commands.booleanCommands.AndBooleanCommand

execute(Object) -
Method in class commands.booleanCommands.EqualBooleanCommand

execute(Object) -
Method in class commands.booleanCommands.GreaterBooleanCommand

execute(Object) -
Method in class commands.booleanCommands.LessBooleanCommand

execute(Object) -
Method in class commands.booleanCommands.NotBooleanCommand

execute(Object) -
Method in class commands.booleanCommands.NotEqualBooleanCommand

execute(Object) -
Method in class commands.booleanCommands.OrBooleanCommand

execute(Object) -
Method in class commands.Command

execute(Object) -
Method in class commands.guiCommands.PenColorQueryGuiCommand

execute(Object) -
Method in class commands.guiCommands.SetPaletteGuiCommand

execute(Object) -
Method in class commands.guiCommands.SetPenColorGuiCommand

execute(Object) -
Method in class commands.guiCommands.SetShapeGuiCommand

execute(Object) -
Method in class commands.guiCommands.ShapeQueryGuiCommand

execute(Object) -
Method in class commands.mathCommands.ATanMathCommand

execute(Object) -
Method in class commands.mathCommands.CosMathCommand

execute(Object) -
Method in class commands.mathCommands.DifferenceMathCommand

execute(Object) -
Method in class commands.mathCommands.LogMathCommand

execute(Object) -
Method in class commands.mathCommands.MinusMathCommand

execute(Object) -
Method in class commands.mathCommands.PowMathCommand

execute(Object) -
Method in class commands.mathCommands.ProductMathCommand

execute(Object) -
Method in class commands.mathCommands.QuotientMathCommand

execute(Object) -
Method in class commands.mathCommands.RandomMathCommand

execute(Object) -
Method in class commands.mathCommands.RemainderMathCommand

execute(Object) -
Method in class commands.mathCommands.SinMathCommand

execute(Object) -
Method in class commands.mathCommands.SumMathCommand

execute(Object) -
Method in class commands.mathCommands.TanMathCommand

execute(Object) -
Method in class commands.turtleCommands.BackTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.ClearScreenTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.ForwardTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.GotoTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.HeadingQueryTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.HideTurtleTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.HomeTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.LeftTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.PenDownQueryTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.PenDownTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.PenUpTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.RightTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.SetHeadingTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.ShowingQueryTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.ShowTurtleTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.XCorQueryTurtleCommand

execute(Object) -
Method in class commands.turtleCommands.YCorQueryTurtleCommand

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I L M N O P Q R S T U V W X Y


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>react password strength meter</title>


text:
import { getActiveTab, captureScreen } from '../utils'

async function init() {
    let tab = await getActiveTab();
    // print(tab.windowId + ':' + tab.id + ' # ' + tab.title);
    console.log(tab.windowId + ':' + tab.id + ' # ' + tab.title);

    // chrome.tabs.captureVisibleTab(dataUrl => {
    //     let $img = new Builder('img').attr('src', dataUrl).style('width', '100%').appendTo(imgContainer);
    // })

    //判断是否已经注入CS,没有的话则注入。
    checkCSNoExistence().then(() => {
        chrome.tabs.executeScript(null, {file: 'content_script.bundle.js'})
    })

    chrome.runtime.onMessage.addListener(msg => {
        console.log('[CS] ext received: ', msg);
    })
}

init();

//utils
function checkCSNoExistence() {
    let resolve = () => null;
    let ret = new Promise(res => {
        resolve = res;
    })
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {type: 'echo'}, function(response) {
            if(response === undefined || response.type !== 'echo') {
                resolve();
            }
        });
    });
    return ret;
}

export function sendMessageToActiveTab(msg) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, msg, function(response) {
            // console.log(response);
        });
    });
}


text:
package guru.nidi.android.view;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.Arrays;
import java.util.List;

/**
 *
 */
public class SimplePagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> fragments;

    public SimplePagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    public SimplePagerAdapter(FragmentManager fm, Fragment... fragments) {
        this(fm, Arrays.asList(fragments));
    }

    @Override
    public CharSequence getPageTitle(int position) {
        final Fragment fragment = fragments.get(position);
        return fragment instanceof Named ? ((Named) fragment).getName() : "";
    }

    @Override
    public Fragment getItem(int i) {
        return fragments.get(i);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    public int indexOf(Fragment fragment) {
        return fragments.indexOf(fragment);
    }
}


text:
package org.compass.core.test.constant;

import org.compass.core.Property;
import org.compass.core.config.CompassConfiguration;
import static org.compass.core.mapping.osem.builder.OSEM.*;

/**
 * @author kimchy
 */
public class ConstantBuilderTests extends ConstantTests {

    @Override
    protected String[] getMappings() {
        return new String[0];
    }

    @Override
    protected void addExtraConf(CompassConfiguration conf) {
        super.addExtraConf(conf);
        conf.addMapping(
                searchable(A.class).alias("a")
                        .add(id("id"))
                        .add(constant("mvalue").values("mValue11", "mValue12"))
                        .add(constant("mvalue2").store(Property.Store.NO).index(Property.Index.ANALYZED).values("mValue21", "mValue22"))
        );
    }
}


text:
<?php
namespace SamIT\AutoUpdater\Diff;

abstract class Base {
    private $initialized = false;

    protected $basePath;
    protected $preCheckFile;

    public function __construct(array $config = [])
    {
        foreach($config as $key => $value) {
            $this->$key = $value;
        }
        $this->init();
    }

    protected function init()
    {
        $this->initialized = true;
    }

    /**
     * Returns the newly created files.
     * @return string[] The relative filenames
     */
    abstract public function getCreated();
    /**
     * Returns the newly created files.
     * @return string[] The relative filenames
     */
    abstract public function getRemoved();

    /**
     * Returns the newly created files.
     * @return string[] The relative filenames
     */
    abstract public function getChanged();

    /**
     * @return string[] Keys are filenames, values are hashes.
     */
    abstract public function getSourceHashes();

    /**
     * @return string[] Keys are filenames, values are hashes.
     */
    abstract public function getTargetHashes();
    /**
     * @return string[] A list of changes between source and target.
     */
    abstract public function getChangeLog();

    /**
     * @return string The source version for this diff.
     */
    abstract public function getFrom();

    /**
     * @return string The target version for this diff.
     */
    abstract public function getTo();

    public function getBasePath() {
        return $this->basePath;
    }

    /**
     *
     * @param string|resource $privateKey A SSL private key to sign the package, or null.
     * @return \SamIT\AutoUpdater\Package\PreUpdate
     */
    public function createPreUpdatePackage(\SamIT\AutoUpdater\Package\Update $update, $privateKey = null) {
         return new \SamIT\AutoUpdater\Package\PreUpdate([
            'removedFiles' => $this->getRemoved(),
            'changedFiles' => $this->getChanged(),
            'createdFiles' => $this->getCreated(),
            'sourceHashes' => $this->getSourceHashes(),
            'targetHashes' => $this->getTargetHashes(),
            'changeLog' => $this->getChangeLog(),
            'privateKey' => $privateKey,
            'hash' => $update->getHash()
        ]);
    }

    /**
     *
     * @param string|resource $privateKey A SSL private key to sign the package, or null.
     * @return \SamIT\AutoUpdater\Package\Update
     */
    public function createUpdatePackage() {
         return new \SamIT\AutoUpdater\Package\Update([
            'changedFiles' => $this->getChanged(),
            'createdFiles' => $this->getCreated(),
            'targetHashes' => $this->getTargetHashes(),
            'basePath' => $this->basePath
        ]);
    }
}


text:
from swgpy.object import *

def create(kernel):
	result = Building()

	result.template = "object/building/general/shared_parking_garage_general.iff"
	result.attribute_template_id = -1
	result.stfName("building_name","parking_garage_general")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
#ifndef TREECORE_INPUTSOURCE_H
#define TREECORE_INPUTSOURCE_H

#include "treecore/MathsFunctions.h"
#include "treecore/LeakedObjectDetector.h"

namespace treecore {

class InputStream;
class String;

//==============================================================================
/**
    A lightweight object that can create a stream to read some kind of resource.

    This may be used to refer to a file, or some other kind of source, allowing a
    caller to create an input stream that can read from it when required.

    @see FileInputSource
*/
class TREECORE_SHARED_API  InputSource
{
public:
    //==============================================================================
    InputSource() noexcept      {}

    /** Destructor. */
    virtual ~InputSource()      {}

    //==============================================================================
    /** Returns a new InputStream to read this item.

        @returns            an inputstream that the caller will delete, or nullptr if
                            the filename isn't found.
    */
    virtual InputStream* createInputStream() = 0;

    /** Returns a new InputStream to read an item, relative.

        @param relatedItemPath  the relative pathname of the resource that is required
        @returns            an inputstream that the caller will delete, or nullptr if
                            the item isn't found.
    */
    virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;

    /** Returns a hash code that uniquely represents this item.
    */
    virtual int64 hashCode() const = 0;

private:
    //==============================================================================
    TREECORE_LEAK_DETECTOR (InputSource)
};

}

#endif   // TREECORE_INPUTSOURCE_H


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/bhkShapePhantom.h"
using namespace Niflib;

//Definition of TYPE constant
const Type bhkShapePhantom::TYPE("bhkShapePhantom", &bhkPhantom::TYPE );

bhkShapePhantom::bhkShapePhantom() {
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

bhkShapePhantom::~bhkShapePhantom() {
	//--BEGIN DESTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

const Type & bhkShapePhantom::GetType() const {
	return TYPE;
}

NiObject * bhkShapePhantom::Create() {
	return new bhkShapePhantom;
}

void bhkShapePhantom::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
	//--BEGIN PRE-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//

	bhkPhantom::Read( in, link_stack, info );

	//--BEGIN POST-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void bhkShapePhantom::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	bhkPhantom::Write( out, link_map, missing_link_stack, info );

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::string bhkShapePhantom::asString( bool verbose ) const {
	//--BEGIN PRE-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//

	stringstream out;
	out << bhkPhantom::asString();
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void bhkShapePhantom::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) {
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//

	bhkPhantom::FixLinks( objects, link_stack, missing_link_stack, info );

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> bhkShapePhantom::GetRefs() const {
	list<Ref<NiObject> > refs;
	refs = bhkPhantom::GetRefs();
	return refs;
}

std::list<NiObject *> bhkShapePhantom::GetPtrs() const {
	list<NiObject *> ptrs;
	ptrs = bhkPhantom::GetPtrs();
	return ptrs;
}

//--This object has no eligable attributes.  No example implementation generated--//

//--BEGIN MISC CUSTOM CODE--//
//--END CUSTOM CODE--//


text:
package edu.mit.isos.context;

/**
 * A factory for creating Resource objects. Defines both floating-point and
 * text arguments for numerical quantities. String arguments avoid potential
 * round-off errors and are used widely in high-performance number formats.
 *
 * @author Paul T. Grogan, ptgrogan@mit.edu
 * @version 0.1.0
 * @since 0.1.0
 */
public abstract class ResourceFactory {
	public static enum Impl {DOUBLE, BIG_DECIMAL};
	public static Impl impl = Impl.DOUBLE;

	/**
	 * Creates an empty resource.
	 *
	 * @return the resource
	 */
	public static Resource create() {
		if(impl==Impl.DOUBLE) {
			return new DoubleArrayResource();
		} else if(impl==Impl.BIG_DECIMAL) {
			return new BigDecimalArrayResource();
		} else throw new RuntimeException(
				"Unknown resource implementation selected.");
	}

	/**
	 * Creates a resource with specified amounts.
	 *
	 * @param amounts the amounts
	 * @return the resource
	 */
	public static Resource create(double[] amounts) {
		String[] strAmounts = new String[amounts.length];
		for(int i = 0; i < amounts.length; i++) {
			strAmounts[i] = String.valueOf(amounts[i]);
		}
		return create(strAmounts);
	}

	/**
	 * Creates a resource with a specified amount of a resource type.
	 *
	 * @param type the type
	 * @param amount the amount
	 * @return the resource
	 */
	public static Resource create(ResourceType type, double amount) {
		return create(type, String.valueOf(amount));
	}

	/**
	 * Creates a resource with a specified amount of a resource type.
	 * String amount argument avoids possible floating point round-off.
	 *
	 * @param type the type
	 * @param amount the amount
	 * @return the resource
	 */
	public static Resource create(ResourceType type, String amount) {
		if(impl==Impl.DOUBLE) {
			return new DoubleArrayResource(type, amount);
		} else if(impl==Impl.BIG_DECIMAL) {
			return new BigDecimalArrayResource(type, amount);
		} else throw new RuntimeException(
				"Unknown resource implementation selected.");
	}

	/**
	 * Creates a resource with specified amounts of resource types.
	 *
	 * @param types the types
	 * @param amounts the amounts
	 * @return the resource
	 */
	public static Resource create(ResourceType[] types, double amounts[]) {
		if(types.length != amounts.length) {
			throw new IllegalArgumentException("Unbalanced arguments. "
					+ types.length + "types, " + amounts.length + " amounts.");
		} else {
			Resource resource = create();
			for(int i = 0; i < types.length; i++) {
				resource = resource.add(create(types[i], amounts[i]));
			}
			return resource;
		}
	}

	/**
	 * Creates a resource with specified amounts of resource types.
	 * String amount argument avoids possible floating point round-off.
	 *
	 * @param types the types
	 * @param amounts the amounts
	 * @return the resource
	 */
	public static Resource create(ResourceType[] types, String amounts[]) {
		if(types.length != amounts.length) {
			throw new IllegalArgumentException("Unbalanced arguments. "
					+ types.length + "types, " + amounts.length + " amounts.");
		} else {
			Resource resource = create();
			for(int i = 0; i < types.length; i++) {
				resource = resource.add(create(types[i], amounts[i]));
			}
			return resource;
		}
	}

	/**
	 * Creates a resource with specified amounts.
	 * String amount argument avoids possible floating point round-off.
	 *
	 * @param amounts the amounts
	 * @return the resource
	 */
	public static Resource create(String[] amounts) {
		if(impl==Impl.DOUBLE) {
			return new DoubleArrayResource(amounts);
		} else if(impl==Impl.BIG_DECIMAL) {
			return new BigDecimalArrayResource(amounts);
		} else throw new RuntimeException(
				"Unknown resource implementation selected.");
	}
}


text:
<?php

namespace GameBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ContactType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName')
            ->add('nickname')
            ->add('email')
            ->add('phone')
            ->add('address')
            ->add('zipcode')
            ->add('city');
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'GameBundle\Entity\Contact',
            'csrf_protection' => false
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'gamebundle_contact';
    }

}


text:
<?php

require_once dirname(__FILE__) . '/CodeTestAbstract.php';

class PHPParser_Tests_ParserTest extends PHPParser_Tests_CodeTestAbstract
{
    /**
     * @dataProvider provideTestParse
     */
    public function testParse($name, $code, $dump) {
        $parser = new PHPParser_Parser(new PHPParser_Lexer_Emulative);
        $dumper = new PHPParser_NodeDumper;

        $stmts = $parser->parse($code);
        $this->assertEquals(
            $this->canonicalize($dump),
            $this->canonicalize($dumper->dump($stmts)),
            $name
        );
    }

    public function provideTestParse() {
        return $this->getTests(dirname(__FILE__) . '/../../code/parser', 'test');
    }

    /**
     * @dataProvider provideTestParseFail
     */
    public function testParseFail($name, $code, $msg) {
        $parser = new PHPParser_Parser(new PHPParser_Lexer_Emulative);

        try {
            $parser->parse($code);

            $this->fail(sprintf('"%s": Expected PHPParser_Error', $name));
        } catch (PHPParser_Error $e) {
            $this->assertEquals($msg, $e->getMessage(), $name);
        }
    }

    public function provideTestParseFail() {
        return $this->getTests(dirname(__FILE__) . '/../../code/parser', 'test-fail');
    }
}


text:
enum
{
	CHILDNODE_UPPER_RIGHT=0,
	CHILDNODE_UPPER_LEFT=1,
	CHILDNODE_LOWER_LEFT=2,
	CHILDNODE_LOWER_RIGHT=3
};

// Corner indices. Used to index m_CornerNeighbors.
enum
{
	CORNER_LOWER_LEFT=0,
	CORNER_UPPER_LEFT=1,
	CORNER_UPPER_RIGHT=2,
	CORNER_LOWER_RIGHT=3
};

// These edge indices must match the edge indices of the CCoreDispSurface.
enum
{
	NEIGHBOREDGE_LEFT=0,
	NEIGHBOREDGE_TOP=1,
	NEIGHBOREDGE_RIGHT=2,
	NEIGHBOREDGE_BOTTOM=3
};

// These denote where one dispinfo fits on another.
// Note: tables are generated based on these indices so make sure to update
//       them if these indices are changed.
typedef enum
{
	CORNER_TO_CORNER=0,
	CORNER_TO_MIDPOINT=1,
	MIDPOINT_TO_CORNER=2
} NeighborSpan;

// These define relative orientations of displacement neighbors.
typedef enum
{
	ORIENTATION_CCW_0=0,
	ORIENTATION_CCW_90=1,
	ORIENTATION_CCW_180=2,
	ORIENTATION_CCW_270=3
} NeighborOrientation;

//=============================================================================

enum
{
	LUMP_ENTITIES					= 0,	// *
	LUMP_PLANES						= 1,	// *
	LUMP_TEXDATA					= 2,	// *
	LUMP_VERTEXES					= 3,	// *
	LUMP_VISIBILITY					= 4,	// *
	LUMP_NODES						= 5,	// *
	LUMP_TEXINFO					= 6,	// *
	LUMP_FACES						= 7,	// *
	LUMP_LIGHTING					= 8,	// *
	LUMP_OCCLUSION					= 9,
	LUMP_LEAFS						= 10,	// *
	LUMP_FACEIDS					= 11,
	LUMP_EDGES						= 12,	// *
	LUMP_SURFEDGES					= 13,	// *
	LUMP_MODELS						= 14,	// *
	LUMP_WORLDLIGHTS				= 15,	//
	LUMP_LEAFFACES					= 16,	// *
	LUMP_LEAFBRUSHES				= 17,	// *
	LUMP_BRUSHES					= 18,	// *
	LUMP_BRUSHSIDES					= 19,	// *
	LUMP_AREAS						= 20,	// *
	LUMP_AREAPORTALS				= 21,	// *
	LUMP_UNUSED0					= 22,
	LUMP_UNUSED1					= 23,
	LUMP_UNUSED2					= 24,
	LUMP_UNUSED3					= 25,
	LUMP_DISPINFO					= 26,
	LUMP_ORIGINALFACES				= 27,
	LUMP_PHYSDISP					= 28,
	LUMP_PHYSCOLLIDE				= 29,
	LUMP_VERTNORMALS				= 30,
	LUMP_VERTNORMALINDICES			= 31,
	LUMP_DISP_LIGHTMAP_ALPHAS		= 32,
	LUMP_DISP_VERTS					= 33,		// CDispVerts
	LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS = 34,	// For each displacement
												//     For each lightmap sample
												//         byte for index
												//         if 255, then index = next byte + 255
												//         3 bytes for barycentric coordinates
	// The game lump is a method of adding game-specific lumps
	// FIXME: Eventually, all lumps could use the game lump system
	LUMP_GAME_LUMP					= 35,
	LUMP_LEAFWATERDATA				= 36,
	LUMP_PRIMITIVES					= 37,
	LUMP_PRIMVERTS					= 38,
	LUMP_PRIMINDICES				= 39,
	// A pak file can be embedded in a .bsp now, and the file system will search the pak
	//  file first for any referenced names, before deferring to the game directory
	//  file system/pak files and finally the base directory file system/pak files.
	LUMP_PAKFILE					= 40,
	LUMP_CLIPPORTALVERTS			= 41,
	// A map can have a number of cubemap entities in it which cause cubemap renders
	// to be taken after running vrad.
	LUMP_CUBEMAPS					= 42,
	LUMP_TEXDATA_STRING_DATA		= 43,
	LUMP_TEXDATA_STRING_TABLE		= 44,
	LUMP_OVERLAYS					= 45,
	LUMP_LEAFMINDISTTOWATER			= 46,
	LUMP_FACE_MACRO_TEXTURE_INFO	= 47,
	LUMP_DISP_TRIS					= 48,
	LUMP_PHYSCOLLIDESURFACE			= 49,	// deprecated.  We no longer use win32-specific havok compression on terrain
	LUMP_WATEROVERLAYS              = 50,
	LUMP_LEAF_AMBIENT_INDEX_HDR		= 51,	// index of LUMP_LEAF_AMBIENT_LIGHTING_HDR
	LUMP_LEAF_AMBIENT_INDEX         = 52,	// index of LUMP_LEAF_AMBIENT_LIGHTING

	// optional lumps for HDR
	LUMP_LIGHTING_HDR				= 53,
	LUMP_WORLDLIGHTS_HDR			= 54,
	LUMP_LEAF_AMBIENT_LIGHTING_HDR	= 55,	// NOTE: this data overrides part of the data stored in LUMP_LEAFS.
	LUMP_LEAF_AMBIENT_LIGHTING		= 56,	// NOTE: this data overrides part of the data stored in LUMP_LEAFS.

	LUMP_XZIPPAKFILE				= 57,   // deprecated. xbox 1: xzip version of pak file
	LUMP_FACES_HDR					= 58,	// HDR maps may have different face data.
	LUMP_MAP_FLAGS                  = 59,   // extended level-wide flags. not present in all levels
	LUMP_OVERLAY_FADES				= 60,	// Fade distances for overlays
};

// Lumps that have versions are listed here
enum
{
	LUMP_LIGHTING_VERSION          = 1,
	LUMP_FACES_VERSION             = 1,
	LUMP_OCCLUSION_VERSION         = 2,
	LUMP_LEAFS_VERSION			   = 1,
	LUMP_LEAF_AMBIENT_LIGHTING_VERSION = 1,
};

#define	HEADER_LUMPS		64

#include "zip_uncompressed.h"

struct lump_t
{
	DECLARE_BYTESWAP_DATADESC();
	int		fileofs, filelen;
	int		version;		// default to zero
	char	fourCC[4];		// default to ( char )0, ( char )0, ( char )0, ( char )0
};

struct dheader_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			ident;
	int			version;
	lump_t		lumps[HEADER_LUMPS];
	int			mapRevision;				// the map's revision (iteration, version) number (added BSPVERSION 6)
};

// level feature flags
#define LVLFLAGS_BAKED_STATIC_PROP_LIGHTING_NONHDR 0x00000001	// was processed by vrad with -staticproplighting, no hdr data
#define LVLFLAGS_BAKED_STATIC_PROP_LIGHTING_HDR    0x00000002   // was processed by vrad with -staticproplighting, in hdr

struct dflagslump_t
{
	DECLARE_BYTESWAP_DATADESC();
	uint32 m_LevelFlags;						// LVLFLAGS_xxx
};

struct lumpfileheader_t
{
	int				lumpOffset;
	int				lumpID;
	int				lumpVersion;
	int				lumpLength;
	int				mapRevision;				// the map's revision (iteration, version) number (added BSPVERSION 6)
};

struct dgamelumpheader_t
{
	DECLARE_BYTESWAP_DATADESC();
	int lumpCount;

	// dgamelump_t follow this
};

// This is expected to be a four-CC code ('lump')
typedef int GameLumpId_t;

// 360 only: game lump is compressed, filelen reflects original size
// use next entry fileofs to determine actual disk lump compressed size
// compression stage ensures a terminal null dictionary entry
#define GAMELUMPFLAG_COMPRESSED	0x0001

struct dgamelump_t
{
	DECLARE_BYTESWAP_DATADESC();
	GameLumpId_t	id;
	unsigned short	flags;
	unsigned short	version;
	int				fileofs;
	int				filelen;
};

extern int g_MapRevision;

struct dmodel_t
{
	DECLARE_BYTESWAP_DATADESC();
	Vector		mins, maxs;
	Vector		origin;					// for sounds or lights
	int			headnode;
	int			firstface, numfaces;	// submodels just draw faces without walking the bsp tree
};

struct dphysmodel_t
{
	DECLARE_BYTESWAP_DATADESC()
	int			modelIndex;
	int			dataSize;
	int			keydataSize;
	int			solidCount;
};

// contains the binary blob for each displacement surface's virtual hull
struct dphysdisp_t
{
	DECLARE_BYTESWAP_DATADESC()
	unsigned short numDisplacements;
	//unsigned short dataSize[numDisplacements];
};

struct dvertex_t
{
	DECLARE_BYTESWAP_DATADESC();
	Vector	point;
};

// planes (x&~1) and (x&~1)+1 are always opposites
struct dplane_t
{
	DECLARE_BYTESWAP_DATADESC();
	Vector	normal;
	float	dist;
	int		type;		// PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
};

#ifndef BSPFLAGS_H
#include "bspflags.h"
#endif

struct dnode_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			planenum;
	int			children[2];	// negative numbers are -(leafs+1), not nodes
	short		mins[3];		// for frustom culling
	short		maxs[3];
	unsigned short	firstface;
	unsigned short	numfaces;	// counting both sides
	short			area;		// If all leaves below this node are in the same area, then
								// this is the area index. If not, this is -1.
};

typedef struct texinfo_s
{
	DECLARE_BYTESWAP_DATADESC();
	float		textureVecsTexelsPerWorldUnits[2][4];			// [s/t][xyz offset]
	float		lightmapVecsLuxelsPerWorldUnits[2][4];			// [s/t][xyz offset] - length is in units of texels/area
	int			flags;				// miptex flags + overrides
	int			texdata;			// Pointer to texture name, size, etc.
} texinfo_t;

#define TEXTURE_NAME_LENGTH	 128			// changed from 64 BSPVERSION 8

struct dtexdata_t
{
	DECLARE_BYTESWAP_DATADESC();
	Vector		reflectivity;
	int			nameStringTableID;				// index into g_StringTable for the texture name
	int			width, height;					// source image
	int			view_width, view_height;		//
};

//-----------------------------------------------------------------------------
// Occluders are simply polygons
//-----------------------------------------------------------------------------
// Flags field of doccluderdata_t
enum
{
	OCCLUDER_FLAGS_INACTIVE = 0x1,
};

struct doccluderdata_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			flags;
	int			firstpoly;				// index into doccluderpolys
	int			polycount;
	Vector		mins;
	Vector		maxs;
	int			area;
};

struct doccluderdataV1_t
{
	int			flags;
	int			firstpoly;				// index into doccluderpolys
	int			polycount;
	Vector		mins;
	Vector		maxs;
};

struct doccluderpolydata_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			firstvertexindex;		// index into doccludervertindices
	int			vertexcount;
	int			planenum;
};

// NOTE: see the section above titled "displacement neighbor rules".
struct CDispSubNeighbor
{
public:
	DECLARE_BYTESWAP_DATADESC();
	unsigned short		GetNeighborIndex() const		{ return m_iNeighbor; }
	NeighborSpan		GetSpan() const					{ return (NeighborSpan)m_Span; }
	NeighborSpan		GetNeighborSpan() const			{ return (NeighborSpan)m_NeighborSpan; }
	NeighborOrientation	GetNeighborOrientation() const	{ return (NeighborOrientation)m_NeighborOrientation; }

	bool				IsValid() const				{ return m_iNeighbor != 0xFFFF; }
	void				SetInvalid()				{ m_iNeighbor = 0xFFFF; }

public:
	unsigned short		m_iNeighbor;		// This indexes into ddispinfos.
											// 0xFFFF if there is no neighbor here.

	unsigned char		m_NeighborOrientation;		// (CCW) rotation of the neighbor wrt this displacement.

	// These use the NeighborSpan type.
	unsigned char		m_Span;						// Where the neighbor fits onto this side of our displacement.
	unsigned char		m_NeighborSpan;				// Where we fit onto our neighbor.
};

// NOTE: see the section above titled "displacement neighbor rules".
class CDispNeighbor
{
public:
	DECLARE_BYTESWAP_DATADESC();
	void				SetInvalid()	{ m_SubNeighbors[0].SetInvalid(); m_SubNeighbors[1].SetInvalid(); }

	// Returns false if there isn't anything touching this edge.
	bool				IsValid()		{ return m_SubNeighbors[0].IsValid() || m_SubNeighbors[1].IsValid(); }

public:
	// Note: if there is a neighbor that fills the whole side (CORNER_TO_CORNER),
	//       then it will always be in CDispNeighbor::m_Neighbors[0]
	CDispSubNeighbor	m_SubNeighbors[2];
};

class CDispCornerNeighbors
{
public:
	DECLARE_BYTESWAP_DATADESC();
	void			SetInvalid()	{ m_nNeighbors = 0; }

public:
	unsigned short	m_Neighbors[MAX_DISP_CORNER_NEIGHBORS];	// indices of neighbors.
	unsigned char	m_nNeighbors;
};

class CDispVert
{
public:
	DECLARE_BYTESWAP_DATADESC();
	Vector		m_vVector;		// Vector field defining displacement volume.
	float		m_flDist;		// Displacement distances.
	float		m_flAlpha;		// "per vertex" alpha values.
};

#define DISPTRI_TAG_SURFACE			(1<<0)
#define DISPTRI_TAG_WALKABLE		(1<<1)
#define DISPTRI_TAG_BUILDABLE		(1<<2)
#define DISPTRI_FLAG_SURFPROP1		(1<<3)
#define DISPTRI_FLAG_SURFPROP2		(1<<4)
#define DISPTRI_TAG_REMOVE			(1<<5)

class CDispTri
{
public:
	DECLARE_BYTESWAP_DATADESC();
	unsigned short m_uiTags;		// Displacement triangle tags.
};

class ddispinfo_t
{
public:
	DECLARE_BYTESWAP_DATADESC();
	int			NumVerts() const		{ return NUM_DISP_POWER_VERTS(power); }
	int			NumTris() const			{ return NUM_DISP_POWER_TRIS(power); }

public:
	Vector		startPosition;						// start position used for orientation -- (added BSPVERSION 6)
	int			m_iDispVertStart;					// Index into LUMP_DISP_VERTS.
	int			m_iDispTriStart;					// Index into LUMP_DISP_TRIS.

    int         power;                              // power - indicates size of map (2^power + 1)
    int         minTess;                            // minimum tesselation allowed
    float       smoothingAngle;                     // lighting smoothing angle
    int         contents;                           // surface contents

	unsigned short	m_iMapFace;						// Which map face this displacement comes from.

	int			m_iLightmapAlphaStart;				// Index into ddisplightmapalpha.
													// The count is m_pParent->lightmapTextureSizeInLuxels[0]*m_pParent->lightmapTextureSizeInLuxels[1].

	int			m_iLightmapSamplePositionStart;		// Index into LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS.

	CDispNeighbor			m_EdgeNeighbors[4];		// Indexed by NEIGHBOREDGE_ defines.
	CDispCornerNeighbors	m_CornerNeighbors[4];	// Indexed by CORNER_ defines.

	enum unnamed { ALLOWEDVERTS_SIZE = PAD_NUMBER( MAX_DISPVERTS, 32 ) / 32 };
	unsigned long	m_AllowedVerts[ALLOWEDVERTS_SIZE];	// This is built based on the layout and sizes of our neighbors
														// and tells us which vertices are allowed to be active.
};

// note that edge 0 is never used, because negative edge nums are used for
// counterclockwise use of the edge in a face
struct dedge_t
{
	DECLARE_BYTESWAP_DATADESC();
	unsigned short	v[2];		// vertex numbers
};

#define	MAXLIGHTMAPS	4

enum dprimitive_type
{
	PRIM_TRILIST=0,
	PRIM_TRISTRIP=1,
};

struct dprimitive_t
{
	DECLARE_BYTESWAP_DATADESC();
	unsigned char type;
	unsigned short	firstIndex;
	unsigned short	indexCount;
	unsigned short	firstVert;
	unsigned short	vertCount;
};

struct dprimvert_t
{
	DECLARE_BYTESWAP_DATADESC();
	Vector		pos;
};

struct dface_t
{
	DECLARE_BYTESWAP_DATADESC();
	unsigned short	planenum;
	byte		side;	// faces opposite to the node's plane direction
	byte		onNode; // 1 of on node, 0 if in leaf

	int			firstedge;		// we must support > 64k edges
	short		numedges;
	short		texinfo;
	// This is a union under the assumption that a fog volume boundary (ie. water surface)
	// isn't a displacement map.
	// FIXME: These should be made a union with a flags or type field for which one it is
	// if we can add more to this.
//	union
//	{
	    short       dispinfo;
		// This is only for surfaces that are the boundaries of fog volumes
		// (ie. water surfaces)
		// All of the rest of the surfaces can look at their leaf to find out
		// what fog volume they are in.
		short		surfaceFogVolumeID;
//	};

	// lighting info
	byte		styles[MAXLIGHTMAPS];
	int			lightofs;		// start of [numstyles*surfsize] samples
    float       area;

	// TODO: make these unsigned chars?
	int			m_LightmapTextureMinsInLuxels[2];
	int			m_LightmapTextureSizeInLuxels[2];

	int origFace;				// reference the original face this face was derived from

public:

	unsigned short GetNumPrims() const;
	void SetNumPrims( unsigned short nPrims );
	bool AreDynamicShadowsEnabled();
	void SetDynamicShadowsEnabled( bool bEnabled );

	// non-polygon primitives (strips and lists)
private:
	unsigned short m_NumPrims;	// Top bit, if set, disables shadows on this surface (this is why there are accessors).

public:
	unsigned short	firstPrimID;

	unsigned int	smoothingGroups;
};

inline unsigned short dface_t::GetNumPrims() const
{
	return m_NumPrims & 0x7FFF;
}

inline void dface_t::SetNumPrims( unsigned short nPrims )
{
	Assert( (nPrims & 0x8000) == 0 );
	m_NumPrims &= ~0x7FFF;
	m_NumPrims |= (nPrims & 0x7FFF);
}

inline bool dface_t::AreDynamicShadowsEnabled()
{
	return (m_NumPrims & 0x8000) == 0;
}

inline void dface_t::SetDynamicShadowsEnabled( bool bEnabled )
{
	if ( bEnabled )
		m_NumPrims &= ~0x8000;
	else
		m_NumPrims |= 0x8000;
}

struct dfaceid_t
{
	DECLARE_BYTESWAP_DATADESC();
	unsigned short	hammerfaceid;
};

// NOTE: Only 7-bits stored!!!
#define LEAF_FLAGS_SKY			0x01		// This leaf has 3D sky in its PVS
#define LEAF_FLAGS_RADIAL		0x02		// This leaf culled away some portals due to radial vis
#define LEAF_FLAGS_SKY2D		0x04		// This leaf has 2D sky in its PVS

#if defined( _X360 )
#pragma bitfield_order( push, lsb_to_msb )
#endif
#pragma warning( disable:4201 )	// C4201: nonstandard extension used: nameless struct/union
struct dleaf_version_0_t
{
	DECLARE_BYTESWAP_DATADESC();
	int				contents;			// OR of all brushes (not needed?)

	short			cluster;

	BEGIN_BITFIELD( bf );
	short			area:9;
	short			flags:7;			// Per leaf flags.
	END_BITFIELD();

	short			mins[3];			// for frustum culling
	short			maxs[3];

	unsigned short	firstleafface;
	unsigned short	numleaffaces;

	unsigned short	firstleafbrush;
	unsigned short	numleafbrushes;
	short			leafWaterDataID; // -1 for not in water

	// Precaculated light info for entities.
	CompressedLightCube m_AmbientLighting;
};

// version 1
struct dleaf_t
{
	DECLARE_BYTESWAP_DATADESC();
	int				contents;			// OR of all brushes (not needed?)

	short			cluster;

	BEGIN_BITFIELD( bf );
	short			area:9;
	short			flags:7;			// Per leaf flags.
	END_BITFIELD();

	short			mins[3];			// for frustum culling
	short			maxs[3];

	unsigned short	firstleafface;
	unsigned short	numleaffaces;

	unsigned short	firstleafbrush;
	unsigned short	numleafbrushes;
	short			leafWaterDataID; // -1 for not in water

	// NOTE: removed this for version 1 and moved into separate lump "LUMP_LEAF_AMBIENT_LIGHTING" or "LUMP_LEAF_AMBIENT_LIGHTING_HDR"
	// Precaculated light info for entities.
//	CompressedLightCube m_AmbientLighting;
};
#pragma warning( default:4201 )	// C4201: nonstandard extension used: nameless struct/union
#if defined( _X360 )
#pragma bitfield_order( pop )
#endif

// each leaf contains N samples of the ambient lighting
// each sample contains a cube of ambient light projected on to each axis
// and a sampling position encoded as a 0.8 fraction (mins=0,maxs=255) of the leaf's bounding box
struct dleafambientlighting_t
{
	DECLARE_BYTESWAP_DATADESC();
	CompressedLightCube	cube;
	byte x;		// fixed point fraction of leaf bounds
	byte y;		// fixed point fraction of leaf bounds
	byte z;		// fixed point fraction of leaf bounds
	byte pad;	// unused
};

struct dleafambientindex_t
{
	DECLARE_BYTESWAP_DATADESC();

	unsigned short ambientSampleCount;
	unsigned short firstAmbientSample;
};

struct dbrushside_t
{
	DECLARE_BYTESWAP_DATADESC();
	unsigned short	planenum;		// facing out of the leaf
	short			texinfo;
	short			dispinfo;		// displacement info (BSPVERSION 7)
	short			bevel;			// is the side a bevel plane? (BSPVERSION 7)
};

struct dbrush_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			firstside;
	int			numsides;
	int			contents;
};

#define	ANGLE_UP	-1
#define	ANGLE_DOWN	-2

// the visibility lump consists of a header with a count, then
// byte offsets for the PVS and PHS of each cluster, then the raw
// compressed bit vectors
#define	DVIS_PVS	0
#define	DVIS_PAS	1
struct dvis_t
{
	int			numclusters;
	int			bitofs[8][2];	// bitofs[numclusters][2]
};

// each area has a list of portals that lead into other areas
// when portals are closed, other areas may not be visible or
// hearable even if the vis info says that it should be
struct dareaportal_t
{
	DECLARE_BYTESWAP_DATADESC();
	unsigned short	m_PortalKey;		// Entities have a key called portalnumber (and in vbsp a variable
									// called areaportalnum) which is used
									// to bind them to the area portals by comparing with this value.

	unsigned short	otherarea;		// The area this portal looks into.

	unsigned short	m_FirstClipPortalVert;	// Portal geometry.
	unsigned short	m_nClipPortalVerts;

	int				planenum;
};

struct darea_t
{
	DECLARE_BYTESWAP_DATADESC();
	int		numareaportals;
	int		firstareaportal;
};

struct dleafwaterdata_t
{
	DECLARE_BYTESWAP_DATADESC();
	float	surfaceZ;
	float	minZ;
	short	surfaceTexInfoID;
};

class CFaceMacroTextureInfo
{
public:
	DECLARE_BYTESWAP_DATADESC();
	// This looks up into g_TexDataStringTable, which looks up into g_TexDataStringData.
	// 0xFFFF if the face has no macro texture.
	unsigned short m_MacroTextureNameID;
};

// lights that were used to illuminate the world
enum emittype_t
{
	emit_surface,		// 90 degree spotlight
	emit_point,			// simple point light source
	emit_spotlight,		// spotlight with penumbra
	emit_skylight,		// directional light with no falloff (surface must trace to SKY texture)
	emit_quakelight,	// linear falloff, non-lambertian
	emit_skyambient,	// spherical light source with no falloff (surface must trace to SKY texture)
};

// Flags for dworldlight_t::flags
#define DWL_FLAGS_INAMBIENTCUBE		0x0001	// This says that the light was put into the per-leaf ambient cubes.

struct dworldlight_t
{
	DECLARE_BYTESWAP_DATADESC();
	Vector		origin;
	Vector		intensity;
	Vector		normal;			// for surfaces and spotlights
	int			cluster;
	emittype_t	type;
    int			style;
	float		stopdot;		// start of penumbra for emit_spotlight
	float		stopdot2;		// end of penumbra for emit_spotlight
	float		exponent;		//
	float		radius;			// cutoff distance
	// falloff for emit_spotlight + emit_point:
	// 1 / (constant_attn + linear_attn * dist + quadratic_attn * dist^2)
	float		constant_attn;
	float		linear_attn;
	float		quadratic_attn;
	int			flags;			// Uses a combination of the DWL_FLAGS_ defines.
	int			texinfo;		//
	int			owner;			// entity that this light it relative to
};

struct dcubemapsample_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			origin[3];			// position of light snapped to the nearest integer
									// the filename for the vtf file is derived from the position
	unsigned char size;				// 0 - default
									// otherwise, 1<<(size-1)
};

#define OVERLAY_BSP_FACE_COUNT	64

#define OVERLAY_NUM_RENDER_ORDERS		(1<<OVERLAY_RENDER_ORDER_NUM_BITS)
#define OVERLAY_RENDER_ORDER_NUM_BITS	2
#define OVERLAY_RENDER_ORDER_MASK		0xC000	// top 2 bits set

struct doverlay_t
{
	DECLARE_BYTESWAP_DATADESC();
	int			nId;
	short		nTexInfo;

	// Accessors..
	void			SetFaceCount( unsigned short count );
	unsigned short	GetFaceCount() const;

	void			SetRenderOrder( unsigned short order );
	unsigned short	GetRenderOrder() const;

private:
	unsigned short	m_nFaceCountAndRenderOrder;

public:
	int			aFaces[OVERLAY_BSP_FACE_COUNT];
	float		flU[2];
	float		flV[2];
	Vector		vecUVPoints[4];
	Vector		vecOrigin;
	Vector		vecBasisNormal;
};

inline void doverlay_t::SetFaceCount( unsigned short count )
{
	m_nFaceCountAndRenderOrder &= OVERLAY_RENDER_ORDER_MASK;
	m_nFaceCountAndRenderOrder |= (count & ~OVERLAY_RENDER_ORDER_MASK);
}

inline unsigned short doverlay_t::GetFaceCount() const
{
	return m_nFaceCountAndRenderOrder & ~OVERLAY_RENDER_ORDER_MASK;
}

inline void doverlay_t::SetRenderOrder( unsigned short order )
{
	m_nFaceCountAndRenderOrder &= ~OVERLAY_RENDER_ORDER_MASK;
	m_nFaceCountAndRenderOrder |= (order << (16 - OVERLAY_RENDER_ORDER_NUM_BITS));	// leave 2 bits for render order.
}

inline unsigned short doverlay_t::GetRenderOrder() const
{
	return (m_nFaceCountAndRenderOrder >> (16 - OVERLAY_RENDER_ORDER_NUM_BITS));
}

struct doverlayfade_t
{
	DECLARE_BYTESWAP_DATADESC();

	float flFadeDistMinSq;
	float flFadeDistMaxSq;
};

#define WATEROVERLAY_BSP_FACE_COUNT				256
#define WATEROVERLAY_RENDER_ORDER_NUM_BITS		2
#define WATEROVERLAY_NUM_RENDER_ORDERS			(1<<WATEROVERLAY_RENDER_ORDER_NUM_BITS)
#define WATEROVERLAY_RENDER_ORDER_MASK			0xC000	// top 2 bits set
struct dwateroverlay_t
{
	DECLARE_BYTESWAP_DATADESC();
	int				nId;
	short			nTexInfo;

	// Accessors..
	void			SetFaceCount( unsigned short count );
	unsigned short	GetFaceCount() const;
	void			SetRenderOrder( unsigned short order );
	unsigned short	GetRenderOrder() const;

private:

	unsigned short	m_nFaceCountAndRenderOrder;

public:

	int				aFaces[WATEROVERLAY_BSP_FACE_COUNT];
	float			flU[2];
	float			flV[2];
	Vector			vecUVPoints[4];
	Vector			vecOrigin;
	Vector			vecBasisNormal;
};

inline void dwateroverlay_t::SetFaceCount( unsigned short count )
{
	m_nFaceCountAndRenderOrder &= WATEROVERLAY_RENDER_ORDER_MASK;
	m_nFaceCountAndRenderOrder |= (count & ~WATEROVERLAY_RENDER_ORDER_MASK);
}

inline unsigned short dwateroverlay_t::GetFaceCount() const
{
	return m_nFaceCountAndRenderOrder & ~WATEROVERLAY_RENDER_ORDER_MASK;
}

inline void dwateroverlay_t::SetRenderOrder( unsigned short order )
{
	m_nFaceCountAndRenderOrder &= ~WATEROVERLAY_RENDER_ORDER_MASK;
	m_nFaceCountAndRenderOrder |= ( order << ( 16 - WATEROVERLAY_RENDER_ORDER_NUM_BITS ) );	// leave 2 bits for render order.
}

inline unsigned short dwateroverlay_t::GetRenderOrder() const
{
	return ( m_nFaceCountAndRenderOrder >> ( 16 - WATEROVERLAY_RENDER_ORDER_NUM_BITS ) );
}

#ifndef _DEF_BYTE_
#define _DEF_BYTE_
typedef unsigned char	byte;
typedef unsigned short	word;
#endif

#define	ANGLE_UP	-1
#define	ANGLE_DOWN	-2

//===============

struct epair_t
{
	epair_t	*next;
	char	*key;
	char	*value;
};

// finalized page of surface's lightmaps
#define MAX_LIGHTMAPPAGE_WIDTH	256
#define MAX_LIGHTMAPPAGE_HEIGHT	128
typedef struct nameForDatadesc_dlightmappage_t // unnamed structs collide in the datadesc macros
{
	DECLARE_BYTESWAP_DATADESC();
	byte	data[MAX_LIGHTMAPPAGE_WIDTH*MAX_LIGHTMAPPAGE_HEIGHT];
	byte	palette[256*4];
} dlightmappage_t;

typedef struct nameForDatadesc_dlightmappageinfo_t // unnamed structs collide in the datadesc macros
{
	DECLARE_BYTESWAP_DATADESC();
	byte			page;			// lightmap page [0..?]
	byte			offset[2];		// offset into page (s,t)
	byte			pad;			// unused
	ColorRGBExp32	avgColor;		// average used for runtime lighting calcs
} dlightmappageinfo_t;

#endif // BSPFILE_H


text:
import Ember from 'ember';
import ControllerUtils from '../mixins/controller-utils';
import ModalHandler from '../mixins/modal-handler';
import NotificationHandler from '../mixins/notification-handler';
import SizeListener from '../mixins/size-listener';

export default Ember.Controller.extend(SizeListener,
        ModalHandler, NotificationHandler, ControllerUtils, {
    documentView: null,
    breadCrumb: null,
    breadCrumbs: null,

    setBreadCrumbs: function() {
        this.set('breadCrumb', null);
        this.set('breadCrumbs', null);
    }.on('init'),

    extractionTypes: ['text', 'number', 'image', 'price', 'raw html',
                      'safe html', 'geopoint', 'url', 'date'],

    setDocumentView: function() {
        this.set('documentView', this.get('document.view'));
    }.on('init'),

    annotationsStore: Ember.computed.reads('document.store'),

    actions: {
        updateField: function(value, field) {
            if (field) {
                this.set(field, value);
            }
        },
    }
});


text:
package org.apache.james.mailbox.store.search;

import java.util.Iterator;
import java.util.List;

import javax.mail.Flags;

import org.apache.james.mailbox.MailboxListener;
import org.apache.james.mailbox.MailboxSession;
import org.apache.james.mailbox.exception.MailboxException;
import org.apache.james.mailbox.model.MessageRange;
import org.apache.james.mailbox.model.UpdatedFlags;
import org.apache.james.mailbox.store.MailboxEventDispatcher.AddedImpl;
import org.apache.james.mailbox.store.MailboxEventDispatcher.ExpungedImpl;
import org.apache.james.mailbox.store.MailboxEventDispatcher.FlagsUpdatedImpl;
import org.apache.james.mailbox.store.MailboxEventDispatcher.MailboxDeletionImpl;
import org.apache.james.mailbox.store.mail.MessageMapper.FetchType;
import org.apache.james.mailbox.store.mail.MessageMapperFactory;
import org.apache.james.mailbox.store.mail.model.MailboxId;
import org.apache.james.mailbox.store.mail.model.Mailbox;
import org.apache.james.mailbox.store.mail.model.Message;

/**
 * {@link MessageSearchIndex} which needs to get registered as global {@link MailboxListener} and so get
 * notified about message changes. This will then allow to update the underlying index.
 *
 *
 * @param <Id>
 */
public abstract class ListeningMessageSearchIndex<Id extends MailboxId> implements MessageSearchIndex<Id>, MailboxListener {

    private MessageMapperFactory<Id> factory;

    public ListeningMessageSearchIndex(MessageMapperFactory<Id> factory) {
        this.factory = factory;
    }

    /**
     * Return the {@link MessageMapperFactory}
     *
     * @return factory
     */
    protected MessageMapperFactory<Id> getFactory() {
        return factory;
    }

    /**
     * Process the {@link org.apache.james.mailbox.MailboxListener.Event} and update the index if
     * something relevant is received
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void event(Event event) {
        final MailboxSession session = event.getSession();

        try {
            if (event instanceof MessageEvent) {
                if (event instanceof AddedImpl) {
                    AddedImpl added = (AddedImpl) event;
                    final Mailbox<Id> mailbox = added.getMailbox();
                    Iterator<Long> uids = added.getUids().iterator();

                    while (uids.hasNext()) {
                        long next = uids.next();
                        Iterator<Message<Id>> messages = factory.getMessageMapper(session).findInMailbox(mailbox, MessageRange.one(next), FetchType.Full, -1);
                        while(messages.hasNext()) {
                            Message<Id> message = messages.next();
                            try {
                                add(session, mailbox, message);
                            } catch (MailboxException e) {
                                session.getLog().debug("Unable to index message " + message.getUid() + " for mailbox " + mailbox, e);
                            }
                        }

                    }
                } else if (event instanceof ExpungedImpl) {
                    ExpungedImpl expunged = (ExpungedImpl) event;
                    final Mailbox<Id> mailbox = expunged.getMailbox();
                    List<Long> uids = expunged.getUids();
                    List<MessageRange> ranges = MessageRange.toRanges(uids);
                    for (int i = 0; i < ranges.size(); i++) {
                        MessageRange range = ranges.get(i);
                        try {
                            delete(session, mailbox, range);
                        } catch (MailboxException e) {
                            session.getLog().debug("Unable to deleted range " + range.toString() + " from index for mailbox " + mailbox, e);
                        }
                    }
                } else if (event instanceof FlagsUpdatedImpl) {
                    FlagsUpdatedImpl flagsUpdated = (FlagsUpdatedImpl) event;
                    final Mailbox<Id> mailbox = flagsUpdated.getMailbox();

                    Iterator<UpdatedFlags> flags = flagsUpdated.getUpdatedFlags().iterator();
                    while(flags.hasNext()) {
                        UpdatedFlags uFlags = flags.next();
                        try {
                            update(session, mailbox, MessageRange.one(uFlags.getUid()), uFlags.getNewFlags(), uFlags.getModSeq());
                        } catch (MailboxException e) {
                            session.getLog().debug("Unable to update flags for message " + uFlags.getUid() + " in index for mailbox " + mailbox, e);
                        }
                    }
                }
            } else if (event instanceof MailboxDeletionImpl) {
                // delete all indexed messages for the mailbox
                delete(session, ((MailboxDeletionImpl) event).getMailbox(), MessageRange.all());
            }
        } catch (MailboxException e) {
            session.getLog().debug("Unable to update index", e);

        }
    }

    /**
     * Never closed
     */
    public boolean isClosed() {
        return false;
    }

    /**
     * Add the {@link Message} for the given {@link Mailbox} to the index
     *
     * @param session
     * @param mailbox
     * @param message
     * @throws MailboxException
     */
    public abstract void add(MailboxSession session, Mailbox<Id> mailbox, Message<Id> message) throws MailboxException;

    /**
     * Delete the {@link MessageRange} for the given {@link Mailbox} from the index
     *
     * @param session
     * @param mailbox
     * @param range
     * @throws MailboxException
     */
    public abstract void delete(MailboxSession session, Mailbox<Id> mailbox, MessageRange range) throws MailboxException;

    /**
     * Update the {@link MessageRange} for the given {@link Mailbox} with the new {@link Flags} in the index
     *
     * @param session
     * @param mailbox
     * @param range
     * @param flags
     * @throws MailboxException
     */
    public abstract void update(MailboxSession session, Mailbox<Id> mailbox, MessageRange range, Flags flags, long modseq) throws MailboxException;
}


text:
// Author(s):
// - Zachary Aaron Patten (aka Seven) seven@sevenengine.com
// Last Edited: 11-16-13

namespace SevenEngine.Physics.Primitives
{
  public class Cone
  {

  }
}


text:
using namespace cms;

class Object {
public:
  int number;

  void cfg(cfg::Cfg& cfg) {
    cfg
    .connectAttr<void()>("emitOn", [](){

    })
    .connectAttr<void()>("executeOn", [](){

    })
    .pushRef<int>("state", this->number);
  }
};

TEST_CASE("cms::cfg::ctree::TreeBuilder", ""){
  SECTION("reset"){
    cfg::ctree::TreeBuilder builder;
    builder.addCfgObjectInstantiator<Object>("Object");
    builder.getModelCollection().loadJsonFromFile(ci::app::getAssetPath("test_treebuilder.json"));

    REQUIRE(builder.getRegistry()->size() == 0);
    REQUIRE(builder.getConfigurator()->getStates().size() == 0);
    REQUIRE(builder.getConfigurator()->getSignals().size() == 0);

    auto obj = builder.build<Object>("Object");
    REQUIRE(builder.getRegistry()->size() == 1);
    REQUIRE(builder.getConfigurator()->getStates().size() == 1);
    REQUIRE(builder.getConfigurator()->getSignals().size() == 2);

    builder.reset();
    REQUIRE(builder.getRegistry()->size() == 0);
    REQUIRE(builder.getConfigurator()->getStates().size() == 0);
    REQUIRE(builder.getConfigurator()->getSignals().size() == 0);
  }

  SECTION("Registry"){
    SECTION("getById for non-existing id") {
      cfg::ctree::TreeBuilder builder;
      REQUIRE(builder.getRegistry()->getById("foobar") == NULL);
    }
  }
}

#endif


text:
/* -----------------------------------------------------------------------------
 *
 * (c) The GHC Team, 1998-2006
 *
 * The IO manager thread in THREADED_RTS.
 * See also libraries/base/GHC/Conc.lhs.
 *
 * ---------------------------------------------------------------------------*/

#include "Rts.h"
#include "IOManager.h"
#include "Prelude.h"
#include <windows.h>

// Here's the Event that we use to wake up the IO manager thread
static HANDLE io_manager_event = INVALID_HANDLE_VALUE;

// must agree with values in GHC.Conc:
#define IO_MANAGER_WAKEUP 0xffffffff
#define IO_MANAGER_DIE    0xfffffffe
// spurios wakeups are returned as zero.
// console events are ((event<<1) | 1)

#if defined(THREADED_RTS)

#define EVENT_BUFSIZ 256
Mutex event_buf_mutex;
StgWord32 event_buf[EVENT_BUFSIZ];
uint32_t next_event;

#endif

HANDLE
getIOManagerEvent (void)
{
    // This function has to exist even in the non-THREADED_RTS,
    // because code in GHC.Conc refers to it.  It won't ever be called
    // unless we're in the threaded RTS, however.
#ifdef THREADED_RTS
    HANDLE hRes;

    ACQUIRE_LOCK(&event_buf_mutex);

    if (io_manager_event == INVALID_HANDLE_VALUE) {
        hRes = CreateEvent ( NULL, // no security attrs
                             true, // manual reset
                             false, // initial state,
                             NULL ); // event name: NULL for private events
        if (hRes == NULL) {
            sysErrorBelch("getIOManagerEvent");
            stg_exit(EXIT_FAILURE);
        }
        io_manager_event = hRes;
    } else {
        hRes = io_manager_event;
    }

    RELEASE_LOCK(&event_buf_mutex);
    return hRes;
#else
    return NULL;
#endif
}

HsWord32
readIOManagerEvent (void)
{
    // This function must exist even in non-THREADED_RTS,
    // see getIOManagerEvent() above.
#if defined(THREADED_RTS)
    HsWord32 res;

    ACQUIRE_LOCK(&event_buf_mutex);

    if (io_manager_event != INVALID_HANDLE_VALUE) {
        if (next_event == 0) {
            res = 0; // no event to return
        } else {
            res = (HsWord32)(event_buf[--next_event]);
            if (next_event == 0) {
                if (!ResetEvent(io_manager_event)) {
                    sysErrorBelch("readIOManagerEvent");
                    stg_exit(EXIT_FAILURE);
                }
            }
        }
    } else {
        res = 0;
    }

    RELEASE_LOCK(&event_buf_mutex);

    // debugBelch("readIOManagerEvent: %d\n", res);
    return res;
#else
    return 0;
#endif
}

void
sendIOManagerEvent (HsWord32 event)
{
#if defined(THREADED_RTS)
    ACQUIRE_LOCK(&event_buf_mutex);

    // debugBelch("sendIOManagerEvent: %d\n", event);
    if (io_manager_event != INVALID_HANDLE_VALUE) {
        if (next_event == EVENT_BUFSIZ) {
            errorBelch("event buffer overflowed; event dropped");
        } else {
            if (!SetEvent(io_manager_event)) {
                sysErrorBelch("sendIOManagerEvent");
                stg_exit(EXIT_FAILURE);
            }
            event_buf[next_event++] = (StgWord32)event;
        }
    }

    RELEASE_LOCK(&event_buf_mutex);
#endif
}

void
ioManagerWakeup (void)
{
    sendIOManagerEvent(IO_MANAGER_WAKEUP);
}

#if defined(THREADED_RTS)
void
ioManagerDie (void)
{
    sendIOManagerEvent(IO_MANAGER_DIE);
    // IO_MANAGER_DIE must be idempotent, as it is called
    // repeatedly by shutdownCapability().  Try conc059(threaded1) to
    // illustrate the problem.
    ACQUIRE_LOCK(&event_buf_mutex);
    io_manager_event = INVALID_HANDLE_VALUE;
    RELEASE_LOCK(&event_buf_mutex);
    // ToDo: wait for the IO manager to pick up the event, and
    // then release the Event and Mutex objects we've allocated.
}

void
ioManagerStart (void)
{
    initMutex(&event_buf_mutex);
    next_event = 0;

    // Make sure the IO manager thread is running
    Capability *cap;
    if (io_manager_event == INVALID_HANDLE_VALUE) {
        cap = rts_lock();
        rts_evalIO(&cap, ensureIOManagerIsRunning_closure, NULL);
        rts_unlock(cap);
    }
}
#endif


text:
<?php
class Controller_Posts extends Controller_Template{

	public function action_index()
	{
		$data['posts'] = Model_Post::find('all');
		$this->template->title = "Posts";
		$this->template->content = View::forge('posts/index', $data);

	}

	public function action_view($id = null)
	{
		is_null($id) and Response::redirect('posts');

		if ( ! $data['post'] = Model_Post::find($id))
		{
			Session::set_flash('error', 'Could not find post #'.$id);
			Response::redirect('posts');
		}

		$this->template->title = "Post";
		$this->template->content = View::forge('posts/view', $data);

	}

	public function action_create()
	{
		if (Input::method() == 'POST')
		{
			$val = Model_Post::validate('create');

			if ($val->run())
			{
				$post = Model_Post::forge(array(
					'title' => Input::post('title'),
					'body' => Input::post('body'),
				));

				if ($post and $post->save())
				{
					Session::set_flash('success', 'Added post #'.$post->id.'.');

					Response::redirect('posts');
				}

				else
				{
					Session::set_flash('error', 'Could not save post.');
				}
			}
			else
			{
				Session::set_flash('error', $val->error());
			}
		}

		$this->template->title = "Posts";
		$this->template->content = View::forge('posts/create');

	}

	public function action_edit($id = null)
	{
		is_null($id) and Response::redirect('posts');

		if ( ! $post = Model_Post::find($id))
		{
			Session::set_flash('error', 'Could not find post #'.$id);
			Response::redirect('posts');
		}

		$val = Model_Post::validate('edit');

		if ($val->run())
		{
			$post->title = Input::post('title');
			$post->body = Input::post('body');

			if ($post->save())
			{
				Session::set_flash('success', 'Updated post #' . $id);

				Response::redirect('posts');
			}

			else
			{
				Session::set_flash('error', 'Could not update post #' . $id);
			}
		}

		else
		{
			if (Input::method() == 'POST')
			{
				$post->title = $val->validated('title');
				$post->body = $val->validated('body');

				Session::set_flash('error', $val->error());
			}

			$this->template->set_global('post', $post, false);
		}

		$this->template->title = "Posts";
		$this->template->content = View::forge('posts/edit');

	}

	public function action_delete($id = null)
	{
		is_null($id) and Response::redirect('posts');

		if ($post = Model_Post::find($id))
		{
			$post->delete();

			Session::set_flash('success', 'Deleted post #'.$id);
		}

		else
		{
			Session::set_flash('error', 'Could not delete post #'.$id);
		}

		Response::redirect('posts');

	}

}


text:
{% extends "dirbalakbase.html" %}

{% block content %}

{{ project }}

            Banned from build:

                Last Commit:

                 Ago
                ()

            Owner:

            Group:

 0">
            Depends On:

                    ( Dependency)

                            Broken hash

                             Commit Behind
                             Behind
                            ()

                        Latest Master

            Does not depend on any other projects

 0">
            Depended By:

                    ( Dependency)

                         Commit Behind
                         Behind
                        ()

                        Latest Master

            Is not dependent by any other projects

            Last Events:

            <button data-bind="enable: newGraphVersionAvailable, click: forceGraphUpdate" class="btn btn-primary">
                New graph available, click to update
            </button>
            <button data-bind="click: requestFetch" class="btn btn-primary">Request Fetch</button>
            <button data-bind="click: updateDependencies" class="btn btn-warning">Update Dependencies</button>

                <input type="checkbox" data-bind="checked: dirbalakBuildRootFSArcs">Dirbalak Build RootFS Arcs

                <input type="checkbox" data-bind="checked: solventRootFSArcs">Solvent RootFS Arcs

{% endblock %}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Management.DataFactories;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using TestEnvironmentFactory = Microsoft.Rest.ClientRuntime.Azure.TestFramework.TestEnvironmentFactory;
using ResourceManagementClient = Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
#if !NETSTANDARD
using Microsoft.Azure.Test;
using TestBase = Microsoft.Azure.Test.TestBase;
#endif

namespace Microsoft.Azure.Commands.DataFactories.Test
{
    public abstract class DataFactoriesScenarioTestsBase : RMTestBase
    {
        private readonly EnvironmentSetupHelper _helper;

        protected DataFactoriesScenarioTestsBase()
        {
            _helper = new EnvironmentSetupHelper();
        }

        protected void SetupManagementClients(MockContext context)
        {
            var dataPipelineManagementClient = GetDataPipelineManagementClient(context);
            var resourceManagementClient = GetResourceManagementClient(context);

            _helper.SetupManagementClients(dataPipelineManagementClient, resourceManagementClient);
        }

        protected void RunPowerShellTest(XunitTracingInterceptor logger, params string[] scripts)
        {
            var sf = new StackTrace().GetFrame(1);
            var callingClassType = sf.GetMethod().ReflectedType?.ToString();
            var mockName = sf.GetMethod().Name;

            _helper.TracingInterceptor = logger;

            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("Microsoft.Resources", null);
            d.Add("Microsoft.Features", null);
            d.Add("Microsoft.Authorization", null);
            var providersToIgnore = new Dictionary<string, string>();
            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);
            HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");

            using (MockContext context = MockContext.Start(callingClassType, mockName))
            {
                SetupManagementClients(context);

                _helper.SetupEnvironment(AzureModule.AzureResourceManager);
                _helper.SetupModules(AzureModule.AzureResourceManager,
                    "ScenarioTests\\Common.ps1",
                    "ScenarioTests\\" + this.GetType().Name + ".ps1",
                    _helper.RMProfileModule,
                    _helper.GetRMModulePath("AzureRM.DataFactories.psd1"),
                    "AzureRM.Resources.ps1");

                _helper.RunPowerShellTest(scripts);
            }
        }

        protected DataFactoryManagementClient GetDataPipelineManagementClient(MockContext context)
        {
#if NETSTANDARD
            //return context.GetServiceClient<DataFactoryManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
            return null;
#else
            return TestBase.GetServiceClient<DataFactoryManagementClient>(new CSMTestEnvironmentFactory());
#endif
        }

        protected ResourceManagementClient GetResourceManagementClient(MockContext context)
        {
            return context.GetServiceClient<ResourceManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
        }
    }
}


text:
package io.github.tailhq.dynaml.utils

import breeze.generic.UFunc
import breeze.numerics.{lgamma, log}

/**
  * @author mandar date: 06/02/2017.
  *
  * Multivariate Gamma function.
  *
  */
object mvlgamma extends UFunc {

  def mvlgammaRec(n: Int, a: Double, gammaAcc: Double): Double = n match {
    case 1 => lgamma(a)+gammaAcc
    case _ => mvlgammaRec(n-1, a, gammaAcc + 0.5*(n-1)*log(math.Pi) + lgamma(a + 0.5*(1-n)))
  }

  implicit object ImplDouble extends Impl2[Int, Double, Double] {
    override def apply(v: Int, v2: Double) = mvlgammaRec(v, v2, 0.0)
  }

}


text:
#ifndef MODULES_BASIC_SEND_COMPLEX_SCALAR_H
#define MODULES_BASIC_SEND_COMPLEX_SCALAR_H

#include <Dataflow/Network/Module.h>
#include <Modules/Basic/share.h>

namespace SCIRun {
namespace Modules {
namespace Basic {

  class SCISHARE SendComplexScalar : public SCIRun::Dataflow::Networks::Module,
    public Has1OutputPort<ComplexMatrixPortTag>,
    public HasNoInputPorts
  {
  public:
    SendComplexScalar();
    virtual void execute() override;
    virtual void setStateDefaults() override {}

    OUTPUT_PORT(0, Scalar, ComplexDenseMatrix);
    MODULE_TRAITS_AND_INFO(NoAlgoOrUI)
  private:
    complex data_;
  };

}}}

#endif


text:
import Router from '@koa/router';
import { pool } from '../../database';
import { acceptValidator } from '../../requestValidators';

export function attachGetPublicTokensHandler(router: Router) {
  router.get(
    '/access-tokens',
    acceptValidator('application/json'),
    async (ctx) => {
      ctx.body = await pool.query(
        `SELECT id, token, createdAt, timeFrom, timeTo, listingLabel
          FROM trackingAccessToken
          WHERE listingLabel IS NOT NULL`,
      );
    },
  );
}


text:
package com.esri.samples.map_spatial_reference;

/**
* Wrapper required for launching a JavaFX 11 app through Gradle or from a jar.
*/
public class MapSpatialReferenceLauncher {

  public static void main(String[] args) {
    MapSpatialReferenceSample.main(args);
  }
}


text:
<?php

class CreateMetaDescription extends Mutator
{

	public function setData($name)
	{
		$this->object = new MetaDescription();
		$this->object->setName($name);
		return $this;
	}

}

?>


text:
import sys
import clr
clr.AddReference('System')
import System

def get_system_information():
    info = System.String(sys.version_info)
    return info

@property
def system_information():
    info = System.String(sys.version_info)
    return info

def echo(something):
    return something

if __name__=="__main__":
    print(get_system_information())
    print(system_information)
    System.Console.ReadLine()