text:
<?php

class Swift_Mime_Headers_IdentificationHeaderTest extends \PHPUnit_Framework_TestCase
{
    public function testTypeIsIdHeader()
    {
        $header = $this->_getHeader('Message-ID');
        $this->assertEquals(Swift_Mime_Header::TYPE_ID, $header->getFieldType());
    }

    public function testValueMatchesMsgIdSpec()
    {
        /* -- RFC 2822, 3.6.4.
     message-id      =       "Message-ID:" msg-id CRLF

     in-reply-to     =       "In-Reply-To:" 1*msg-id CRLF

     references      =       "References:" 1*msg-id CRLF

     msg-id          =       [CFWS] "<" id-left "@" id-right ">" [CFWS]

     id-left         =       dot-atom-text / no-fold-quote / obs-id-left

     id-right        =       dot-atom-text / no-fold-literal / obs-id-right

     no-fold-quote   =       DQUOTE *(qtext / quoted-pair) DQUOTE

     no-fold-literal =       "[" *(dtext / quoted-pair) "]"
     */

        $header = $this->_getHeader('Message-ID');
        $header->setId('id-left@id-right');
        $this->assertEquals('<id-left@id-right>', $header->getFieldBody());
    }

    public function testIdCanBeRetrievedVerbatim()
    {
        $header = $this->_getHeader('Message-ID');
        $header->setId('id-left@id-right');
        $this->assertEquals('id-left@id-right', $header->getId());
    }

    public function testMultipleIdsCanBeSet()
    {
        $header = $this->_getHeader('References');
        $header->setIds(array('a@b', 'x@y'));
        $this->assertEquals(array('a@b', 'x@y'), $header->getIds());
    }

    public function testSettingMultipleIdsProducesAListValue()
    {
        /* -- RFC 2822, 3.6.4.
     The "References:" and "In-Reply-To:" field each contain one or more
     unique message identifiers, optionally separated by CFWS.

     .. SNIP ..

     in-reply-to     =       "In-Reply-To:" 1*msg-id CRLF

     references      =       "References:" 1*msg-id CRLF
     */

        $header = $this->_getHeader('References');
        $header->setIds(array('a@b', 'x@y'));
        $this->assertEquals('<a@b> <x@y>', $header->getFieldBody());
    }

    public function testIdLeftCanBeQuoted()
    {
        /* -- RFC 2822, 3.6.4.
     id-left         =       dot-atom-text / no-fold-quote / obs-id-left
     */

        $header = $this->_getHeader('References');
        $header->setId('"ab"@c');
        $this->assertEquals('"ab"@c', $header->getId());
        $this->assertEquals('<"ab"@c>', $header->getFieldBody());
    }

    public function testIdLeftCanContainAnglesAsQuotedPairs()
    {
        /* -- RFC 2822, 3.6.4.
     no-fold-quote   =       DQUOTE *(qtext / quoted-pair) DQUOTE
     */

        $header = $this->_getHeader('References');
        $header->setId('"a\\<\\>b"@c');
        $this->assertEquals('"a\\<\\>b"@c', $header->getId());
        $this->assertEquals('<"a\\<\\>b"@c>', $header->getFieldBody());
    }

    public function testIdLeftCanBeDotAtom()
    {
        $header = $this->_getHeader('References');
        $header->setId('a.b+&%$.c@d');
        $this->assertEquals('a.b+&%$.c@d', $header->getId());
        $this->assertEquals('<a.b+&%$.c@d>', $header->getFieldBody());
    }

    public function testInvalidIdLeftThrowsException()
    {
        try {
            $header = $this->_getHeader('References');
            $header->setId('a b c@d');
            $this->fail(
                'Exception should be thrown since "a b c" is not valid id-left.'
                );
        } catch (Exception $e) {
        }
    }

    public function testIdRightCanBeDotAtom()
    {
        /* -- RFC 2822, 3.6.4.
     id-right        =       dot-atom-text / no-fold-literal / obs-id-right
     */

        $header = $this->_getHeader('References');
        $header->setId('a@b.c+&%$.d');
        $this->assertEquals('a@b.c+&%$.d', $header->getId());
        $this->assertEquals('<a@b.c+&%$.d>', $header->getFieldBody());
    }

    public function testIdRightCanBeLiteral()
    {
        /* -- RFC 2822, 3.6.4.
     no-fold-literal =       "[" *(dtext / quoted-pair) "]"
     */

        $header = $this->_getHeader('References');
        $header->setId('a@[1.2.3.4]');
        $this->assertEquals('a@[1.2.3.4]', $header->getId());
        $this->assertEquals('<a@[1.2.3.4]>', $header->getFieldBody());
    }

    public function testInvalidIdRightThrowsException()
    {
        try {
            $header = $this->_getHeader('References');
            $header->setId('a@b c d');
            $this->fail(
                'Exception should be thrown since "b c d" is not valid id-right.'
                );
        } catch (Exception $e) {
        }
    }

    public function testMissingAtSignThrowsException()
    {
        /* -- RFC 2822, 3.6.4.
     msg-id          =       [CFWS] "<" id-left "@" id-right ">" [CFWS]
     */

        try {
            $header = $this->_getHeader('References');
            $header->setId('abc');
            $this->fail(
                'Exception should be thrown since "abc" is does not contain @.'
                );
        } catch (Exception $e) {
        }
    }

    public function testSetBodyModel()
    {
        $header = $this->_getHeader('Message-ID');
        $header->setFieldBodyModel('a@b');
        $this->assertEquals(array('a@b'), $header->getIds());
    }

    public function testGetBodyModel()
    {
        $header = $this->_getHeader('Message-ID');
        $header->setId('a@b');
        $this->assertEquals(array('a@b'), $header->getFieldBodyModel());
    }

    public function testStringValue()
    {
        $header = $this->_getHeader('References');
        $header->setIds(array('a@b', 'x@y'));
        $this->assertEquals('References: <a@b> <x@y>'."\r\n", $header->toString());
    }

    private function _getHeader($name)
    {
        return new Swift_Mime_Headers_IdentificationHeader($name, new Swift_Mime_Grammar());
    }
}


text:
package org.apache.sqoop.util;

import org.junit.runner.RunWith;
import org.junit.runners.model.InitializationError;
import org.junit.runners.parameterized.TestWithParameters;

import java.lang.annotation.Annotation;

public class BlockJUnit4ClassRunnerWithParameters extends org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters {
  public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test) throws InitializationError {
    super(test);
  }

  @Override
  protected Annotation[] getRunnerAnnotations() {
    Annotation[] allAnnotations = getTestClass().getAnnotations();
    Annotation[] annotationsWithoutRunWith = new Annotation[allAnnotations.length - 1];
    int i = 0;
    for (Annotation annotation: allAnnotations) {
      if (!annotation.annotationType().equals(RunWith.class)) {
        annotationsWithoutRunWith[i] = annotation;
        ++i;
      }
    }
    return annotationsWithoutRunWith;
  }
}

redpajama_set_name: RedPajamaGithub


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>RepositoryAttribute Constructor</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

RepositoryAttribute Constructor

 Initializes a new instance of the RepositoryAttribute class.

Overload List

 Initializes a new instance of the RepositoryAttribute class.

        public RepositoryAttribute();

 Initialize a new instance of the RepositoryAttribute class with the name of the repository.

        public RepositoryAttribute(string);

See Also

        RepositoryAttribute Class | log4net.Config Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="RepositoryAttribute class, constructors">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
layout: default
title: The "color-palette" control
slug: color-palette
subtitle: Learn how to create controls using Kirki
mainMaxWidth: 50rem;
bodyClasses: control page
returns: string
heroButtons:
  - url: ../controls
    class: white button round border-only
    icon: fa fa-arrow-circle-o-left
    label: Back to Controls
---

The `color-palette` control allows you to define an array of colors and users can choose from those colors. Internally the control is a simple radio control with some additional styling to make color selection easier.

You can define inside the `choices` arguments an array of colors, the style (`round` or not) and also the size each color will have. See the examples below.

### Example

```php
Kirki::add_field( 'kirki_demo', array(
	'type'        => 'color-palette',
	'settings'    => 'color_palette_setting_0',
	'label'       => esc_attr__( 'Color-Palette', 'kirki' ),
	'description' => esc_attr__( 'This is a color-palette control', 'kirki' ),
	'section'     => 'color_palette_section',
	'default'     => '#888888',
	'choices'     => array(
		'colors' => array( '#000000', '#222222', '#444444', '#666666', '#888888', '#aaaaaa', '#cccccc', '#eeeeee', '#ffffff' ),
		'style'  => 'round',
	),
) );
```
The result of the above example would look like this:

Additionally the `Kirki_Helper` class provides helper methods in case you want to use Google's [Material Design color palettes](https://material.io/guidelines/style/color.html#color-color-palette).

Some additional examples using those helper methods:

#### Material-design Colors - All.

```php
Kirki::add_field( 'kirki_demo', array(
	'type'        => 'color-palette',
	'settings'    => 'color_palette_setting_4',
	'label'       => esc_attr__( 'Color-Palette', 'kirki' ),
	'description' => esc_attr__( 'Material Design Colors - all', 'kirki' ),
	'section'     => 'color_palette_section',
	'default'     => '#F44336',
	'choices'     => array(
		'colors' => Kirki_Helper::get_material_design_colors( 'all' ),
		'size'   => 17,
	),
) );
```

#### Material-design Colors - Primary

```php
Kirki::add_field( 'kirki_demo', array(
	'type'        => 'color-palette',
	'settings'    => 'color_palette_setting_1',
	'label'       => esc_attr__( 'Color-Palette', 'kirki' ),
	'description' => esc_attr__( 'Material Design Colors - primary', 'kirki' ),
	'section'     => 'color_palette_section',
	'default'     => '#000000',
	'choices'     => array(
		'colors' => Kirki_Helper::get_material_design_colors( 'primary' ),
		'size'   => 25,
	),
) );
```

#### All Material-design Colors - Reds

```php
Kirki::add_field( 'kirki_demo', array(
	'type'        => 'color-palette',
	'settings'    => 'color_palette_setting_2',
	'label'       => esc_attr__( 'Color-Palette', 'kirki' ),
	'description' => esc_attr__( 'Material Design Colors - red', 'kirki' ),
	'section'     => 'color_palette_section',
	'default'     => '#FF1744',
	'choices'     => array(
		'colors' => Kirki_Helper::get_material_design_colors( 'red' ),
		'size'   => 16,
	),
) );
```

#### All Material-design Colors - A100 variation.

```php
Kirki::add_field( 'kirki_demo', array(
	'type'        => 'color-palette',
	'settings'    => 'color_palette_setting_3',
	'label'       => esc_attr__( 'Color-Palette', 'kirki' ),
	'description' => esc_attr__( 'Material Design Colors - A100', 'kirki' ),
	'section'     => 'color_palette_section',
	'default'     => '#FF80AB',
	'choices'     => array(
		'colors' => Kirki_Helper::get_material_design_colors( 'A100' ),
		'size'   => 60,
		'style'  => 'round',
	),
) );
```


text:
CREATE PROCEDURE [auth].[auth_Groups_GetById]
	@id int
AS
	SELECT	[Id],
			[Name],
			[Description],
			[AudienceId],
			[CreatedByUserId],
			[CreatedByClientId],
			[CreatedDate],
			[UpdatedByUserId],
			[UpdatedByClientId],
			[UpdatedDate],
			[IsDeleted],
			[IsSystemId]
	FROM	[Groups]
	WHERE	[Id]=@id and [IsDeleted]=0


text:
.. currentmodule:: machine

class SD -- secure digital memory card
======================================

The SD card class allows to configure and enable the memory card
module of the WiPy and automatically mount it as ``/sd`` as part
of the file system. There are several pin combinations that can be
used to wire the SD card socket to the WiPy and the pins used can
be specified in the constructor. Please check the `pinout and alternate functions
table. <https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png>`_ for
more info regarding the pins which can be remapped to be used with a SD card.

Example usage::

    from machine import SD
    import os
    # clk cmd and dat0 pins must be passed along with
    # their respective alternate functions
    sd = machine.SD(pins=('GP10', 'GP11', 'GP15'))
    os.mount(sd, '/sd')
    # do normal file operations

Constructors
------------

.. class:: SD(id,... )

   Create a SD card object. See ``init()`` for parameters if initialization.

Methods
-------

.. method:: SD.init(id=0, pins=('GP10', 'GP11', 'GP15'))

   Enable the SD card. In order to initalize the card, give it a 3-tuple:
   ``(clk_pin, cmd_pin, dat0_pin)``.

.. method:: SD.deinit()

   Disable the SD card.


text:
package com.meidusa.venus.validate;

import java.lang.reflect.Method;
import java.util.HashMap;

import com.meidusa.venus.validate.chain.ValidatorChain;
import com.meidusa.venus.validate.chain.factory.ValidatorChainFactory;
import com.meidusa.venus.validate.chain.factory.VenusValidatorChainFactory;

/**
 * ValidatorManager impelmentation. Load validatorChain while being used.
 *
 * @author lichencheng.daisy
 * @since 1.0.0-SNAPSHOT
 *
 */
public class VenusValidatorManager implements ValidatorManager {
    private ValidatorChainFactory chainFactory;

    private HashMap<Method, ValidatorChain> validatorChainMapping;

    public ValidatorChainFactory getChainFactory() {
        return chainFactory;
    }

    public void setChainFactory(ValidatorChainFactory chainFactory) {
        this.chainFactory = chainFactory;
    }

    @Override
    public ValidatorChain getValidatorChain(Method method) {

        ValidatorChain endpointChains = this.validatorChainMapping.get(method);
        if (endpointChains == null) {
            synchronized (validatorChainMapping) {
                endpointChains = chainFactory.createValidatorChain(method);
                validatorChainMapping.put(method, endpointChains);
            }
        }
        return endpointChains;
    }

    @Override
    public void init() {
        this.validatorChainMapping = new HashMap<Method, ValidatorChain>();
        this.chainFactory = new VenusValidatorChainFactory();

    }

}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

#If False Then
Imports System.ComponentModel.Composition
Imports Microsoft.CodeAnalysis.Shared.TestHooks

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
    <Export(GetType(IAsynchronousOperationListener))>
    <Export(GetType(IAsynchronousOperationWaiter))>
    <Feature(FeatureAttribute.CompletionSet)>
    Friend Class CompletionWaiter
        Inherits AsynchronousOperationListener

    End Class
End Namespace
#End If


text:
module Turing
  # turing version
  VERSION = "0.1.0"
end


text:
using System;
using BackpackLoginExample.Settings;
using HedgehogSoft.BackpackLogin;

namespace BackpackLoginExample
{
    internal class Program
    {
        // ReSharper disable once UnusedMember.Local
        private static void Main()
        {
            Console.WriteLine("Press a key to start login process.");
            Console.ReadKey();
            Loader.LoadSettings();
            Console.WriteLine($"{ConsoleSettings.Instance["username"]} will login to backpack.tf");
            var backpackLoginClient = new BackpackLoginClient();
            var cookieContainer = backpackLoginClient.Login(
                ConsoleSettings.Instance["username"],
                ConsoleSettings.Instance["password"],
                ConsoleSettings.Instance["sharedSecret"]);
            Console.WriteLine($"Login successful. Found {cookieContainer.Count} Cookies.");
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss version="2.0">
    <channel>
        <title>CyberGIS Center</title>
        <link>http://illinois.edu/calendar/list/4766</link>
        <description>CyberGIS Center</description>
    </channel>
</rss>


text:
package ru.job4j.tracker.start;

import ru.job4j.tracker.models.Comment;
import ru.job4j.tracker.models.Item;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by a8 on 13.12.16.
 */
public class Tracker {

    /** Контейнер для заявок. */
    private Item[] items = new Item[10];

    /** Указатель на индекс массива заявок. */
    private int position = 0;

    /** Поле счетчика идентификатора заявки. */
    private int id = 100;

    /**
     * Метод генерирует строковый идентификатор заявки.
     * @return - строка идентификатора.
     */
    private String generateId() {
        return "I" + String.valueOf(id++);
    }

    /**
     * Метод добавляет новую заявку {@link Item} в хранилище {@link Tracker#items}.
     * @param item - передаваемая заявка
     * @return - сохраненная заявка
     */
    Item addItem(Item item) {
        item.setId(generateId());
        item.setDate(new Date());
        this.items[position++] = item;
        return item;
    }

    /**
     * Метод поиска заявки {@link Item} в хранилище {@link Tracker#items} по ее названию.
     * @param name - название искомой заявки
     * @return - змассив найденных заявок
     */
    public Item[] findItemByName(String name) {
        Item[] res = new Item[position];
        int ind = 0;
        for (int i = 0; i < position; i++) {
            if (this.items[i] != null && this.items[i].getName().contains(name)) {
                res[ind++] = this.items[i];
            }
        }
        return res;
    }

    /**
     * Метод поиска заявки {@link Item} в хранилище {@link Tracker#items} по ее описанию.
     * @param desc - описание искомой заявки
     * @return - массив найденных заявок
     */
    public Item[] findItemByDesc(String desc) {
        Item[] res = new Item[position];
        int ind = 0;
        for (int i = 0; i < position; i++) {
            if (this.items[i] != null && this.items[i].getDescription().contains(desc)) {
                res[ind++] = this.items[i];
            }
        }
        return res;
    }

    /**
     * Метод поиска заявки {@link Item} в хранилище {@link Tracker#items} по полю {@link Item#create}.
     * @param create - параметр для поиска
     * @return - массив найденных заявок
     */
    public Item[] findItemByCreate(String create) {
        Item[] res = new Item[position];
        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern("dd.MM.yyyy");
        int ind = 0;
        for (int i = 0; i < position; i++) {
            if (this.items[i] != null && create.equals(format.format(this.items[i].getDate()))) {
                res[ind++] = this.items[i];
            }
        }
        return res;
    }

    /**
     * Метод заменяет заявку в хранилище другой.
     * @param item - "свежая" заявка
     */
    public void updItem(Item item) {
        Item updItem = null;
        int itemInd = 0;

        for (int index = 0; index < position; index++) {
            if (items[index] != null && items[index].getId().equals(item.getId())) {
                updItem = items[index];
                itemInd = index;
                break;
            }
        }

        if (updItem != null) {
            if (!"".equals(item.getName())) {
                updItem.setName(item.getName());
            }

            if (!"".equals(item.getDescription())) {
                updItem.setDescription(item.getDescription());
            }
            System.out.println(updItem);

            items[itemInd] = updItem;
        } else {
            System.out.println("Заявка с id " + item.getId() + " не найдена!");
        }

    }

    /**
     * Метод удаляет переданный Item из хранилища.
     * @param item - удаляемая заявка
     * @return заявка, если найдена, если нет - null
     */
    public Item deleteItem(Item item) {
        Item res = null;
        int i;
        for (i = 0; i < position; i++) {
            if (items[i] != null && items[i].equals(item)) {
                res = items[i];
                items[i] = null;
                break;
            }
        }
        // сдвиг последующих элементов
        for (int j = i; j < position; j++) {
            items[j] = items[j + 1];
        }

        // декремент текущего индекса хранилища
        if (position != 0) {
            position--;
        }

        return res;
    }

    /**
     * Метод добавляет комментарий к переданной заявке.
     * @param item - заявка, к которой добавляется комментарий.
     * @param comment - добавляемый комментарий.
     * @return - добавленный комментарий
     */
    public Comment addComment(Item item, Comment comment) {
        if (item != null) {
            item.addComment(comment);
        }
        return comment;
    }

    /**
     * Метод возвращает массив комментариев, относящихся к переданной заявке.
     * @param item - заявка
     * @return - массив комментариев
     */
    public Comment[] getAllComments(Item item) {
        return item.getComments();
    }

    /**
     * Метод возвращает массив актуальной длины с заявками.
     * @return массив заявок
     */
    public Item[] getAllItems() {
        Item[] result = new Item[position];
        for (int i = 0; i < position; i++) {
            result[i] = items[i];
        }
        return result;
    }

    /**
     * Метод выводит в консоль переданный массив заявок.
     * @param items - массив заявок для отображения
     */
    public void display(Item[] items) {
        for (Item item : items) {
            if (item != null) {
                System.out.println(item);
            }
        }
    }
}


text:
<?php declare(strict_types=1);

namespace ApiClients\Client\Github\Resource\Async;

use ApiClients\Client\Github\Resource\EmptyEvent as BaseEmptyEvent;

class EmptyEvent extends BaseEmptyEvent
{
}


text:
<?php

/*
 * This file is part of the EmharCqrsInfrastructure bundle.
 *
 * (c) Emmanuel Harleaux
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Emhar\CqrsInfrastructureBundle\CommandHandler;

use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManager;
use Emhar\CqrsInfrastructure\Command\CommandInterface;
use Emhar\CqrsInfrastructure\CommandBus\CommandBusInterface;
use Emhar\CqrsInfrastructure\CommandHandler\AbstractCommandHandler;
use Emhar\CqrsInfrastructure\CommandHandler\AbstractInfrastructureExceptionListeningCommandHandler;
use Emhar\CqrsInfrastructure\Event\EventContainerInterface;
use Emhar\CqrsInfrastructureBundle\CommandBus\CqrsEventsCollectedEvent;
use Emhar\CqrsInfrastructureBundle\CommandBus\JmsJobQueueCommandBus;
use Emhar\CqrsInfrastructureBundle\CommandBus\SymfonyEventDispatcherCommandEvent;
use Emhar\CqrsInfrastructureBundle\Event\SymfonyEventDispatcherEvent;
use Emhar\CqrsInfrastructureBundle\Util\Debug;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class CommandHandlerAdapterUtils
{
    /**
     * @var EventDispatcherInterface
     */
    protected $eventDispatcher;

    /**
     * @var ManagerRegistry
     */
    protected $doctrineRegistry;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var RequestStack
     */
    protected $requestStack;

    /**
     * @var TokenStorageInterface
     */
    protected $tokenStorage;

    /**
     * @var JmsJobQueueCommandBus
     */
    protected $asyncBus;

    /**
     * @var EventContainerInterface
     */
    protected $eventCollector;

    /**
     * @param EventDispatcherInterface $eventDispatcher
     * @param ManagerRegistry $doctrineRegistry
     * @param LoggerInterface $logger
     * @param RequestStack $requestStack
     * @param TokenStorageInterface $tokenStorage
     * @param JmsJobQueueCommandBus $asyncBus
     * @param EventContainerInterface $eventCollector
     */
    public function __construct(EventDispatcherInterface $eventDispatcher, ManagerRegistry $doctrineRegistry, LoggerInterface $logger, RequestStack $requestStack, TokenStorageInterface $tokenStorage, JmsJobQueueCommandBus $asyncBus, EventContainerInterface $eventCollector)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->doctrineRegistry = $doctrineRegistry;
        $this->logger = $logger;
        $this->requestStack = $requestStack;
        $this->tokenStorage = $tokenStorage;
        $this->asyncBus = $asyncBus;
        $this->eventCollector = $eventCollector;
    }

    /**
     * @param SymfonyEventDispatcherCommandEvent|null $commandEvent
     * @param $executionId
     */
    public function logCommand(SymfonyEventDispatcherCommandEvent $commandEvent = null, $executionId)
    {
        if ($commandEvent) {
            $message = '';
            if ($executionId) {
                $message .= 'EId:' . $executionId . ',';
            }
            if ($token = $this->tokenStorage->getToken()) {
                $message .= 'P:' . $token->getUsername() . ',';
            }
            if ($request = $this->requestStack->getMasterRequest()) {
                if ($request->headers->has('x-user-name')) {
                    $message .= 'U:' . $request->headers->get('x-user-name') . ',';
                }
                $message .= 'Ips: ' . implode(';', $request->getClientIps()) . ', ';
            }
            $message .= Debug::dump($commandEvent->getCommand(), 10, true, false);
            $this->logger->info($message);
        }
    }

    /**
     * @param array $arguments
     * @return SymfonyEventDispatcherCommandEvent|null
     */
    public function getCommandEvent(array &$arguments)
    {
        foreach ($arguments as $key => $argument) {
            if ($argument instanceof SymfonyEventDispatcherCommandEvent) {
                $arguments[$key] = $argument->getCommand();
                return $argument;
            }
        }
        return null;
    }

    /**
     * @param SymfonyEventDispatcherCommandEvent|null $commandEvent
     */
    public function dispatchModelEvents(SymfonyEventDispatcherCommandEvent $commandEvent = null)
    {
        $events = $this->eventCollector->getEvents();
        foreach ($events as $event) {
            $event->setUserNotificationEnabled($commandEvent ? $commandEvent->isUserNotificationEnabled() : true);
            $this->eventDispatcher->dispatch(get_class($event), new SymfonyEventDispatcherEvent($event));
        }
    }

    /**
     * @param string $executionId
     */
    public function runModelEvents(string $executionId)
    {
        $cqrsEventsCollectedEvent = new CqrsEventsCollectedEvent($executionId);
        $this->eventDispatcher->dispatch('cqrs-events-collected', $cqrsEventsCollectedEvent);
    }

    /**
     * @param EntityManager $em
     * @param \Exception $e
     * @param CommandInterface $command
     * @throws \Doctrine\DBAL\ConnectionException
     */
    public function handleError(AbstractCommandHandler $handler, \Exception $e, SymfonyEventDispatcherCommandEvent $commandEvent = null, string $executionId)
    {
        $em = $this->doctrineRegistry->getManager();
        while ($em->getConnection()->getTransactionNestingLevel() > 0) {
            $em->getConnection()->rollback();
        }
        $em->close();
        if ($commandEvent) {
            if ($commandEvent->isAsync()
                && $handler->canBeRetried($e, $commandEvent->getRetryCounter())
            ) {
                $this->doctrineRegistry->resetManager();
                $this->asyncBus->cancelPostedCommand();
                if ($handler instanceof AbstractInfrastructureExceptionListeningCommandHandler) {
                    $handler->onInfrastructureException($e, $commandEvent->getCommand());
                }

                $this->asyncBus->postCommand(
                    $commandEvent->getCommand(),
                    $commandEvent->isUserNotificationEnabled(),
                    CommandBusInterface::DEFAULT_QUEUE,
                    CommandBusInterface::PRIORITY_NORMAL,
                    null,
                    false,
                    $commandEvent->getOptions(),
                    $commandEvent->getRetryCounter() + 1
                );
                $this->runModelEvents($executionId);
                $this->doctrineRegistry->getManager()->flush();
                $commandEvent->setError($e);
                return;
            }
            if ($handler instanceof AbstractInfrastructureExceptionListeningCommandHandler) {
                $this->doctrineRegistry->resetManager();
                $handler->onInfrastructureException($e, $commandEvent->getCommand());
                $this->doctrineRegistry->getManager()->flush();
            }
        }
        throw $e;
    }
}


text:
var vmModule = require("./home-view-model");
var frameModule = require("ui/frame");
var sound = require("nativescript-sound");

var pageModules = (function() {
	var bananaSound = sound.create("~/sounds/banana.mp3");
	var tapButtonSound = sound.create("~/sounds/tap-button.mp3");

	var pageModules = {
		pageLoaded: function(args) {
			var page = args.object;
			page.bindingContext = vmModule.homeViewModel;
			topmost = frameModule.topmost();
		},
		bananaSoundPlay: function() {
			bananaSound.play();
		},
		navigateToPlayPage: function() {
			tapButtonSound.play();
			var navigationEntry = {
				moduleName: "./views/play/play",
				backstackVisible: false,
                animated: true,
                navigationTransition: {
                    transition: "flip "
                },
			};

			topmost.navigate(navigationEntry);
		},
		navigateToScorePage: function() {
			tapButtonSound.play();
			var navigationEntry = {
				moduleName: "./views/score/score",
				backstackVisible: true,
                animated: true,
                navigationTransition: {
                    transition: "flip "
                },
			};

			topmost.navigate(navigationEntry);
		}
	};

	return pageModules;
})();

exports.pageLoaded = pageModules.pageLoaded;
exports.bananaSoundPlay = pageModules.bananaSoundPlay;
exports.navigateToPlayPage = pageModules.navigateToPlayPage;
exports.navigateToScorePage = pageModules.navigateToScorePage;


text:
namespace app { namespace Fuse { namespace Drawing { struct Contour; } } }

namespace app {
namespace Uno {
namespace Collections {

struct EnumerableExtensions_LinkedList__Fuse_Drawing_Contour;

struct EnumerableExtensions_LinkedList__Fuse_Drawing_Contour__uType : ::uClassType
{
};

EnumerableExtensions_LinkedList__Fuse_Drawing_Contour__uType* EnumerableExtensions_LinkedList__Fuse_Drawing_Contour__typeof();

void EnumerableExtensions_LinkedList__Fuse_Drawing_Contour___ObjInit(EnumerableExtensions_LinkedList__Fuse_Drawing_Contour* __this, ::app::Fuse::Drawing::Contour* item, EnumerableExtensions_LinkedList__Fuse_Drawing_Contour* next);
EnumerableExtensions_LinkedList__Fuse_Drawing_Contour* EnumerableExtensions_LinkedList__Fuse_Drawing_Contour__New_1(::uStatic* __this, ::app::Fuse::Drawing::Contour* item, EnumerableExtensions_LinkedList__Fuse_Drawing_Contour* next);

struct EnumerableExtensions_LinkedList__Fuse_Drawing_Contour : ::uObject
{
    ::uStrong< ::app::Fuse::Drawing::Contour*> Item;
    ::uStrong< EnumerableExtensions_LinkedList__Fuse_Drawing_Contour*> Next;

    void _ObjInit(::app::Fuse::Drawing::Contour* item, EnumerableExtensions_LinkedList__Fuse_Drawing_Contour* next) { EnumerableExtensions_LinkedList__Fuse_Drawing_Contour___ObjInit(this, item, next); }
};

}}}

#endif


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Http;
    using System.Threading;

    /// <summary>
    /// The interface IDriveItemSearchRequest.
    /// </summary>
    public partial interface IDriveItemSearchRequest : IBaseRequest
    {

        /// <summary>
        /// Issues the GET request.
        /// </summary>
        System.Threading.Tasks.Task<IDriveItemSearchCollectionPage> GetAsync();

        /// <summary>
        /// Issues the GET request.
        /// </summary>
        /// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
        /// <returns>The task to await for async call.</returns>
        System.Threading.Tasks.Task<IDriveItemSearchCollectionPage> GetAsync(
            CancellationToken cancellationToken);

        /// <summary>
        /// Adds the specified expand value to the request.
        /// </summary>
        /// <param name="value">The expand value.</param>
        /// <returns>The request object to send.</returns>
        IDriveItemSearchRequest Expand(string value);

        /// <summary>
        /// Adds the specified select value to the request.
        /// </summary>
        /// <param name="value">The select value.</param>
        /// <returns>The request object to send.</returns>
        IDriveItemSearchRequest Select(string value);

        /// <summary>
        /// Adds the specified top value to the request.
        /// </summary>
        /// <param name="value">The top value.</param>
        /// <returns>The request object to send.</returns>
        IDriveItemSearchRequest Top(int value);

        /// <summary>
        /// Adds the specified filter value to the request.
        /// </summary>
        /// <param name="value">The filter value.</param>
        /// <returns>The request object to send.</returns>
        IDriveItemSearchRequest Filter(string value);

        /// <summary>
        /// Adds the specified skip value to the request.
        /// </summary>
        /// <param name="value">The skip value.</param>
        /// <returns>The request object to send.</returns>
        IDriveItemSearchRequest Skip(int value);

        /// <summary>
        /// Adds the specified orderby value to the request.
        /// </summary>
        /// <param name="value">The orderby value.</param>
        /// <returns>The request object to send.</returns>
        IDriveItemSearchRequest OrderBy(string value);
    }
}


text:
let expect = require('chai').expect;
let getStack = require('../src/get-stack.js');
let path = require('path');

describe('get-stack.js', function() {
	it('should exist', function() {
		expect(getStack).to.be.a('function');
	});
	it('should return the stack trace', function() {
		let x = getStack();
		let first = x.shift().getFileName();
		let pieces = first.split(path.sep);
		expect(pieces.pop()).to.equal('get-stack.js');
		expect(pieces.pop()).to.equal('test');
	});
});


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace client.financial.accountsReceivable.input.paymentEntry
{
    public partial class arDocsPopup : Form
    {
        private client.financial.accountsReceivable.input.paymentEntry.Form1 parentForm = null;
        private ctDynamicsSL.financial.accountsReceivable.input.paymentEntry.ARDoc[] myARDocs = null;
        public arDocsPopup(client.financial.accountsReceivable.input.paymentEntry.Form1 inParentForm, String inRefNbr)
        {
            InitializeComponent();
            parentForm = inParentForm;
            myARDocs = parentForm.myPEObj.getARDocsByBatNbrAndRefNbr(parentForm.tbBatNbr.Text, inRefNbr);
            this.gvARDocs.DataSource = myARDocs;
        }

        private void gvARDocs_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            String custID = "";
            try
            {
                custID = gvARDocs.Rows[e.RowIndex].Cells["CUSTID"].Value.ToString();
            }
            catch { }
            parentForm.tbCustID.Text = custID;

            String refNbr = "";
            try
            {
                refNbr = gvARDocs.Rows[e.RowIndex].Cells["REFNBR"].Value.ToString();
            }
            catch { }
            if (refNbr != "")
            {
                parentForm.myScreen.myARDoc = myARDocs[e.RowIndex];
                parentForm.tbRefNbr.Text = refNbr;
                parentForm.loadARTrans();
            }
            this.Close();
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Demo</title>
    <link href="rich-text-editor.css" rel="stylesheet">

Test HTML5 required attribute:

    <form>

<textarea required></textarea>

<button type="submit">Submit</button>

    </form>


text:
from optparse import OptionParser
from scipy.spatial import distance as dist
import matplotlib.pyplot as plt
import numpy as np
import argparse
import glob
import cv2
import sys
import pickle

###########################
def image_match_histogram( all_files, options ):
    histograms = {}
    image_files = []

    # loop over all images
    for (i, fname) in enumerate(all_files):
        if options.ipath:
            path_fname = options.ipath + '/' + fname
        else:
            path_fname = fname

        # read in image
        image = cv2.imread( path_fname );

        if image is None:
            print path_fname + " : fail to read"
            continue

        image_files.append(fname)

        if image.shape[2] == 1:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

        print i, path_fname, image.shape

        v = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
        v = v.flatten()
        hist = v / sum(v)
        histograms[fname] = hist

    pickle.dump( histograms, open( options.opath+"/color_feature.p","wb") )

    # feature matrix
    feature_matrix = np.zeros( (len(histograms), len(hist)) )
    for (i,fi) in enumerate(image_files):
        feature_matrix[i,:] = histograms[image_files[i]]
    pickle.dump( feature_matrix, open( options.opath+"/color_matrix.p","wb") )

    dists = np.zeros((len(image_files), len(image_files)))
    knn = {}
    # pairwise comparison
    for (i, fi) in enumerate(image_files):
        for (j, fj) in enumerate(image_files):
            if i <= j:
                d = cv2.compareHist( histograms[fi], histograms[fj], cv2.cv.CV_COMP_INTERSECT)
                dists[i,j] = d
                dists[j,i] = d

    pickle.dump( dists, open( options.opath+"/color_affinity.p","wb") )

    # K nearest neighbors
    k=int(options.top)
    print 'knn'
    for (i, fi) in enumerate(image_files):
        vec = sorted( zip(dists[i,:], image_files), reverse = True )
        knn[fi] = vec[:k]
        print knn[fi]
    pickle.dump( knn, open( options.opath+"/color_knn.p","wb") )

    # Kmeans clustering
    term_crit = (cv2.TERM_CRITERIA_EPS, 100, 0.01)
    print feature_matrix

    ret, labels, centers = cv2.kmeans(np.float32(feature_matrix), int(options.cluster_count), term_crit, 10, cv2.KMEANS_RANDOM_CENTERS )

    label_list=[]
    for (i,l) in enumerate(labels):
        label_list.append(l[0])
    print label_list

    image_label = zip( image_files, label_list )
    print image_label
    pickle.dump( image_label, open( options.opath+"/color_clustering.p","wb") )

###########################
def main():
    usage = "usage: %prog [options] image_list_file \n"
    usage += " image match"
    parser = OptionParser(usage=usage)

    parser.add_option("-i", "--input_path", default="",
                      action="store", dest="ipath",
                      help="input path")

    parser.add_option("-o", "--output_path", default=".",
                      action="store", dest="opath",
                      help="output path")

    parser.add_option("-f", "--feature", default="color_histogram",
                      action="store", dest="feature",
                      help="color_histogram; sift_match;dist_info")

    parser.add_option("-m", "--method", default="Intersection",
                      action="store", dest="method",
                      help="Intersection;L1;L2")

    parser.add_option("-t", "--top", default="5",
                      action="store", dest="top",
                      help="Top nearest neighbors")

    parser.add_option("-c", "--cluster_count", default="3",
                      action="store", dest="cluster_count",
                      help="Number of clusters")

    parser.add_option("-d", "--debug", default="0",
                      action="store", dest="debug_mode",
                      help="debug intermediate results")

    (options, args) = parser.parse_args()

    if len(args) < 1 :
        print "Need one argument: image_list_file \n"
        sys.exit(1)

    image_files = [line.strip() for line in open(args[0])]

    if options.feature == "color_histogram":
        image_match_histogram( image_files, options )

if __name__=="__main__":
    main()


text:
<?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInite12736997344b956caa22abe7591c052
{
    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {

        }, null, ClassLoader::class);
    }
}


text:
namespace AGO.Core.Model.Security
{
	/// <summary>
	/// Container for localizable names of project roles (extended in modules)
	/// </summary>
	public abstract class BaseProjectRoles
	{
		public static readonly string Administrator = "Administrator";
	}
}


text:
package test.daoTest;

import test.junit.Test;

public class ResultsTest {

    @Test
    public void FileTest() {

    }

}


text:
import Link from 'next/link'

export default function Relative1() {
  return (
    <div id="relative-1">
      On relative 1<Link href="./relative-2">To relative 2</Link>
    </div>
  )
}


text:
Lua-Builder-for-LIFX-Ruby-HTTP-API
==================================

This is a Lua script generator for managing LIFX bulbs via Vera Scenes, making use of the unofficial LIFX Ruby HTTP API, https://github.com/chendo/lifx-http

1. Get A Raspberry Pi (or other *nix computer that you're happy with keeping on all the time)
2. Ensure it has a static IP on your local network - otherwise if the IP keeps changing, this won't work too well. For mine, the IP is 192.168.1.221
3. Ruby v2.0 (Raspbian has an older version, so I had to follow these instructions to get 2.0 installed: (http://jam.im/blog/2013/03/03/installing-ruby-2-and-rvm-on-a-raspberry-pi/) (this took forever to finsih!!)
4. Make sure root can see the new file by changing the /bin/ruby binary to point to the new ruby that is placed somewhere obscure in your own folder. For me, it: /home/cdrum/.rvm/rubies/ruby-2.1.3/bin/ruby
5. The (unofficial) Ruby HTTP API for controlling LIFX bulbs: https://github.com/chendo/lifx-http (and follow those instructions on getting it installed).

Then all you do is run this command an copy and paste the output in the Luup Lua scene settings.

See this blog post for some details on installing the above: http://www.cdrum.com/2014/10/connecting-lifx-bulbs-with-vera-z-wave.html


text:
<?php

use \Aliyun\OSS\Models\OSSOptions;

return array(
	OSSOptions::ENDPOINT => 'http://oss.aliyuncs.com',
);


text:
using Ds3.Runtime;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Ds3.Calls
{
    public class GetAggregatePhysicalPlacementRequest : Ds3Request
    {
        public string BucketName { get; private set; }
        public IEnumerable<string> Objects { get; private set; }

        public GetAggregatePhysicalPlacementRequest(string bucketName, IEnumerable<string> objects)
        {
            this.BucketName = bucketName;
            this.Objects = objects;
            this.QueryParams.Add("operation", "get_physical_placement");
        }

        internal override Stream GetContentStream()
        {
            var objectNodes = this.Objects.Select(name => new XElement("Object").SetAttributeValueFluent("Name", name));
            return new XDocument()
                .AddFluent(new XElement("Objects").AddAllFluent(objectNodes))
                .WriteToMemoryStream();
        }

        internal override HttpVerb Verb
        {
            get { return HttpVerb.PUT; }
        }

        internal override string Path
        {
            get { return "/_rest_/bucket/" + this.BucketName; }
        }
    }
}


text:
import { OpaqueToken } from '@angular/core';

export * from './BaseContract';
export * from './BaseConnection';
export * from './ConnectionWorker';
export * from './Field';
export * from './RemoteKeys';
export * from './RemoteKey';
export * from './ForeignKey';
export * from './Logger';
export * from './Types';
export { Fetchable } from './Fetchable';
export let API_BASE = new OpaqueToken('API_BASE');


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__negative_strncpy_51b.c
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-51b.tmpl.c
*/
/*
 * @description
 * CWE: 194 Unexpected Sign Extension
 * BadSource: negative Set data to a fixed negative number
 * GoodSource: Positive integer
 * Sink: strncpy
 *    BadSink : Copy strings using strncpy() with the length of data
 * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files
 *
 * */

#include "std_testcase.h"

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

void CWE194_Unexpected_Sign_Extension__negative_strncpy_51b_badSink(short data)
{
    {
        char source[100];
        char dest[100] = "";
        memset(source, 'A', 100-1);
        source[100-1] = '\0';
        if (data < 100)
        {
            /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
             * the sign extension could result in a very large number */
            strncpy(dest, source, data);
            dest[data] = '\0'; /* strncpy() does not always NULL terminate */
        }
        printLine(dest);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE194_Unexpected_Sign_Extension__negative_strncpy_51b_goodG2BSink(short data)
{
    {
        char source[100];
        char dest[100] = "";
        memset(source, 'A', 100-1);
        source[100-1] = '\0';
        if (data < 100)
        {
            /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
             * the sign extension could result in a very large number */
            strncpy(dest, source, data);
            dest[data] = '\0'; /* strncpy() does not always NULL terminate */
        }
        printLine(dest);
    }
}

#endif /* OMITGOOD */


text:
<?php
namespace WS\Finanzen\Domain\Repository;

/*
 * This file is part of the WS.Finanzen package.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\Repository;

/**
 * @Flow\Scope("singleton")
 */
class MembershipFeeRepository extends Repository {

}


text:
package com.thoughtworks.webstub.server.servlet.matcher

import com.thoughtworks.webstub.SmartSpec
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import com.thoughtworks.webstub.config.{Header, Request, HttpConfiguration}
import scala.collection.JavaConversions._
import javax.servlet.http.HttpServletRequest
import org.mockito.Mockito._

@RunWith(classOf[JUnitRunner])
class HeadersMatcherSpec extends SmartSpec{
  val request = requestWithHeader("x", "y")

  it ("should match when expected headers is present") {
    val configuration = configurationWithRequestHeaders("x" -> "y");
    new HeadersMatcher(request).matches(configuration) should be(true)
  }

  it ("should not match when expected header is absent") {
    val configuration = configurationWithRequestHeaders("x" -> "y", "a" -> "b");
    new HeadersMatcher(request).matches(configuration) should be(false)
  }

  def requestWithHeader(name: String, value: String) = {
    val request = mock[HttpServletRequest]
    when(request.getHeader(name)).thenReturn(value)
    request
  }

  def configurationWithRequestHeaders(headers: (String, String)*) = {
    val h = headers.map { case (k, v) => new Header(k, v) }
    new HttpConfiguration(new Request(null, null, null, h), null)
  }
}


text:
package com.github.fellowship_of_the_bus
package tdtd
package game

import IDMap._
import scala.collection.mutable.Set
import lib.game.GameConfig
import scala.math._
import GameMap._

trait TowerType {
	def damage: Float
	def damage_=(d: Float): Unit
	def fireRate: Int
	def fireRate_=(r: Int): Unit
	def range: Float
	def range_=(r: Float): Unit
	def aoe: Float
	def aoe_=(area: Float): Unit
	def currAI: AI
	def currAI_=(ai: AI) : Unit
	def id: Int
	def id_=(i: Int): Unit
	def projectileID: Int
	def projectileID_=(p: Int): Unit
	def speed: Float
	def speed_=(s: Float): Unit
	def value: Int
	def value_=(i: Int): Unit
	def name: String
  def basename: String
	def name_=(s: String): Unit
  def cost : Int
  def cost_=(i:Int): Unit
	def description: String
	def description_=(s: String): Unit
	def hotkey: Char
	def hotkey_=(c: Char): Unit
	def describe() : List[String] = {
		val fireSpeed = fireRate / GameConfig.FrameRate.toFloat
		var ret = List(
			s"Value: ${value}",
      if (cost == 0) {
        "Max Level"
      } else {
        s"Upgrade Cost: $cost"
      },
			f"Damage: ${damage}%.1f",
			f"Fire Rate: $fireSpeed%.1f seconds",
			f"Range: ${range}%.1f"
		)
		if (aoe != 0.0f) {
			ret = ret ++ List(f"Area of Effect: ${aoe}%.1f")
		}
		ret = ret ++ List(
			s"Default AI: ${currAI}",
			s"Description: ${description}",
			s"Hotkey: ${hotkey}"
		)
		ret
	}
	def init() = {
    val att = TowerMap.towerMap((id,1))
    val att1 = TowerMap.towerMap((id,2))
    damage = att.dmg.toFloat
    fireRate = att.rate
    range = att.range
    aoe = att.aoe
    speed = att.projspd
    value = att.cost
    cost = att1.cost
  }
}

abstract class Tower(xc: Float, yc: Float, towerType: TowerType) extends GameObject(xc, yc) {
	protected var nextShot = 0
	val kind = towerType
	val id = towerType.id
	var currAI = towerType.currAI
	val height = 1.0f
	val width = 1.0f
	// r += 0.5f
	// c += 0.5f
	var kills = 0
	var dmgDone = 0f
	var level = 1
	var boughtAI = false

	def sell(): Int = {
		inactivate
		kind.value / 2
	}

  towerType.name = towerType.basename + " Level 1"

  def upgradable () = level < 3

  var damage = towerType.damage
  var fireRate = towerType.fireRate
  var range = towerType.range
  var aoe = towerType.aoe
  var speed = towerType.speed
  var value = towerType.value
  var name = towerType.name
  var basename = towerType.basename
  var cost = towerType.cost

	def upgrade() = {
    val att = TowerMap.towerMap((id,level+1))
    if (level != 2) {
      val att1 = TowerMap.towerMap((id,level+2))
      cost = att1.cost
    } else {
      cost = 0
    }
    level += 1
    damage = att.dmg.toFloat
    fireRate = att.rate
    range = att.range
    aoe = att.aoe
    speed = att.projspd
    value += att.cost
    name = basename + s" Level $level"
  }

	def upgradeCost() : Int = {
    if (level >=3 ) {
      return 0
    }
    val att = TowerMap.towerMap((id,level+1))
    att.cost
  }

	def startRound(): Int = 0

	def setRotation(tar: Enemy) {
		val rVec = tar.r - r
    	val cVec = tar.c - c
    	val theta = atan2(rVec, cVec)
      	rotation = toDegrees(theta).asInstanceOf[Float] + 90f
	}

	def tick() : List[Projectile] = {
		if(nextShot <= 0) {
			val enemies = map.aoe(r, c, range)
			if (!enemies.isEmpty) {
				nextShot = fireRate
				val target = currAI.pick(r, c, enemies)
				setRotation(target)
				val proj = Projectile(r, c, target, this)
				proj.setMap(map)
				List(proj)
			} else {
				List()
			}
		} else {
			nextShot -= 1
			List()
		}
	}

	def setAI(ai: AI) : Unit = {
		currAI = ai
	}

	def describe() : List[String] = {
		val fireSpeed = fireRate / GameConfig.FrameRate.toFloat
		var ret = List(
			s"Value: ${value}",
      if (cost == 0) {
        "Max Level"
      } else {
        s"Upgrade Cost: $cost"
      },
			f"Damage: ${damage}%.1f",
			f"Fire Rate: $fireSpeed%.1f seconds",
			f"Range: ${range}%.1f"
		)
		if (aoe != 0.0f) {
			ret = ret ++ List(f"Area of Effect: ${aoe}%.1f")
		}
		ret = ret ++ List(
			s"Current AI: ${currAI}",
			s"Kills: $kills",
			f"Damage Dealt: $dmgDone%.1f",
			s"Description: ${kind.description}"
		)
		ret
	}
}

abstract class SlowingTower(xc: Float, yc: Float, towerType: SlowingTowerType) extends Tower(xc, yc, towerType) {
	override val kind = towerType
  var slowMult = towerType.slowMult

  override def upgrade = {
    super.upgrade()
    val att = TowerMap.towerMap((id,level))
    slowMult = 1f - att.slow
  }

	override def tick() : List[Projectile] = {
		if (nextShot == 0) {
			val enemies = map.aoe(r,c, range)
			if (!enemies.isEmpty) {
				nextShot = fireRate
				enemies.foreach(enemy => {
						val slow = new SlowEffect(towerType.slowMult, towerType.slowTime)
						enemy.slow(slow)
					}
				)
			}
			List()
		} else {
			nextShot -= 1
			List()
		}
	}

	override def describe() : List[String] = {
		val time = towerType.slowTime / GameConfig.FrameRate.toFloat
		val mult = ((1f - slowMult) * 100).toInt
		val ret = List(
			s"Value: ${value}",
      if (cost == 0) {
        "Max Level"
      } else {
        s"Upgrade Cost: $cost"
      },
			s"Slow Multiplier: $mult%",
			f"Slow Time: ${time}%.1f seconds",
			f"Range: ${range}%.1f",
			s"Description: ${towerType.description}"
		)
		ret
	}
}

abstract class MazingTower(xc: Float, yc: Float, towerType: TowerType) extends Tower(xc, yc, towerType) {
	override def tick() : List[Projectile] = List()
}

trait SlowingTowerType extends TowerType {
	def slowMult: Float
	def slowMult_=(m: Float): Unit
	def slowTime : Int
	def slowTime_=(t: Int): Unit

	override def describe() : List[String] = {
		val time = slowTime / GameConfig.FrameRate.toFloat
		val mult = ((1f - slowMult) * 100).toInt
		List(
			s"Value: ${value}",
      if (cost ==0) {
        "Max Level"
      } else {
        s"Upgrade Cost: $cost"
      },
			s"Slow Multiplier: $mult%",
			f"Slow Time: $time%.1f seconds",
			f"Range: ${range}%.1f",
			s"Description: ${description}",
			s"Hotkey: ${hotkey}"
		)
	}

	override def init() : Unit = {
		super.init()
		val att = TowerMap.towerMap((id,1))
		slowMult = 1f - att.slow
	}
}

class HarpoonTower(xc: Float, yc: Float) extends Tower(xc, yc, HarpoonTower) {

}

object HarpoonTower extends TowerType {
  var cost = 0
	var range = 2.0f
	var damage = 2.0f
	var fireRate = 60
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = HarpoonTowerID
	var projectileID = HarpoonID
	var speed = 0.25f
	var value = 10
	var basename = "Harpoon Tower"
	var name = "Harpoon Tower Level 1"
	var description = "Basic single\n  target tower, can be placed\n  above water and below water"
	var hotkey = 'H'
  init
}

class CannonTower(xc: Float, yc: Float) extends Tower(xc, yc, CannonTower) {
}

object CannonTower extends TowerType {
  var cost = 0
	var range = 2.5f
	var damage = 5.0f
	var fireRate = 120
	var aoe = 1.0f
	var currAI: AI = new ClosestToGoalAI
	var id = CannonTowerID
	var projectileID = CannonballID
	var speed = 0.2f
	var value = 20
	var basename = "Cannon Tower"
	var name = "Cannon Tower Level 1"
	var description = "Basic AoE tower\n  can only be placed above water"
	var hotkey = 'C'
  init
}

class TorpedoTower(xc: Float, yc: Float) extends Tower(xc, yc, TorpedoTower) {
	private var maps = List[GameMap]()
	override def setMap(m: GameMap): Unit = {
		maps = m :: maps
	}

	override def tick() : List[Projectile] = {
		if(nextShot == 0) {
			val enemies = maps.foldRight(Set[Enemy]())((map, set) => {
					if (set.isEmpty) {
						val enemies = map.aoe(r, c, range)
						if (!enemies.isEmpty) {
							enemies
						} else {
							set
						}
					} else {
						set
					}
				}
			)
			if (!enemies.isEmpty) {
				nextShot = fireRate
				val target = currAI.pick(r, c, enemies)
				setRotation(target)
				val proj = Projectile(r, c, target, this)
				proj.setMap(target.getMap)
				List(proj)
			} else {
				List()
			}
		} else {
			nextShot -= 1
			List()
		}
	}
}

object TorpedoTower extends TowerType {
  var cost = 0
	var range = 3.25f
	var damage = 6.0f
	var fireRate = 90
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = TorpedoTowerID
	var projectileID = TorpedoID
	var speed = 0.3f
	var value = 30
	var basename = "Torpedo Tower"
	var name = "Torpedo Tower Level 1"
	var description = "Single target tower\n  Placed below water, but\n  can fire at both levels"
	var hotkey = 'T'
  init
}

class OilDrillTower(xc: Float, yc: Float) extends MazingTower(xc, yc, OilDrillTower) {
	private var maps = List[GameMap]()
	override def setMap(m: GameMap): Unit = {
		maps = m :: maps
	}

  var cash = 30
	override def upgrade() = {
    val att = TowerMap.towerMap((id,level+1))
    super.upgrade()
    cash = att.money
  }

	override def startRound() : Int = {
		cash
	}

	override def describe() : List[String] = {
		List(
			s"Value: ${value}",
      if (cost == 0) {
        "Max Level"
      } else {
        s"Upgrade Cost: $cost"
      },
			s"Cash Earned per Round: $cash",
			s"Description: ${kind.description}"
		)
	}
}

object OilDrillTower extends TowerType {
  var cost = 0
	var range = 0.0f
	var damage = 0.0f
	var fireRate = 0
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = OilDrillTowerID
	var projectileID = HarpoonID
	var speed = 0.0f
	var value = 200
	var basename = "Oil Drill"
	var name = "Oil Drill Level 1"
	var description = "Money generator\n  Earns money at the start\n  of each round\n  Takes up spot above and\n  below water"
	var hotkey = 'O'

	override def describe() : List[String] = {
    val cash = 30
		List(
			s"Value: ${value}",
      s"Upgrade Cost: $cash",
			s"Cash Earned per Round: $cash",
			s"Description: ${description}"
		)
	}
  init
}

class IceTowerBottom(xc: Float, yc: Float) extends SlowingTower(xc, yc, IceTowerBottom) {

}

object IceTowerBottom extends SlowingTowerType {
  var cost = 0
	var range = 1.0f
	var damage = 0.0f
	var fireRate = 10
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = IceTowerBottomID
	var projectileID = HarpoonID
	var speed = 2.0f
	var value = 20
	var basename = "Ice Tower"
	var name = "Ice Tower Level 1"
	var slowMult = 0.75f
	var slowTime = 20
	var description = "Slowing tower\n  Placed below and slows in area\n  Adds ice block to same spot\n  above water which blocks\n  enemies"
	var hotkey = 'I'
  init
}

class IceTowerTop(xc: Float, yc: Float) extends MazingTower(xc, yc, IceTowerTop) {
	override def upgradeCost(): Int = 0

	override def upgrade(): Unit = {}

}

object IceTowerTop extends TowerType {
  var cost = 0
	var range = 0.0f
	var damage = 0.0f
	var fireRate = 120
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = IceTowerTopID
	var projectileID = HarpoonID
	var speed = 0.0f
	var value = 0
	var basename = "Ice Tower"
	var name = "Ice Tower Level 1"
	var description = ""
	var hotkey = 'I'
}

class DepthChargeTower(xc: Float, yc: Float) extends Tower(xc, yc, DepthChargeTower) {
}

object DepthChargeTower extends TowerType {
  var cost = 0
	var range = 1.5f
	var damage = 5.0f
	var fireRate = 120
	var aoe = 1.0f
	var currAI: AI = new RandomAI
	var id = DepthChargeTowerID
	var projectileID = HarpoonID
	var speed = 0.2f
	var value = 20
	var basename = "Depth Charge"
	var name = "Depth Charge Level 1"
	var description = "AoE tower\n  Placed above water, but fires\n  at enemies below water"
	var hotkey = 'D'
  init
}

class WhirlpoolBottom(xc: Float, yc: Float) extends MazingTower(xc, yc, WhirlpoolBottom) {
	var slowMult = 0.75f
	var slowTime = 30
}

object WhirlpoolBottom extends TowerType {
  var cost = 0
	var range = 4.0f
	var damage = 0.0f
	var fireRate = 10
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = WhirlpoolBottomID
	var projectileID = HarpoonID
	var speed = 2.0f
	var value = 20
	var basename = "Whirlpool Tower"
	var name = "Whirlpool Tower Level 1"
	var description = "Slowing tower\n  Placed below water, slows\n  enemies in area above water"
	var hotkey = 'W'
  init
}

class WhirlpoolTop(xc: Float, yc: Float) extends SlowingTower(xc, yc, WhirlpoolTop) {

}

object WhirlpoolTop extends SlowingTowerType {
  var cost = 0
	var range = 4.0f
	var damage = 0.0f
	var fireRate = 1
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = WhirlpoolTopID
	var projectileID = HarpoonID
	var speed = 0.0f
	var value = 0
	var basename = "Whirlpool Tower"
	var name = "Whirlpool Tower Level 1"
	var slowMult = 0.75f
	var slowTime = 20
	var description = "Slowing tower\n  Placed below water, slows\n  enemies in area above water"
	var hotkey = 'W'
  init
}

class MissileTower(xc: Float, yc: Float) extends Tower(xc, yc, MissileTower) {
	var numTargets = 3

	override def tick() : List[Projectile] = {
		if(nextShot == 0) {
			val enemies = map.aoe(r, c, range)
			if (!enemies.isEmpty) {
				nextShot = fireRate
				var projectiles = List[Projectile]()
				for(i <- 1 to numTargets) {
					if (!enemies.isEmpty) {
						val target = currAI.pick(r, c, enemies)
						if (i == 1) {
							setRotation(target)
						}
						val proj = Projectile(r, c, target, this)
						proj.setMap(map)
						projectiles = proj :: projectiles
						enemies.remove(target)
					}
				}
				projectiles
			} else {
				List()
			}
		} else {
			nextShot -= 1
			List()
		}
	}
}

object MissileTower extends TowerType {
  var cost = 0
	var range = 2.0f
	var damage = 3.0f
	var fireRate = 40
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = MissileTowerID
	var projectileID = MissileID
	var speed = 0.3f
	var value = 50
	var basename = "Missile Tower"
	var name = "Missile Tower Level 1"
	var description = "Multitarget tower\n  Placed above water\n  Fires at multiple enemies\n  within range"
	var hotkey = 'M'
  init
}

class NetTower(xc: Float, yc: Float) extends Tower(xc, yc, NetTower) {

	override def tick(): List[Projectile] = {
		if(nextShot == 0) {
			val enemies = map.aoe(r, c, range)
			if (!enemies.isEmpty) {
				nextShot = fireRate
				val target = currAI.pick(r, c, enemies)
				setRotation(target)
				val proj = Projectile(r, c, target, this)
				proj.setMap(map)
				List(proj)
			} else {
				List()
			}
		} else {
			nextShot -= 1
			List()
		}
	}
}

object NetTower extends TowerType {
  var cost = 0
	var range = 2.0f
	var damage = 0.0f
	var fireRate = 90
	var aoe = 0.0f
	var currAI: AI = new RandomAI
	var id = NetTowerID
	var projectileID = NetID
	var speed = 0.5f
	var value = 100
	var basename = "Net Tower"
	var name = "Net Tower Level 1"
	var description = "Single target tower\n  Placed above water\n  Temporarily stops targeted\n  enemy from moving"
	var hotkey = 'N'
  init
}

class SteamTower(xc: Float, yc: Float) extends Tower(xc, yc, SteamTower) {

	override def tick(): List[Projectile] = {
		if(nextShot == 0) {
			val enemiesU = Set[Enemy]()
			val enemiesL = Set[Enemy]()
			val enemiesD = Set[Enemy]()
			val enemiesR = Set[Enemy]()

			for(i <- 1 to range.toInt) {
				map(r+i,c) match {
					case Some(tile) => enemiesU ++= tile.enemies
					case None => ()
				}
				map(r-i,c) match {
					case Some(tile) => enemiesD ++= tile.enemies
					case None => ()
				}
				map(r,c+i) match {
					case Some(tile) => enemiesR ++= tile.enemies
					case None => ()
				}
				map(r,c-i) match {
					case Some(tile) => enemiesL ++= tile.enemies
					case None => ()
				}
			}
			val enemies = enemiesU ++ enemiesL ++ enemiesR ++ enemiesD
			if (!enemies.isEmpty) {
				nextShot = fireRate
				val target = currAI.pick(r, c, enemiesU, enemiesD, enemiesL, enemiesR)
				var dir = Up
				if (target.r.toInt > r.toInt) {
					dir = Down
				} else if (target.r.toInt < r.toInt) {
					dir = Up
				} else if (target.c.toInt > c.toInt) {
					dir = Right
				} else {
					dir = Left
				}
				val proj = Projectile(r, c, dir, this)
				proj.setMap(map)
				List(proj)
			} else {
				List()
			}
		} else {
			nextShot -= 1
			List()
		}
	}
}

object SteamTower extends TowerType {
  var cost = 0
	var range = 2.5f
	var damage = 5.0f
	var fireRate = 90
	var aoe = 1.0f
	var currAI: AI = new SteamRandomAI
	var id = SteamTowerID
	var projectileID = SteamID
	var speed = 1.0f
	var value = 30
	var basename = "Steam Tower"
	var name = "Steam Tower Level 1"
	var description = "Line damage tower\n  Placed below water\n  Damages all enemies in one\n  in one of four directions"
	var hotkey = 'S'
  init
}

object Tower {
	def apply(id: Int, xc: Float, yc: Float) : Tower = {
		id match {
			case HarpoonTowerID => new HarpoonTower(xc, yc)
			case CannonTowerID => new CannonTower(xc, yc)
			case TorpedoTowerID => new TorpedoTower(xc, yc)
			case OilDrillTowerID => new OilDrillTower(xc,yc)
			case IceTowerBottomID => new IceTowerBottom(xc, yc)
			case IceTowerTopID => new IceTowerTop(xc, yc)
			case DepthChargeTowerID => new DepthChargeTower(xc, yc)
			case WhirlpoolBottomID => new WhirlpoolBottom(xc, yc)
			case WhirlpoolTopID => new WhirlpoolTop(xc, yc)
			case MissileTowerID => new MissileTower(xc, yc)
			case NetTowerID => new NetTower(xc, yc)
			case SteamTowerID => new SteamTower(xc, yc)
		}
	}
	def apply(id: Int) : TowerType = {
		id match {
			case HarpoonTowerID => HarpoonTower
			case CannonTowerID => CannonTower
			case TorpedoTowerID => TorpedoTower
			case OilDrillTowerID => OilDrillTower
			case IceTowerBottomID => IceTowerBottom
			case IceTowerTopID => IceTowerTop
			case DepthChargeTowerID => DepthChargeTower
			case WhirlpoolBottomID => WhirlpoolBottom
			case WhirlpoolTopID => WhirlpoolTop
			case MissileTowerID => MissileTower
			case NetTowerID => NetTower
			case SteamTowerID => SteamTower
		}
	}
}


text:
package nl.xillio.migrationtool.template;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import me.biesaart.utils.Log;
import nl.xillio.util.XillioHomeFolder;
import nl.xillio.xill.api.XillEnvironment;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Utility class for creating robots from templates.
 */
public class Templater {

    /**
     * Default path to template files.
     */
    public static final Path DEFAULT_TEMPLATES_PATH = Paths.get(XillioHomeFolder.forXillIDE().toURI()).resolve("templates");
    private static final Configuration CONFIG = new Configuration(Configuration.VERSION_2_3_22);
    private Path templatesDirectory;
    private static final Logger LOGGER = Log.get();

    /**
     * Default constructor. Sets up the {@link Configuration} and default templates.
     *
     * @throws IOException if a problem occurs during creating default folders/templates
     */
    public Templater() throws IOException {
        templatesDirectory = Templater.DEFAULT_TEMPLATES_PATH;
        if (!Files.exists(templatesDirectory)) {
            Files.createDirectories(templatesDirectory);
        }
        Path defaultTemplate = templatesDirectory.resolve("default" + XillEnvironment.ROBOT_TEMPLATE_EXTENSION);
        if (!Files.exists(defaultTemplate)) {
            try (InputStream defaultTemplateRes = getClass().getResource("/templates/default" + XillEnvironment.ROBOT_TEMPLATE_EXTENSION).openStream()) {
                Files.copy(defaultTemplateRes, defaultTemplate);
            }
        }
        Templater.CONFIG.setDirectoryForTemplateLoading(templatesDirectory.toFile());
        Templater.CONFIG.setDefaultEncoding("UTF-8");
        Templater.CONFIG.setTemplateExceptionHandler((exception, env, out) -> {
            try {
                out.write("[ERROR: " + exception.getBlamedExpressionString() + "]");
            } catch (IOException e) {
                throw new TemplateException("Failed to print error message. Cause: " + e, env);
            }
        });
    }

    /**
     * The list of currently available templates (as defined by {@link XillEnvironment#ROBOT_TEMPLATE_EXTENSION} files being in the template folder).
     *
     * @return the list of available templates
     */
    public List<String> getTemplateNames() throws IOException {
        return Files.list(templatesDirectory)
                .map(Path::getFileName)
                .map(Path::toString)
                .map(String::toLowerCase)
                .filter(name -> name.endsWith(XillEnvironment.ROBOT_TEMPLATE_EXTENSION.toLowerCase()))
                .collect(Collectors.toList());
    }

    /**
     * Returns a default model with some already initialized key-value pairs.
     * Currently:
     *

     *
{@code date}: the current date

     *
{@code userName}: the current logged in user

     *

     *
     * @return a default template model
     */
    public static Map<String, Object> getDefaultModel() {
        Map<String, Object> defaultModel = new HashMap<>();
        defaultModel.put("date", LocalDate.now());
        defaultModel.put("userName", System.getProperty("user.name"));
        return defaultModel;
    }

    /**
     * Renders a template using a model and writes it in the provided output file.
     *
     * @param templateName the template to render
     * @param model        the model to use during the rendering
     * @param output       the file in which the template will be rendered
     * @return the output file
     * @throws IOException       if permissions are not sufficient, files are missing or any other IO problem
     * @throws TemplateException if the template couldn't be processed
     */
    public Path render(String templateName, Map<String, Object> model, Path output) throws IOException, TemplateException {
        if (templateName != null) {
            Template template = Templater.CONFIG.getTemplate(templateName);
            OutputStreamWriter out = new FileWriter(output.toFile());
            template.process(model, out);
        } else {
            FileUtils.write(output.toFile(), "", false);
        }
        return output;
    }

}


text:
package com.github.dozermapper.protobuf.builder;

import com.github.dozermapper.core.BeanBuilder;
import com.google.protobuf.Message;

/**
 * {@link BeanBuilder} that instantiates {@link Message}
 */
public class ProtoBeanBuilder implements BeanBuilder {

    protected Message.Builder internalProtoBuilder;
    protected Class<? extends Message> beanClass;

    /**
     * {@link BeanBuilder} which is used to create instances of {@link Message} via {@link Message.Builder}
     *
     * @param internalProtoBuilder builder for {@link Message}
     * @param beanClass            type of {@link Message} to create
     */
    public ProtoBeanBuilder(Message.Builder internalProtoBuilder, Class<? extends Message> beanClass) {
        this.internalProtoBuilder = internalProtoBuilder;
        this.beanClass = beanClass;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<? extends Message> beanClass() {
        return beanClass;
    }

    /**
     * Get the {@link Message.Builder}
     *
     * @return instance of {@link Message.Builder}
     */
    public Message.Builder internalProtoBuilder() {
        return internalProtoBuilder;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object build() {
        return internalProtoBuilder.build();
    }
}


text:
use smallvec::SmallVec;
use syntax::SmolStr;

use crate::{tt_iter::TtIter, ParseError};

/// Consider
///
/// ```
/// macro_rules! an_macro {
///     ($x:expr + $y:expr) => ($y * $x)
/// }
/// ```
///
/// Stuff to the left of `=>` is a [`MetaTemplate`] pattern (which is matched
/// with input).
///
/// Stuff to the right is a [`MetaTemplate`] template which is used to produce
/// output.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct MetaTemplate(pub(crate) Vec<Op>);

impl MetaTemplate {
    pub(crate) fn parse_pattern(pattern: &tt::Subtree) -> Result<MetaTemplate, ParseError> {
        MetaTemplate::parse(pattern, Mode::Pattern)
    }

    pub(crate) fn parse_template(template: &tt::Subtree) -> Result<MetaTemplate, ParseError> {
        MetaTemplate::parse(template, Mode::Template)
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = &Op> {
        self.0.iter()
    }

    fn parse(tt: &tt::Subtree, mode: Mode) -> Result<MetaTemplate, ParseError> {
        let mut src = TtIter::new(tt);

        let mut res = Vec::new();
        while let Some(first) = src.next() {
            let op = next_op(first, &mut src, mode)?;
            res.push(op);
        }

        Ok(MetaTemplate(res))
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Op {
    Var { name: SmolStr, kind: Option<MetaVarKind>, id: tt::TokenId },
    Ignore { name: SmolStr, id: tt::TokenId },
    Index { depth: u32 },
    Repeat { tokens: MetaTemplate, kind: RepeatKind, separator: Option<Separator> },
    Leaf(tt::Leaf),
    Subtree { tokens: MetaTemplate, delimiter: Option<tt::Delimiter> },
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum RepeatKind {
    ZeroOrMore,
    OneOrMore,
    ZeroOrOne,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum MetaVarKind {
    Path,
    Ty,
    Pat,
    PatParam,
    Stmt,
    Block,
    Meta,
    Item,
    Vis,
    Expr,
    Ident,
    Tt,
    Lifetime,
    Literal,
}

#[derive(Clone, Debug, Eq)]
pub(crate) enum Separator {
    Literal(tt::Literal),
    Ident(tt::Ident),
    Puncts(SmallVec<[tt::Punct; 3]>),
}

// Note that when we compare a Separator, we just care about its textual value.
impl PartialEq for Separator {
    fn eq(&self, other: &Separator) -> bool {
        use Separator::*;

        match (self, other) {
            (Ident(a), Ident(b)) => a.text == b.text,
            (Literal(a), Literal(b)) => a.text == b.text,
            (Puncts(a), Puncts(b)) if a.len() == b.len() => {
                let a_iter = a.iter().map(|a| a.char);
                let b_iter = b.iter().map(|b| b.char);
                a_iter.eq(b_iter)
            }
            _ => false,
        }
    }
}

impl Separator {
    pub(crate) fn tt_count(&self) -> usize {
        match self {
            Separator::Literal(_) => 1,
            Separator::Ident(_) => 1,
            Separator::Puncts(it) => it.len(),
        }
    }
}

#[derive(Clone, Copy)]
enum Mode {
    Pattern,
    Template,
}

fn next_op<'a>(first: &tt::TokenTree, src: &mut TtIter<'a>, mode: Mode) -> Result<Op, ParseError> {
    let res = match first {
        tt::TokenTree::Leaf(leaf @ tt::Leaf::Punct(tt::Punct { char: '$', .. })) => {
            // Note that the '$' itself is a valid token inside macro_rules.
            let second = match src.next() {
                None => return Ok(Op::Leaf(leaf.clone())),
                Some(it) => it,
            };
            match second {
                tt::TokenTree::Subtree(subtree) => match subtree.delimiter_kind() {
                    Some(tt::DelimiterKind::Parenthesis) => {
                        let (separator, kind) = parse_repeat(src)?;
                        let tokens = MetaTemplate::parse(subtree, mode)?;
                        Op::Repeat { tokens, separator, kind }
                    }
                    Some(tt::DelimiterKind::Brace) => match mode {
                        Mode::Template => {
                            parse_metavar_expr(&mut TtIter::new(subtree)).map_err(|()| {
                                ParseError::unexpected("invalid metavariable expression")
                            })?
                        }
                        Mode::Pattern => {
                            return Err(ParseError::unexpected(
                                "`${}` metavariable expressions are not allowed in matchers",
                            ))
                        }
                    },
                    _ => {
                        return Err(ParseError::expected(
                            "expected `$()` repetition or `${}` expression",
                        ))
                    }
                },
                tt::TokenTree::Leaf(leaf) => match leaf {
                    tt::Leaf::Ident(ident) if ident.text == "crate" => {
                        // We simply produce identifier `$crate` here. And it will be resolved when lowering ast to Path.
                        Op::Leaf(tt::Leaf::from(tt::Ident { text: "$crate".into(), id: ident.id }))
                    }
                    tt::Leaf::Ident(ident) => {
                        let kind = eat_fragment_kind(src, mode)?;
                        let name = ident.text.clone();
                        let id = ident.id;
                        Op::Var { name, kind, id }
                    }
                    tt::Leaf::Literal(lit) if is_boolean_literal(lit) => {
                        let kind = eat_fragment_kind(src, mode)?;
                        let name = lit.text.clone();
                        let id = lit.id;
                        Op::Var { name, kind, id }
                    }
                    tt::Leaf::Punct(punct @ tt::Punct { char: '$', .. }) => match mode {
                        Mode::Pattern => {
                            return Err(ParseError::unexpected(
                                "`$$` is not allowed on the pattern side",
                            ))
                        }
                        Mode::Template => Op::Leaf(tt::Leaf::Punct(*punct)),
                    },
                    tt::Leaf::Punct(_) | tt::Leaf::Literal(_) => {
                        return Err(ParseError::expected("expected ident"))
                    }
                },
            }
        }
        tt::TokenTree::Leaf(tt) => Op::Leaf(tt.clone()),
        tt::TokenTree::Subtree(subtree) => {
            let tokens = MetaTemplate::parse(subtree, mode)?;
            Op::Subtree { tokens, delimiter: subtree.delimiter }
        }
    };
    Ok(res)
}

fn eat_fragment_kind(src: &mut TtIter<'_>, mode: Mode) -> Result<Option<MetaVarKind>, ParseError> {
    if let Mode::Pattern = mode {
        src.expect_char(':').map_err(|()| ParseError::unexpected("missing fragment specifier"))?;
        let ident = src
            .expect_ident()
            .map_err(|()| ParseError::unexpected("missing fragment specifier"))?;
        let kind = match ident.text.as_str() {
            "path" => MetaVarKind::Path,
            "ty" => MetaVarKind::Ty,
            "pat" => MetaVarKind::Pat,
            "pat_param" => MetaVarKind::PatParam,
            "stmt" => MetaVarKind::Stmt,
            "block" => MetaVarKind::Block,
            "meta" => MetaVarKind::Meta,
            "item" => MetaVarKind::Item,
            "vis" => MetaVarKind::Vis,
            "expr" => MetaVarKind::Expr,
            "ident" => MetaVarKind::Ident,
            "tt" => MetaVarKind::Tt,
            "lifetime" => MetaVarKind::Lifetime,
            "literal" => MetaVarKind::Literal,
            _ => return Ok(None),
        };
        return Ok(Some(kind));
    };
    Ok(None)
}

fn is_boolean_literal(lit: &tt::Literal) -> bool {
    matches!(lit.text.as_str(), "true" | "false")
}

fn parse_repeat(src: &mut TtIter<'_>) -> Result<(Option<Separator>, RepeatKind), ParseError> {
    let mut separator = Separator::Puncts(SmallVec::new());
    for tt in src {
        let tt = match tt {
            tt::TokenTree::Leaf(leaf) => leaf,
            tt::TokenTree::Subtree(_) => return Err(ParseError::InvalidRepeat),
        };
        let has_sep = match &separator {
            Separator::Puncts(puncts) => !puncts.is_empty(),
            _ => true,
        };
        match tt {
            tt::Leaf::Ident(_) | tt::Leaf::Literal(_) if has_sep => {
                return Err(ParseError::InvalidRepeat)
            }
            tt::Leaf::Ident(ident) => separator = Separator::Ident(ident.clone()),
            tt::Leaf::Literal(lit) => separator = Separator::Literal(lit.clone()),
            tt::Leaf::Punct(punct) => {
                let repeat_kind = match punct.char {
                    '*' => RepeatKind::ZeroOrMore,
                    '+' => RepeatKind::OneOrMore,
                    '?' => RepeatKind::ZeroOrOne,
                    _ => match &mut separator {
                        Separator::Puncts(puncts) if puncts.len() != 3 => {
                            puncts.push(*punct);
                            continue;
                        }
                        _ => return Err(ParseError::InvalidRepeat),
                    },
                };
                return Ok((has_sep.then(|| separator), repeat_kind));
            }
        }
    }
    Err(ParseError::InvalidRepeat)
}

fn parse_metavar_expr(src: &mut TtIter<'_>) -> Result<Op, ()> {
    let func = src.expect_ident()?;
    let args = src.expect_subtree()?;

    if args.delimiter_kind() != Some(tt::DelimiterKind::Parenthesis) {
        return Err(());
    }

    let mut args = TtIter::new(args);

    let op = match &*func.text {
        "ignore" => {
            let ident = args.expect_ident()?;
            Op::Ignore { name: ident.text.clone(), id: ident.id }
        }
        "index" => {
            let depth = if args.len() == 0 { 0 } else { args.expect_u32_literal()? };
            Op::Index { depth }
        }
        _ => return Err(()),
    };

    if args.next().is_some() {
        return Err(());
    }

    Ok(op)
}


text:
using System;
using System.Collections;
using System.Text;
using System.Reflection;
using Microsoft.VsSDK.UnitTestLibrary;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VSSDK.Tools.VsIdeTesting;
using Run00.GitWorkItems;

namespace GitWorkItems_UnitTests.MyToolWindowTest
{
	///
	///This is a test class for MyToolWindowTest and is intended
	///to contain all MyToolWindowTest Unit Tests
	///
	[TestClass()]
	public class MyToolWindowTest
	{

		///
		///MyToolWindow Constructor test
		///
		[TestMethod()]
		public void MyToolWindowConstructorTest()
		{

			//var target = new QueryResultsView();
			//Assert.IsNotNull(target, "Failed to create an instance of MyToolWindow");

			//MethodInfo method = target.GetType().GetMethod("get_Content", BindingFlags.Public | BindingFlags.Instance);
			//Assert.IsNotNull(method.Invoke(target, null), "MyControl object was not instantiated");

		}

		///
		///Verify the Content property is valid.
		///
		[TestMethod()]
		public void WindowPropertyTest()
		{
			//var target = new QueryResultsView();
			//Assert.IsNotNull(target.Content, "Content property was null");
		}

	}
}


text:
const path = require('path');

exports.isDevMode = function () {
  return process.env.NODE_ENV !== 'production';
};

exports.resolve = function (filename) {
  return path.resolve(__dirname, '../', filename);
};


text:
using namespace UAlbertaBot;

namespace UAlbertaBot
{
namespace Assert
{
    std::string lastErrorMessage;

    const std::string currentDateTime()
    {
        time_t     now = time(0);
        struct tm  tstruct;
        char       buf[80];
        //tstruct = *localtime(&now);
		localtime_s(&tstruct, &now);
        strftime(buf, sizeof(buf), "%Y-%m-%d_%X", &tstruct);

        return buf;
    }

    void ReportFailure(const char * condition, const char * file, int line, const char * msg, ...)
    {
        char messageBuffer[1024] = "";
        if (msg != nullptr)
        {
            va_list args;
            va_start(args, msg);
            //vsprintf(messageBuffer, msg, args);
			vsnprintf_s(messageBuffer, 1024, msg, args);
            va_end(args);
        }

        std::stringstream ss;
        ss                                              << std::endl;
        ss << "!Assert:   " << condition                << std::endl;
        ss << "File:      " << file                     << std::endl;
        ss << "Message:   " << messageBuffer            << std::endl;
        ss << "Line:      " << line                     << std::endl;
        ss << "Time:      " << currentDateTime()        << std::endl;

        lastErrorMessage = messageBuffer;

        std::cerr << ss.str();
        BWAPI::Broodwar->printf("%s", ss.str().c_str());

        if (Config::Debug::LogAssertToErrorFile)
        {
            Logger::LogAppendToFile(Config::Debug::ErrorLogFilename, ss.str());
        }
    }
}
}


text:
from neutron.common import constants
from neutron.extensions import portbindings
from neutron.plugins.ml2.drivers import mech_openvswitch
from neutron.tests.unit.ml2 import _test_mech_agent as base

class OpenvswitchMechanismBaseTestCase(base.AgentMechanismBaseTestCase):
    VIF_TYPE = portbindings.VIF_TYPE_OVS
    CAP_PORT_FILTER = True
    AGENT_TYPE = constants.AGENT_TYPE_OVS

    GOOD_MAPPINGS = {'fake_physical_network': 'fake_bridge'}
    GOOD_TUNNEL_TYPES = ['gre', 'vxlan']
    GOOD_CONFIGS = {'bridge_mappings': GOOD_MAPPINGS,
                    'tunnel_types': GOOD_TUNNEL_TYPES}

    BAD_MAPPINGS = {'wrong_physical_network': 'wrong_bridge'}
    BAD_TUNNEL_TYPES = ['bad_tunnel_type']
    BAD_CONFIGS = {'bridge_mappings': BAD_MAPPINGS,
                   'tunnel_types': BAD_TUNNEL_TYPES}

    AGENTS = [{'alive': True,
               'configurations': GOOD_CONFIGS}]
    AGENTS_DEAD = [{'alive': False,
                    'configurations': GOOD_CONFIGS}]
    AGENTS_BAD = [{'alive': False,
                   'configurations': GOOD_CONFIGS},
                  {'alive': True,
                   'configurations': BAD_CONFIGS}]

    def setUp(self):
        super(OpenvswitchMechanismBaseTestCase, self).setUp()
        self.driver = mech_openvswitch.OpenvswitchMechanismDriver()
        self.driver.initialize()

class OpenvswitchMechanismGenericTestCase(OpenvswitchMechanismBaseTestCase,
                                          base.AgentMechanismGenericTestCase):
    pass

class OpenvswitchMechanismLocalTestCase(OpenvswitchMechanismBaseTestCase,
                                        base.AgentMechanismLocalTestCase):
    pass

class OpenvswitchMechanismFlatTestCase(OpenvswitchMechanismBaseTestCase,
                                       base.AgentMechanismFlatTestCase):
    pass

class OpenvswitchMechanismVlanTestCase(OpenvswitchMechanismBaseTestCase,
                                       base.AgentMechanismVlanTestCase):
    pass

class OpenvswitchMechanismGreTestCase(OpenvswitchMechanismBaseTestCase,
                                      base.AgentMechanismGreTestCase):
    pass


text:
/*
 * nhash.h
 * Charlotte Koch <cfkoch@edgebsd.org>
 */

#ifndef NHASH_H
#define NHASH_H

#include <mruby.h>

/*
 * nhash is an opaque structure.
 */
struct nhash {
  mrb_value _hash;
};
typedef struct nhash nhash;

nhash *nhash_new(void);
void nhash_free(nhash *hash);
void nhash_set(nhash *hash, const char *key, const void *ptr);
void *nhash_get(const nhash *hash, const char *key);
void nhash_delete(nhash *hash, const char *key);
char *nhash_inspect(const nhash *hash);

/* */

/*
 * nstringhash is an opaque structure.
 */
struct nstringhash {
  mrb_value _hash;
};
typedef struct nstringhash nstringhash;

nstringhash *nstringhash_new(void);
void nstringhash_free(nstringhash *hash);
void nstringhash_set(nstringhash *hash, const char *key, const char *value);
char *nstringhash_get(const nstringhash *hash, const char *key);
void nstringhash_delete(nstringhash *hash, const char *key);
char *nstringhash_inspect(const nstringhash *hash);

#endif /* NHASH_H */


text:
<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="red_kite_cms_add_block" pattern="/{_locale}/addBlock">
        <default key="_controller">RedKiteCmsBundle:Blocks:addBlock</default>
        <default key="_locale">en</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="red_kite_cms_edit_block" pattern="/{_locale}/editBlock/{locked}">
        <default key="_controller">RedKiteCmsBundle:Blocks:editBlock</default>
        <default key="_locale">en</default>
        <default key="locked">idBlock</default>
        <requirement key="_method">POST</requirement>
    </route>

    <route id="red_kite_cms_delete_block" pattern="/{_locale}/deleteBlock/{locked}">
        <default key="_controller">RedKiteCmsBundle:Blocks:deleteBlock</default>
        <default key="_locale">en</default>
        <default key="locked">idBlock</default>
        <requirement key="_method">POST</requirement>
    </route>
</routes>


text:
import React, { Component } from 'react';

export default class AboutDescription extends Component {
  render() {
    return (
      <div className="about-description">
        This demo creates a live visualization of over 250,000 vehicle
        complaints compiled by the National Highway Traffic Safety
        Administration (NHTSA) from 1995 to 2014. It is built with the Zoomdata
        API, which allows companies to tap the big data processing capability of
        Zoomdata, with whatever application they like.
      </div>
    );
  }
}