text:
package com.evolveum.midpoint.wf.impl.util;

import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

import javax.xml.namespace.QName;
import java.io.Serializable;

/**
 * Helper class that allows putting (almost) arbitrary objects into Activiti processes.
 *
 * Generally, prism objects and containers and jaxb objects are stored in their XML form,
 * allowing for safe deserialization in potentially newer version of midpoint.
 *
 * Other serializable items are stored as such.
 *
 * There's a child class (JaxbValueContainer) that allows directly retrieving XML representation of the object
 * (if there's one).
 *
 * @author mederly
 */
public class SingleItemSerializationSafeContainerImpl<T> implements SerializationSafeContainer<T> {

    private static final long serialVersionUID = 7269803380754945968L;

    private static final Trace LOGGER = TraceManager.getTrace(SingleItemSerializationSafeContainerImpl.class);
    public static final int MAX_WIDTH = 500;

    // this is the actual (directly usable) value of the item
    private transient T actualValue;

    // if there's no need to encode the value, it is stored in the first attribute
    // if there is (e.g. for PrismObjects) the encoded value is stored in the second attribute
    private T valueForStorageWhenNotEncoded;
    protected String valueForStorageWhenEncoded;

    // beware, for JAXB, PRISM_OBJECT and PRISM_CONTAINER encoding schemes the value must be XML, as it might be
    // exposed through JaxbValueContainer
    protected EncodingScheme encodingScheme;

    private transient PrismContext prismContext;

    public SingleItemSerializationSafeContainerImpl(T value, PrismContext prismContext) {
        Validate.notNull(prismContext, "prismContext must not be null");
        this.prismContext = prismContext;
        setValue(value);
    }

    @Override
    public void setValue(T value) {
        this.actualValue = value;

        checkPrismContext();
        if (value != null && prismContext.canSerialize(value)) {
            try {
                this.valueForStorageWhenEncoded = prismContext.xmlSerializer().serializeAnyData(value, new QName("value"));
            } catch (SchemaException e) {
                throw new SystemException("Couldn't serialize value of type " + value.getClass() + ": " + e.getMessage(), e);
            }
            this.valueForStorageWhenNotEncoded = null;
            encodingScheme = EncodingScheme.PRISM;
        } else if (value == null || value instanceof Serializable) {
            this.valueForStorageWhenNotEncoded = value;
            this.valueForStorageWhenEncoded = null;
            encodingScheme = EncodingScheme.NONE;
            if (value instanceof Itemable) {
                throw new IllegalStateException("Itemable value is used as not-encoded serializable item; value = " + value);
            }
        } else {
            throw new IllegalStateException("Attempt to put non-serializable item " + value.getClass() + " into " + this.getClass().getSimpleName());
        }
    }

    private void checkPrismContext() {
        Validate.notNull(prismContext, "In SerializationSafeContainer the prismContext is not set up");
    }

    @Override
    public T getValue() {

        if (actualValue != null) {
            return actualValue;
        }

        if (valueForStorageWhenNotEncoded != null) {
            actualValue = valueForStorageWhenNotEncoded;
            return actualValue;
        }

        if (valueForStorageWhenEncoded != null) {
            if (prismContext == null) {
                throw new IllegalStateException("PrismContext not set for SerializationSafeContainer holding " + StringUtils.abbreviate(valueForStorageWhenEncoded, MAX_WIDTH));
            }

            if (encodingScheme == EncodingScheme.PRISM) {
                try {
                    PrismValue prismValue = prismContext.parserFor(valueForStorageWhenEncoded).xml().parseItemValue();
                    actualValue = prismValue != null ? prismValue.getRealValue() : null;
                } catch (SchemaException e) {
                    throw new SystemException("Couldn't deserialize value from JAXB: " + StringUtils.abbreviate(valueForStorageWhenEncoded, MAX_WIDTH), e);
                }
                return actualValue;
            } else {
                throw new IllegalStateException("Unexpected encoding scheme " + encodingScheme);
            }
        }

        return null;
    }

    @Override
    public PrismContext getPrismContext() {
        return prismContext;
    }

    @Override
    public void setPrismContext(PrismContext prismContext) {
        this.prismContext = prismContext;
    }

    // for testing purposes
    @Override
    public void clearActualValue() {
        actualValue = null;
    }

    public enum EncodingScheme { PRISM, NONE };

    @Override
    public String toString() {
        return "SerializationSafeContainer{" +
                "actualValue " + (actualValue != null ? "SET" : "NOT SET") +
                ", valueForStorageWhenNotEncoded=" + valueForStorageWhenNotEncoded +
                ", valueForStorageWhenEncoded='" + valueForStorageWhenEncoded + '\'' +
                ", encodingScheme=" + encodingScheme +
                ", prismContext " + (prismContext != null ? "SET" : "NOT SET") +
                '}';
    }

    @Override
    public String debugDump(int indent) {
        StringBuilder sb = new StringBuilder();
        if (actualValue != null) {
			debugDumpValue(indent, sb, actualValue);
		} else if (valueForStorageWhenNotEncoded != null) {
			debugDumpValue(indent, sb, valueForStorageWhenNotEncoded);
		} else if (valueForStorageWhenEncoded != null) {
			DebugUtil.debugDumpWithLabel(sb, "encoded value", valueForStorageWhenEncoded, indent);
		} else {
			DebugUtil.debugDumpWithLabel(sb, "value", "null", indent);
		}
        return sb.toString();
    }

	private void debugDumpValue(int indent, StringBuilder sb, T value) {
		if (value instanceof DebugDumpable) {
			DebugUtil.debugDumpWithLabel(sb, "value", (DebugDumpable) value, indent);
			return;
		}
		String stringValue = null;
		if (value instanceof ExpressionType) {
			// brutal hack...
			String xml;
			try {
				xml = prismContext.xmlSerializer().serializeRealValue(value, SchemaConstantsGenerated.C_EXPRESSION);
				stringValue = DebugUtil.fixIndentInMultiline(indent, DebugDumpable.INDENT_STRING, xml);
			} catch (SchemaException e) {
				LOGGER.warn("Couldn't serialize an expression: {}", value, e);
			}
		}
		if (stringValue == null) {
			stringValue = String.valueOf(value);
		}
		DebugUtil.debugDumpWithLabel(sb, "value", stringValue, indent);
	}
}


text:
UW.Accordion = Backbone.View.extend({

    //what element becomes an accordion
    el: '.uw-accordion',

    events: {
        'click h3' : 'animate'
    },

    initialize: function () {
        _.bindAll(this, 'animate');
        this.$el.find('h3').addClass('inactive');
        this.$el.find('div').addClass('inactive');
    },

    animate: function (e) {
        var $target = $(e.target);
        if ($target.hasClass('inactive')) {
            this.$el.find('h3.active').removeClass('active').addClass('inactive');
            this.$el.find('div.active').animate({height: '0px'}, 500, function () {
                var $this = $(this);
                $this.removeClass('active').addClass('inactive');
                $this.removeAttr('style');
            });
            $target.removeClass('inactive').addClass('active');
            var $next = $target.next('div.inactive');
            $next.removeClass('inactive').addClass('active');
            var $next_height = $next.outerHeight(true);
            $next.removeClass('active');
            $next.animate({height: $next_height}, 500, function() {
                $next.addClass('active');
                $next.removeAttr('style');
            });
        }
        else {
            $target.removeClass('active').addClass('inactive');
            $target.next('div.active').animate({height: '0px'}, 500, function () {
                var $this = $(this);
                $this.removeClass('active').addClass('inactive');
                $this.removeAttr('style');
            });
        }
    },
});

redpajama_set_name: RedPajamaGithub


text:
package org.telegram.telegrambots.extensions.bots.commandbot.commands;

import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.bots.AbsSender;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;

/**
 * This class manages all the commands for a bot. You can register and deregister commands on demand
 *
 * @author Timo Schulz (Mit0x2)
 */
public final class CommandRegistry implements ICommandRegistry {

    private final Map<String, IBotCommand> commandRegistryMap = new HashMap<>();
    private final boolean allowCommandsWithUsername;
    private final Supplier<String> botUsernameSupplier;
    private BiConsumer<AbsSender, Message> defaultConsumer;

    /**
     * Creates a Command registry
     * @param allowCommandsWithUsername True to allow commands with username, false otherwise
     * @param botUsernameSupplier       Bot username supplier
     */
    public CommandRegistry(boolean allowCommandsWithUsername, Supplier<String> botUsernameSupplier) {
        this.allowCommandsWithUsername = allowCommandsWithUsername;
        this.botUsernameSupplier = botUsernameSupplier;
    }

    @Override
    public void registerDefaultAction(BiConsumer<AbsSender, Message> defaultConsumer) {
        this.defaultConsumer = defaultConsumer;
    }

    @Override
    public final boolean register(IBotCommand botCommand) {
        if (commandRegistryMap.containsKey(botCommand.getCommandIdentifier())) {
            return false;
        }
        commandRegistryMap.put(botCommand.getCommandIdentifier(), botCommand);
        return true;
    }

    @Override
    public final Map<IBotCommand, Boolean> registerAll(IBotCommand... botCommands) {
        Map<IBotCommand, Boolean> resultMap = new HashMap<>(botCommands.length);
        for (IBotCommand botCommand : botCommands) {
            resultMap.put(botCommand, register(botCommand));
        }
        return resultMap;
    }

    @Override
    public final boolean deregister(IBotCommand botCommand) {
        if (commandRegistryMap.containsKey(botCommand.getCommandIdentifier())) {
            commandRegistryMap.remove(botCommand.getCommandIdentifier());
            return true;
        }
        return false;
    }

    @Override
    public final Map<IBotCommand, Boolean> deregisterAll(IBotCommand... botCommands) {
        Map<IBotCommand, Boolean> resultMap = new HashMap<>(botCommands.length);
        for (IBotCommand botCommand : botCommands) {
            resultMap.put(botCommand, deregister(botCommand));
        }
        return resultMap;
    }

    @Override
    public final Collection<IBotCommand> getRegisteredCommands() {
        return commandRegistryMap.values();
    }

    @Override
    public final IBotCommand getRegisteredCommand(String commandIdentifier) {
        return commandRegistryMap.get(commandIdentifier);
    }

    /**
     * Executes a command action if the command is registered.
     *
     * @apiNote  If the command is not registered and there is a default consumer,
     * that action will be performed
     *
     * @param absSender absSender
     * @param message input message
     * @return True if a command or default action is executed, false otherwise
     */
    public final boolean executeCommand(AbsSender absSender, Message message) {
        if (message.hasText()) {
            String text = message.getText();
            if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) {
                String commandMessage = text.substring(1);
                String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP);

                String command = removeUsernameFromCommandIfNeeded(commandSplit[0]);

                if (commandRegistryMap.containsKey(command)) {
                    String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length);
                    commandRegistryMap.get(command).processMessage(absSender, message, parameters);
                    return true;
                } else if (defaultConsumer != null) {
                    defaultConsumer.accept(absSender, message);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * if {@link #allowCommandsWithUsername} is enabled, the username of the bot is removed from
     * the command
     * @param command Command to simplify
     * @return Simplified command
     * @throws java.lang.NullPointerException if {@code allowCommandsWithUsername} is {@code true}
     *                                        and {@code botUsernameSupplier} returns {@code null}
     */
    private String removeUsernameFromCommandIfNeeded(String command) {
        if (allowCommandsWithUsername) {
            String botUsername = Objects.requireNonNull(botUsernameSupplier.get(), "Bot username must not be null");
            return command.replaceAll("(?i)@" + Pattern.quote(botUsername), "").trim();
        }
        return command;
    }
}


text:
<?php

namespace Lug\Component\Grid\Tests\Model\Builder;

use Lug\Component\Grid\Model\Builder\ColumnBuilder;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class ColumnBuilderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ColumnBuilder
     */
    private $builder;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->builder = new ColumnBuilder();
    }

    public function testBuild()
    {
        $column = $this->builder->build(['name' => $name = 'my.name']);

        $this->assertSame($name, $column->getName());
        $this->assertSame($name, $column->getLabel());
        $this->assertSame('text', $column->getType());
        $this->assertFalse($column->hasOptions());
    }

    public function testBuildWithFullOptions()
    {
        $column = $this->builder->build([
            'name'    => $name = 'my.name',
            'label'   => $label = 'my.label',
            'type'    => $type = 'my.type',
            'options' => $options = ['foo' => 'bar'],
        ]);

        $this->assertSame($name, $column->getName());
        $this->assertSame($label, $column->getLabel());
        $this->assertSame($type, $column->getType());
        $this->assertSame($options, $column->getOptions());
    }

    public function testBuildResource()
    {
        $column = $this->builder->build([
            'name'    => $name = 'my.name',
            'type'    => $type = 'resource',
            'options' => $options = ['foo' => 'bar'],
        ]);

        $this->assertSame($name, $column->getName());
        $this->assertSame($name, $column->getLabel());
        $this->assertSame($type, $column->getType());
        $this->assertSame(array_merge($options, ['resource' => $name]), $column->getOptions());
    }

    /**
     * @expectedException \Lug\Component\Grid\Exception\ConfigNotFoundException
     * @expectedExceptionMessage The column config "name" could not be found.
     */
    public function testBuildWithMissingName()
    {
        $this->builder->build([]);
    }
}


text:
from __future__ import print_function, division
from plumbum import cli
from plumbum.lib import six

class TestValidator:
    def test_named(self):
        class Try(object):
            @cli.positional(x=abs, y=str)
            def main(selfy, x, y):
                pass

        assert Try.main.positional == [abs, str]
        assert Try.main.positional_varargs == None

    def test_position(self):
        class Try(object):
            @cli.positional(abs, str)
            def main(selfy, x, y):
                pass

        assert Try.main.positional == [abs, str]
        assert Try.main.positional_varargs == None

    def test_mix(self):
        class Try(object):
            @cli.positional(abs, str, d=bool)
            def main(selfy, x, y, z, d):
                pass

        assert Try.main.positional == [abs, str, None, bool]
        assert Try.main.positional_varargs == None

    def test_var(self):
        class Try(object):
            @cli.positional(abs, str, int)
            def main(selfy, x, y, *g):
                pass

        assert Try.main.positional == [abs, str]
        assert Try.main.positional_varargs == int

    def test_defaults(self):
        class Try(object):
            @cli.positional(abs, str)
            def main(selfy, x, y = 'hello'):
                pass

        assert Try.main.positional == [abs, str]

class TestProg:
    def test_prog(self, capsys):
        class MainValidator(cli.Application):
            @cli.positional(int, int, int)
            def main(self, myint, myint2, *mylist):
                print(repr(myint), myint2, mylist)

        _, rc = MainValidator.run(["prog", "1", "2", '3', '4', '5'], exit = False)
        assert rc == 0
        assert "1 2 (3, 4, 5)" == capsys.readouterr()[0].strip()

    def test_failure(self, capsys):
        class MainValidator(cli.Application):
            @cli.positional(int, int, int)
            def main(self, myint, myint2, *mylist):
                print(myint, myint2, mylist)
        _, rc = MainValidator.run(["prog", "1.2", "2", '3', '4', '5'], exit = False)

        assert rc == 2
        value = capsys.readouterr()[0].strip()
        assert 'int' in value
        assert 'not' in value
        assert '1.2' in value

    def test_defaults(self, capsys):
        class MainValidator(cli.Application):
            @cli.positional(int, int)
            def main(self, myint, myint2=2):
                print(repr(myint), repr(myint2))

        _, rc = MainValidator.run(["prog", "1"], exit = False)
        assert rc == 0
        assert "1 2" == capsys.readouterr()[0].strip()

        _, rc = MainValidator.run(["prog", "1", "3"], exit = False)
        assert rc == 0
        assert "1 3" ==  capsys.readouterr()[0].strip()


text:
package cn.com.grocery.test;

import java.io.FileNotFoundException;

import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;

public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {
    static {
      try {
        Log4jConfigurer.initLogging("classpath:log4j.xml");
      } catch (FileNotFoundException ex) {
        System.err.println("Cannot Initialize log4j");
      }
    }
    public JUnit4ClassRunner(Class<?> clazz) throws InitializationError {
      super(clazz);
    }
  }


text:
package com.suscipio_solutions.consecro_mud.Races;
import java.util.List;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Areas.interfaces.Area;
import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Weapon;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMath;

public class Humanoid extends StdRace
{
	@Override public String ID(){	return "Humanoid"; }
	@Override public String name(){ return "Humanoid"; }
	@Override public int shortestMale(){return 64;}
	@Override public int shortestFemale(){return 59;}
	@Override public int heightVariance(){return 12;}
	@Override public int lightestWeight(){return 90;}
	@Override public int weightVariance(){return 90;}
	@Override public long forbiddenWornBits(){return 0;}
	@Override public String racialCategory(){return "Humanoid";}

	//  							  an ey ea he ne ar ha to le fo no gi mo wa ta wi
	private static final int[] parts={0 ,2 ,2 ,1 ,1 ,2 ,2 ,1 ,2 ,2 ,1 ,0 ,1 ,1 ,0 ,0 };
	@Override public int[] bodyMask(){return parts;}

	private final int[] agingChart={0,1,3,15,35,53,70,74,78};
	@Override public int[] getAgingChart(){return agingChart;}

	protected static Vector<RawMaterial> resources=new Vector<RawMaterial>();
	@Override public int availabilityCode(){return Area.THEME_FANTASY|Area.THEME_SKILLONLYMASK;}

	@Override
	public Weapon myNaturalWeapon()
	{ return funHumanoidWeapon();	}

	@Override
	public String healthText(MOB viewer, MOB mob)
	{
		final double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints()));

		if(pct<.10)
			return "^r" + mob.name(viewer) + "^r is mortally wounded and will soon die.^N";
		else
		if(pct<.20)
			return "^r" + mob.name(viewer) + "^r is covered in blood.^N";
		else
		if(pct<.30)
			return "^r" + mob.name(viewer) + "^r is bleeding badly from lots of wounds.^N";
		else
		if(pct<.40)
			return "^y" + mob.name(viewer) + "^y has numerous bloody wounds and gashes.^N";
		else
		if(pct<.50)
			return "^y" + mob.name(viewer) + "^y has some bloody wounds and gashes.^N";
		else
		if(pct<.60)
			return "^p" + mob.name(viewer) + "^p has a few bloody wounds.^N";
		else
		if(pct<.70)
			return "^p" + mob.name(viewer) + "^p is cut and bruised.^N";
		else
		if(pct<.80)
			return "^g" + mob.name(viewer) + "^g has some minor cuts and bruises.^N";
		else
		if(pct<.90)
			return "^g" + mob.name(viewer) + "^g has a few bruises and scratches.^N";
		else
		if(pct<.99)
			return "^g" + mob.name(viewer) + "^g has a few small bruises.^N";
		else
			return "^c" + mob.name(viewer) + "^c is in perfect health.^N";
	}
	@Override
	public List<RawMaterial> myResources()
	{
		synchronized(resources)
		{
			if(resources.size()==0)
			{
				resources.addElement(makeResource
				("a "+name().toLowerCase()+" brain",RawMaterial.RESOURCE_MEAT));
				resources.addElement(makeResource
				("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_BLOOD));
				resources.addElement(makeResource
				("a pile of "+name().toLowerCase()+" bones",RawMaterial.RESOURCE_BONE));
			}
		}
		return resources;
	}
}


text:
require 'spec_helper_unit'

describe AccountTypeCommands::Update do
  let(:command) { described_class.new(params, logger: logger) }
  let(:params) do
    {
      price_plan: {
        account_type: account_type_literal,
        rate_limit: rate_limit_params
      }
    }
  end
  let(:account_type_literal) { 'FREE' }
  let(:logger) { Carto::Common::Logger.new }
  let(:account_type) { create(:account_type, account_type: account_type_literal) }
  let(:original_rate_limit) { account_type.rate_limit }

  describe '#run' do
    context 'when the associated rate limit has changed' do
      let(:new_rate_limit) { create(:rate_limits_pro) }
      let(:rate_limit_params) { new_rate_limit.api_attributes }

      before { account_type.save }

      it 'updates the rate limit' do
        command.run

        expect(account_type.reload.rate_limit).to eq(new_rate_limit)
      end

      it 'enqueues a job to sync rate limits in Redis' do
        Resque.expects(:enqueue).once.with(
          Resque::UserJobs::RateLimitsJobs::SyncRedis,
          account_type.account_type
        )

        command.run
      end
    end

    context 'when the associated rate limit has not changed' do
      let(:rate_limit_params) { original_rate_limit.api_attributes }

      before { account_type.save }

      it 'does not update the rate limit attributes' do
        command.run

        expect(account_type.reload.rate_limit).to eq(original_rate_limit)
      end

      it 'does not sync rate limit information in Redis' do
        Resque.expects(:enqueue).never

        command.run
      end

      it 'does not create a new rate limit record' do
        expect { command.run }.to change(Carto::RateLimit, :count).by(0)
      end
    end

    context 'when not receiving any rate limit data' do
      let(:params) { { price_plan: { account_type: account_type_literal } } }

      before { account_type.save }

      it 'preserves the current rate limit and raises an error' do
        Resque.expects(:enqueue).never

        expect { command.run }.to raise_error(ActiveRecord::RecordInvalid)

        expect(account_type.reload.rate_limit).to eq(original_rate_limit)
      end
    end

    context 'when the account type does not exist' do
      let(:rate_limit_params) {}

      it 'raises an error' do
        expect { command.run }.to raise_error(ActiveRecord::RecordNotFound)
      end
    end
  end
end


text:
package com.mycompany.myproj.remote1.security;

import java.security.Permission;

public class CustomSecurityManager extends SecurityManager {

  @Override
  public void checkPermission(Permission arg0, Object arg1) {
  }

  @Override
  public void checkPermission(Permission arg0) {
  }

}


text:
package org.drools.impact.analysis.graph;

public enum ReactivityType {
    POSITIVE,
    NEGATIVE,
    UNKNOWN;

    public ReactivityType negate() {
        switch (this) {
            case POSITIVE: return NEGATIVE;
            case NEGATIVE: return POSITIVE;
        }
        return UNKNOWN;
    }

    public ReactivityType combine(ReactivityType type) {
        return this == type ? this : UNKNOWN;
    }

    public static ReactivityType decode(boolean positive) {
        return positive ? POSITIVE : NEGATIVE;
    }
}


text:
    <title>The Bridge</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

		Министерство культуры
Российской Федерации
Портал Культура.рф
Проект «Образы России»

Pushkin's memorial estate (Vyazemy estate)

The Bridge

The bridge at the dam, on the Big Smolensk road, now Mozhaisk Road, was built in 1820-1824 on the initiative of the Moscow Governor-General Prince D.V.Golitsyn. It was built by the military department under the supervision of E. Evert. It is a single-span bridge made of brick, faced with white stone. In 1970s it was reconstructed in reinforced concrete, the roadbed was extended by 7 meters. Architectural forms and stone facade were restored partially. Empire-style cast-iron railing with eagles in stamps was replaced by modern fencing of metal pipes.

Культура.рф © Портал культурного наследия России


text:
import gtk
import gtk.gdk
from envxdot import EnvironmentDotWindow
from ARM import *
import NodeDialogFactory

class EnvironmentModelViewer(EnvironmentDotWindow):
  def __init__(self,environmentName,dp):
    EnvironmentDotWindow.__init__(self,environmentName,dp)
    self.dbProxy = dp
    self.environment = self.dbProxy.dimensionObject(environmentName,'environment')
    self.widget.connect('clicked', self.on_url_clicked)
    self.widget.connect('button_press_event', self.onClick)

  def onClick(self,widget,event):
    try:
      if event.button == 3:
        print self.widget.get_url(event.x,event.y).url
      return 1
    except AttributeError:
      pass

  def on_url_clicked(self, widget, url, event):
    dialog = NodeDialogFactory.build(url,self.environment.name())
    return True

  def onTypeClicked(self, widget, event):
    pass

  def onNameClicked(self, widget, event):
    pass

  def ShowModal(self, tLinks):
    self.updateModel(tLinks)
    self.connect('destroy', gtk.main_quit)
    self.set_modal(True)
    gtk.main()

  def updateModel(self,tLinks):
    self.traceModel = tLinks
    xdotcode = self.traceModel.graph()
    environmentNames = self.dbProxy.getDimensionNames('environment')
    environmentNames.sort(key=str.lower)
    self.loadFilters(environmentNames,tLinks.dimensions(),tLinks.objects())
    self.set_xdotcode(xdotcode)
    self.blockHandlers()
    self.environmentCombo.set_active(environmentNames.index(self.environment.name()))
    self.unblockHandlers()
    self.widget.zoom_to_fit()


text:
.navbar-center {
    text-align: center;
}
.navbar-nav {
  width: 100%;
  text-align: center;
}
.navbar-nav > li {
  float: none;
  display: inline-block;
}


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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.nesscomputing</groupId>
    <artifactId>ness-oss-parent</artifactId>
    <version>34</version>
  </parent>

  <scm>
    <connection>scm:git:git://github.com/NessComputing/components-ness-pg.git</connection>
    <developerConnection>scm:git:git@github.com:NessComputing/components-ness-pg.git</developerConnection>
    <url>http://github.com/NessComputing/components-ness-pg</url>
    <tag>HEAD</tag>
  </scm>

  <groupId>com.nesscomputing.components</groupId>
  <artifactId>ness-pg-embedded</artifactId>
  <version>2.6.3-SNAPSHOT</version>
  <description>Embedded PostgreSQL driver</description>

  <dependencies>
    <dependency>
      <groupId>com.nesscomputing.components</groupId>
      <artifactId>ness-config</artifactId>
      <version>2.3.0</version>
    </dependency>

    <dependency>
      <groupId>org.jdbi</groupId>
      <artifactId>jdbi</artifactId>
      <version>2.38.1</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
    </dependency>

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
    </dependency>

    <dependency>
      <groupId>commons-configuration</groupId>
      <artifactId>commons-configuration</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.code.findbugs</groupId>
      <artifactId>jsr305</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>9.1-901-1.jdbc4</version>
    </dependency>

    <dependency>
      <groupId>com.nesscomputing.migratory</groupId>
      <artifactId>migratory-core</artifactId>
      <version>3.1.1</version>
    </dependency>

    <dependency>
      <groupId>com.nesscomputing.components</groupId>
      <artifactId>ness-integration-testing</artifactId>
      <version>3.3.0</version>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>com.nesscomputing.testing</groupId>
      <artifactId>kawala-lessio</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.objenesis</groupId>
      <artifactId>objenesis</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.9.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

require_once __DIR__ . '/../../../vendor/autoload.php';

// [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_sync]
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Asset\V1\AnalyzeIamPolicyLongrunningResponse;
use Google\Cloud\Asset\V1\AssetServiceClient;
use Google\Cloud\Asset\V1\IamPolicyAnalysisOutputConfig;
use Google\Cloud\Asset\V1\IamPolicyAnalysisQuery;
use Google\Rpc\Status;

/**
 * Analyzes IAM policies asynchronously to answer which identities have what
 * accesses on which resources, and writes the analysis results to a Google
 * Cloud Storage or a BigQuery destination. For Cloud Storage destination, the
 * output format is the JSON format that represents a
 * [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. This method implements the
 * [google.longrunning.Operation][google.longrunning.Operation], which allows you to track the operation
 * status. We recommend intervals of at least 2 seconds with exponential
 * backoff retry to poll the operation result. The metadata contains the
 * metadata for the long-running operation.
 *
 * @param string $analysisQueryScope The relative name of the root asset. Only resources and IAM policies within
 *                                   the scope will be analyzed.
 *
 *                                   This can only be an organization number (such as "organizations/123"), a
 *                                   folder number (such as "folders/123"), a project ID (such as
 *                                   "projects/my-project-id"), or a project number (such as "projects/12345").
 *
 *                                   To know how to get organization id, visit [here
 *                                   ](https://cloud.google.com/resource-manager/docs/creating-managing-organization#retrieving_your_organization_id).
 *
 *                                   To know how to get folder or project id, visit [here
 *                                   ](https://cloud.google.com/resource-manager/docs/creating-managing-folders#viewing_or_listing_folders_and_projects).
 */
function analyze_iam_policy_longrunning_sample(string $analysisQueryScope): void
{
    // Create a client.
    $assetServiceClient = new AssetServiceClient();

    // Prepare any non-scalar elements to be passed along with the request.
    $analysisQuery = (new IamPolicyAnalysisQuery())
        ->setScope($analysisQueryScope);
    $outputConfig = new IamPolicyAnalysisOutputConfig();

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $assetServiceClient->analyzeIamPolicyLongrunning($analysisQuery, $outputConfig);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var AnalyzeIamPolicyLongrunningResponse $response */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $analysisQueryScope = '[SCOPE]';

    analyze_iam_policy_longrunning_sample($analysisQueryScope);
}
// [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_sync]


text:
package com.github.katjahahn.parser.sections.rsrc.version

import java.io.RandomAccessFile
import com.github.katjahahn.parser.IOUtil._
import com.github.katjahahn.parser.ScalaIOUtil.{ using, hex }
import com.github.katjahahn.parser.ByteArrayUtil
import com.github.katjahahn.parser.FileFormatException

class VersionString(
  val wLength: Int,
  val wValueLength: Int,
  val wType: Int,
  val szKey: String,
  val value: String) {

  override def toString(): String =
    szKey + ": " + { if (value.trim.isEmpty) "-" else value }
}

object VersionString {

  //TODO move to utility class
  private val byteSize = 1
  private val wordSize = 2
  private val dwordSize = 4
  private val qwordSize = 8

  private val szKeyMaxDigits = "LegalTrademarks ".length

  def apply(offset: Long, raf: RandomAccessFile): VersionString = {

    def isValidKey(key: String):Boolean = !(key.trim.isEmpty)

    val wLength = ByteArrayUtil.bytesToInt(loadBytes(offset, wordSize, raf))
    val maxOffset = offset + wLength
    val wValueLength = ByteArrayUtil.bytesToInt(loadBytes(offset + wordSize, wordSize, raf))
    val wType = ByteArrayUtil.bytesToInt(loadBytes(offset + wordSize * 2, wordSize, raf))
    val szBytes = loadBytes(offset + wordSize * 3, szKeyMaxDigits * dwordSize, raf).toList
    var prev = 0
    val szSize = szBytes.indexWhere { x => val i = prev; prev = x; i == 0 && x == 0 }
    val szKey = new String(szBytes.take(szSize).toArray, "UTF_16LE")
    if (isValidKey(szKey)) {
      val valueOffsetStart = offset + wordSize * 3 + szSize
      val valueOffset = valueOffsetStart + loadBytes(valueOffsetStart, wValueLength * wordSize, raf).indexWhere(0 !=)
      val bytesToRead = Math.min(maxOffset - valueOffset, wValueLength * wordSize).toInt
      val value = new String(loadBytes(valueOffset, bytesToRead, raf), "UTF_16LE")
      new VersionString(wLength, wValueLength, wType, szKey, value)
    } else {
      throw new FileFormatException("invalid version string szKey");
    }
  }

}


text:
import java.io.*;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws IOException {
        Client m = new Client();
        m.connect();
    }

    private void connect() throws IOException {
        //declare a scanner so we can write a message
        // localhost ip
        String ip = "0.0.0.0";
        int port = 4444;
        Socket socket = null;
        String name;
        try {
            //connect
            socket = new Socket(ip, port);
            //initialize streams
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            if (in.readUTF().equals("0")) {
                name = "player1";
            } else {
                name = "player2";
            }
            System.out.println(name);
            //start a thread which will start listening for messages
            new ReceiveMessage(in).start();
            // send the name to the server!
            out.writeUTF(name);
        } catch (IOException e) {
            e.printStackTrace();
            if (!socket.isClosed()) socket.close();
        }
    }

    class ReceiveMessage extends Thread {
        DataInputStream in;

        ReceiveMessage(DataInputStream in) {
            this.in = in;
        }

        public void run() {
            String message;
            while (true)
                try {
                    message = in.readUTF();
                    System.out.println(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}


text:
namespace imdex {

using class_ptr = const uintptr_t*;
using vtable_ptr = const uintptr_t*;

static constexpr ptrdiff_t Uncached = PTRDIFF_MAX;
static constexpr ptrdiff_t Bad = PTRDIFF_MAX - 1;

template <typename T>
vtable_ptr getVTable(const T* obj) noexcept {
    return reinterpret_cast<vtable_ptr>(*reinterpret_cast<class_ptr>(obj));
}

template <typename To, typename From>
To fast_dynamic_cast(From* from) noexcept {
    thread_local static ptrdiff_t cacheOffset = Uncached;
    thread_local static vtable_ptr cacheVtable = nullptr;

    if (!from)
        return nullptr;

    using T = std::conditional_t<std::is_const_v<From>, const char, char>;

    const auto vtable = getVTable(from);
    if (vtable == cacheVtable) {
        switch (cacheOffset) {
            case Bad:
                return nullptr;
            case Uncached:
                break;
            default:
                return reinterpret_cast<To>(reinterpret_cast<T*>(from) + cacheOffset);
        }
    }

    cacheVtable = vtable;

    To res = dynamic_cast<To>(from);
    if (!res) {
        cacheOffset = Bad;
        return nullptr;
    }

    cacheOffset = reinterpret_cast<const char*>(res) - reinterpret_cast<const char*>(from);
    return res;
}

template <typename To, typename From>
To fast_dynamic_cast(From& from) {
    using Ptr = std::add_pointer_t<std::remove_reference_t<To>>;
    using ToPtr = std::conditional_t<std::is_const_v<To>,
                                     std::add_const_t<Ptr>,
                                     Ptr>;
    auto* res = fast_dynamic_cast<ToPtr>(std::addressof(from));
    if (!res)
#if _HAS_EXCEPTIONS
        throw std::bad_cast();
#else
        std::terminate();
#endif
    return *res;
}

} // imdex namespace


text:
using System;
using System.Linq;

using ASC.Core;
using ASC.Security.Cryptography;

using ConfigurationConstants = ASC.Core.Configuration.Constants;
using UserConstants = ASC.Core.Users.Constants;

namespace ASC.Data.Backup.Tasks.Modules
{
    internal static class Helpers
    {
        private static readonly Guid[] SystemUsers = new[]
            {
                Guid.Empty,
                ConfigurationConstants.CoreSystem.ID,
                ConfigurationConstants.Guest.ID,
                UserConstants.LostUser.ID
            };

        private static readonly Guid[] SystemGroups = new[]
            {
                Guid.Empty,
                UserConstants.LostGroupInfo.ID,
                UserConstants.GroupAdmin.ID,
                UserConstants.GroupEveryone.ID,
                UserConstants.GroupVisitor.ID,
                UserConstants.GroupUser.ID,
                new Guid("{EA942538-E68E-4907-9394-035336EE0BA8}"), //community product
                new Guid("{1e044602-43b5-4d79-82f3-fd6208a11960}"), //projects product
                new Guid("{6743007C-6F95-4d20-8C88-A8601CE5E76D}"), //crm product
                new Guid("{E67BE73D-F9AE-4ce1-8FEC-1880CB518CB4}"), //documents product
                new Guid("{F4D98AFD-D336-4332-8778-3C6945C81EA0}"), //people product
                new Guid("{2A923037-8B2D-487b-9A22-5AC0918ACF3F}"), //mail product
                new Guid("{32D24CB5-7ECE-4606-9C94-19216BA42086}"), //calendar product
                new Guid("{37620AE5-C40B-45ce-855A-39DD7D76A1FA}"), //birthdays product
                new Guid("{BF88953E-3C43-4850-A3FB-B1E43AD53A3E}")  //talk product
            };

        public static bool IsEmptyOrSystemUser(string id)
        {
            Guid g;
            return string.IsNullOrEmpty(id) || Guid.TryParse(id, out g) && SystemUsers.Contains(g);
        }

        public static bool IsEmptyOrSystemGroup(string id)
        {
            Guid g;
            return string.IsNullOrEmpty(id) || Guid.TryParse(id, out g) && SystemGroups.Contains(g);
        }

        public static string CreateHash(string s)
        {
            return !string.IsNullOrEmpty(s) && s.StartsWith("S|") ? InstanceCrypto.Encrypt(Crypto.GetV(s.Substring(2), 1, false)) : s;
        }

        public static string CreateHash2(string s)
        {
            return !string.IsNullOrEmpty(s) ? "S|" + Crypto.GetV(InstanceCrypto.Decrypt(s), 1, true) : s;
        }
    }
}


text:
It's a build and deploy using [phing](https://www.phing.info/) and [envoy](https://github.com/laravel/envoy)

Also starring:
- [YUI Compressor](http://yui.github.io/yuicompressor/)
- [AWS SDK](http://aws.amazon.com/pt/sdk-for-php/)
- [OptiPNG](http://optipng.sourceforge.net/)
- [jpegtran](http://jpegclub.org/jpegtran/)

## Installation

## Configuration

## Usage

## License

This software is licensed under the [MIT license](http://opensource.org/licenses/MIT)

## Versioning

This project follows the [Semantic Versioning](http://semver.org/)

## Thanks

An amazing "Thank you, guys!" for [Jetbrains](https://www.jetbrains.com/) folks,
who kindly empower this project with a free open-source license for [PhpStorm](https://www.jetbrains.com/phpstorm/) which can bring a whole new level of joy for coding.

[![Jetbrains][2]][1]

[![PhpStorm][4]][3]

  [1]: https://www.jetbrains.com/
  [2]: https://www.jetbrains.com/company/docs/logo_jetbrains.png
  [3]: https://www.jetbrains.com/phpstorm/
  [4]: https://www.jetbrains.com/phpstorm/documentation/docs/logo_phpstorm.png


text:
<!doctype html>

        <title>Jquery file processor - by Wouter Vroege</title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" href="css/style.css" type="text/css"/>
        <link rel="stylesheet" href="css/blackboard.css" type="text/css"/>

jQuery.fileprocessor.js - by Wouter Vroege

    <input type="file" multiple id="image-uploader" accept="image/*"/>

    <input type="file" multiple id="file-uploader"/>


text:
package org.fcrepo.kernel.api;

/**
 * The Fedora Transaction Manager abstraction
 *
 * @author mohideen
 */
public interface TransactionManager {

    /**
     * Create a new fedora transaction
     *
     * @return {@link Transaction} The new fedora transaction
     */
    Transaction create();

    /**
     * Get an existing fedora transaction
     *
     * @param transactionId the id of the transaction to be returned
     * @return {@link Transaction} the fedora transaction associated with the provided id
     */
    Transaction get(String transactionId);
}


text:
/**
 * Admin lists.
 */
ul.admin-list {
  margin: 0;
  padding: 0;
}
.admin-list li {
  position: relative;
  border-top: 1px solid #bfbfbf;
  margin: 0;
  list-style-type: none;
  list-style-image: none;
  padding: 0;
}
.admin-list.compact li {
  border: none;
}
.admin-list li a {
  background: url(../../../../misc/icons/bebebe/chevron-disc-right.svg) no-repeat 1px 16px; /* LTR */
  display: block;
  padding: 14px 15px 14px 25px; /* LTR */
  min-height: 0;
}
[dir="rtl"] .admin-list li a {
  background: url(../../../../misc/icons/bebebe/chevron-disc-left.svg) no-repeat right 16px;
  padding-right: 25px;
  padding-left: 15px;
}
.admin-list.compact li a {
  background-image:  none;
  padding: 2px 0;
}
.admin-list li a:hover,
.admin-list li a:focus,
.admin-list li a:active {
  text-decoration: none;
}
.admin-list li a .label {
  font-size: 1.0769em;
}
.admin-list li a:hover .label,
.admin-list li a:focus .label,
.admin-list li a:active .label {
  text-decoration: underline;
}


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

        <title>CruiseControl.NET : Support</title>
	    <link rel="stylesheet" href="styles/site.css" type="text/css" />
        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">

                            CruiseControl.NET : Support

					    This page last changed on Nov 12, 2008 by williams.

CruiseControl.NET is not a commercial piece of software, so we cannot guarantee support. However, we do have some ways to help you with issues you may have:

If you subscribe to the CCNet-user mailing list , and post any query you may have somebody will usually come back with a response fairly quickly. You can also use the CCNet-user mailing list to provide feedback (improvement ideas, feature requests, etc.)

Check the FAQ page.

The CruiseControl.NET Community Site  is a public forum for discussing issues and features, along with providing a F.A.Q.

Please do NOT request support by adding comments to the confluence documentation.  Comments will be removed.

			    Document generated by Confluence on Jan 30, 2010 19:07


text:
package enmime

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestPlainTextPart(t *testing.T) {
	r := openPart("textplain.raw")
	p, err := ParseMIME(r)

	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.Header().Get("Content-Transfer-Encoding"), "7bit",
		"Exepcted Header to have data")
	assert.Equal(t, p.ContentType(), "text/plain", "Expected type to be set")
	assert.Contains(t, string(p.Content()), "Test of text/plain section",
		"Expected correct data in p.Content")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")
}

func TestQuotedPrintablePart(t *testing.T) {
	r := openPart("quoted-printable.raw")
	p, err := ParseMIME(r)

	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.Header().Get("Content-Transfer-Encoding"), "quoted-printable",
		"Exepcted Header to have data")
	assert.Equal(t, p.ContentType(), "text/plain", "Expected type to be set")
	assert.Equal(t, string(p.Content()), "Start=ABC=Finish",
		"Expected correct data in p.Content")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")
}

func TestMultiAlternParts(t *testing.T) {
	r := openPart("multialtern.raw")
	p, err := ParseMIME(r)

	// Examine root
	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.ContentType(), "multipart/alternative", "Expected type to be set")
	assert.Equal(t, len(p.Content()), 0, "Root should not have Content")
	assert.NotNil(t, p.FirstChild(), "Root should have a FirstChild")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")

	// Examine first child
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/plain", "First child should have been text")
	assert.Contains(t, string(p.Content()), "A text section", "First child contains wrong content")
	assert.NotNil(t, p.NextSibling(), "First child should have a sibling")

	// Examine sibling
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/html", "Second child should have been html")
	assert.Contains(t, string(p.Content()), "An HTML section", "Second child contains wrong content")
	assert.Nil(t, p.NextSibling(), "Second child should not have a sibling")
}

func TestMultiMixedParts(t *testing.T) {
	r := openPart("multimixed.raw")
	p, err := ParseMIME(r)

	// Examine root
	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.ContentType(), "multipart/mixed", "Expected type to be set")
	assert.Equal(t, len(p.Content()), 0, "Root should not have Content")
	assert.NotNil(t, p.FirstChild(), "Root should have a FirstChild")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")

	// Examine first child
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/plain", "First child should have been text")
	assert.Contains(t, string(p.Content()), "Section one", "First child contains wrong content")
	assert.NotNil(t, p.NextSibling(), "First child should have a sibling")

	// Examine sibling
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/plain", "Second child should have been html")
	assert.Contains(t, string(p.Content()), "Section two", "Second child contains wrong content")
	assert.Nil(t, p.NextSibling(), "Second child should not have a sibling")
}

func TestMultiOtherParts(t *testing.T) {
	r := openPart("multiother.raw")
	p, err := ParseMIME(r)

	// Examine root
	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.ContentType(), "multipart/x-enmime", "Expected type to be set")
	assert.Equal(t, len(p.Content()), 0, "Root should not have Content")
	assert.NotNil(t, p.FirstChild(), "Root should have a FirstChild")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")

	// Examine first child
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/plain", "First child should have been text")
	assert.Contains(t, string(p.Content()), "Section one", "First child contains wrong content")
	assert.NotNil(t, p.NextSibling(), "First child should have a sibling")

	// Examine sibling
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/plain", "Second child should have been html")
	assert.Contains(t, string(p.Content()), "Section two", "Second child contains wrong content")
	assert.Nil(t, p.NextSibling(), "Second child should not have a sibling")
}

func TestNestedAlternParts(t *testing.T) {
	r := openPart("nestedmulti.raw")
	p, err := ParseMIME(r)

	// Examine root
	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.ContentType(), "multipart/alternative", "Expected type to be set")
	assert.Equal(t, len(p.Content()), 0, "Root should not have Content")
	assert.NotNil(t, p.FirstChild(), "Root should have a FirstChild")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")

	// Examine first child
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/plain", "First child should have been text")
	assert.Contains(t, string(p.Content()), "A text section", "First child contains wrong content")
	assert.NotNil(t, p.NextSibling(), "First child should have a sibling")

	// Examine sibling
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "multipart/related", "Second child should have been another multipart")
	assert.Equal(t, len(p.Content()), 0, "Second child should not have Content")
	assert.Nil(t, p.NextSibling(), "Second child should not have a sibling")
	assert.NotNil(t, p.FirstChild(), "Second child should have a child")

	// First nested
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/html", "First nested should have been html")
	assert.Contains(t, string(p.Content()), "An HTML section", "First nested contains wrong content")
	assert.NotNil(t, p.NextSibling(), "First nested should have a sibling")

	// Second nested
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/plain", "Second nested should have been text")
	assert.Equal(t, p.Disposition(), "inline", "Second nested should be inline disposition")
	assert.Equal(t, p.FileName(), "attach.txt", "Second nested should have correct filename")
	assert.Contains(t, string(p.Content()), "An inline text attachment", "Second nested contains wrong content")
	assert.NotNil(t, p.NextSibling(), "Second nested should have a sibling")

	// Third nested
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/plain", "Third nested should have been text")
	assert.Equal(t, p.Disposition(), "inline", "Third nested should be inline disposition")
	assert.Equal(t, p.FileName(), "attach2.txt", "Third nested should have correct filename")
	assert.Contains(t, string(p.Content()), "Another inline text attachment",
		"Third nested contains wrong content")
	assert.Nil(t, p.NextSibling(), "Third nested should not have a sibling")
}

func TestMultiBase64Parts(t *testing.T) {
	r := openPart("multibase64.raw")
	p, err := ParseMIME(r)

	// Examine root
	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.ContentType(), "multipart/mixed", "Expected type to be set")
	assert.Equal(t, len(p.Content()), 0, "Root should not have Content")
	assert.NotNil(t, p.FirstChild(), "Root should have a FirstChild")
	assert.Nil(t, p.NextSibling(), "Root should never have a sibling")

	// Examine first child
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/plain", "First child should have been text")
	assert.Contains(t, string(p.Content()), "A text section", "First child contains wrong content")
	assert.NotNil(t, p.NextSibling(), "First child should have a sibling")

	// Examine sibling
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/html", "Second child should be html")
	assert.Nil(t, p.NextSibling(), "Second child should not have a sibling")
	assert.Nil(t, p.FirstChild(), "Second child should not have a child")
	assert.Contains(t, string(p.Content()), "<html>",
		"Second child should have <html> as decoded content")
}

func TestBadBoundaryTerm(t *testing.T) {
	r := openPart("badboundary.raw")
	p, err := ParseMIME(r)

	// Examine root
	if !assert.Nil(t, err, "Parsing should not have generated an error") {
		t.FailNow()
	}
	assert.NotNil(t, p, "Root node should not be nil")
	assert.Equal(t, p.ContentType(), "multipart/alternative", "Expected type to be set")

	// Examine first child
	p = p.FirstChild()
	assert.Equal(t, p.ContentType(), "text/plain", "First child should have been text")
	assert.NotNil(t, p.NextSibling(), "First child should have a sibling")

	// Examine sibling
	p = p.NextSibling()
	assert.Equal(t, p.ContentType(), "text/html", "Second child should have been html")
	assert.Contains(t, string(p.Content()), "An HTML section", "Second child contains wrong content")
	assert.Nil(t, p.NextSibling(), "Second child should not have a sibling")
}

// openPart is a test utility function to open a part as a reader
func openPart(filename string) *bufio.Reader {
	// Open test part for parsing
	raw, err := os.Open(filepath.Join("test-data", "parts", filename))
	if err != nil {
		panic(fmt.Sprintf("Failed to open test data: %v", err))
	}

	// Wrap in a buffer
	return bufio.NewReader(raw)
}


text:
Dockerfiles for building docker images used in Synapse CI tests.

Builds
------

- Travis-Ci |travisci|_
- pyup.io |pyupio|_
- Dockerhub https://hub.docker.com/r/vertexproject/synapse-docker-testimages/

.. |travisci| image:: https://travis-ci.org/vertexproject/synapse-docker-testimages.svg?branch=master
.. _travisci: https://travis-ci.org/vertexproject/synapse-docker-testimages

.. |pyupio| image:: https://pyup.io/repos/github/vertexproject/synapse-docker-testimages/shield.svg
.. _pyupio: https://pyup.io/repos/github/vertexproject/synapse-docker-testimages/


text:
/*
 * 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.
 */
package io.prestosql.type;

import com.google.common.collect.ImmutableList;
import io.prestosql.RowPagesBuilder;
import io.prestosql.Session;
import io.prestosql.metadata.MetadataManager;
import io.prestosql.operator.DriverYieldSignal;
import io.prestosql.operator.project.PageProcessor;
import io.prestosql.spi.Page;
import io.prestosql.spi.type.BigintType;
import io.prestosql.spi.type.DecimalType;
import io.prestosql.spi.type.DoubleType;
import io.prestosql.spi.type.SqlDecimal;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.gen.ExpressionCompiler;
import io.prestosql.sql.gen.PageFunctionCompiler;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.TypeProvider;
import io.prestosql.sql.relational.RowExpression;
import io.prestosql.sql.relational.SqlToRowExpressionTranslator;
import io.prestosql.sql.tree.Expression;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;
import org.testng.annotations.Test;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.google.common.collect.Iterables.getOnlyElement;
import static io.prestosql.RowPagesBuilder.rowPagesBuilder;
import static io.prestosql.SessionTestUtils.TEST_SESSION;
import static io.prestosql.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext;
import static io.prestosql.metadata.FunctionKind.SCALAR;
import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.operator.scalar.FunctionAssertions.createExpression;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.DecimalType.createDecimalType;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.testing.TestingConnectorSession.SESSION;
import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static java.lang.String.format;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;
import static java.util.stream.Collectors.toList;
import static org.openjdk.jmh.annotations.Scope.Thread;

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 3)
@Warmup(iterations = 20, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, timeUnit = TimeUnit.MILLISECONDS)
public class BenchmarkDecimalOperators
{
    private static final int PAGE_SIZE = 30000;

    private static final DecimalType SHORT_DECIMAL_TYPE = createDecimalType(10, 0);
    private static final DecimalType LONG_DECIMAL_TYPE = createDecimalType(20, 0);

    private static final SqlParser SQL_PARSER = new SqlParser();

    @State(Thread)
    public static class CastDoubleToDecimalBenchmarkState
            extends BaseState
    {
        private static final int SCALE = 2;

        @Param({"10", "35", "BIGINT"})
        private String precision = "10";

        @Setup
        public void setup()
        {
            addSymbol("d1", DOUBLE);

            String expression;
            if (precision.equals("BIGINT")) {
                setDoubleMaxValue(Long.MAX_VALUE);
                expression = "CAST(d1 AS BIGINT)";
            }
            else {
                setDoubleMaxValue(Math.pow(9, Integer.valueOf(precision) - SCALE));
                expression = format("CAST(d1 AS DECIMAL(%s, %d))", precision, SCALE);
            }
            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object castDoubleToDecimalBenchmark(CastDoubleToDecimalBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testCastDoubleToDecimalBenchmark()
    {
        CastDoubleToDecimalBenchmarkState state = new CastDoubleToDecimalBenchmarkState();
        state.setup();
        castDoubleToDecimalBenchmark(state);
    }

    @State(Thread)
    public static class CastDecimalToDoubleBenchmarkState
            extends BaseState
    {
        private static final int SCALE = 10;

        @Param({"15", "35"})
        private String precision = "15";

        @Setup
        public void setup()
        {
            addSymbol("v1", createDecimalType(Integer.valueOf(precision), SCALE));

            String expression = "CAST(v1 AS DOUBLE)";
            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object castDecimalToDoubleBenchmark(CastDecimalToDoubleBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testCastDecimalToDoubleBenchmark()
    {
        CastDecimalToDoubleBenchmarkState state = new CastDecimalToDoubleBenchmarkState();
        state.setup();
        castDecimalToDoubleBenchmark(state);
    }

    @State(Thread)
    public static class CastDecimalToVarcharBenchmarkState
            extends BaseState
    {
        private static final int SCALE = 10;

        @Param({"15", "35"})
        private String precision = "35";

        @Setup
        public void setup()
        {
            addSymbol("v1", createDecimalType(Integer.valueOf(precision), SCALE));

            String expression = "CAST(v1 AS VARCHAR)";
            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object castDecimalToVarcharBenchmark(CastDecimalToVarcharBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testCastDecimalToVarcharBenchmark()
    {
        CastDecimalToVarcharBenchmarkState state = new CastDecimalToVarcharBenchmarkState();
        state.setup();
        castDecimalToVarcharBenchmark(state);
    }

    @State(Thread)
    public static class AdditionBenchmarkState
            extends BaseState
    {
        @Param({"d1 + d2",
                "d1 + d2 + d3 + d4",
                "s1 + s2",
                "s1 + s2 + s3 + s4",
                "l1 + l2",
                "l1 + l2 + l3 + l4",
                "s2 + l3 + l1 + s4"})
        private String expression = "d1 + d2";

        @Setup
        public void setup()
        {
            addSymbol("d1", DOUBLE);
            addSymbol("d2", DOUBLE);
            addSymbol("d3", DOUBLE);
            addSymbol("d4", DOUBLE);

            addSymbol("s1", createDecimalType(10, 5));
            addSymbol("s2", createDecimalType(7, 2));
            addSymbol("s3", createDecimalType(12, 2));
            addSymbol("s4", createDecimalType(2, 1));

            addSymbol("l1", createDecimalType(35, 10));
            addSymbol("l2", createDecimalType(25, 5));
            addSymbol("l3", createDecimalType(20, 6));
            addSymbol("l4", createDecimalType(25, 8));

            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object additionBenchmark(AdditionBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testAdditionBenchmark()
    {
        AdditionBenchmarkState state = new AdditionBenchmarkState();
        state.setup();
        additionBenchmark(state);
    }

    @State(Thread)
    public static class MultiplyBenchmarkState
            extends BaseState
    {
        @Param({"d1 * d2",
                "d1 * d2 * d3 * d4",
                "i1 * i2",
                // short short -> short
                "s1 * s2",
                "s1 * s2 * s5 * s6",
                // short short -> long
                "s3 * s4",
                // long short -> long
                "l2 * s2",
                "l2 * s2 * s5 * s6",
                // short long -> long
                "s1 * l2",
                // long long -> long
                "l1 * l2"})
        private String expression = "d1 * d2";

        @Setup
        public void setup()
        {
            addSymbol("d1", DOUBLE);
            addSymbol("d2", DOUBLE);
            addSymbol("d3", DOUBLE);
            addSymbol("d4", DOUBLE);

            addSymbol("i1", BIGINT);
            addSymbol("i2", BIGINT);

            addSymbol("s1", createDecimalType(5, 2));
            addSymbol("s2", createDecimalType(3, 1));
            addSymbol("s3", createDecimalType(10, 5));
            addSymbol("s4", createDecimalType(10, 2));
            addSymbol("s5", createDecimalType(3, 2));
            addSymbol("s6", createDecimalType(2, 1));

            addSymbol("l1", createDecimalType(19, 10));
            addSymbol("l2", createDecimalType(19, 5));

            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object multiplyBenchmark(MultiplyBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testMultiplyBenchmark()
    {
        MultiplyBenchmarkState state = new MultiplyBenchmarkState();
        state.setup();
        multiplyBenchmark(state);
    }

    @State(Thread)
    public static class DivisionBenchmarkState
            extends BaseState
    {
        @Param({"d1 / d2",
                "d1 / d2 / d3 / d4",
                "i1 / i2",
                "i1 / i2 / i3 / i4",
                // short short -> short
                "s1 / s2",
                "s1 / s2 / s2 / s2",
                // short short -> long
                "s1 / s3",
                // short long -> short
                "s2 / l1",
                // long short -> long
                "l1 / s2",
                // short long -> long
                "s3 / l1",
                // long long -> long
                "l2 / l3",
                "l2 / l4 / l4 / l4",
                "l2 / s4 / s4 / s4"})
        private String expression = "d1 / d2";

        @Setup
        public void setup()
        {
            addSymbol("d1", DOUBLE);
            addSymbol("d2", DOUBLE);
            addSymbol("d3", DOUBLE);
            addSymbol("d4", DOUBLE);

            addSymbol("i1", BIGINT);
            addSymbol("i2", BIGINT);
            addSymbol("i3", BIGINT);
            addSymbol("i4", BIGINT);

            addSymbol("s1", createDecimalType(8, 3));
            addSymbol("s2", createDecimalType(6, 2));
            addSymbol("s3", createDecimalType(17, 7));
            addSymbol("s4", createDecimalType(3, 2));

            addSymbol("l1", createDecimalType(19, 3));
            addSymbol("l2", createDecimalType(20, 3));
            addSymbol("l3", createDecimalType(21, 10));
            addSymbol("l4", createDecimalType(19, 4));

            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object divisionBenchmark(DivisionBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testDivisionBenchmark()
    {
        DivisionBenchmarkState state = new DivisionBenchmarkState();
        state.setup();
        divisionBenchmark(state);
    }

    @State(Thread)
    public static class ModuloBenchmarkState
            extends BaseState
    {
        @Param({"d1 % d2",
                "d1 % d2 % d3 % d4",
                "i1 % i2",
                "i1 % i2 % i3 % i4",
                // short short -> short
                "s1 % s2",
                "s1 % s2 % s2 % s2",
                // short long -> short
                "s2 % l2",
                // long short -> long
                "l3 % s3",
                // short long -> long
                "s4 % l3",
                // long long -> long
                "l2 % l3",
                "l2 % l3 % l4 % l1"})
        private String expression = "d1 % d2";

        @Setup
        public void setup()
        {
            addSymbol("d1", DOUBLE);
            addSymbol("d2", DOUBLE);
            addSymbol("d3", DOUBLE);
            addSymbol("d4", DOUBLE);

            addSymbol("i1", BIGINT);
            addSymbol("i2", BIGINT);
            addSymbol("i3", BIGINT);
            addSymbol("i4", BIGINT);

            addSymbol("s1", createDecimalType(8, 3));
            addSymbol("s2", createDecimalType(6, 2));
            addSymbol("s3", createDecimalType(9, 0));
            addSymbol("s4", createDecimalType(12, 2));

            addSymbol("l1", createDecimalType(19, 3));
            addSymbol("l2", createDecimalType(20, 3));
            addSymbol("l3", createDecimalType(21, 10));
            addSymbol("l4", createDecimalType(19, 4));

            generateRandomInputPage();
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object moduloBenchmark(ModuloBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testModuloBenchmark()
    {
        ModuloBenchmarkState state = new ModuloBenchmarkState();
        state.setup();
        moduloBenchmark(state);
    }

    @State(Thread)
    public static class InequalityBenchmarkState
            extends BaseState
    {
        @Param({"d1 < d2",
                "d1 < d2 AND d1 < d3 AND d1 < d4 AND d2 < d3 AND d2 < d4 AND d3 < d4",
                "s1 < s2",
                "s1 < s2 AND s1 < s3 AND s1 < s4 AND s2 < s3 AND s2 < s4 AND s3 < s4",
                "l1 < l2",
                "l1 < l2 AND l1 < l3 AND l1 < l4 AND l2 < l3 AND l2 < l4 AND l3 < l4"})
        private String expression = "d1 < d2";

        @Setup
        public void setup()
        {
            addSymbol("d1", DOUBLE);
            addSymbol("d2", DOUBLE);
            addSymbol("d3", DOUBLE);
            addSymbol("d4", DOUBLE);

            addSymbol("s1", SHORT_DECIMAL_TYPE);
            addSymbol("s2", SHORT_DECIMAL_TYPE);
            addSymbol("s3", SHORT_DECIMAL_TYPE);
            addSymbol("s4", SHORT_DECIMAL_TYPE);

            addSymbol("l1", LONG_DECIMAL_TYPE);
            addSymbol("l2", LONG_DECIMAL_TYPE);
            addSymbol("l3", LONG_DECIMAL_TYPE);
            addSymbol("l4", LONG_DECIMAL_TYPE);

            generateInputPage(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object inequalityBenchmark(InequalityBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testInequalityBenchmark()
    {
        InequalityBenchmarkState state = new InequalityBenchmarkState();
        state.setup();
        inequalityBenchmark(state);
    }

    @State(Thread)
    public static class DecimalToShortDecimalCastBenchmarkState
            extends BaseState
    {
        @Param({"cast(l_38_30 as decimal(8, 0))",
                "cast(l_26_18 as decimal(8, 0))",
                "cast(l_20_12 as decimal(8, 0))",
                "cast(l_20_8 as decimal(8, 0))",
                "cast(s_17_9 as decimal(8, 0))"})
        private String expression = "cast(l_38_30 as decimal(8, 0))";

        @Setup
        public void setup()
        {
            addSymbol("l_38_30", createDecimalType(38, 30));
            addSymbol("l_26_18", createDecimalType(26, 18));
            addSymbol("l_20_12", createDecimalType(20, 12));
            addSymbol("l_20_8", createDecimalType(20, 8));
            addSymbol("s_17_9", createDecimalType(17, 9));

            generateInputPage(10000, 10000, 10000, 10000, 10000);
            generateProcessor(expression);
        }
    }

    @Benchmark
    public Object decimalToShortDecimalCastBenchmark(DecimalToShortDecimalCastBenchmarkState state)
    {
        return execute(state);
    }

    @Test
    public void testDecimalToShortDecimalCastBenchmark()
    {
        DecimalToShortDecimalCastBenchmarkState state = new DecimalToShortDecimalCastBenchmarkState();
        state.setup();
        decimalToShortDecimalCastBenchmark(state);
    }

    private Object execute(BaseState state)
    {
        return ImmutableList.copyOf(
                state.getProcessor().process(
                        SESSION,
                        new DriverYieldSignal(),
                        newSimpleAggregatedMemoryContext().newLocalMemoryContext(PageProcessor.class.getSimpleName()),
                        state.getInputPage()));
    }

    private static class BaseState
    {
        private final MetadataManager metadata = createTestMetadataManager();
        private final TypeAnalyzer typeAnalyzer = new TypeAnalyzer(new SqlParser(), metadata);
        private final Session session = testSessionBuilder().build();
        private final Random random = new Random();

        protected final Map<String, Symbol> symbols = new HashMap<>();
        protected final Map<Symbol, Type> symbolTypes = new HashMap<>();
        private final Map<Symbol, Integer> sourceLayout = new HashMap<>();
        protected final List<Type> types = new LinkedList<>();

        protected Page inputPage;
        private PageProcessor processor;
        private double doubleMaxValue = 2L << 31;

        public Page getInputPage()
        {
            return inputPage;
        }

        public PageProcessor getProcessor()
        {
            return processor;
        }

        protected void addSymbol(String name, Type type)
        {
            Symbol symbol = new Symbol(name);
            symbols.put(name, symbol);
            symbolTypes.put(symbol, type);
            sourceLayout.put(symbol, types.size());
            types.add(type);
        }

        protected void generateRandomInputPage()
        {
            RowPagesBuilder buildPagesBuilder = rowPagesBuilder(types);

            for (int i = 0; i < PAGE_SIZE; i++) {
                Object[] values = types.stream()
                        .map(this::generateRandomValue)
                        .collect(toList()).toArray();

                buildPagesBuilder.row(values);
            }

            inputPage = getOnlyElement(buildPagesBuilder.build());
        }

        protected void generateInputPage(int... initialValues)
        {
            RowPagesBuilder buildPagesBuilder = rowPagesBuilder(types);
            buildPagesBuilder.addSequencePage(PAGE_SIZE, initialValues);
            inputPage = getOnlyElement(buildPagesBuilder.build());
        }

        protected void generateProcessor(String expression)
        {
            processor = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0)).compilePageProcessor(Optional.empty(), ImmutableList.of(rowExpression(expression))).get();
        }

        protected void setDoubleMaxValue(double doubleMaxValue)
        {
            this.doubleMaxValue = doubleMaxValue;
        }

        private RowExpression rowExpression(String value)
        {
            Expression expression = createExpression(value, metadata, TypeProvider.copyOf(symbolTypes));

            return SqlToRowExpressionTranslator.translate(
                    expression,
                    SCALAR,
                    typeAnalyzer.getTypes(TEST_SESSION, TypeProvider.copyOf(symbolTypes), expression),
                    sourceLayout,
                    metadata.getFunctionRegistry(),
                    metadata.getTypeManager(),
                    TEST_SESSION,
                    true);
        }

        private Object generateRandomValue(Type type)
        {
            if (type instanceof DoubleType) {
                return random.nextDouble() * (2L * doubleMaxValue) - doubleMaxValue;
            }
            if (type instanceof DecimalType) {
                return randomDecimal((DecimalType) type);
            }
            if (type instanceof BigintType) {
                int randomInt = random.nextInt();
                return randomInt == 0 ? 1 : randomInt;
            }
            throw new UnsupportedOperationException(type.toString());
        }

        private SqlDecimal randomDecimal(DecimalType type)
        {
            int maxBits = (int) (Math.log(Math.pow(10, type.getPrecision())) / Math.log(2));
            BigInteger bigInteger = new BigInteger(maxBits, random);

            if (bigInteger.equals(ZERO)) {
                bigInteger = ONE;
            }

            if (random.nextBoolean()) {
                bigInteger = bigInteger.negate();
            }

            return new SqlDecimal(bigInteger, type.getPrecision(), type.getScale());
        }
    }

    public static void main(String[] args)
            throws RunnerException
    {
        Options options = new OptionsBuilder()
                .verbosity(VerboseMode.NORMAL)
                .include(".*" + BenchmarkDecimalOperators.class.getSimpleName() + ".*")
                .build();

        new Runner(options).run();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="706fdf65-89ac-4856-8c56-576bcc0bf6c6" name="Default" comment="">
      <change beforePath="$PROJECT_DIR$/.idea/modules.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/modules.xml" afterDir="false" />
      <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
    </list>
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager">
    <option name="groupingKeys">
      <option value="directory" />
    </option>
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="tsp-facepile.php" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/tsp-facepile.php">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="427">
              <caret line="65" column="7" lean-forward="true" selection-start-line="59" selection-end-line="65" selection-end-column="7" />
              <folding>
                <element signature="e#10#655#0#PHP" expanded="true" />
                <element signature="e#2717#2924#1#PHP" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="FindInProjectRecents">
    <findStrings>
      <find>shortcode_settings.tpl</find>
      <find>The Software People</find>
      <find>www.thesoftwarepeople.com</find>
      <find>http://lab.thesoftwarepeople.com/tracker</find>
      <find>thesoftwarepeople</find>
      <find>TSP Easy Dev</find>
      <find>(TSP)</find>
      <find>TSP</find>
      <find>@(param|return) none</find>
      <find>@(return|param) none</find>
      <find>easy-dev-form-fields.tpl.</find>
      <find>EASY_DEV_FORM_FIELDS</find>
    </findStrings>
    <replaceStrings>
      <replace>Let A Pro Do IT!</replace>
      <replace>www.letaprodoit.com</replace>
      <replace>https://lab.letaprodoit.com/public</replace>
      <replace>letaprodoit</replace>
      <replace>LAPDI Easy Dev</replace>
      <replace>(LAPDI)</replace>
      <replace>LAPDI</replace>
      <replace>@$1 void</replace>
    </replaceStrings>
    <dirStrings>
      <dir>$PROJECT_DIR$</dir>
    </dirStrings>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/README.txt" />
        <option value="$PROJECT_DIR$/tsp-facepile.php" />
        <option value="$PROJECT_DIR$/TSP_Easy_Dev.config.php" />
        <option value="$PROJECT_DIR$/assets/templates/tsp-facepile_child-page-instructions.tpl" />
        <option value="$PROJECT_DIR$/TSP_Easy_Dev.extend.php" />
      </list>
    </option>
  </component>
  <component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
    <sorting>DEFINITION_ORDER</sorting>
  </component>
  <component name="NodePackageJsonFileManager">
    <packageJsonPaths />
  </component>
  <component name="PhpServers">
    <servers />
  </component>
  <component name="PhpWorkspaceProjectConfiguration">
    <include_path>
      <path value="$USER_HOME$/Sites/_testsites/wordpress_latest" />
    </include_path>
  </component>
  <component name="ProjectFrameBounds" extendedState="6">
    <option name="y" value="23" />
    <option name="width" value="1600" />
    <option name="height" value="938" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
  <component name="ProjectView">
    <navigator proportions="" version="1">
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <expand>
            <path>
              <item name="Plugins: Facepile" type="b2602c69:ProjectViewProjectNode" />
              <item name="trunk" type="462c0819:PsiDirectoryNode" />
            </path>
            <path>
              <item name="Plugins: Facepile" type="b2602c69:ProjectViewProjectNode" />
              <item name="trunk" type="462c0819:PsiDirectoryNode" />
              <item name="assets" type="462c0819:PsiDirectoryNode" />
            </path>
          </expand>
          <select />
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="WebServerToolWindowFactoryState" value="true" />
    <property name="WebServerToolWindowPanel.toolwindow.highlight.mappings" value="true" />
    <property name="WebServerToolWindowPanel.toolwindow.highlight.symlinks" value="true" />
    <property name="WebServerToolWindowPanel.toolwindow.show.date" value="false" />
    <property name="WebServerToolWindowPanel.toolwindow.show.permissions" value="false" />
    <property name="WebServerToolWindowPanel.toolwindow.show.size" value="false" />
    <property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
    <property name="nodejs_npm_path_reset_for_default_project" value="true" />
    <property name="settings.editor.selected.configurable" value="editor.preferences.import" />
  </component>
  <component name="RecentsManager">
    <key name="MoveFile.RECENT_KEYS">
      <recent name="$PROJECT_DIR$/assets" />
    </key>
  </component>
  <component name="RunDashboard">
    <option name="ruleStates">
      <list>
        <RuleState>
          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
          <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
      </list>
    </option>
  </component>
  <component name="SvnConfiguration">
    <configuration />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="706fdf65-89ac-4856-8c56-576bcc0bf6c6" name="Default" comment="" />
      <created>1540117296060</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1540117296060</updated>
      <workItem from="1540117297272" duration="2656000" />
      <workItem from="1540120328515" duration="1342000" />
      <workItem from="1540124326382" duration="76000" />
      <workItem from="1540126092186" duration="9000" />
    </task>
    <task id="LOCAL-00001" summary="Initial commit">
      <created>1540124375930</created>
      <option name="number" value="00001" />
      <option name="presentableId" value="LOCAL-00001" />
      <option name="project" value="LOCAL" />
      <updated>1540124375930</updated>
    </task>
    <option name="localTasksCounter" value="2" />
    <servers />
  </component>
  <component name="TimeTrackingManager">
    <option name="totallyTimeSpent" value="4083000" />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="23" width="1600" height="938" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info anchor="bottom" id="TODO" order="6" />
      <window_info anchor="bottom" id="Event Log" order="7" side_tool="true" />
      <window_info anchor="bottom" id="Database Changes" order="7" show_stripe_button="false" />
      <window_info anchor="bottom" id="Version Control" order="7" visible="true" weight="0.32936978" />
      <window_info anchor="bottom" id="Run" order="2" />
      <window_info anchor="bottom" id="Terminal" order="7" />
      <window_info anchor="right" id="Remote Host" order="3" weight="0.32991013" />
      <window_info active="true" content_ui="combo" id="Project" order="0" visible="true" weight="0.25930682" />
      <window_info anchor="bottom" id="Docker" order="7" show_stripe_button="false" />
      <window_info anchor="right" id="Database" order="3" />
      <window_info id="Structure" order="1" side_tool="true" weight="0.25" />
      <window_info id="Favorites" order="2" side_tool="true" />
      <window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
      <window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
      <window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
      <window_info anchor="right" id="Commander" order="0" weight="0.4" />
      <window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
      <window_info anchor="bottom" id="Messages" order="7" />
      <window_info anchor="bottom" id="Message" order="0" />
      <window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
      <window_info anchor="bottom" id="File Transfer" order="7" visible="true" weight="0.32936978" />
      <window_info anchor="bottom" id="Find" order="1" />
    </layout>
  </component>
  <component name="TypeScriptGeneratedFilesManager">
    <option name="version" value="1" />
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <MESSAGE value="Initial commit" />
    <option name="LAST_COMMIT_MESSAGE" value="Initial commit" />
  </component>
  <component name="WordPressConfiguration" enabled="true">
    <wordpressPath>$USER_HOME$/Sites/_testsites/wordpress_latest</wordpressPath>
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/assets/templates/tsp-facepile_child-page-instructions.tpl">
      <provider selected="true" editor-type-id="text-editor">
        <state>
          <caret column="68" selection-start-column="68" selection-end-column="68" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/TSP_Easy_Dev.extend.php">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="1725">
          <caret line="130" column="15" selection-start-line="130" selection-start-column="15" selection-end-line="130" selection-end-column="15" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/tsp-facepile.php">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="45">
          <caret line="3" column="93" selection-start-line="3" selection-start-column="93" selection-end-line="3" selection-end-column="93" />
          <folding>
            <element signature="e#10#655#0#PHP" expanded="true" />
            <element signature="e#2717#2924#1#PHP" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/tsp-facepile.css">
      <provider selected="true" editor-type-id="text-editor" />
    </entry>
    <entry file="file://$PROJECT_DIR$/README.txt">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="786">
          <caret line="59" column="2" selection-start-line="59" selection-start-column="2" selection-end-line="59" selection-end-column="2" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/README.md">
      <provider selected="true" editor-type-id="split-provider[text-editor;markdown-preview-editor]">
        <state split_layout="SPLIT">
          <first_editor />
          <second_editor />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/assets/templates/tsp-facepile_widget.tpl">
      <provider selected="true" editor-type-id="text-editor" />
    </entry>
    <entry file="file://$PROJECT_DIR$/assets/templates/tsp-facepile_child-page-instructions.tpl">
      <provider selected="true" editor-type-id="text-editor">
        <state>
          <caret column="68" selection-start-column="68" selection-end-column="68" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/templates/default_form.tpl" />
    <entry file="file://$PROJECT_DIR$/TSP_Easy_Dev.config.php">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="-833">
          <caret line="24" column="77" lean-forward="true" selection-start-line="24" selection-start-column="77" selection-end-line="24" selection-end-column="77" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/TSP_Easy_Dev.extend.php">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="397">
          <caret line="153" column="11" lean-forward="true" selection-start-line="153" selection-start-column="11" selection-end-line="153" selection-end-column="11" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/tsp-facepile.php">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="427">
          <caret line="65" column="7" lean-forward="true" selection-start-line="59" selection-end-line="65" selection-end-column="7" />
          <folding>
            <element signature="e#10#655#0#PHP" expanded="true" />
            <element signature="e#2717#2924#1#PHP" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
// +build !providerless

package interfaceclient

import (
	"context"

	"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
	"k8s.io/legacy-cloud-providers/azure/retry"
)

const (
	// APIVersion is the API version for network.
	APIVersion = "2019-06-01"

	// ComputeAPIVersion is the API version for compute. It is required to get VMSS network interface.
	ComputeAPIVersion = "2017-03-30"
)

// Interface is the client interface for NetworkInterface.
// Don't forget to run the following command to generate the mock client:
// mockgen -source=$GOPATH/src/k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/interface.go -package=mockinterfaceclient Interface > $GOPATH/src/k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go
type Interface interface {
	// Get gets a network.Interface.
	Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (result network.Interface, rerr *retry.Error)

	// GetVirtualMachineScaleSetNetworkInterface gets a network.Interface of VMSS VM.
	GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result network.Interface, rerr *retry.Error)

	// CreateOrUpdate creates or updates a network.Interface.
	CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error
}


text:
extern NSString *const ARBCollectionViewCascadeLayoutHeaderFooter;

extern NSUInteger const ARBCollectionViewCascadeLayoutHeaderItemNumber;
extern NSUInteger const ARBCollectionViewCascadeLayoutFooterItemNumber;

@protocol ARBCollectionViewCascadeLayoutDelegate;

@interface ARBCollectionViewCascadeLayout : UICollectionViewLayout

@property (nonatomic, weak) id<ARBCollectionViewCascadeLayoutDelegate> delegate;
@property (nonatomic, assign) CGFloat itemPadding;
@property (nonatomic, assign) NSInteger numColumnsLandscape;
@property (nonatomic, assign) NSInteger numColumnsPortrait;

@end

@protocol ARBCollectionViewCascadeLayoutDelegate <NSObject>

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(ARBCollectionViewCascadeLayout *)collectionViewLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath;

@optional
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(ARBCollectionViewCascadeLayout *)collectionViewLayout heightForHeaderInSection:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(ARBCollectionViewCascadeLayout *)collectionViewLayout heightForFooterInSection:(NSInteger)section;

@end


text:
using SimplInject;

namespace DummyProject
{
    [SimplInject(SimplInjectScope.Singleton)]
    public class SingletonConcreteClass : IAmAnotherInterface
    {
    }
}


text:
module.exports = {
  caption: 'Template',
  view: resource('./view/index.js')
};


text:
define(function (require) {
    var apiServices = require('apiServices'),
        ko = require('knockout');

    return function () {
        var self = this;

        selectedItem = ko.observable();
        self.name = ko.observable();

        add = function () {

        }

        selectItem = function (item) {

        }

        removeItem = function (item) {
            if (selectedScpProduct() === undefined) return;

            apiServices.removeScpVariable(selectedScpProduct().id, selectedScpProduct().operation, item.name());
        }
    }
});