text:
package com.github.gavlyukovskiy.sample;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
public class SampleController {

    private final DataSource dataSource;

    public SampleController(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @RequestMapping("/commit")
    public List<Map<String, String>> select() {
        List<Map<String, String>> results = new ArrayList<>();
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS")) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            while (resultSet.next()) {
                Map<String, String> result = new HashMap<>();
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    result.put(columnName, resultSet.getString(columnName));
                }
                results.add(result);
            }
            connection.commit();
        }
        catch (Exception e) {
            throw new IllegalStateException(e);
        }
        return results;
    }

    @RequestMapping("/rollback")
    public List<Map<String, String>> rollback() {
        List<Map<String, String>> results = new ArrayList<>();
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS")) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            while (resultSet.next()) {
                Map<String, String> result = new HashMap<>();
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    result.put(columnName, resultSet.getString(columnName));
                }
                results.add(result);
            }
            connection.rollback();
        }
        catch (Exception e) {
            throw new IllegalStateException(e);
        }
        return results;
    }

    @RequestMapping("/query-error")
    public void error() {
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement()) {
            statement.execute("SELECT UNDEFINED()");
        }
        catch (Exception ignored) {
        }
    }
}


text:
template <class T> class scoped_array {
 private:
  T* data_;
};

class TestClass {
 private:
  scoped_ptr<int[]> test_field_;
};

scoped_ptr<int[]> TestFunction(scoped_ptr<int[]> x, scoped_ptr<int[]>) {
  scoped_ptr<scoped_array<int>(scoped_array<int> test, scoped_array<int>)[]> y;
  scoped_ptr<int[]>(*function_pointer)(scoped_ptr<int[]> test,
                                       scoped_ptr<int[]>);
  scoped_ptr<int[]> test_variable;
}

redpajama_set_name: RedPajamaGithub


text:
function epvalue = readfrompipeout(obj, epaddr, bsize, psize)

%READFROMPIPEOUT  Read data from a PipeOut.
%  epVALUE=READFROMPIPEOUT(OBJ,epADDR,SIZE) reads SIZE number of elements
%  from a PipeOut endpoint.  The elements of evVALUE are unsigned bytes
%  (8 bits : 0..255) stored as fints (floating point integers).
%  epADDR the endpoint address of the PipeOut endpoint.
%
%  epVALUE=READFROMPIPEOUT(OBJ,epADDR,SIZE,PSIZE) subdivides the read
%  transfer into smaller packets of size PSIZE.
%  By default, PSIZE = SIZE.
%
%  The valid endpoint address ranges are:
%
%    0x00-0x1F : WireIn
%    0x20-0x3F : WireOut
%    0x40-0x5F : TriggerIn
%    0x60-0x7F : TriggerOut
%    0x80-0x9F : PipeIn
%  * 0xA0-0xBF : PipeOut
%
%  Copyright (c) 2005 Opal Kelly Incorporated
%  $Rev: 971 $ $Date: 2011-05-27 08:59:56 -0500 (Fri, 27 May 2011) $

if ~exist('psize', 'var') | isempty(psize), psize = bsize; end

% Allocate a buffer for ReadFromPipeOut.
psize = min(psize,bsize);
persistent buf pv;
buf(psize,1) = uint8(0);
epvalue(bsize,1) = uint8(0);
pv = libpointer('uint8Ptr', buf);

if (psize == bsize),
	buf(bsize,1) = uint8(0);
	calllib('okFrontPanel', 'okFrontPanel_ReadFromPipeOut', obj.ptr, epaddr, bsize, pv);
	epvalue = get(pv, 'value');
else
	kk = (1:psize)';
	for k = 1:fix(bsize/psize),
		[x,pv] = calllib('okFrontPanel', 'okFrontPanel_ReadFromPipeOut', obj.ptr, epaddr, psize, pv);
		epvalue(kk) = buf;
		kk = kk+psize;
	end
	psize_last = mod(bsize,psize);
	kk = kk(1:psize_last);
	[x,pv] = calllib('okFrontPanel', 'okFrontPanel_ReadFromPipeOut', obj.ptr, epaddr, size_last, pv);
	epvalue(kk) = buf(1:psize_last);
end
clear buf;


text:
class ServerUsageHourly
  include Sidekiq::Worker
  sidekiq_options unique: :until_executed

  def perform
    Account.all.find_each do |account|
      user    = account.user
      payg    = user.servers.where(payment_type: 'payg')
      next if payg.empty?

      begin
        ServerUsageHourlyTask.new(user, payg).process
      rescue Exception => e
        ErrorLogging.new.track_exception(e, extra: { current_user: user, source: 'ServerUsageHourly' })
      end
    end
  end
end


text:
package sun.awt.motif;

import java.awt.im.spi.InputMethod;
import sun.awt.X11InputMethodDescriptor;

/**
 * Provides sufficient information about an input method
 * to enable selection and loading of that input method.
 * The input method itself is only loaded when it is actually used.
 *
 * @since JDK1.3
 */

class MInputMethodDescriptor extends X11InputMethodDescriptor {

    /**
     * @see java.awt.im.spi.InputMethodDescriptor#createInputMethod
     */
    public InputMethod createInputMethod() throws Exception {
        return new MInputMethod();
    }
}


text:
package ru.yandex.qatools.allure.experimental;

import org.junit.Before;
import org.junit.Test;

import java.net.URL;
import java.net.URLClassLoader;

import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 04.06.14
 */
public class ListenersNotifierSPITest {

    private ListenersNotifier notifier;

    @Before
    public void setUp() throws Exception {
        URL url = getClass().getClassLoader().getResource("testdata/");
        URLClassLoader classLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());

        notifier = new ListenersNotifier(classLoader);
    }

    @Test
    public void listenersCountTest() throws Exception {
        assertThat(notifier.getListeners(), hasSize(1));
    }
}


text:
var mealSchema = mongoose.Schema({
  _id: { $oid: String },
  name: String,
  foodList: [Schema.Types.ObjectID]
});

mealSchema.methods.addFoodItem(ObjectID) {
  this.foodList.push(ObjectID);
  this.save();
}

module.exports = mongoose.model('meal', mealSchema);


text:
@interface BackBaseViewController ()

@end

@implementation BackBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.navigationItem.leftBarButtonItem = nil;
    self.view.backgroundColor = [UIColor whiteColor];
}

@end


text:
package io.quantumdb.core.backends.integration.types;

import static io.quantumdb.core.schema.definitions.Column.Hint.AUTO_INCREMENT;
import static io.quantumdb.core.schema.definitions.Column.Hint.NOT_NULL;
import static io.quantumdb.core.schema.definitions.Column.Hint.PRIMARY_KEY;
import static io.quantumdb.core.schema.definitions.PostgresTypes.bigint;
import static io.quantumdb.core.schema.definitions.PostgresTypes.bigserial;
import static io.quantumdb.core.schema.definitions.PostgresTypes.bool;
import static io.quantumdb.core.schema.definitions.PostgresTypes.bytea;
import static io.quantumdb.core.schema.definitions.PostgresTypes.chars;
import static io.quantumdb.core.schema.definitions.PostgresTypes.date;
import static io.quantumdb.core.schema.definitions.PostgresTypes.doubles;
import static io.quantumdb.core.schema.definitions.PostgresTypes.floats;
import static io.quantumdb.core.schema.definitions.PostgresTypes.integer;
import static io.quantumdb.core.schema.definitions.PostgresTypes.numeric;
import static io.quantumdb.core.schema.definitions.PostgresTypes.oid;
import static io.quantumdb.core.schema.definitions.PostgresTypes.serial;
import static io.quantumdb.core.schema.definitions.PostgresTypes.smallint;
import static io.quantumdb.core.schema.definitions.PostgresTypes.smallserial;
import static io.quantumdb.core.schema.definitions.PostgresTypes.text;
import static io.quantumdb.core.schema.definitions.PostgresTypes.timestamp;
import static io.quantumdb.core.schema.definitions.PostgresTypes.uuid;
import static io.quantumdb.core.schema.definitions.PostgresTypes.varchar;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.quantumdb.core.backends.Backend;
import io.quantumdb.core.backends.Config;
import io.quantumdb.core.backends.DatabaseMigrator.MigrationException;
import io.quantumdb.core.backends.PostgresqlDatabase;
import io.quantumdb.core.migration.Migrator;
import io.quantumdb.core.planner.TableCreator;
import io.quantumdb.core.schema.definitions.Catalog;
import io.quantumdb.core.schema.definitions.Column;
import io.quantumdb.core.schema.definitions.Table;
import io.quantumdb.core.utils.BatchInserter;
import io.quantumdb.core.versioning.Changelog;
import io.quantumdb.core.versioning.RefLog;
import io.quantumdb.core.versioning.RefLog.ColumnRef;
import io.quantumdb.core.versioning.State;
import lombok.Getter;

@Getter
public class PostgresqlTypesScenario extends PostgresqlDatabase {

	public static final String NUMERIC_SMALL_ID = "table_bb4afbec1e";
	public static final String NUMERIC_ID = "table_968ee03f3c";
	public static final String NUMERIC_BIG_ID = "table_582b679a79";
	public static final String CHARACTER_ID = "table_0137af8ae7";
	public static final String BINARY_ID = "table_ad471f5e8b";
	public static final String DATE_ID = "table_588068de2b";
	public static final String BOOLEAN_ID = "table_81462aed99";
	public static final String UUID_ID = "table_5e6d789720";
	public static final String OID_ID = "table_84ec85b580";

	private Backend backend;
	private Catalog catalog;
	private Migrator migrator;
	private Changelog changelog;
	private RefLog refLog;
	private State state;

	@Override
	public void before() throws SQLException, MigrationException, ClassNotFoundException {
		super.before();

		TableCreator tableCreator = new TableCreator(getConfig());

		Table numeric_small = new Table(NUMERIC_SMALL_ID)
				// Serial will automatically create a sequence (AUTO_INCREMENT) and NOT_NULL constraint
				.addColumn(new Column("id", smallserial(), PRIMARY_KEY))
				.addColumn(new Column("smallint", smallint(), NOT_NULL))
				.addColumn(new Column("smallnumeric_integer", numeric(5, 0), NOT_NULL))
				.addColumn(new Column("smallnumeric_decimal", numeric(5, 2), NOT_NULL))
				.addColumn(new Column("smallnumeric", numeric(5), NOT_NULL));

		Table numeric = new Table(NUMERIC_ID)
				.addColumn(new Column("id", serial(), PRIMARY_KEY))
				.addColumn(new Column("int", integer(), NOT_NULL))
				.addColumn(new Column("float", floats(), NOT_NULL))
				.addColumn(new Column("double", doubles(), NOT_NULL))
				.addColumn(new Column("numeric_integer", numeric(10, 0), NOT_NULL))
				.addColumn(new Column("numeric_decimal", numeric(10, 5), NOT_NULL))
				.addColumn(new Column("numeric", numeric(10), NOT_NULL));

		Table numeric_big = new Table(NUMERIC_BIG_ID)
				.addColumn(new Column("id", bigserial(), PRIMARY_KEY))
				.addColumn(new Column("bigint", bigint(), NOT_NULL))
				.addColumn(new Column("bignumeric_integer", numeric(1000, 0), NOT_NULL))
				.addColumn(new Column("bignumeric_decimal", numeric(1000, 100), NOT_NULL))
				.addColumn(new Column("bignumeric", numeric(), NOT_NULL));

		Table character = new Table(CHARACTER_ID)
				.addColumn(new Column("id", bigint(), PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL))
				.addColumn(new Column("varchar_unlimited", varchar(), NOT_NULL))
				.addColumn(new Column("varchar_10", varchar(10), NOT_NULL))
				.addColumn(new Column("varchar_100", varchar(100), NOT_NULL))
				.addColumn(new Column("char", chars(1), NOT_NULL))
				.addColumn(new Column("char_100", chars(100), NOT_NULL))
				.addColumn(new Column("text", text(), NOT_NULL));

		Table binary = new Table(BINARY_ID)
				.addColumn(new Column("id", bigint(), PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL))
				.addColumn(new Column("bytea", bytea(), NOT_NULL));

		Table date = new Table(DATE_ID)
				.addColumn(new Column("id", bigint(), PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL))
				.addColumn(new Column("date", date(), NOT_NULL))
				.addColumn(new Column("timestamp_0", timestamp(false, 0), NOT_NULL))
				.addColumn(new Column("timestamp_6", timestamp(false, 6), NOT_NULL))
				.addColumn(new Column("timestamptz_0", timestamp(true, 0), NOT_NULL))
				.addColumn(new Column("timestamptz_6", timestamp(false, 6), NOT_NULL));

		Table bool = new Table(BOOLEAN_ID)
				.addColumn(new Column("id", bigint(), PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL))
				.addColumn(new Column("bool", bool(), NOT_NULL));

		Table uuid = new Table(UUID_ID)
				.addColumn(new Column("id", bigint(), PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL))
				.addColumn(new Column("uuid", uuid(), NOT_NULL));

		Table oid = new Table(OID_ID)
				.addColumn(new Column("id", bigint(), PRIMARY_KEY, AUTO_INCREMENT, NOT_NULL))
				.addColumn(new Column("oid", oid(), NOT_NULL));

		Set<Table> tables = Sets.newHashSet(numeric_small, numeric, numeric_big, character, binary, date, bool, uuid, oid);

		catalog = new Catalog(getCatalogName());
		tables.forEach(catalog::addTable);

		tableCreator.create(getConnection(), tables);

		Config config = new Config();
		config.setUrl(getJdbcUrl() + "/" + getCatalogName());
		config.setUser(getJdbcUser());
		config.setPassword(getJdbcPass());
		config.setCatalog(getCatalogName());
		config.setDriver(getJdbcDriver());

		backend = config.getBackend();

		state = backend.loadState();
		changelog = state.getChangelog();

		// Register pre-existing tables in root version.
		catalog = state.getCatalog();
		refLog = state.getRefLog();

		Map<String, String> refIds = Maps.newHashMap();
		refIds.put("numeric_small", NUMERIC_SMALL_ID);
		refIds.put("numeric", NUMERIC_ID);
		refIds.put("numeric_big", NUMERIC_BIG_ID);
		refIds.put("character", CHARACTER_ID);
		refIds.put("binary", BINARY_ID);
		refIds.put("date", DATE_ID);
		refIds.put("bool", BOOLEAN_ID);
		refIds.put("uuid", UUID_ID);
		refIds.put("oid", OID_ID);

		refIds.forEach((tableName, refId) -> {
			Table table = catalog.getTable(refId);
			List<ColumnRef> columns = table.getColumns().stream()
					.map(column -> new ColumnRef(column.getName()))
					.collect(Collectors.toList());

			refLog.addTable(tableName, refId, changelog.getRoot(), columns);
		});

		backend.persistState(state, null);
		migrator = new Migrator(backend);
	}

	public void insertTestData() throws SQLException {
		getConnection().setAutoCommit(false);
		getConnection().createStatement().execute("SET CONSTRAINTS ALL DEFERRED");

		BatchInserter.insertInto(getConnection(), NUMERIC_SMALL_ID, "smallint", "smallnumeric_integer", "smallnumeric_decimal", "smallnumeric")
				.values(1, new BigDecimal("1"), new BigDecimal("123.45"), new BigDecimal("12345"))
				.values(2, new BigDecimal("2"), new BigDecimal("123.456"), new BigDecimal("1234.5"))
				.insert();

		BatchInserter.insertInto(getConnection(), NUMERIC_ID, "int", "float", "double", "numeric_integer", "numeric_decimal", "numeric")
				.values(1, 1.23456f, 1.234567890123456d, new BigDecimal("1000000000"), new BigDecimal("1234.567894"), new BigDecimal("123.9"))
				.values(2, 123f, 123d, new BigDecimal("123"), new BigDecimal("123"), new BigDecimal("123"))
				.insert();

		BatchInserter.insertInto(getConnection(), NUMERIC_BIG_ID, "bigint", "bignumeric_integer", "bignumeric_decimal", "bignumeric")
				.values(9223372036854775807L, new BigDecimal("1234567890123456789012345678901234567890"),
						new BigDecimal("1234567890123456789012345678901234567890.1234567890123456789012345678901234567890"),
						new BigDecimal("1234567890123456789012345678901234567890.1234567890123456789012345678901234567890"))
				.insert();

		BatchInserter.insertInto(getConnection(), CHARACTER_ID, "varchar_unlimited", "varchar_10", "varchar_100", "char", "char_100", "text")
				.values("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut " +
								"labore et dolore magna aliqua. Sit amet cursus sit amet dictum sit amet. Cras fermentum odio " +
								"eu feugiat pretium nibh ipsum. Viverra nam libero justo laoreet sit amet cursus sit amet. Nun" +
								"c scelerisque viverra mauris in aliquam sem fringilla. Varius duis at consectetur lorem. Cons" +
								"ectetur adipiscing elit pellentesque habitant morbi tristique senectus et. Urna neque viverra" +
								" justo nec ultrices dui sapien eget. Vel facilisis volutpat est velit egestas dui. Facilisis " +
								"magna etiam tempor orci eu lobortis. Cursus mattis molestie a iaculis at erat pellentesque. I" +
								"n arcu cursus euismod quis viverra. Massa enim nec dui nunc mattis enim ut tellus elementum.",
						"max 10 cha", "max 100 characters", "t", "space padded to 100", "Lorem Ipsum")
				.values("Lorem Ipsum", "string_ten", "String, max 100 characters",
						"f", "space padded to 100", "Lorem Ipsum")
				.insert();

		BatchInserter.insertInto(getConnection(), BINARY_ID, "bytea")
				.values("pdf_file".getBytes())
				.insert();

		Timestamp timestamp = new Timestamp(1600000000123L);
		timestamp.setNanos(123456789);
		BatchInserter.insertInto(getConnection(), DATE_ID, "date", "timestamp_0", "timestamp_6", "timestamptz_0", "timestamptz_6")
				.values(new Date(1600000000123L), timestamp,
						timestamp, timestamp,
						timestamp)
				.insert();

		BatchInserter.insertInto(getConnection(), BOOLEAN_ID, "bool")
				.values(true)
				.values(false)
				.insert();

		BatchInserter.insertInto(getConnection(), UUID_ID, "uuid")
				.values(UUID.fromString("4cc75deb-cd5f-49e8-b94c-c692103e370c"))
				.insert();

		BatchInserter.insertInto(getConnection(), OID_ID, "oid")
				.values(1234)
				.insert();

		getConnection().setAutoCommit(true);
	}

}


text:
import { TStringArrayEncoding } from '../../options/TStringArrayEncoding';

import { IStringArrayScopeCallsWrappersData } from '../../../interfaces/node-transformers/string-array-transformers/IStringArrayScopeCallsWrappersData';

export type TStringArrayScopeCallsWrappersDataByEncoding = Partial<{
    [key in TStringArrayEncoding]: IStringArrayScopeCallsWrappersData;
}>;


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { layoutsRoutes } from './layouts.routes';

import { LayoutsComponent } from './layouts.component';
import { LayoutsOverviewComponent } from './overview/overview.component';
import { NavViewComponent } from './nav-view/nav-view.component';
import { NavListComponent } from './nav-list/nav-list.component';
import { CardOverComponent } from './card-over/card-over.component';
import { ManageListComponent } from './manage-list/manage-list.component';

import { MdButtonModule, MdListModule, MdIconModule, MdCardModule, MdToolbarModule, MdCoreModule } from '@angular/material';

import { CovalentLayoutModule, CovalentExpansionPanelModule, CovalentStepsModule, CovalentMediaModule } from '../../../platform/core';
import { CovalentHighlightModule } from '../../../platform/highlight';

import { DocumentationToolsModule } from '../../documentation-tools';

import { ToolbarModule } from '../../components/toolbar/toolbar.module';

@NgModule({
  declarations: [
    LayoutsComponent,
    LayoutsOverviewComponent,
    NavViewComponent,
    NavListComponent,
    CardOverComponent,
    ManageListComponent,
  ],
  imports: [
    /** Angular Modules */
    CommonModule,
    /** Material Modules */
    MdCoreModule,
    MdButtonModule,
    MdListModule,
    MdIconModule,
    MdCardModule,
    MdToolbarModule,
    /** Covalent Modules */
    CovalentLayoutModule,
    CovalentExpansionPanelModule,
    CovalentStepsModule,
    CovalentMediaModule,
    CovalentHighlightModule,
    DocumentationToolsModule,
    layoutsRoutes,
    ToolbarModule,
  ],
})
export class LayoutsModule {}


text:
#ifndef SOLVER_H_DEFINED
#define SOLVER_H_DEFINED

void run_tests();
int evaluate(int a, char op, int b, int *answer);
int satisfy_paren();
int solve_equation(char* str, int *answer);

#endif // SOLVER_H_DEFINED


text:
param([parameter(Mandatory = $true)]
      [string]$OutputPath,
      [parameter(Mandatory = $true)]
      [string]$TemplatePath)

# Make sure we stop on exceptions
$ErrorActionPreference = "Stop"
$FileKind = "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}"

function Get-SolutionDir {
    if($dte.Solution -and $dte.Solution.IsOpen) {
        return Split-Path $dte.Solution.FullName
    }
    else {
        throw "Solution not avaliable"
    }
}

function Ensure-Solution {
    if(!$dte.Solution -or !$dte.Solution.IsOpen) {
        New-Solution
    }
}

function Close-Solution
{
    if ($dte.Solution -and $dte.Solution.IsOpen)
    {
        $dte.Solution.Close()
    }
}

function Open-Solution
{
    param
    (
        [string]
        [parameter(Mandatory = $true)]
        $Path
    )

    $dte.Solution.Open($Path)
}

function Ensure-Dir {
    param(
        [string]
        [parameter(Mandatory = $true)]
        $Path
    )
    if(!(Test-Path $Path)) {
        mkdir $Path | Out-Null
    }
}

function New-Solution {
    param(
        [string]$solutionName
    )

    if ($solutionName) {
        $name = $solutionName
    }
    else {
        $id = New-Guid
        $name = "Solution_$id"
    }

    $solutionDir = Join-Path $OutputPath $name
    $solutionPath = Join-Path $solutionDir $name

    Ensure-Dir $solutionDir

    $dte.Solution.Create($solutionDir, $name) | Out-Null
    $dte.Solution.SaveAs($solutionPath) | Out-Null
}

function New-Project {
    param(
         [parameter(Mandatory = $true)]
         [string]$TemplateName,
         [string]$ProjectName,
         [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $id = New-Guid
    if (!$ProjectName) {
        $ProjectName = $TemplateName + "_$id"
    }

    # Make sure there is a solution
    Ensure-Solution

    # Get the zip file where the project template is located
    $projectTemplatePath = Join-Path $TemplatePath "$TemplateName.zip"

    # Find the vs template file
    $projectTemplateFilePath = @(Get-ChildItem $projectTemplatePath -Filter *.vstemplate)[0].FullName

    # Get the output path of the project
    if($SolutionFolder) {
        $destPath = Join-Path (Get-SolutionDir) (Join-Path $SolutionFolder.Name $projectName)
    }
    else {
        $destPath = Join-Path (Get-SolutionDir) $projectName
    }

    # Store the active window so that we can set focus to it after the command completes
    # When we add a project to VS it usually tries to set focus to some page
    $window = $dte.ActiveWindow

    if($SolutionFolder) {
        $SolutionFolder.Object.AddFromTemplate($projectTemplateFilePath, $destPath, $projectName) | Out-Null
    }
    else {
        # Add the project to the solution from th template file specified
        $dte.Solution.AddFromTemplate($projectTemplateFilePath, $destPath, $projectName, $false) | Out-Null
    }

    # Close all active documents
    $dte.Documents | %{ try { $_.Close() } catch { } }

    # Change the configuration of the project to x86
    $dte.Solution.SolutionBuild.SolutionConfigurations | % { if ($_.PlatformName -eq 'x86') { $_.Activate() } } | Out-Null

    # Set the focus back on the shell
    $window.SetFocus()

    # Return the project
    if ($SolutionFolder) {
        $solutionFolderPath = Get-SolutionFolderPathRecursive $SolutionFolder
        $project = Get-Project "$($solutionFolderPath)$projectName" -ErrorAction SilentlyContinue
    }
    else {
        $project = Get-Project $projectName -ErrorAction SilentlyContinue
    }

    if(!$project) {
        $project = Get-Project "$destPath\"
    }

    $project
}

function Get-SolutionFolderPathRecursive([parameter(mandatory=$true)]$solutionFolder) {
    $path = ''
    while ($solutionFolder -ne $null) {
        $path = "$($solutionFolder.Name)\$path"
        $solutionFolder = $solutionFolder.ParentProjectItem.ContainingProject
    }
    return $path
}

function New-SolutionFolder {
    param(
        [string]$Name,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $id = New-Guid
    if(!$Name) {
        $Name = "SolutionFolder_$id"
    }

    if(!$SolutionFolder) {
        # Make sure there is a solution
        Ensure-Solution

        $solution = Get-Interface $dte.Solution ([EnvDTE80.Solution2])
    }
    elseif($SolutionFolder.Object.AddSolutionFolder) {
        $solution = $SolutionFolder.Object
    }

    $solution.AddSolutionFolder($Name)
}

function New-ClassLibrary {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project ClassLibrary $ProjectName
}

function New-ConsoleApplication {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project ConsoleApplication $ProjectName
}

function New-WebApplication {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project EmptyWebApplicationProject40 $ProjectName
}

function New-MvcApplication {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project EmptyMvcWebApplicationProjectTemplatev4.0.csaspx $ProjectName
}

function New-WebSite {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project EmptyWeb $ProjectName
}

function New-FSharpLibrary {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project FSharpLibrary $ProjectName
}

function New-FSharpConsoleApplication {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project FSharpConsoleApplication $ProjectName
}

function New-WPFApplication {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project WPFApplication $ProjectName
}

function New-SilverlightClassLibrary {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project SilverlightClassLibrary $ProjectName
}

function New-SilverlightApplication {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    $SolutionFolder | New-Project SilverlightProject $ProjectName
}

function New-WindowsPhoneClassLibrary {
    param(
        [string]$ProjectName,
        [parameter(ValueFromPipeline = $true)]$SolutionFolder
    )

    try {
        $SolutionFolder | New-Project WindowsPhoneClassLibrary $ProjectName
    }
    catch {
        # If we're unable to create the project that means we probably don't have some SDK installed
        # Signal to the runner that we want to skip this test
        throw "SKIP: $($_)"
    }
}

function New-TextFile {
    $dte.ItemOperations.NewFile('General\Text File')
    $dte.ActiveDocument.Object("TextDocument")
}

function Build-Project {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [string]$Configuration
    )
    if(!$Configuration) {
        # If no configuration was specified then use
        $Configuration = $dte.Solution.SolutionBuild.ActiveConfiguration.Name
    }

    # Build the project and wait for it to complete
    $dte.Solution.SolutionBuild.BuildProject($Configuration, $Project.UniqueName, $true)
}

function Get-AssemblyReference {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true)]
        [string]$Reference
    )
    try {
        return $Project.Object.References.Item($Reference)
    }
    catch {
    }
    return $null
}

function Get-PropertyValue {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true)]
        [string]$PropertyName
    )
    try {
        $property = $Project.Properties.Item($PropertyName)
        if($property) {
            return $property.Value
        }
    }
    catch {
    }
    return $null
}

function Get-MsBuildPropertyValue {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true)]
        [string]$PropertyName
    )

    $msBuildProject = Get-MsBuildProject $project
    return $msBuildProject.GetPropertyValue($PropertyName)

    return $null
}

function Get-MsBuildProject
{
    param(
        [parameter(Mandatory = $true)]
        $project
    )

    $projectCollection = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection

    $loadedProjects = $projectCollection.GetLoadedProjects($project.FullName)
    if ($loadedProjects.Count -gt 0) {
        foreach ($p in $loadedProjects) {
            return $p
        }
    }

    $projectCollection.LoadProject($project.FullName)
}

function Get-ProjectDir {
    param(
        [parameter(Mandatory = $true)]
        $Project
    )
    Get-PropertyValue $Project FullPath
}

function Get-OutputPath {
    param(
        [parameter(Mandatory = $true)]
        $Project
    )

    $outputPath = $Project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value
    Join-Path (Get-ProjectDir) $outputPath
}

function Get-Errors {
    $dte.ExecuteCommand("View.ErrorList", " ")

    # Make sure there are no errors in the error list
    $errorList = $dte.Windows | ?{ $_.Caption -eq 'Error List' } | Select -First 1

    if(!$errorList) {
        throw "Unable to locate the error list"
    }

    # Get the list of errors from the error list
    $errorList.Object.ErrorItems
}

function Get-ProjectItemPath {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Path
    )
    $item = Get-ProjectItem $Project $Path

    if($item) {
        return $item.Properties.Item("FullPath").Value
    }
}

function Remove-ProjectItem {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Path
    )

    $item = Get-ProjectItem $Project $Path
    $path = Get-ProjectItemPath $Project $Path
    $item.Remove()
    Remove-Item $path
}

function Get-ProjectItem {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Path
    )
    Process {
        $pathParts = $Path.Split('\')
        $projectItems = $Project.ProjectItems

        foreach($part in $pathParts) {
            if(!$part -or $part -eq '') {
                continue
            }

            try {
                $subItem = $projectItems.Item($part)
            }
            catch {
                return $null
            }

            $projectItems = $subItem.ProjectItems
        }

        if($subItem.Kind -eq $FileKind) {
            return $subItem
        }

        # Force array
       return  ,$projectItems
    }
}

function Add-File {
    param(
        [parameter(Mandatory = $true)]
        $Project,
        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$FilePath
    )

    $Project.ProjectItems.AddFromFileCopy($FilePath) | out-null
}

function Add-ProjectReference {
    param (
        [parameter(Mandatory = $true)]
        $ProjectFrom,
        [parameter(Mandatory = $true)]
        $ProjectTo
    )

    if($ProjectFrom.Object.References.AddProject) {
        $ProjectFrom.Object.References.AddProject($ProjectTo) | Out-Null
    }
    elseif($ProjectFrom.Object.References.AddFromProject) {
        $ProjectFrom.Object.References.AddFromProject($ProjectTo) | Out-Null
    }
}

function Remove-Project {
    param (
        [parameter(Mandatory = $true)]
        $Project
    )

    $dte.Solution.Remove($Project)
}

function Get-SolutionPath {
    $dte.Solution.Properties.Item("Path").Value
}

function Close-Solution {
    if ($dte.Solution) {
        $dte.Solution.Close()
    }
}

function Enable-PackageRestore {
    if (!$dte.Solution -or !$dte.Solution.IsOpen)
    {
        throw "No solution is available."
    }

    $componentService = Get-VSComponentModel
    $packageRestoreManager = $componentService.GetService([NuGet.VisualStudio.IPackageRestoreManager])
    $packageRestoreManager.EnableCurrentSolutionForRestore($false)
}


text:
# Greg's Slider

Slider component for react. 🔥🔥🔥

Special thanks to [@abacon](https://github.com/abacon) & [@derekr](https://github.com/derekr) for answering all my questions!

## Demo

[✨DEMO ✨](http://gregdmathews.com/greg-slider/)

## Installing

```bash
$ npm install greg-slider
```

If you aren't using browserify, a
[compiled version of greg-slider](dist/slider.js) is available.

## Details
A `<GregSlider />` element is an improved upon version of an HTML5 range type input. You are able to smoothly drag the handle no matter how large or small the number of your steps are, and you are able to style it more effectively. You can also add tick marks to your steps if you wish. `<GregSlider />` is also compatible with IE9.

## API
Props:

**`value`**: Determines the start position of your slider. Must be a number between `min` and `max`. Default `value` is `min`.

**`min`**: The smallest number you want in the range. Default `min` is 0.

**`max`**: The largest number you want in the range. Default `max` is 10.

**`ticks`**: A boolean to show tick marks on the slider. Default true.

**`onChange`**: A function that will be fired when the position of the handle changes. Default none

**`snapToTick`**: A boolean to have the handle snap to a tick mark. Default true

## Example usage

```js
/** @jsx React.DOM */
var React = require('react'),
	GregSlider = require('greg-slider');

var App = React.createClass({

  handleChange: function () {
		console.log('Change');
	},

	render: function () {
		return (
			<GregSlider
				value={0}
				min={0}
				max={10}
				ticks={true}
				snapToTick={true}
				grid={[25, 25]}
				zIndex={100}
				onChange={this.handleChange} />
		);
	}
});

React.renderComponent(<App/>, document.body);
```

value: React.PropTypes.number,
min: React.PropTypes.number,
max: React.PropTypes.number,
ticks: React.PropTypes.bool,
onChange: React.PropTypes.func,
snapToTick: React.PropTypes.bool

## Contributing

- Fork the project
- Make changes.
- Double check changes work by adding it to the examples: `$ ./build-examples`
- Update README with appropriate docs.
- Commit and PR

## License

MIT


text:
package com.google.javascript.rhino.jstype;

import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN;

import com.google.common.base.Joiner;
<<<<<<>>>>>> 5c522db6e745151faa1d8dc310d145e94f78ac77
import com.google.common.collect.Lists;
import com.google.javascript.rhino.ErrorReporter;

import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * The {@code UnionType} implements a common JavaScript idiom in which the
 * code is specifically designed to work with multiple input types.  Because
 * JavaScript always knows the run-time type of an object value, this is safer
 * than a C union.

 *
 * For instance, values of the union type {@code (String,boolean)} can be of
 * type {@code String} or of type {@code boolean}. The commutativity of the
 * statement is captured by making {@code (String,boolean)} and
 * {@code (boolean,String)} equal.

 *
 * The implementation of this class prevents the creation of nested
 * unions.

 */
public class UnionType extends JSType {
  private static final long serialVersionUID = 1L;

  Collection<JSType> alternates;
  private int hashcode;

  /**
   * Creates a union type.
   *
   * @param alternates the alternates of the union
   */
  UnionType(JSTypeRegistry registry, Collection<JSType> alternates) {
    super(registry);
    this.alternates = alternates;
    this.hashcode = this.alternates.hashCode();
  }

  /**
   * Gets the alternate types of this union type.
   * @return The alternate types of this union type. The returned set is
   *     immutable.
   */
  public Collection<JSType> getAlternates() {
    for (JSType t : alternates) {
      if (t.isUnionType()) {
        rebuildAlternates();
        break;
      }
    }
    return alternates;
  }

  /**
   * Use UnionTypeBuilder to rebuild the list of alternates and hashcode
   * of the current UnionType.
   */
  private void rebuildAlternates() {
    UnionTypeBuilder builder = new UnionTypeBuilder(registry);
    for (JSType alternate : alternates) {
      builder.addAlternate(alternate);
    }
    alternates = builder.getAlternates();
    hashcode = alternates.hashCode();
  }

  /**
   * This predicate is used to test whether a given type can appear in a
   * numeric context, such as an operand of a multiply operator.
   *
   * @return true if the type can appear in a numeric context.
   */
  @Override
  public boolean matchesNumberContext() {
    // TODO(user): Reverse this logic to make it correct instead of generous.
    for (JSType t : alternates) {
      if (t.matchesNumberContext()) {
        return true;
      }
    }
    return false;
  }

  /**
   * This predicate is used to test whether a given type can appear in a
   * {@code String} context, such as an operand of a string concat ({@code +})
   * operator.

   *
   * All types have at least the potential for converting to {@code String}.
   * When we add externally defined types, such as a browser OM, we may choose
   * to add types that do not automatically convert to {@code String}.
   *
   * @return {@code true} if not {@link VoidType}
   */
  @Override
  public boolean matchesStringContext() {
    // TODO(user): Reverse this logic to make it correct instead of generous.
    for (JSType t : alternates) {
      if (t.matchesStringContext()) {
        return true;
      }
    }
    return false;
  }

  /**
   * This predicate is used to test whether a given type can appear in an
   * {@code Object} context, such as the expression in a {@code with}
   * statement.

   *
   * Most types we will encounter, except notably {@code null}, have at least
   * the potential for converting to {@code Object}.  Host defined objects can
   * get peculiar.

   *
   * VOID type is included here because while it is not part of the JavaScript
   * language, functions returning 'void' type can't be used as operands of
   * any operator or statement.

   *
   * @return {@code true} if the type is not {@link NullType} or
   *         {@link VoidType}
   */
  @Override
  public boolean matchesObjectContext() {
    // TODO(user): Reverse this logic to make it correct instead of generous.
    for (JSType t : alternates) {
      if (t.matchesObjectContext()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public JSType findPropertyType(String propertyName) {
    JSType propertyType = null;

    for (JSType alternate : getAlternates()) {
      // Filter out the null/undefined type.
      if (alternate.isNullType() || alternate.isVoidType()) {
        continue;
      }

      JSType altPropertyType = alternate.findPropertyType(propertyName);
      if (altPropertyType == null) {
        continue;
      }

      if (propertyType == null) {
        propertyType = altPropertyType;
      } else {
        propertyType = propertyType.getLeastSupertype(altPropertyType);
      }
    }

    return propertyType;
  }

  @Override
  public boolean canBeCalled() {
    for (JSType t : alternates) {
      if (!t.canBeCalled()) {
        return false;
      }
    }
    return true;
  }

  @Override
  public JSType autobox() {
    UnionTypeBuilder restricted = new UnionTypeBuilder(registry);
    for (JSType t : alternates) {
      restricted.addAlternate(t.autobox());
    }
    return restricted.build();
  }

  @Override
  public JSType restrictByNotNullOrUndefined() {
    UnionTypeBuilder restricted = new UnionTypeBuilder(registry);
    for (JSType t : alternates) {
      restricted.addAlternate(t.restrictByNotNullOrUndefined());
    }
    return restricted.build();
  }

  @Override
  public TernaryValue testForEquality(JSType that) {
    TernaryValue result = null;
    for (JSType t : alternates) {
      TernaryValue test = t.testForEquality(that);
      if (result == null) {
        result = test;
      } else if (!result.equals(test)) {
        return UNKNOWN;
      }
    }
    return result;
  }

  /**
   * This predicate determines whether objects of this type can have the
   * {@code null} value, and therefore can appear in contexts where
   * {@code null} is expected.
   *
   * @return {@code true} for everything but {@code Number} and
   *         {@code Boolean} types.
   */
  @Override
  public boolean isNullable() {
    for (JSType t : alternates) {
      if (t.isNullable()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean isUnknownType() {
    for (JSType t : alternates) {
      if (t.isUnknownType()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean isStruct() {
    for (JSType typ : getAlternates()) {
      if (typ.isStruct()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean isDict() {
    for (JSType typ : getAlternates()) {
      if (typ.isDict()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public JSType getLeastSupertype(JSType that) {
    if (!that.isUnknownType() && !that.isUnionType()) {
      for (JSType alternate : alternates) {
        if (!alternate.isUnknownType() && that.isSubtype(alternate)) {
          return this;
        }
      }
    }

    return getLeastSupertype(this, that);
  }

  JSType meet(JSType that) {
    UnionTypeBuilder builder = new UnionTypeBuilder(registry);
    for (JSType alternate : alternates) {
      if (alternate.isSubtype(that)) {
        builder.addAlternate(alternate);
      }
    }

    if (that.isUnionType()) {
      for (JSType otherAlternate : that.toMaybeUnionType().alternates) {
        if (otherAlternate.isSubtype(this)) {
          builder.addAlternate(otherAlternate);
        }
      }
    } else if (that.isSubtype(this)) {
      builder.addAlternate(that);
    }
    JSType result = builder.build();
    if (!result.isNoType()) {
      return result;
    } else if (this.isObject() && (that.isObject() && !that.isNoType())) {
      return getNativeType(JSTypeNative.NO_OBJECT_TYPE);
    } else {
      return getNativeType(JSTypeNative.NO_TYPE);
    }
  }

  /**
   * Two union types are equal if, after flattening nested union types,
   * they have the same number of alternates and all alternates are equal.
   */
  boolean checkUnionEquivalenceHelper(
      UnionType that, EquivalenceMethod eqMethod) {
    Collection<JSType> thatAlternates = that.getAlternates();
    if (eqMethod == EquivalenceMethod.IDENTITY
        && getAlternates().size() != thatAlternates.size()) {
      return false;
    }
    for (JSType alternate : thatAlternates) {
      if (!hasAlternate(alternate, eqMethod)) {
        return false;
      }
    }
    return true;
  }

  private boolean hasAlternate(JSType type, EquivalenceMethod eqMethod) {
    for (JSType alternate : getAlternates()) {
      if (alternate.checkEquivalenceHelper(type, eqMethod)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean hasProperty(String pname) {
    for (JSType alternate : alternates) {
      if (alternate.hasProperty(pname)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public int hashCode() {
    return this.hashcode;
  }

  @Override
  public UnionType toMaybeUnionType() {
    return this;
  }

  @Override
  public boolean isObject() {
    for (JSType alternate : alternates) {
      if (!alternate.isObject()) {
        return false;
      }
    }
    return true;
  }

  /**
   * A {@link UnionType} contains a given type (alternate) iff the member
   * vector contains it.
   *
   * @param type The alternate which might be in this union.
   *
   * @return {@code true} if the alternate is in the union
   */
  public boolean contains(JSType type) {
    for (JSType alt : alternates) {
      if (alt.isEquivalentTo(type)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Returns a more restricted union type than {@code this} one, in which all
   * subtypes of {@code type} have been removed.

   *
   * Examples:
   *

   *
{@code (number,string)} restricted by {@code number} is
   *     {@code string}

   *
{@code (null, EvalError, URIError)} restricted by
   *     {@code Error} is {@code null}

   *

   *
   * @param type the supertype of the types to remove from this union type
   */
  public JSType getRestrictedUnion(JSType type) {
    UnionTypeBuilder restricted = new UnionTypeBuilder(registry);
    for (JSType t : alternates) {
      // Keep all unknown/unresolved types.
      if (t.isUnknownType() || t.isNoResolvedType() || !t.isSubtype(type)) {
        restricted.addAlternate(t);
      }
    }
    return restricted.build();
  }

  @Override String toStringHelper(boolean forAnnotations) {
    StringBuilder result = new StringBuilder();
    boolean firstAlternate = true;

    result.append("(");
    SortedSet<JSType> sorted = new TreeSet<JSType>(ALPHA);
    sorted.addAll(alternates);
    for (JSType t : sorted) {
      if (!firstAlternate) {
        result.append("|");
      }
      result.append(t.toStringHelper(forAnnotations));
      firstAlternate = false;
    }
    result.append(")");
    return result.toString();
  }

  @Override
  public boolean isSubtype(JSType that) {
    // unknown
    if (that.isUnknownType()) {
      return true;
    }
    // all type
    if (that.isAllType()) {
      return true;
    }
    for (JSType element : alternates) {
      if (!element.isSubtype(that)) {
        return false;
      }
    }
    return true;
  }

  @Override
  public JSType getRestrictedTypeGivenToBooleanOutcome(boolean outcome) {
    // gather elements after restriction
    UnionTypeBuilder restricted = new UnionTypeBuilder(registry);
    for (JSType element : alternates) {
      restricted.addAlternate(
          element.getRestrictedTypeGivenToBooleanOutcome(outcome));
    }
    return restricted.build();
  }

  @Override
  public BooleanLiteralSet getPossibleToBooleanOutcomes() {
    BooleanLiteralSet literals = BooleanLiteralSet.EMPTY;
    for (JSType element : alternates) {
      literals = literals.union(element.getPossibleToBooleanOutcomes());
      if (literals == BooleanLiteralSet.BOTH) {
        break;
      }
    }
    return literals;
  }

  @Override
  public TypePair getTypesUnderEquality(JSType that) {
    UnionTypeBuilder thisRestricted = new UnionTypeBuilder(registry);
    UnionTypeBuilder thatRestricted = new UnionTypeBuilder(registry);
    for (JSType element : alternates) {
      TypePair p = element.getTypesUnderEquality(that);
      if (p.typeA != null) {
        thisRestricted.addAlternate(p.typeA);
      }
      if (p.typeB != null) {
        thatRestricted.addAlternate(p.typeB);
      }
    }
    return new TypePair(
        thisRestricted.build(),
        thatRestricted.build());
  }

  @Override
  public TypePair getTypesUnderInequality(JSType that) {
    UnionTypeBuilder thisRestricted = new UnionTypeBuilder(registry);
    UnionTypeBuilder thatRestricted = new UnionTypeBuilder(registry);
    for (JSType element : alternates) {
      TypePair p = element.getTypesUnderInequality(that);
      if (p.typeA != null) {
        thisRestricted.addAlternate(p.typeA);
      }
      if (p.typeB != null) {
        thatRestricted.addAlternate(p.typeB);
      }
    }
    return new TypePair(
        thisRestricted.build(),
        thatRestricted.build());
  }

  @Override
  public TypePair getTypesUnderShallowInequality(JSType that) {
    UnionTypeBuilder thisRestricted = new UnionTypeBuilder(registry);
    UnionTypeBuilder thatRestricted = new UnionTypeBuilder(registry);
    for (JSType element : alternates) {
      TypePair p = element.getTypesUnderShallowInequality(that);
      if (p.typeA != null) {
        thisRestricted.addAlternate(p.typeA);
      }
      if (p.typeB != null) {
        thatRestricted.addAlternate(p.typeB);
      }
    }
    return new TypePair(
        thisRestricted.build(),
        thatRestricted.build());
  }

  @Override
  public <T> T visit(Visitor<T> visitor) {
    return visitor.caseUnionType(this);
  }

  @Override <T> T visit(RelationshipVisitor<T> visitor, JSType that) {
    return visitor.caseUnionType(this, that);
  }

  @Override
  JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) {
    setResolvedTypeInternal(this); // for circularly defined types.

<<<<<<< HEAD
    boolean changed = false;
    ImmutableList.Builder<JSType> resolvedTypes = ImmutableList.builder();
    for (JSType alternate : alternates) {
      JSType newAlternate = alternate.resolve(t, scope);
      changed |= (alternate != newAlternate);
      resolvedTypes.add(alternate);
    }
    if (changed) {
      Collection<JSType> newAlternates = resolvedTypes.build();
      Preconditions.checkState(
          newAlternates.hashCode() == this.hashcode);
      alternates = newAlternates;
    }
=======
    // Just resolve the alternates, but do not update as that breaks some error
    // reporting cases.
    for (JSType alternate : alternates) {
      alternate.resolve(t, scope);
    }
    // Ensure the union is in a normalized state.
    rebuildAlternates();
>>>>>>> 5c522db6e745151faa1d8dc310d145e94f78ac77
    return this;
  }

  @Override
  public String toDebugHashCodeString() {
    List<String> hashCodes = Lists.newArrayList();
    for (JSType a : alternates) {
      hashCodes.add(a.toDebugHashCodeString());
    }
    return "{(" + Joiner.on(",").join(hashCodes) + ")}";
  }

  @Override
  public boolean setValidator(Predicate<JSType> validator) {
    for (JSType a : alternates) {
      a.setValidator(validator);
    }
    return true;
  }

  @Override
  public JSType collapseUnion() {
    JSType currentValue = null;
    ObjectType currentCommonSuper = null;
    for (JSType a : alternates) {
      if (a.isUnknownType()) {
        return getNativeType(JSTypeNative.UNKNOWN_TYPE);
      }

      ObjectType obj = a.toObjectType();
      if (obj == null) {
        if (currentValue == null && currentCommonSuper == null) {
          // If obj is not an object, then it must be a value.
          currentValue = a;
        } else {
          // Multiple values and objects will always collapse to the ALL_TYPE.
          return getNativeType(JSTypeNative.ALL_TYPE);
        }
      } else if (currentValue != null) {
        // Values and objects will always collapse to the ALL_TYPE.
        return getNativeType(JSTypeNative.ALL_TYPE);
      } else if (currentCommonSuper == null) {
        currentCommonSuper = obj;
      } else {
        currentCommonSuper =
            registry.findCommonSuperObject(currentCommonSuper, obj);
      }
    }
    return currentCommonSuper;
  }

  @Override
  public void matchConstraint(JSType constraint) {
    for (JSType alternate : alternates) {
      alternate.matchConstraint(constraint);
    }
  }

  @Override
  public boolean hasAnyTemplateTypesInternal() {
    for (JSType alternate : alternates) {
      if (alternate.hasAnyTemplateTypes()) {
        return true;
      }
    }
    return false;
  }
}


text:
<?php

namespace Gedmo\Mapping\Annotation;

use Doctrine\Common\Annotations\Annotation;

/**
 * Timestampable annotation for Timestampable behavioral extension
 *
 * @Annotation
 * @Target("PROPERTY")
 *
 * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
final class Timestampable extends Annotation
{
    /** @var string */
    public $on = 'update';
    /** @var string|array */
    public $field;
    /** @var mixed */
    public $value;
}


text:
(function(){
    'use strict';

    angular.module('ws.settings')
        .service('WsSettings', function($rootScope, localStorageService, UserSession, SETTINGS, SETTINGS_EVENTS){
            var user;
            var settingsKey;
            var settings;
            var self = this;

            function _initSettings(){
                user = UserSession.getUser()
                settingsKey = 'settings_' + ((user.username) ? user.username : 'general');
                settings = localStorageService.get(settingsKey) || null;
                if(settings == undefined) {
                    var darkMode = SETTINGS.DARK_MODE;
                    var autoDark = SETTINGS.AUTO_DARK_MODE;
                    var settings = {};
                    settings[darkMode] = false;
                    settings[autoDark] = true;
                    localStorageService.set(settingsKey, settings);
                }else {
                    $rootScope.$broadcast(SETTINGS_EVENTS.SETTINGS_CHANGED);
                }

                return settings;
            }

            settings = _initSettings();

            $rootScope.$on('LocalStorageModule.notification.setitem', function(event, data){
                if(data.key === settingsKey) {
                    settings = localStorageService.get(settingsKey);
                    if(settings) {
                        $rootScope.$broadcast(SETTINGS_EVENTS.SETTINGS_CHANGED);
                    }
                }
            });

            $rootScope.$on('ws.user.login', function(){
                _initSettings();
            });

            $rootScope.$on('ws.user.logout', function(){
               _initSettings();
            });

            this.get = function(key) {
                return localStorageService.get(settingsKey)[key];
            }

            this.set = function(key, value) {
                settings[key] = value;
                localStorageService.set(settingsKey, settings);
                return this;
            }

            this.getSettingsKey = function() {
                return settingsKey;
            }

            this.bind = function(scope) {
                return localStorageService.bind(scope, settingsKey);
            };
        });
})();


text:
require 'cdo/date'
require 'dynamic_config/dcdo'
require 'dynamic_config/gatekeeper'
require 'dynamic_config/page_mode'

class ApplicationController < ActionController::Base
  include LocaleHelper
  include ApplicationHelper

#  commenting this stuff out because even if we don't have a reader configured it will set stuff in the session
# include SeamlessDatabasePool::ControllerFilter
#  use_database_pool :all => :master

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  # this is needed to avoid devise breaking on email param
  before_filter :configure_permitted_parameters, if: :devise_controller?

  around_filter :with_locale

  before_action :fix_crawlers_with_bad_accept_headers

  def fix_crawlers_with_bad_accept_headers
    # append text/html as an acceptable response type for Edmodo and weebly-agent's malformed HTTP_ACCEPT header.

    if request.formats.include?("image/*") &&
        (request.user_agent.include?("Edmodo") || request.user_agent.include?("weebly-agent"))
      request.formats.append Mime::HTML
    end
  end

  # Configure development only filters.
  if Rails.env.development?
    # Enable or disable the rack mini-profiler if the 'pp' query string parameter is set.
    # pp='disabled' will disable it; any other value will enable it.
    before_filter :maybe_enable_profiler
    def maybe_enable_profiler
      pp = params['pp']
      if pp
        ENV['RACK_MINI_PROFILER'] = (pp == 'disabled') ? 'off' : 'on'
      end
    end

    before_filter :configure_web_console
    # Enable the Rails web console if params['dbg'] is set, or disable it
    # if params['dbg'] is 'off'.
    def configure_web_console
      if params[:dbg]
        cookies[:dbg] = (params[:dbg] != 'off') ? 'on' : nil
      end
      @use_web_console = cookies[:dbg]
    end
  end

  def reset_session_endpoint
    client_state.reset
    reset_session
    render text: 'OK <script>sessionStorage.clear()</script>'
  end

  rescue_from CanCan::AccessDenied do
    if !current_user && request.format == :html
      # we don't know who you are, you can try to sign in
      authenticate_user!
    else
      # we know who you are, you shouldn't be here
      head :forbidden
    end
  end

  # missing templates are usually a result of the user agent
  # requesting a file in the wrong format, send a 404 instead of a 500
  rescue_from ActionView::MissingTemplate do |_exception|
    render_404
  end

  def render_404
    respond_to do |format|
      format.html { render file: 'public/404.html', layout: 'layouts/application', status: :not_found }
      format.all { head :not_found }
    end
  end

  def render_500
    respond_to do |format|
      format.html { render file: 'public/500.html', layout: 'layouts/application', status: :internal_server_error }
      format.all { head :internal_server_error}
    end
  end

  def prevent_caching
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end

  protected

  PERMITTED_USER_FIELDS = [:name, :username, :email, :password, :password_confirmation,
                           :locale, :gender, :login,
                           :remember_me, :age, :school, :full_address, :user_type,
                           :hashed_email]

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) do |u| u.permit PERMITTED_USER_FIELDS end
    devise_parameter_sanitizer.for(:sign_up) do |u| u.permit PERMITTED_USER_FIELDS end
    devise_parameter_sanitizer.for(:sign_in) do |u| u.permit PERMITTED_USER_FIELDS end
  end

  def with_locale
    I18n.with_locale(locale) do
      yield
    end
  end

  def milestone_response(options)
    response = {
      timestamp: DateTime.now.to_milliseconds
    }
    script_level = options[:script_level]

    if script_level
      response[:script_id] = script_level.script.id
      response[:level_id] = script_level.level.id

      previous_level = script_level.previous_level
      if previous_level
        response[:previous_level] = build_script_level_path(previous_level)
      end

      # if they solved it, figure out next level
      if options[:solved?]
        response[:total_lines] = options[:total_lines]
        response[:trophy_updates] = options[:trophy_updates] unless options[:trophy_updates].blank?
        response[:new_level_completed] = options[:new_level_completed]
        response[:level_path] = build_script_level_path(script_level)
        script_level_solved_response(response, script_level)
      else # not solved
        response[:message] = 'try again'
      end
    else
      response[:message] = 'no script provided'
    end

    if options[:level_source].try(:id)
      response[:level_source] = level_source_url(id: options[:level_source].id)
      response[:phone_share_url] = send_to_phone_url
      response[:level_source_id] = options[:level_source].id
    end

    if options[:share_failure]
      response[:share_failure] = options[:share_failure]
    end

    if HintViewRequest.enabled?
      if script_level && current_user
        response[:hint_view_requests] = HintViewRequest.milestone_response(script_level.script, script_level.level, current_user)
        response[:hint_view_request_url] = hint_view_requests_path
      end
    end

    if PuzzleRating.enabled?
      response[:puzzle_ratings_enabled] = script_level && PuzzleRating.can_rate?(script_level.script, script_level.level, current_user)
    end

    # logged in users can:
    if current_user
      # save solved levels to a gallery (subject to
      # additional logic in the blockly code because blockly owns
      # which levels are worth saving)
      if options[:level_source].try(:id) &&
          options[:solved?] &&
          options[:activity] &&
          options[:level_source_image]
        response[:save_to_gallery_url] = gallery_activities_path(gallery_activity: {activity_id: options[:activity].id})
      end
    end

    unless options[:solved?]
      # Call method to generate hint and related attributes, copying results into response.
      hint_details = ExperimentActivity.determine_hint({
                                                         level_source: options[:level_source],
                                                         current_user: current_user,
                                                         enable_external_hints: Rails.env.production?,
                                                         ip: request.remote_ip,
                                                         uri: request.referer,
                                                         activity: options[:activity]})
      response[:hint] = hint_details[:hint] if hint_details[:hint]
      response[:hint_request_placement] = hint_details[:hint_request_placement] if
        hint_details[:hint_request_placement]
      response[:hint_requested_url] =
        activity_hint_path(hint_details[:activity_hint]) if hint_details[:activity_hint]
    end

    # Set up the background design
    response[:design] = ExperimentActivity::TYPE_FEEDBACK_DESIGN_WHITE

    response[:activity_id] = options[:activity] && options[:activity].id

    response
  end

  def current_user
    super
  end

  def set_locale_cookie(locale)
    cookies[:language_] = { value: locale, domain: :all, expires: 10.years.from_now}
  end

  def require_levelbuilder_mode
    unless Rails.application.config.levelbuilder_mode
      raise CanCan::AccessDenied.new('Cannot create or modify levels from this environment.')
    end
  end

  def require_admin
    authorize! :read, :reports
  end
end


text:
			Logout

				Set up a New Reminder:

			<form style="margin-bottom:0;" method="link" action="./homepage.html">
				<input type = "hidden" id="name" value="" name="username" >
				<input type="submit" value="Back">
			</form>


text:
TODO (gkalpak): Add docs. Mention:
- Testing on CI.
  Relevant files: `scripts/ci/test-aio.sh`, `aio/aio-builds-setup/scripts/test.sh`
- Deploying from CI.
  Relevant files: `scripts/ci/deploy.sh`, `aio/scripts/deploy-to-firebase.sh`


text:
/*
 * Author: tdanford
 * Date: Dec 3, 2008
 */
package edu.psu.compbio.seqcode.gse.utils.models.bns;

import java.util.*;

import edu.psu.compbio.seqcode.gse.utils.graphs.DirectedAlgorithms;
import edu.psu.compbio.seqcode.gse.utils.graphs.DirectedGraph;
import edu.psu.compbio.seqcode.gse.utils.models.Model;
import edu.psu.compbio.seqcode.gse.utils.models.data.DataFrame;
import edu.psu.compbio.seqcode.gse.utils.probability.FiniteDistribution;

public class BN<X extends Model> {

	public DirectedGraph graph;

	private Map<String,BNVar> vars;
	private Map<String,BNCpd> cpds;
	private DataFrame<X> data;

	public BN(BN bn) {
		data = bn.data;
		vars = new TreeMap<String,BNVar>(bn.vars);
		cpds = new TreeMap<String,BNCpd>(bn.cpds);
		graph = new DirectedGraph(bn.graph);
	}

	public BN(DataFrame<X> d, String... varNames) {
		data = d;
		graph = new DirectedGraph();
		vars = new TreeMap<String,BNVar>();
		cpds = new TreeMap<String,BNCpd>();

		for(int i = 0; i < varNames.length; i++) {
			if(vars.containsKey(varNames[i])) {
				throw new IllegalArgumentException(varNames[i]);
			}
			BNVar var = new BNVar(varNames[i], data.fieldValues(varNames[i]));
			vars.put(varNames[i], var);
			graph.addVertex(varNames[i]);
		}

		// No call to learnCPDs(), since we presume that the user will add some edges to
		// the graph first, and then call that method him/herself.
	}

	public BN(DataFrame<X> d, DirectedGraph g) {
		data = d;
		graph = g;
		vars = new TreeMap<String,BNVar>();
		cpds = new TreeMap<String,BNCpd>();

		Set<String> verts = graph.getVertices();

		for(String varName : verts) {
			BNVar var = new BNVar(varName, data.fieldValues(varName));
			vars.put(varName, var);
		}

		learnCPDs();
	}

	public FiniteDistribution posterior(X m, String var) {
		BNVar bnvar = vars.get(var);
		Object bnvalue = bnvar.findValue(m);
		if(bnvalue != null) {
			int code = bnvar.encode(bnvalue);
			return new FiniteDistribution(bnvar.size(), code);
		}

		return null;
	}

	public void print() {
		DirectedAlgorithms algos = new DirectedAlgorithms(graph);
		Vector<String> verts = algos.getTopologicalOrdering();
		graph.printGraph(System.out);
		for(String name : verts) {
			cpds.get(name).print();
			System.out.println();
		}
	}

	public DataFrame<X> getData() { return data; }

	public Set<String> varNames() { return graph.getVertices(); }

	public X sample() {
		try {
			X model = data.getModelClass().newInstance();
			DirectedAlgorithms algos = new DirectedAlgorithms(graph);
			Vector<String> verts = algos.getTopologicalOrdering();

			for(String v : verts) {
				cpds.get(v).resample(model);
			}
			return model;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	public double logLikelihood(Model m) {
		double sum = 0.0;
		for(String varName : cpds.keySet()) {
			sum += cpds.get(varName).logLikelihood(m);
		}
		return sum;
	}

	public double logLikelihood(Iterator<? extends Model> ms) {
		double sum = 0.0;
		while(ms.hasNext()) {
			sum += logLikelihood(ms.next());
		}
		return sum;
	}

	public double logLikelihood() {
		return logLikelihood(data.iterator());
	}

	public BNVar getVar(String v) {
		return vars.get(v);
	}

	public BNCpd getCPD(String v) {
		return cpds.get(v);
	}

	public int countParameters() {
		int count = 0;
		for(String key : cpds.keySet()) {
			count += cpds.get(key).countParameters();
		}
		return count;
	}

	public int countParameters(String child, String... parents) {
		BNVar cvar = vars.get(child);
		int count = cvar.size();

		for(int i = 0; i < parents.length; i++) {
			count *= vars.get(parents[i]).size();
		}

		return count;
	}

	public void learnCPDs() {
		DirectedAlgorithms algos = new DirectedAlgorithms(graph);
		if(algos.hasCycle()) {
			throw new IllegalStateException("Graph has a cycle.");
		}

		for(String name : vars.keySet()) {
			cpds.put(name, learnCPD(name));
		}
	}

	private BNCpd learnCPD(String node) {
		Set<String> parentNames = graph.getParents(node);

		BNVar[] parents = new BNVar[parentNames.size()];
		BNVar child = vars.get(node);
		int pi = 0;
		for(String p : parentNames) {
			parents[pi++] = vars.get(p);
		}

		BNCpd cpd = new BNCpd(parents, child);

		cpd.learn(data.iterator());

		return cpd;
	}
}


text:
/* Generated by Together */

package it.finsiel.siged.mvc.vo.lookup;

/**
 * @persistent
 * @rdbPhysicalName PROVINCE
 * @rdbPhysicalPrimaryKeyName SYS_C0021966
 */
public class ProvinciaVO {
    public ProvinciaVO() {
    }

    public ProvinciaVO(long provinciaId, String descrizioneProvincia) {
        this.provinciaId = provinciaId;
        this.descrizioneProvincia = descrizioneProvincia;
    }

    /**
     * @rdbPhysicalName provincia_id
     * @rdbNotNull
     * @rdbSize 22
     * @rdbDigits 0
     * @rdbLogicalType DECIMAL
     * @rdbPrimaryKey
     */
    private long provinciaId;

    /**
     * @rdbPhysicalName CODI_PROVINCIA
     * @rdbNotNull
     * @rdbSize 2
     * @rdbDigits 0
     * @rdbLogicalType VARCHAR
     */
    private String codProvincia;

    /**
     * @rdbPhysicalName DESC_PROVINCIA
     * @rdbNotNull
     * @rdbSize 50
     * @rdbDigits 0
     * @rdbLogicalType VARCHAR
     */
    private String descrizioneProvincia;

    /** @rdbPhysicalName SYS_C0021967 */
    private RegioneVO fkRegione;

    /**
     * @return Returns the codProvincia.
     */
    public String getCodProvincia() {
        return codProvincia;
    }

    /**
     * @param codProvincia
     *            The codProvincia to set.
     */
    public void setCodProvincia(String codProvincia) {
        this.codProvincia = codProvincia;
    }

    /**
     * @return Returns the descrizioneProvincia.
     */
    public String getDescrizioneProvincia() {
        return descrizioneProvincia;
    }

    /**
     * @param descrizioneProvincia
     *            The descrizioneProvincia to set.
     */
    public void setDescrizioneProvincia(String descrizioneProvincia) {
        this.descrizioneProvincia = descrizioneProvincia;
    }

    /**
     * @return Returns the fkRegione.
     */
    public RegioneVO getFkRegione() {
        return fkRegione;
    }

    /**
     * @param fkRegione
     *            The fkRegione to set.
     */
    public void setFkRegione(RegioneVO fkRegione) {
        this.fkRegione = fkRegione;
    }

    /**
     * @return Returns the provinciaId.
     */
    public long getProvinciaId() {
        return provinciaId;
    }

    /**
     * @param provinciaId
     *            The provinciaId to set.
     */
    public void setProvinciaId(long provinciaId) {
        this.provinciaId = provinciaId;
    }
}


text:
using Aspose.BarCode.Generation;

namespace Aspose.BarCode.Examples.CSharp.BarcodeGeneration
{
    internal class CodablockFAspectRatio : OneDBase
    {
		public static void Run()
        {
            string path = GetFolder();
            System.Console.WriteLine("CodablockFAspectRatio:");

            BarcodeGenerator gen = new BarcodeGenerator(EncodeTypes.CodablockF, "Aspose");
            gen.Parameters.Barcode.XDimension.Pixels = 2;
            //set CodablockF aspect ratio 15
            gen.Parameters.Barcode.Codablock.AspectRatio = 15;
            gen.Save($"{path}CodablockFAspectRatio15.png", BarCodeImageFormat.Png);
            //set CodablockF aspect ratio 30
            gen.Parameters.Barcode.Codablock.AspectRatio = 30;
            gen.Save($"{path}CodablockFAspectRatio30.png", BarCodeImageFormat.Png);
        }
    }
}


text:
package xyy.java.note.dm.template;

/**
 * @author xyy
 * @version 1.0 2017/3/9.
 * @since 1.0
 */
public class RefreshBeverageTest {
    public static void main(String[] args) {
        RefreshBeverage refreshBeverage = new Coffee();
        refreshBeverage.prepareBeverageTemplate();
    }
}


text:
package org.smoothbuild.compile.ps.ast;

import static java.lang.String.join;
import static java.util.Collections.rotate;
import static org.smoothbuild.out.log.Log.error;
import static org.smoothbuild.out.log.Maybe.maybe;
import static org.smoothbuild.out.log.Maybe.maybeLogs;
import static org.smoothbuild.util.collect.Lists.map;
import static org.smoothbuild.util.graph.SortTopologically.sortTopologically;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.smoothbuild.compile.lang.base.Loc;
import org.smoothbuild.compile.lang.base.Nal;
import org.smoothbuild.compile.ps.ast.expr.RefP;
import org.smoothbuild.compile.ps.ast.refable.ItemP;
import org.smoothbuild.compile.ps.ast.refable.PolyEvaluableP;
import org.smoothbuild.compile.ps.ast.type.ArrayTP;
import org.smoothbuild.compile.ps.ast.type.FuncTP;
import org.smoothbuild.compile.ps.ast.type.TypeP;
import org.smoothbuild.out.log.Log;
import org.smoothbuild.out.log.Maybe;
import org.smoothbuild.util.collect.NList;
import org.smoothbuild.util.collect.Sets;
import org.smoothbuild.util.graph.GraphEdge;
import org.smoothbuild.util.graph.GraphNode;
import org.smoothbuild.util.graph.SortTopologically.TopologicalSortingRes;

import com.google.common.collect.ImmutableList;

public class AstSorter {
  public static Maybe<Ast> sortParsedByDeps(Ast ast) {
    var sortedTs = sortStructsByDeps(ast.structs());
    if (sortedTs.sorted() == null) {
      Log error = createCycleError("Type hierarchy", sortedTs.cycle());
      return maybeLogs(error);
    }
    var sortedEvaluables = sortEvaluablesByDeps(ast.evaluables());
    if (sortedEvaluables.sorted() == null) {
      Log error = createCycleError("Dependency graph", sortedEvaluables.cycle());
      return maybeLogs(error);
    }
    Ast sorted = new Ast(sortedTs.valuesReversed(), sortedEvaluables.valuesReversed());
    return maybe(sorted);
  }

  private static TopologicalSortingRes<String, PolyEvaluableP, Loc> sortEvaluablesByDeps(
      ImmutableList<PolyEvaluableP> evaluables) {
    HashSet<String> names = new HashSet<>();
    evaluables.forEach(r -> names.add(r.name()));

    HashSet<GraphNode<String, PolyEvaluableP, Loc>> nodes = new HashSet<>();
    nodes.addAll(map(evaluables, r -> evaluable(r, names)));
    return sortTopologically(nodes);
  }

  private static GraphNode<String, PolyEvaluableP, Loc> evaluable(PolyEvaluableP evaluable,
      Set<String> names) {
    Set<GraphEdge<Loc, String>> deps = new HashSet<>();
    new AstVisitor() {
      @Override
      public void visitRef(RefP ref) {
        super.visitRef(ref);
        if (names.contains(ref.name())) {
          deps.add(new GraphEdge<>(ref.loc(), ref.name()));
        }
      }
    }.visitEvaluable(evaluable);
    return new GraphNode<>(evaluable.name(), evaluable, ImmutableList.copyOf(deps));
  }

  private static TopologicalSortingRes<String, StructP, Loc> sortStructsByDeps(
      NList<StructP> structs) {
    var structNames = Sets.map(structs, Nal::name);
    var nodes = map(structs, struct -> structToGraphNode(struct, structNames));
    return sortTopologically(nodes);
  }

  private static GraphNode<String, StructP, Loc> structToGraphNode(
      StructP struct, Set<String> funcNames) {
    Set<GraphEdge<Loc, String>> deps = new HashSet<>();
    new AstVisitor() {
      @Override
      public void visitField(ItemP field) {
        super.visitField(field);
        addToDeps(field.type());
      }

      private void addToDeps(TypeP type) {
        switch (type) {
          case ArrayTP arrayT -> addToDeps(arrayT.elemT());
          case FuncTP funcT -> {
            addToDeps(funcT.resT());
            funcT.paramTs().forEach(this::addToDeps);
          }
          default -> {
            if (funcNames.contains(type.name())) {
              deps.add(new GraphEdge<>(type.loc(), type.name()));
            }
          }
        }
      }
    }.visitStruct(struct);
    return new GraphNode<>(struct.name(), struct, ImmutableList.copyOf(deps));
  }

  private static Log createCycleError(String name, List<GraphEdge<Loc, String>> cycle) {
    // Choosing edge with lowest line number and printing a cycle starting from that edge
    // is a way to make report deterministic and (as a result) to make testing those reports simple.
    int edgeIndex = chooseEdgeWithLowestLineNumber(cycle);
    rotate(cycle, -edgeIndex);

    String previous = cycle.get(cycle.size() - 1).targetKey();
    var lines = new ArrayList<String>();
    for (var current : cycle) {
      String dependency = current.targetKey();
      lines.add(current.value() + ": " + previous + " -> " + dependency);
      previous = dependency;
    }
    return error(name + " contains cycle:\n" + join("\n", lines));
  }

  private static int chooseEdgeWithLowestLineNumber(List<GraphEdge<Loc, String>> cycle) {
    int lowestLineNumber = Integer.MAX_VALUE;
    int result = 0;
    for (int i = 0; i < cycle.size(); i++) {
      int line = cycle.get(i).value().line();
      if (line < lowestLineNumber) {
        lowestLineNumber = line;
        result = i;
      }
    }
    return result;
  }

}


text:
function getError (action, option, xhr) {
  let msg = ''
  if (xhr.response) {
    msg = `${xhr.status} ${xhr.response.error || xhr.response}`
  } else if (xhr.responseText) {
    msg = `${xhr.status} ${xhr.responseText}`
  } else {
    msg = `fail to post ${action} ${xhr.status}`
  }

  const err = new Error(msg)
  err.status = xhr.status
  err.method = 'post'
  err.url = action
  return err
}

function getBody (xhr) {
  const text = xhr.responseText || xhr.response
  if (!text) {
    return text
  }

  try {
    return JSON.parse(text)
  } catch (e) {
    return text
  }
}

export default function upload (option) {
  if (typeof XMLHttpRequest === 'undefined') {
    return
  }

  const xhr = new XMLHttpRequest()
  const action = option.action

  if (xhr.upload) {
    xhr.upload.onprogress = function progress (e) {
      if (e.total > 0) {
        e.percent = e.loaded / e.total * 100
      }
      option.onProgress(e)
    }
  }

  const formData = new FormData()

  if (option.data) {
    Object.keys(option.data).map(key => {
      formData.append(key, option.data[key])
    })
  }

  formData.append(option.filename, option.file)

  xhr.onerror = function error (e) {
    option.onError(e, xhr)
  }

  xhr.onload = function onload () {
    if (xhr.status < 200 || xhr.status >= 300) {
      return option.onError(getError(action, option, xhr), xhr)
    }

    option.onSuccess(getBody(xhr))
  }

  xhr.open('post', action, true)

  if (option.withCredentials && 'withCredentials' in xhr) {
    xhr.withCredentials = true
  }

  const headers = option.headers || {}

  for (let item in headers) {
    if (headers.hasOwnProperty(item) && headers[item] !== null) {
      xhr.setRequestHeader(item, headers[item])
    }
  }
  xhr.send(formData)
  return xhr
}


text:
require "./test/test_helper"

require "minitest/spec"
require "minitest/unit"

require "ok/assert"
require "ok/adapters/minitest"

describe "basic assert features" do

  before do
    @test_case_instance = Class.new(Ok::MiniTestAdapter.minitest_base_class).new("x")
  end

  it "raises minitest assertion failures" do
    test_case_instance = Class.new(Ok::MiniTestAdapter.minitest_base_class).new("x")
    assert {
      rescuing {
        test_case_instance.assert { 1==2 }
      }.is_a?(MiniTest::Assertion)
    }
  end

  it "passes asserts with no block up to the framework's assert method" do
    e = rescuing { assert(1 == 2) }
    assert { e.message == "Failed assertion, no message given." }

    e = rescuing { assert(1 == 2, "black is white") }
    assert { e.message == "black is white" }
  end

  it "passes denys with no block up to the framework's assert method" do
    e = rescuing { deny(2 + 2 == 4) }
    assert { e.message == "Failed assertion, no message given." }

    e = rescuing { deny(2 + 2 == 4, "up is down") }
    assert { e.message == "up is down" }
  end

  # TODO: optionally print a warning when calling the framework assert

  it "makes Ok's assert and deny available to minitest tests" do
    class MyFailingAssertTest < Ok::MiniTestAdapter.minitest_base_class
      def initialize
        super("assert test")
      end

      def test_fail
        assert { 1==2 }
      end
    end

    class MyFailingDenyTest < Ok::MiniTestAdapter.minitest_base_class
      def initialize
        super("deny test")
      end

      def test_fail
        deny { 1==1 }
      end
    end

    msg = rescuing { MyFailingAssertTest.new.test_fail }.message
    assert { msg.include?("Expected (1 == 2)") }

    msg = rescuing { MyFailingDenyTest.new.test_fail }.message
    assert { msg.include?("Didn't expect (1 == 1)") }
  end
end

describe 'reports number of assertions' do
  before do
    @test = Class.new(Ok::MiniTestAdapter.minitest_base_class).new("x")
  end

  it 'assert{} should bump number of assertions' do
    @test.assert {true}
    assert {@test.minitest_assertion_count == 1}
  end

  it 'assert() should not bump twice number of assertions' do
    @test.assert(true)
    assert {@test.minitest_assertion_count == 1}
  end

  it 'deny{} should bump number of assertions' do
    @test.deny {false}
    assert {@test.minitest_assertion_count == 1}
  end

  it 'deny() should bump once number of assertions' do
    @test.deny(false)
    assert {@test.minitest_assertion_count == 1}
  end
end


text:
package spvwallet

import (
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/peer"
	"github.com/btcsuite/btcd/wire"
	"time"
)

var (
	maxHash              *chainhash.Hash
	MAX_UNCONFIRMED_TIME time.Duration = time.Hour * 24 * 7
)

func init() {
	h, err := chainhash.NewHashFromStr("0000000000000000000000000000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}
	maxHash = h
}

func (w *SPVWallet) startChainDownload(p *peer.Peer) {
	w.mutex.Lock()
	defer w.mutex.Unlock()
	if w.blockchain.ChainState() == SYNCING {
		height, _ := w.blockchain.db.Height()
		if height >= uint32(p.LastBlock()) {
			moar := w.PeerManager.CheckForMoreBlocks(height)
			if !moar {
				log.Info("Chain download complete")
				w.blockchain.SetChainState(WAITING)
				w.Rebroadcast()
				close(w.blockQueue)
			}
			return
		}
		gBlocks := wire.NewMsgGetBlocks(maxHash)
		hashes := w.blockchain.GetBlockLocatorHashes()
		gBlocks.BlockLocatorHashes = hashes
		p.QueueMessage(gBlocks, nil)
	}
}

func (w *SPVWallet) onMerkleBlock(p *peer.Peer, m *wire.MsgMerkleBlock) {
	if w.blockchain.ChainState() == SYNCING && w.PeerManager.DownloadPeer().ID() == p.ID() {
		queueHash := <-w.blockQueue
		headerHash := m.Header.BlockHash()
		if !headerHash.IsEqual(&queueHash) {
			log.Errorf("Peer%d is sending us blocks out of order", p.ID())
			p.Disconnect()
			return
		}
	}
	txids, err := checkMBlock(m)
	if err != nil {
		log.Errorf("Peer%d sent an invalid MerkleBlock", p.ID())
		p.Disconnect()
		return
	}
	newBlock, height, err := w.blockchain.CommitHeader(m.Header)
	if err != nil {
		log.Warning(err)
		return
	}
	if !newBlock {
		return
	}
	for _, txid := range txids {
		w.mutex.Lock()
		w.toDownload[*txid] = int32(height)
		w.mutex.Unlock()
	}
	log.Debugf("Received Merkle Block %s at height %d\n", m.Header.BlockHash().String(), height)
	if len(w.blockQueue) == 0 && w.blockchain.ChainState() == SYNCING {
		go w.startChainDownload(p)
	}
	if w.blockchain.ChainState() == WAITING {
		txns, err := w.txstore.Txns().GetAll()
		if err != nil {
			log.Error(err)
			return
		}
		now := time.Now()
		for _, t := range txns {
			if now.After(t.Timestamp.Add(MAX_UNCONFIRMED_TIME)) && t.Height == int32(0) {
				log.Noticef("Marking tx as dead %s", t.Txid)
				h, err := chainhash.NewHashFromStr(t.Txid)
				if err != nil {
					log.Error(err)
					continue
				}
				err = w.txstore.markAsDead(*h)
				if err != nil {
					log.Error(err)
					continue
				}
			}
		}
	}
}

func (w *SPVWallet) onTx(p *peer.Peer, m *wire.MsgTx) {
	w.mutex.RLock()
	height := w.toDownload[m.TxHash()]
	w.mutex.RUnlock()
	hits, err := w.txstore.Ingest(m, height)
	if err != nil {
		log.Errorf("Error ingesting tx: %s\n", err.Error())
		return
	}
	if hits == 0 {
		log.Debugf("Tx %s from Peer%d had no hits, filter false positive.", m.TxHash().String(), p.ID())
		w.fPositives <- p
		return
	}
	w.updateFilterAndSend(p)
	log.Infof("Tx %s from Peer%d ingested and matches %d utxo/adrs.", m.TxHash().String(), p.ID(), hits)

	// FIXME: right now the hash stays in memory forever. We need to delete it but the way the code works,
	// FIXME: doing so will cause the height to get reset to zero if a peer relays the tx to us again.
}

func (w *SPVWallet) onInv(p *peer.Peer, m *wire.MsgInv) {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Error(err)
			}
		}()
		for _, inv := range m.InvList {
			switch inv.Type {
			case wire.InvTypeBlock:
				// Kind of lame to send separate getData messages but this allows us
				// to take advantage of the timeout on the upper layer. Otherwise we
				// need separate timeout handling.
				inv.Type = wire.InvTypeFilteredBlock
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
				if w.blockchain.ChainState() == SYNCING && w.PeerManager.DownloadPeer() != nil && w.PeerManager.DownloadPeer().ID() == p.ID() {
					w.blockQueue <- inv.Hash
				}
			case wire.InvTypeTx:
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
			default:
				continue
			}

		}
	}()
}

func (w *SPVWallet) onGetData(p *peer.Peer, m *wire.MsgGetData) {
	log.Debugf("Received getdata request from Peer%d\n", p.ID())
	var sent int32
	for _, thing := range m.InvList {
		if thing.Type == wire.InvTypeTx {
			tx, _, _, err := w.txstore.Txns().Get(thing.Hash)
			if err != nil {
				log.Errorf("Error getting tx %s: %s", thing.Hash.String(), err.Error())
			}
			p.QueueMessage(tx, nil)
			sent++
			continue
		}
		// didn't match, so it's not something we're responding to
		log.Debugf("We only respond to tx requests, ignoring")

	}
	log.Debugf("Sent %d of %d requested items to Peer%d", sent, len(m.InvList), p.ID())
}

func (w *SPVWallet) fPositiveHandler(quit chan int) {
	for {
		select {
		case peer := <-w.fPositives:
			w.mutex.RLock()
			falsePostives, _ := w.fpAccumulator[peer.ID()]
			w.mutex.RUnlock()
			falsePostives++
			if falsePostives > 7 {
				w.updateFilterAndSend(peer)
				log.Debugf("Reset %d false positives for Peer%d\n", falsePostives, peer.ID())
				// reset accumulator
				falsePostives = 0
			}
			w.mutex.Lock()
			w.fpAccumulator[peer.ID()] = falsePostives
			w.mutex.Unlock()
		case <-quit:
			break
		}
	}
}

func (w *SPVWallet) updateFilterAndSend(p *peer.Peer) {
	filt, err := w.txstore.GimmeFilter()
	if err != nil {
		log.Errorf("Error creating filter: %s\n", err.Error())
		return
	}
	// send filter
	p.QueueMessage(filt.MsgFilterLoad(), nil)
	log.Debugf("Sent filter to Peer%d\n", p.ID())
}

func (w *SPVWallet) Rebroadcast() {
	// get all unconfirmed txs
	invMsg, err := w.txstore.GetPendingInv()
	if err != nil {
		log.Errorf("Rebroadcast error: %s", err.Error())
	}
	if len(invMsg.InvList) == 0 { // nothing to broadcast, so don't
		return
	}
	for _, peer := range w.PeerManager.connectedPeers {
		peer.QueueMessage(invMsg, nil)
	}
}


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

<systemConfiguration oid="00000000-0000-0000-0000-000000000001" version="0"
                     xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
                     xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
                     xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
    <name>SystemConfiguration</name>

    <globalSecurityPolicyRef oid="00000000-0000-0000-0000-000000000120"/>
    <logging>
        <classLogger>
            <level>ERROR</level>
            <package>ro.isdc.wro.extensions.processor.css.Less4jProcessor</package>
        </classLogger>
        <classLogger>

            <level>OFF</level>
            <package>org.hibernate.engine.jdbc.spi.SqlExceptionHelper</package>
        </classLogger>

        <classLogger>
            <level>OFF</level>
            <package>org.hibernate.engine.jdbc.batch.internal.BatchingBatch</package>
        </classLogger>

        <classLogger>
            <level>WARN</level>
            <package>org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl</package>
        </classLogger>

        <classLogger>
            <level>OFF</level>
            <package>org.hibernate.internal.ExceptionMapperStandardImpl</package>
        </classLogger>
        <classLogger>

            <level>OFF</level>
            <package>net.sf.jasperreports.engine.fill.JRFillDataset</package>
        </classLogger>
        <classLogger>

            <level>WARN</level>
            <package>org.apache.wicket.resource.PropertiesFactory</package>
        </classLogger>
        <classLogger>

            <level>ERROR</level>
            <package>org.springframework.context.support.ResourceBundleMessageSource</package>
        </classLogger>
        <classLogger>

            <level>INFO</level>
            <package>com.evolveum.midpoint.model.impl.lens.projector.Projector</package>
        </classLogger>
        <classLogger>

            <level>INFO</level>
            <package>com.evolveum.midpoint.model.impl.lens.Clockwork</package>
        </classLogger>

        <appender xsi:type="c:FileAppenderConfigurationType" name="MIDPOINT_LOG"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <pattern>%date [%X{subsystem}] [%thread] %level \(%logger\): %msg%n</pattern>
            <fileName>${midpoint.home}/log/midpoint.log</fileName>
            <filePattern>${midpoint.home}/log/midpoint-%d{yyyy-MM-dd}.%i.log</filePattern>
            <maxHistory>10</maxHistory>
            <maxFileSize>100MB</maxFileSize>
            <append>true</append>
        </appender>

        <appender xsi:type="c:FileAppenderConfigurationType" name="MIDPOINT_PROFILE_LOG"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <pattern>%date %level: %msg%n</pattern>
            <fileName>${midpoint.home}/log/midpoint-profile.log</fileName>
            <filePattern>${midpoint.home}/log/midpoint-profile-%d{yyyy-MM-dd}.%i.log</filePattern>
            <maxHistory>10</maxHistory>
            <maxFileSize>100MB</maxFileSize>
            <append>true</append>
        </appender>
        <rootLoggerAppender>MIDPOINT_LOG</rootLoggerAppender>
        <rootLoggerLevel>INFO</rootLoggerLevel>
        <auditing>
            <enabled>false</enabled>
            false
        </auditing>
    </logging>
    <cleanupPolicy>
        <auditRecords>
            <maxAge>P3M</maxAge>
        </auditRecords>
        <closedTasks>
            <maxAge>P1M</maxAge>
        </closedTasks>
    </cleanupPolicy>
    <adminGuiConfiguration>
        <userDashboardLink>
            <targetUrl>/self/profile</targetUrl>
            Profile
            <description>View/edit your profile</description>
            <icon>
                <cssClass>fa fa-user</cssClass>
            </icon>
            <color>green</color>
            <authorization>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#selfProfile</authorization>
            <authorization>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#selfAll</authorization>
        </userDashboardLink>
        <userDashboardLink>
            <targetUrl>/self/credentials</targetUrl>
            Credentials
            <description>View/edit your credentials</description>
            <icon>
                <cssClass>fa fa-shield</cssClass>
            </icon>
            <color>blue</color>
            <authorization>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#selfCredentials</authorization>
            <authorization>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#selfAll</authorization>
        </userDashboardLink>
        <userDashboardLink>
            <targetUrl>/admin/users</targetUrl>
            List users
            <icon>
                <cssClass>fa fa-users</cssClass>
            </icon>
            <color>red</color>
            <authorization>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#users</authorization>
        </userDashboardLink>
        <userDashboardLink>
            <targetUrl>/admin/resources</targetUrl>
            List resources
            <icon>
                <cssClass>fa fa-database</cssClass>
            </icon>
            <color>purple</color>
            <authorization>http://midpoint.evolveum.com/xml/ns/public/security/authorization-ui-3#resources</authorization>
        </userDashboardLink>
        <enableExperimentalFeatures>true</enableExperimentalFeatures>
    </adminGuiConfiguration>
    <internals>
      <enableExperimentalCode>true</enableExperimentalCode>
   </internals>
   <fullTextSearch>
     <indexed>
        <item>name</item>
        <item>description</item>
     </indexed>
     <indexed>
        <objectType>UserType</objectType>
        <item>fullName</item>
        <item>givenName</item>
        <item>familyName</item>
        <item>additionalName</item>
        <item>nickName</item>
        <item>emailAddress</item>
        <item>telephoneNumber</item>
        <item>honorificPrefix</item>
        <item>honorificSuffix</item>
        <item>title</item>
        <item>employeeNumber</item>
        <item>employeeType</item>
        <item>costCenter</item>
        <item>organization</item>
        <item>organizationalUnit</item>
        <item>locality</item>
     </indexed>
     <indexed>
        <objectType>AbstractRoleType</objectType>
        <item>displayName</item>
        <item>identifier</item>
     </indexed>
     <indexed>
        <objectType>RoleType</objectType>
        <item>roleType</item>
     </indexed>
     <indexed>
        <objectType>OrgType</objectType>
        <item>orgType</item>
        <item>costCenter</item>
        <item>locality</item>
        <item>mailDomain</item>
     </indexed>
     <indexed>
        <objectType>ServiceType</objectType>
        <item>serviceType</item>
        <item>locality</item>
     </indexed>
  </fullTextSearch>
</systemConfiguration>


text:
/* global angular */
(function () {
    'use strict';

    var Item = function ($resource) {
        return $resource('/data/itemData.json', null, {
            'query':  { method: 'GET', isArray: true, cache: true }
        });
    };

    Item.$inject = ['$resource'];

    angular
        .module('wizardServices')
        .factory('Item', Item);
})();