text:
/**
 * This plugin provides "drag-down" and "copy-down" functionalities, both operated
 * using the small square in the right bottom of the cell selection.
 *
 * "Drag-down" expands the value of the selected cells to the neighbouring
 * cells when you drag the small square in the corner.
 *
 * "Copy-down" copies the value of the selection to all empty cells
 * below when you double click the small square.
 */
(function (Handsontable) {
  'use strict';

  function Autofill(instance) {
    this.instance = instance;
    this.addingStarted = false;

    var $document = $(document),
      wtOnCellCornerMouseDown,
      wtOnCellMouseOver;

    $(this.instance.$table).off('mouseup.' + instance.guid).on('mouseup.' + instance.guid, function (event) {
      if (instance.autofill.handle && instance.autofill.handle.isDragged) {
        if (instance.autofill.handle.isDragged > 1) {
          instance.autofill.apply();
        }
        instance.autofill.handle.isDragged = 0;
      }
    });

    /*
     * Appeding autofill-specific methods to walkontable event settings
     */
    wtOnCellCornerMouseDown = this.instance.view.wt.wtSettings.settings.onCellCornerMouseDown;
    this.instance.view.wt.wtSettings.settings.onCellCornerMouseDown = function(event) {
      instance.autofill.handle.isDragged = 1;
      wtOnCellCornerMouseDown(event);
    }

    wtOnCellMouseOver = this.instance.view.wt.wtSettings.settings.onCellMouseOver;
    this.instance.view.wt.wtSettings.settings.onCellMouseOver = function(event, coords, TD, wt) {

      if (instance.autofill && (!instance.view.isMouseDown() && instance.autofill.handle && instance.autofill.handle.isDragged)) {
        instance.autofill.handle.isDragged++;
        instance.autofill.showBorder(coords);
        instance.autofill.checkIfNewRowNeeded();
      }

      wtOnCellMouseOver(event, coords, TD, wt);
    }

    this.instance.view.wt.wtSettings.settings.onCellCornerDblClick = function () {
      instance.autofill.selectAdjacent();
    };

  };

  /**
   * Create fill handle and fill border objects
   */
  Autofill.prototype.init = function () {
    this.handle = {};
  },

  /**
   * Hide fill handle and fill border permanently
   */
    Autofill.prototype.disable = function () {
      this.handle.disabled = true;
    },

  /**
   * Selects cells down to the last row in the left column, then fills down to that cell
   */
    Autofill.prototype.selectAdjacent = function () {
      var select, data, r, maxR, c;

      if (this.instance.selection.isMultiple()) {
        select = this.instance.view.wt.selections.area.getCorners();
      }
      else {
        select = this.instance.view.wt.selections.current.getCorners();
      }

      data = this.instance.getData();
      rows : for (r = select[2] + 1; r < this.instance.countRows(); r++) {
        for (c = select[1]; c <= select[3]; c++) {
          if (data[r][c]) {
            break rows;
          }
        }
        if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) {
          maxR = r;
        }
      }
      if (maxR) {
        this.instance.view.wt.selections.fill.clear();
        this.instance.view.wt.selections.fill.add(new WalkontableCellCoords(select[0], select[1]));
        this.instance.view.wt.selections.fill.add(new WalkontableCellCoords(maxR, select[3]));
        this.apply();
      }
    },

  /**
   * Apply fill values to the area in fill border, omitting the selection border
   */
    Autofill.prototype.apply = function () {
      var drag, select, start, end, _data;

      this.handle.isDragged = 0;

      drag = this.instance.view.wt.selections.fill.getCorners();
      if (!drag) {
        return;
      }

      this.instance.view.wt.selections.fill.clear();

      if (this.instance.selection.isMultiple()) {
        select = this.instance.view.wt.selections.area.getCorners();
      }
      else {
        select = this.instance.view.wt.selections.current.getCorners();
      }

      if (drag[0] === select[0] && drag[1] < select[1]) {
        start = new WalkontableCellCoords(
          drag[0],
          drag[1]
        );
        end = new WalkontableCellCoords(
          drag[2],
          select[1] - 1
        );
      }
      else if (drag[0] === select[0] && drag[3] > select[3]) {
        start = new WalkontableCellCoords(
          drag[0],
          select[3] + 1
        );
        end = new WalkontableCellCoords(
          drag[2],
          drag[3]
        );
      }
      else if (drag[0] < select[0] && drag[1] === select[1]) {
        start = new WalkontableCellCoords(
          drag[0],
          drag[1]
        );
        end = new WalkontableCellCoords(
          select[0] - 1,
          drag[3]
        );
      }
      else if (drag[2] > select[2] && drag[1] === select[1]) {
        start = new WalkontableCellCoords(
          select[2] + 1,
          drag[1]
        );
        end = new WalkontableCellCoords(
          drag[2],
          drag[3]
        );
      }

      if (start) {
        var selRange = {from: this.instance.getSelectedRange().from, to: this.instance.getSelectedRange().to};

        _data = this.instance.getData(selRange.from.row,selRange.from.col,selRange.to.row,selRange.to.col);

        Handsontable.hooks.run(this.instance, 'beforeAutofill', start, end, _data);

        this.instance.populateFromArray(start.row, start.col, _data, end.row, end.col, 'autofill');

        this.instance.selection.setRangeStart(new WalkontableCellCoords(drag[0], drag[1]));
        this.instance.selection.setRangeEnd(new WalkontableCellCoords(drag[2], drag[3]));
      }
      /*else {
       //reset to avoid some range bug
       selection.refreshBorders();
       }*/
    },

  /**
   * Show fill border
   * @param {WalkontableCellCoords} coords
   */
    Autofill.prototype.showBorder = function (coords) {
      var topLeft = this.instance.getSelectedRange().getTopLeftCorner();
      var bottomRight = this.instance.getSelectedRange().getBottomRightCorner();
      if (this.instance.getSettings().fillHandle !== 'horizontal' && (bottomRight.row < coords.row || topLeft.row > coords.row)) {
        coords = new WalkontableCellCoords(coords.row, bottomRight.col);
      }
      else if (this.instance.getSettings().fillHandle !== 'vertical') {
        coords = new WalkontableCellCoords(bottomRight.row, coords.col);
      }
      else {
        return; //wrong direction
      }

      this.instance.view.wt.selections.fill.clear();
      this.instance.view.wt.selections.fill.add(this.instance.getSelectedRange().from);
      this.instance.view.wt.selections.fill.add(this.instance.getSelectedRange().to);
      this.instance.view.wt.selections.fill.add(coords);
      this.instance.view.render();
    }

  Autofill.prototype.checkIfNewRowNeeded = function() {
    var fillCorners,
      tableRows = this.instance.countRows(),
      that = this;

    if(this.instance.view.wt.selections.fill.cellRange && this.addingStarted === false) {
      fillCorners = this.instance.view.wt.selections.fill.getCorners();

      if(fillCorners[2] === tableRows - 1) {
        this.addingStarted = true;

        setTimeout(function() {
          that.instance.alter('insert_row');
          that.addingStarted = false;
        }, 200);
      }
    }

  }

  Handsontable.hooks.add('afterInit', function(){
    var autofill = new Autofill(this);

    if (typeof this.getSettings().fillHandle !== "undefined") {
      if (autofill.handle && this.getSettings().fillHandle === false) {
        autofill.disable();
      }
      else if (!autofill.handle && this.getSettings().fillHandle !== false) {
        this.autofill = autofill;
        this.autofill.init();
      }
    }

  });

  Handsontable.Autofill = Autofill;

})(Handsontable);


text:
<?php

namespace Keboola\UnitTest\Client;

use GuzzleHttp\Psr7\Request;
use Keboola\StorageApi\Client;
use Keboola\StorageApi\Client\RequestTimeoutMiddleware;
use PHPUnit\Framework\TestCase;

class RequestTimeoutMiddlewareTest extends TestCase
{
    /**
     * @return void
     */
    public function testWillSetDefaultTimeout(): void
    {
        $assertingHandler = function ($request, $options) {
            $this->assertSame(RequestTimeoutMiddleware::REQUEST_TIMEOUT_DEFAULT, $options['timeout']);
        };
        $requestMock = new Request('GET', '/lorem-ipsum');

        $middleware = RequestTimeoutMiddleware::factory()($assertingHandler);

        $middleware($requestMock, []);
    }

    /**
     * @return void
     */
    public function testWillOverrideTimeout(): void
    {
        $assertingHandler = function ($request, $options) {
            $this->assertSame(RequestTimeoutMiddleware::REQUEST_TIMEOUT_DEFAULT, $options['timeout']);
        };
        $requestMock = new Request('GET', '/lorem-ipsum');

        $middleware = RequestTimeoutMiddleware::factory()($assertingHandler);

        $middleware($requestMock, ['timeout' => 300]);
    }

    /**
     * @return void
     */
    public function testWillSetDeleteTimeout(): void
    {
        $assertingHandler = function ($request, $options) {
            $this->assertSame(RequestTimeoutMiddleware::REQUEST_TIMEOUT_EXTENDED, $options['timeout']);
        };
        $requestMock = new Request('DELETE', '/lorem-ipsum');

        $middleware = RequestTimeoutMiddleware::factory()($assertingHandler);

        $middleware($requestMock, []);
    }

    /**
     * @return void
     */
    public function testWillSetManualExtendedTimeout(): void
    {
        $assertingHandler = function ($request, $options) {
            $this->assertSame(RequestTimeoutMiddleware::REQUEST_TIMEOUT_EXTENDED, $options['timeout']);
        };
        $requestMock = new Request('DELETE', '/lorem-ipsum');

        $middleware = RequestTimeoutMiddleware::factory()($assertingHandler);

        $middleware($requestMock, [Client::REQUEST_OPTION_EXTENDED_TIMEOUT => true, 'timeout' => 123]);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.boot.cli.command.archive;

import java.io.File;

import org.springframework.boot.cli.command.Command;
import org.springframework.boot.loader.tools.Layouts;
import org.springframework.boot.loader.tools.LibraryScope;

/**
 * {@link Command} to create a self-contained executable jar file from a CLI application.
 *
 * @author Andy Wilkinson
 * @author Phillip Webb
 */
public class JarCommand extends ArchiveCommand {

	public JarCommand() {
		super("jar", "Create a self-contained executable jar "
				+ "file from a Spring Groovy script", new JarOptionHandler());
	}

	private static final class JarOptionHandler extends ArchiveOptionHandler {

		JarOptionHandler() {
			super("jar", new Layouts.Jar());
		}

		@Override
		protected LibraryScope getLibraryScope(File file) {
			return LibraryScope.COMPILE;
		}

	}

}


text:
package com.alphalog.geocoder.security.controller;

import java.security.Principal;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alphalog.geocoder.security.domain.User;
import com.alphalog.geocoder.security.service.UserService;

@RestController
@RequestMapping("/users")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/current", method = RequestMethod.GET)
	public User getUser(Principal principal) {
		return   ((User)((OAuth2Authentication) principal).getUserAuthentication().getPrincipal());
	}

	@RequestMapping(method = RequestMethod.POST)
	public void createUser(@Valid @RequestBody User user) {
		userService.create(user);
	}
}


text:
chroma
======
[![Download](https://api.bintray.com/packages/itspriyesh/maven/chroma/images/download.svg)](https://bintray.com/itspriyesh/maven/chroma/_latestVersion)
[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-chroma-green.svg?style=true)](https://android-arsenal.com/details/1/3339)

A simple, lightweight color picker for Android written in Kotlin (interoperable with Java).

Download
--------
Add the following dependency to your projects `build.gradle`:
``` groovy
compile 'me.priyesh:chroma:1.0.2'
```

Usage
-----
To display a color picker `DialogFragment`:

``` java
new ChromaDialog.Builder()
    .initialColor(Color.GREEN)
    .colorMode(ColorMode.RGB) // There's also ARGB and HSV
    .onColorSelected(color -> /* do your stuff */)
    .create()
    .show(getSupportFragmentManager(), "ChromaDialog");
```

Check out the [sample project](chroma-sample) for more details.

License
-------
    Copyright 2016 Priyesh Patel

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
import {MigrationInterface, QueryRunner} from "typeorm";

export class instancePinnedClip1607151207216 implements MigrationInterface {
    name = 'instancePinnedClip1607151207216'

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "meta" ADD "pinnedClipId" character varying(32)`);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "meta" DROP COLUMN "pinnedClipId"`);
    }

}


text:
package nodes.stats

import breeze.linalg.{max, sum, DenseVector}
import breeze.numerics._
import workflow.Transformer

/**
 * Divides each row by the max of its two-norm and 2.2e-16.
 */
object NormalizeRows extends Transformer[DenseVector[Double], DenseVector[Double]] {
  def apply(in: DenseVector[Double]): DenseVector[Double] = {
    val norm = max(sqrt(sum(pow(in, 2.0))), 2.2e-16)
    in / norm
  }
}


text:
TEMPLATEDIR=/home/griffin/pulsar/simulations/full
SCRIPTDIR=/home/griffin/pulsar/simulations/scripts
DICTSCRIPT=pklReduceDict.py

mkdir $TEMPLATEDIR/J0613-0200/results/analysis/
cd $TEMPLATEDIR/J0613-0200/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J0613.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1045-4509/results/analysis/
cd $TEMPLATEDIR/J1045-4509/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1045.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1824-2452/results/analysis/
cd $TEMPLATEDIR/J1824-2452/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1824.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1939+2134/results/analysis/
cd $TEMPLATEDIR/J1939+2134/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1939.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1600-3053/results/analysis/
cd $TEMPLATEDIR/J1600-3053/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1600.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1643-1224/results/analysis/
cd $TEMPLATEDIR/J1643-1224/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1643.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1732-5049/results/analysis/
cd $TEMPLATEDIR/J1732-5049/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1732.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1909-3744/results/analysis/
cd $TEMPLATEDIR/J1909-3744/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1909.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J2129-5721/results/analysis/
cd $TEMPLATEDIR/J2129-5721/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J2129.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J0437-4715/results/analysis/
cd $TEMPLATEDIR/J0437-4715/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J0437.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J0711-6830/results/analysis/
cd $TEMPLATEDIR/J0711-6830/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J0711.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1024-0719/results/analysis/
cd $TEMPLATEDIR/J1024-0719/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1024.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1603-7202/results/analysis/
cd $TEMPLATEDIR/J1603-7202/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1603.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1713+0747/results/analysis/
cd $TEMPLATEDIR/J1713+0747/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1713.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1730-2304/results/analysis/
cd $TEMPLATEDIR/J1730-2304/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1730.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1744-1134/results/analysis/
cd $TEMPLATEDIR/J1744-1134/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1744.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1857+0943/results/analysis/
cd $TEMPLATEDIR/J1857+0943/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1857.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J2124-3358/results/analysis/
cd $TEMPLATEDIR/J2124-3358/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J2124.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J1022+1001/results/analysis/
cd $TEMPLATEDIR/J1022+1001/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J1022.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl

mkdir $TEMPLATEDIR/J2145-0750/results/analysis/
cd $TEMPLATEDIR/J2145-0750/results/analysis/
$SCRIPTDIR/$DICTSCRIPT  --mjd=../../J2145.simulate.mjd ../tim*.pkl ../rms*.txt -o analysisDict.pkl


text:
package org.apache.flink.table.planner.runtime.utils

import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.java.tuple.{Tuple1, Tuple2}
import org.apache.flink.api.java.typeutils.{GenericTypeInfo, ListTypeInfo, PojoField, PojoTypeInfo, RowTypeInfo}
import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.api.scala.typeutils.Types
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.dataformat.{BaseRow, BinaryString}
import org.apache.flink.table.functions.{AggregateFunction, FunctionContext, ScalarFunction}
import org.apache.flink.types.Row

import com.google.common.base.Charsets
import com.google.common.io.Files

import java.io.File
import java.lang.{Iterable => JIterable}
import java.sql.{Date, Timestamp}
import java.time.{Instant, LocalDate, LocalDateTime, LocalTime}
import java.util
import java.util.TimeZone
import java.util.concurrent.atomic.AtomicInteger

import scala.annotation.varargs

object UserDefinedFunctionTestUtils {

  // ------------------------------------------------------------------------------------
  // AggregateFunctions
  // ------------------------------------------------------------------------------------

  class MyPojoAggFunction extends AggregateFunction[MyPojo, CountAccumulator] {

    def accumulate(acc: CountAccumulator, value: MyPojo): Unit = {
      if (value != null) {
        acc.f0 += value.f2
      }
    }

    def retract(acc: CountAccumulator, value: MyPojo): Unit = {
      if (value != null) {
        acc.f0 -= value.f2
      }
    }

    override def getValue(acc: CountAccumulator): MyPojo = {
      new MyPojo(acc.f0.asInstanceOf[Int], acc.f0.asInstanceOf[Int])
    }

    def merge(acc: CountAccumulator, its: JIterable[CountAccumulator]): Unit = {
      val iter = its.iterator()
      while (iter.hasNext) {
        acc.f0 += iter.next().f0
      }
    }

    override def createAccumulator(): CountAccumulator = {
      new CountAccumulator
    }

    def resetAccumulator(acc: CountAccumulator): Unit = {
      acc.f0 = 0L
    }
  }

  /** The initial accumulator for count aggregate function */
  class CountAccumulator extends Tuple1[Long] {
    f0 = 0L //count
  }

  class VarArgsAggFunction extends AggregateFunction[Long, CountAccumulator] {

    @varargs
    def accumulate(acc: CountAccumulator, value: Long, args: String*): Unit = {
      acc.f0 += value
      args.foreach(s => acc.f0 += s.toLong)
    }

    @varargs
    def retract(acc: CountAccumulator, value: Long, args: String*): Unit = {
      acc.f0 -= value
      args.foreach(s => acc.f0 -= s.toLong)
    }

    override def getValue(acc: CountAccumulator): Long = {
      acc.f0
    }

    def merge(acc: CountAccumulator, its: JIterable[CountAccumulator]): Unit = {
      val iter = its.iterator()
      while (iter.hasNext) {
        acc.f0 += iter.next().f0
      }
    }

    override def createAccumulator(): CountAccumulator = {
      new CountAccumulator
    }

    def resetAccumulator(acc: CountAccumulator): Unit = {
      acc.f0 = 0L
    }
  }

  /** Counts how often the first argument was larger than the second argument. */
  class LargerThanCount extends AggregateFunction[Long, Tuple1[Long]] {

    def accumulate(acc: Tuple1[Long], a: Long, b: Long): Unit = {
      if (a > b) acc.f0 += 1
    }

    def retract(acc: Tuple1[Long], a: Long, b: Long): Unit = {
      if (a > b) acc.f0 -= 1
    }

    override def createAccumulator(): Tuple1[Long] = Tuple1.of(0L)

    override def getValue(acc: Tuple1[Long]): Long = acc.f0
  }

  class CountNullNonNull extends AggregateFunction[String, Tuple2[Long, Long]] {

    override def createAccumulator(): Tuple2[Long, Long] = Tuple2.of(0L, 0L)

    override def getValue(acc: Tuple2[Long, Long]): String = s"${acc.f0}|${acc.f1}"

    def accumulate(acc: Tuple2[Long, Long], v: String): Unit = {
      if (v == null) {
        acc.f1 += 1
      } else {
        acc.f0 += 1
      }
    }

    def retract(acc: Tuple2[Long, Long], v: String): Unit = {
      if (v == null) {
        acc.f1 -= 1
      } else {
        acc.f0 -= 1
      }
    }
  }

  class CountPairs extends AggregateFunction[Long, Tuple1[Long]] {

    def accumulate(acc: Tuple1[Long], a: String, b: String): Unit = {
      acc.f0 += 1
    }

    def retract(acc: Tuple1[Long], a: String, b: String): Unit = {
      acc.f0 -= 1
    }

    override def createAccumulator(): Tuple1[Long] = Tuple1.of(0L)

    override def getValue(acc: Tuple1[Long]): Long = acc.f0
  }

  // ------------------------------------------------------------------------------------
  // ScalarFunctions
  // ------------------------------------------------------------------------------------

  @SerialVersionUID(1L)
  object MyHashCode extends ScalarFunction {
    def eval(s: String): Int = s.hashCode()
  }

  @SerialVersionUID(1L)
  object OldHashCode extends ScalarFunction {
    def eval(s: String): Int = -1
  }

  @SerialVersionUID(1L)
  object StringFunction extends ScalarFunction {
    def eval(s: String): String = s
  }

  @SerialVersionUID(1L)
  object MyStringFunc extends ScalarFunction {
    def eval(s: String): String = s + "haha"
  }

  @SerialVersionUID(1L)
  object BinaryStringFunction extends ScalarFunction {
    def eval(s: BinaryString): BinaryString = s
  }

  @SerialVersionUID(1L)
  object DateFunction extends ScalarFunction {
    def eval(d: Date): String = d.toString
  }

  @SerialVersionUID(1L)
  object LocalDateFunction extends ScalarFunction {
    def eval(d: LocalDate): String = d.toString
  }

  @SerialVersionUID(1L)
  object TimestampFunction extends ScalarFunction {
    def eval(t: java.sql.Timestamp): String = t.toString
  }

  @SerialVersionUID(1L)
  object DateTimeFunction extends ScalarFunction {
    def eval(t: LocalDateTime): String = t.toString
  }

  @SerialVersionUID(1L)
  object TimeFunction extends ScalarFunction {
    def eval(t: java.sql.Time): String = t.toString
  }

  @SerialVersionUID(1L)
  object LocalTimeFunction extends ScalarFunction {
    def eval(t: LocalTime): String = t.toString
  }

  @SerialVersionUID(1L)
  object InstantFunction extends ScalarFunction {
    def eval(t: Instant): Instant = t

    override def getResultType(signature: Array[Class[_]]) = Types.INSTANT
  }

  // Understand type: Row wrapped as TypeInfoWrappedDataType.
  @SerialVersionUID(1L)
  object RowFunc extends ScalarFunction {
    def eval(s: String): Row = Row.of(s)

    override def getResultType(signature: Array[Class[_]]) =
      new RowTypeInfo(Types.STRING)
  }

  @SerialVersionUID(1L)
  object RowToStrFunc extends ScalarFunction {
    def eval(s: BaseRow): String = s.getString(0).toString
  }

  // generic.
  @SerialVersionUID(1L)
  object ListFunc extends ScalarFunction {
    def eval(s: String): java.util.List[String] = util.Arrays.asList(s)

    override def getResultType(signature: Array[Class[_]]) =
      new ListTypeInfo(Types.STRING)
  }

  // internal but wrapped as TypeInfoWrappedDataType.
  @SerialVersionUID(1L)
  object StringFunc extends ScalarFunction {
    def eval(s: String): String = s

    override def getResultType(signature: Array[Class[_]]): TypeInformation[String] =
      Types.STRING
  }

  @SerialVersionUID(1L)
  object MyPojoFunc extends ScalarFunction {
    def eval(s: MyPojo): Int = s.f2

    override def getParameterTypes(signature: Array[Class[_]]): Array[TypeInformation[_]] =
      Array(MyToPojoFunc.getResultType(signature))
  }

  @SerialVersionUID(1L)
  object MyToPojoFunc extends ScalarFunction {
    def eval(s: Int): MyPojo = new MyPojo(s, s)

    override def getResultType(signature: Array[Class[_]]): PojoTypeInfo[MyPojo] = {
      val cls = classOf[MyPojo]
      new PojoTypeInfo[MyPojo](classOf[MyPojo], util.Arrays.asList(
        new PojoField(cls.getDeclaredField("f1"), Types.INT),
        new PojoField(cls.getDeclaredField("f2"), Types.INT)))
    }
  }

  @SerialVersionUID(1L)
  object ToCompositeObj extends ScalarFunction {
    def eval(id: Int, name: String, age: Int): CompositeObj = {
      CompositeObj(id, name, age, "0.0")
    }

    def eval(id: Int, name: String, age: Int, point: String): CompositeObj = {
      CompositeObj(id, name, age, point)
    }
  }

  @SerialVersionUID(1L)
  object TestWrapperUdf extends ScalarFunction {
    def eval(id: Int): Int = {
      id
    }

    def eval(id: String): String = {
      id
    }
  }

  @SerialVersionUID(1L)
  class TestAddWithOpen extends ScalarFunction {

    var isOpened: Boolean = false

    override def open(context: FunctionContext): Unit = {
      super.open(context)
      isOpened = true
      TestAddWithOpen.aliveCounter.incrementAndGet()
    }

    def eval(a: Long, b: Long): Long = {
      if (!isOpened) {
        throw new IllegalStateException("Open method is not called.")
      }
      a + b
    }

    def eval(a: Long, b: Int): Long = {
      eval(a, b.asInstanceOf[Long])
    }

    override def close(): Unit = {
      TestAddWithOpen.aliveCounter.decrementAndGet()
    }
  }

  object TestAddWithOpen {
    /** A thread-safe counter to record how many alive TestAddWithOpen UDFs */
    val aliveCounter = new AtomicInteger(0)
  }

  @SerialVersionUID(1L)
  object TestMod extends ScalarFunction {
    def eval(src: Long, mod: Int): Long = {
      src % mod
    }
  }

  @SerialVersionUID(1L)
  object TestExceptionThrown extends ScalarFunction {
    def eval(src: String): Int = {
      throw new NumberFormatException("Cannot parse this input.")
    }
  }

  @SerialVersionUID(1L)
  class ToMillis extends ScalarFunction {
    def eval(t: Timestamp): Long = {
      t.toInstant.toEpochMilli + TimeZone.getDefault.getOffset(t.toInstant.toEpochMilli)
    }
  }

  @SerialVersionUID(1L)
  object MyNegative extends ScalarFunction {
    def eval(d: java.math.BigDecimal): java.lang.Object = d.negate()

    override def getResultType(signature: Array[Class[_]]): TypeInformation[_] = Types.JAVA_BIG_DEC
  }

  @SerialVersionUID(1L)
  object IsNullUDF extends ScalarFunction {
    def eval(v: Any): Boolean = v == null

    override def getResultType(signature: Array[Class[_]]): TypeInformation[_] = Types.BOOLEAN
  }

  // ------------------------------------------------------------------------------------
  // POJOs
  // ------------------------------------------------------------------------------------

  class MyPojo() {
    var f1: Int = 0
    var f2: Int = 0

    def this(f1: Int, f2: Int) {
      this()
      this.f1 = f1
      this.f2 = f2
    }

    override def equals(other: Any): Boolean = other match {
      case that: MyPojo =>
        (that canEqual this) &&
          f1 == that.f1 &&
          f2 == that.f2
      case _ => false
    }

    def canEqual(other: Any): Boolean = other.isInstanceOf[MyPojo]

    override def toString = s"MyPojo($f1, $f2)"
  }

  case class CompositeObj(id: Int, name: String, age: Int, point: String)

  // ------------------------------------------------------------------------------------
  // Utils
  // ------------------------------------------------------------------------------------

  def setJobParameters(env: ExecutionEnvironment, parameters: Map[String, String]): Unit = {
    val conf = new Configuration()
    parameters.foreach {
      case (k, v) => conf.setString(k, v)
    }
    env.getConfig.setGlobalJobParameters(conf)
  }

  def setJobParameters(env: StreamExecutionEnvironment, parameters: Map[String, String]): Unit = {
    val conf = new Configuration()
    parameters.foreach {
      case (k, v) => conf.setString(k, v)
    }
    env.getConfig.setGlobalJobParameters(conf)
  }

  def setJobParameters(
      env: org.apache.flink.streaming.api.environment.StreamExecutionEnvironment,
      parameters: Map[String, String]): Unit = {
    val conf = new Configuration()
    parameters.foreach {
      case (k, v) => conf.setString(k, v)
    }
    env.getConfig.setGlobalJobParameters(conf)
  }

  def writeCacheFile(fileName: String, contents: String): String = {
    val tempFile = File.createTempFile(this.getClass.getName + "-" + fileName, "tmp")
    tempFile.deleteOnExit()
    Files.write(contents, tempFile, Charsets.UTF_8)
    tempFile.getAbsolutePath
  }
}

class RandomClass(var i: Int)

class GenericAggregateFunction extends AggregateFunction[java.lang.Integer, RandomClass] {
  override def getValue(accumulator: RandomClass): java.lang.Integer = accumulator.i

  override def createAccumulator(): RandomClass = new RandomClass(0)

  override def getResultType: TypeInformation[java.lang.Integer] =
    new GenericTypeInfo[Integer](classOf[Integer])

  override def getAccumulatorType: TypeInformation[RandomClass] = new GenericTypeInfo[RandomClass](
    classOf[RandomClass])

  def accumulate(acc: RandomClass, value: Int): Unit = {
    acc.i = value
  }

  def retract(acc: RandomClass, value: Int): Unit = {
    acc.i = value
  }

  def resetAccumulator(acc: RandomClass): Unit = {
    acc.i = 0
  }
}


text:
package org.projectfloodlight.openflow.protocol.ver13;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFOxmBsnVxlanNetworkIdMaskedVer13 implements OFOxmBsnVxlanNetworkIdMasked {
    private static final Logger logger = LoggerFactory.getLogger(OFOxmBsnVxlanNetworkIdMaskedVer13.class);
    // version: 1.3
    final static byte WIRE_VERSION = 4;
    final static int LENGTH = 12;

        private final static VxlanNI DEFAULT_VALUE = VxlanNI.ZERO;
        private final static VxlanNI DEFAULT_VALUE_MASK = VxlanNI.ZERO;

    // OF message fields
    private final VxlanNI value;
    private final VxlanNI mask;
//
    // Immutable default instance
    final static OFOxmBsnVxlanNetworkIdMaskedVer13 DEFAULT = new OFOxmBsnVxlanNetworkIdMaskedVer13(
        DEFAULT_VALUE, DEFAULT_VALUE_MASK
    );

    // package private constructor - used by readers, builders, and factory
    OFOxmBsnVxlanNetworkIdMaskedVer13(VxlanNI value, VxlanNI mask) {
        if(value == null) {
            throw new NullPointerException("OFOxmBsnVxlanNetworkIdMaskedVer13: property value cannot be null");
        }
        if(mask == null) {
            throw new NullPointerException("OFOxmBsnVxlanNetworkIdMaskedVer13: property mask cannot be null");
        }
        this.value = value;
        this.mask = mask;
    }

    // Accessors for OF message fields
    @Override
    public long getTypeLen() {
        return 0x32b08L;
    }

    @Override
    public VxlanNI getValue() {
        return value;
    }

    @Override
    public VxlanNI getMask() {
        return mask;
    }

    @Override
    public MatchField<VxlanNI> getMatchField() {
        return MatchField.BSN_VXLAN_NETWORK_ID;
    }

    @Override
    public boolean isMasked() {
        return true;
    }

    public OFOxm<VxlanNI> getCanonical() {
        if (VxlanNI.NO_MASK.equals(mask)) {
            return new OFOxmBsnVxlanNetworkIdVer13(value);
        } else if(VxlanNI.FULL_MASK.equals(mask)) {
            return null;
        } else {
            return this;
        }
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_13;
    }

    public OFOxmBsnVxlanNetworkIdMasked.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFOxmBsnVxlanNetworkIdMasked.Builder {
        final OFOxmBsnVxlanNetworkIdMaskedVer13 parentMessage;

        // OF message fields
        private boolean valueSet;
        private VxlanNI value;
        private boolean maskSet;
        private VxlanNI mask;

        BuilderWithParent(OFOxmBsnVxlanNetworkIdMaskedVer13 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public long getTypeLen() {
        return 0x32b08L;
    }

    @Override
    public VxlanNI getValue() {
        return value;
    }

    @Override
    public OFOxmBsnVxlanNetworkIdMasked.Builder setValue(VxlanNI value) {
        this.value = value;
        this.valueSet = true;
        return this;
    }
    @Override
    public VxlanNI getMask() {
        return mask;
    }

    @Override
    public OFOxmBsnVxlanNetworkIdMasked.Builder setMask(VxlanNI mask) {
        this.mask = mask;
        this.maskSet = true;
        return this;
    }
    @Override
    public MatchField<VxlanNI> getMatchField() {
        return MatchField.BSN_VXLAN_NETWORK_ID;
    }

    @Override
    public boolean isMasked() {
        return true;
    }

    @Override
    public OFOxm<VxlanNI> getCanonical()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_13;
    }

        @Override
        public OFOxmBsnVxlanNetworkIdMasked build() {
                VxlanNI value = this.valueSet ? this.value : parentMessage.value;
                if(value == null)
                    throw new NullPointerException("Property value must not be null");
                VxlanNI mask = this.maskSet ? this.mask : parentMessage.mask;
                if(mask == null)
                    throw new NullPointerException("Property mask must not be null");

                //
                return new OFOxmBsnVxlanNetworkIdMaskedVer13(
                    value,
                    mask
                );
        }

    }

    static class Builder implements OFOxmBsnVxlanNetworkIdMasked.Builder {
        // OF message fields
        private boolean valueSet;
        private VxlanNI value;
        private boolean maskSet;
        private VxlanNI mask;

    @Override
    public long getTypeLen() {
        return 0x32b08L;
    }

    @Override
    public VxlanNI getValue() {
        return value;
    }

    @Override
    public OFOxmBsnVxlanNetworkIdMasked.Builder setValue(VxlanNI value) {
        this.value = value;
        this.valueSet = true;
        return this;
    }
    @Override
    public VxlanNI getMask() {
        return mask;
    }

    @Override
    public OFOxmBsnVxlanNetworkIdMasked.Builder setMask(VxlanNI mask) {
        this.mask = mask;
        this.maskSet = true;
        return this;
    }
    @Override
    public MatchField<VxlanNI> getMatchField() {
        return MatchField.BSN_VXLAN_NETWORK_ID;
    }

    @Override
    public boolean isMasked() {
        return true;
    }

    @Override
    public OFOxm<VxlanNI> getCanonical()throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Property canonical not supported in version 1.3");
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_13;
    }

//
        @Override
        public OFOxmBsnVxlanNetworkIdMasked build() {
            VxlanNI value = this.valueSet ? this.value : DEFAULT_VALUE;
            if(value == null)
                throw new NullPointerException("Property value must not be null");
            VxlanNI mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK;
            if(mask == null)
                throw new NullPointerException("Property mask must not be null");

            return new OFOxmBsnVxlanNetworkIdMaskedVer13(
                    value,
                    mask
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFOxmBsnVxlanNetworkIdMasked> {
        @Override
        public OFOxmBsnVxlanNetworkIdMasked readFrom(ByteBuf bb) throws OFParseError {
            // fixed value property typeLen == 0x32b08L
            int typeLen = bb.readInt();
            if(typeLen != 0x32b08)
                throw new OFParseError("Wrong typeLen: Expected=0x32b08L(0x32b08L), got="+typeLen);
            VxlanNI value = VxlanNI.read4Bytes(bb);
            VxlanNI mask = VxlanNI.read4Bytes(bb);

            OFOxmBsnVxlanNetworkIdMaskedVer13 oxmBsnVxlanNetworkIdMaskedVer13 = new OFOxmBsnVxlanNetworkIdMaskedVer13(
                    value,
                      mask
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", oxmBsnVxlanNetworkIdMaskedVer13);
            return oxmBsnVxlanNetworkIdMaskedVer13;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFOxmBsnVxlanNetworkIdMaskedVer13Funnel FUNNEL = new OFOxmBsnVxlanNetworkIdMaskedVer13Funnel();
    static class OFOxmBsnVxlanNetworkIdMaskedVer13Funnel implements Funnel<OFOxmBsnVxlanNetworkIdMaskedVer13> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFOxmBsnVxlanNetworkIdMaskedVer13 message, PrimitiveSink sink) {
            // fixed value property typeLen = 0x32b08L
            sink.putInt(0x32b08);
            message.value.putTo(sink);
            message.mask.putTo(sink);
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFOxmBsnVxlanNetworkIdMaskedVer13> {
        @Override
        public void write(ByteBuf bb, OFOxmBsnVxlanNetworkIdMaskedVer13 message) {
            // fixed value property typeLen = 0x32b08L
            bb.writeInt(0x32b08);
            message.value.write4Bytes(bb);
            message.mask.write4Bytes(bb);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFOxmBsnVxlanNetworkIdMaskedVer13(");
        b.append("value=").append(value);
        b.append(", ");
        b.append("mask=").append(mask);
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFOxmBsnVxlanNetworkIdMaskedVer13 other = (OFOxmBsnVxlanNetworkIdMaskedVer13) obj;

        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        if (mask == null) {
            if (other.mask != null)
                return false;
        } else if (!mask.equals(other.mask))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime * result + ((value == null) ? 0 : value.hashCode());
        result = prime * result + ((mask == null) ? 0 : mask.hashCode());
        return result;
    }

}


text:
class SelectionRectGraphicsWidget : public QGraphicsWidget
{
  Q_OBJECT

public:
  enum RectOp {Add,Remove,Done,UnDone,Explorable,UnExplorable,Safe,UnSafe,Reset};

  SelectionRectGraphicsWidget(QGraphicsItem *parent=0);

  void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0 );

public slots:

  void setOpDone()         {lastop_=op_=Done; update();}
  void setOpUnDone()       {lastop_=op_=UnDone; update();}
  void setOpAdd()          {lastop_=op_=Add; update();}
  void setOpRemove()       {lastop_=op_=Remove; update();}
  void setOpExplorable()   {lastop_=op_=Explorable; update();}
  void setOpUnExplorable() {lastop_=op_=UnExplorable; update();}
  void setOpSafe()         {lastop_=op_=Safe; update();}
  void setOpUnSafe()       {lastop_=op_=UnSafe; update();}
  void setOpUserReset()    {lastop_=op_=Reset; update();}
  void commit();
  void cancel();

signals:
  void addSelectedArea(QPainterPath& path);
  void removeSelectedArea(QPainterPath& path);
  void markSelectedAreaAsDone(QPainterPath& path);
  void markSelectedAreaAsNotDone(QPainterPath& path);
  void markSelectedAreaAsExplorable(QPainterPath& path);
  void markSelectedAreaAsNotExplorable(QPainterPath& path);
  void markSelectedAreaAsSafe(QPainterPath& path);
  void markSelectedAreaAsNotSafe(QPainterPath& path);
  void markSelectedAreaUserReset(QPainterPath& path);

protected:
  virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);

  virtual void focusInEvent(QFocusEvent *event);
  virtual void focusOutEvent(QFocusEvent *event);

private:
  RectOp op_;
  static RectOp lastop_;

  void createActions();

  QColor getPenColor();
  QColor getBaseColor();
};

class StageScene : public QGraphicsScene
{
  Q_OBJECT

public:
  enum Mode {DrawRect, Pick, DoNothing};

  StageScene(QObject *parent=0);

  virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
  virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
  virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

public slots:
  void setMode(Mode mode);

signals:
  void addSelectedArea(QPainterPath& path);
  void removeSelectedArea(QPainterPath& path);
  void markSelectedAreaAsDone(QPainterPath& path);
  void markSelectedAreaAsNotDone(QPainterPath& path);
  void markSelectedAreaAsExplorable(QPainterPath& path);
  void markSelectedAreaAsNotExplorable(QPainterPath& path);
  void markSelectedAreaAsSafe(QPainterPath& path);
  void markSelectedAreaAsNotSafe(QPainterPath& path);
  void markSelectedAreaUserReset(QPainterPath& path);

private:
  QGraphicsWidget *current_item_;
  Mode mode_;

};


text:
package io.jenkins.blueocean.preload;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Item;
import io.jenkins.blueocean.commons.stapler.Export;
import io.jenkins.blueocean.rest.factory.BluePipelineFactory;
import io.jenkins.blueocean.rest.model.BluePipeline;
import jenkins.model.Jenkins;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Preload pipeline onto the page if the requested page is a pipeline page.
 *
 * @author tom.fennelly@gmail.com
 */
@Extension
public class PipelineStatePreloader extends RESTFetchPreloader {

    private static final Logger LOGGER = Logger.getLogger(PipelineStatePreloader.class.getName());

    @Override
    protected FetchData getFetchData(@NonNull BlueUrlTokenizer blueUrl) {
        // e.g. /blue/organizations/jenkins/Pipeline (or a url on that)
        if (!blueUrl.hasPart(BlueUrlTokenizer.UrlPart.PIPELINE)) {
            // Not interested in it
            return null;
        }

        Jenkins jenkins = Jenkins.get();
        String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);

        try {
            Item pipelineJobItem = jenkins.getItemByFullName(pipelineFullName);

            if (pipelineJobItem != null) {
                BluePipeline bluePipeline = (BluePipeline) BluePipelineFactory.resolve(pipelineJobItem);
                if (bluePipeline != null) {
                    try {
                        return new FetchData(bluePipeline.getLink().getHref(), Export.toJson(bluePipeline));
                    } catch (IOException e) {
                        LOGGER.log(Level.FINE, String.format("Unable to preload pipeline '%s'. Serialization error.", pipelineJobItem.getUrl()), e);
                        return null;
                    }
                } else {
                    LOGGER.log(Level.FINE, String.format("Unable to preload pipeline '%s'. Failed to convert to Blue Ocean Resource.", pipelineJobItem.getUrl()));
                    return null;
                }
            }
        } catch (Exception e) {
            LOGGER.log(Level.FINE, String.format("Unable to find pipeline named '%s'.", pipelineFullName), e);
            return null;
        }

        // Don't preload any data on the page.
        return null;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/tmp/tmp-deduplicated6473225542751369835/blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/java/com/google/android/gmscore/integ/client/cast/framework/res/values-sv/cast_strings.xml -->
    <eat-comment/>
    <string msgid="366047012176970604" name="cast_casting_to_device">"Castar till %1$s"</string>
    <string msgid="4431992200264667209" name="cast_disconnect">"Koppla från"</string>
    <string msgid="7884080323096468593" name="cast_forward">"Framåt"</string>
    <string msgid="6424889955881797947" name="cast_forward_10">"Tio sekunder framåt"</string>
    <string msgid="7868672855975238403" name="cast_forward_30">"Trettio sekunder framåt"</string>
    <string msgid="6885943100773268783" name="cast_intro_overlay_button_text">"@android:string/ok"</string>
    <string msgid="5637297909372905371" name="cast_mute">"Stäng av ljudet"</string>
    <string msgid="5308503786390460607" name="cast_pause">"Pausa"</string>
    <string msgid="5906987965619702702" name="cast_play">"Spela upp"</string>
    <string msgid="1739665135565985480" name="cast_rewind">"Spola tillbaka"</string>
    <string msgid="6432793028560778843" name="cast_rewind_10">"Spola tillbaka tio sekunder"</string>
    <string msgid="4677199707225681325" name="cast_rewind_30">"Spola tillbaka trettio sekunder"</string>
    <string msgid="3991548379225047363" name="cast_skip_next">"Hoppa till nästa objekt"</string>
    <string msgid="8369073097776576935" name="cast_skip_prev">"Hoppa till föregående objekt"</string>
    <string msgid="9191388946729723891" name="cast_stop">"Stoppa"</string>
    <string msgid="1219622777438777099" name="cast_stop_live_stream">"Stoppa liveströmningen"</string>
    <string msgid="4250321332248956563" name="cast_tracks_chooser_dialog_audio">"Ljud"</string>
    <string msgid="1162380934229249476" name="cast_tracks_chooser_dialog_cancel">"Avbryt"</string>
    <string msgid="5563446400083425854" name="cast_tracks_chooser_dialog_no_audio_tracks">"Det finns inga ljudspår"</string>
    <string msgid="7413336699113748535" name="cast_tracks_chooser_dialog_no_text_tracks">"Det finns inga textspår"</string>
    <string msgid="2332432312191219516" name="cast_tracks_chooser_dialog_no_tracks_available">"Det finns inga spår"</string>
    <string msgid="1176688358580178396" name="cast_tracks_chooser_dialog_none">"Inga"</string>
    <string msgid="3804878371876790270" name="cast_tracks_chooser_dialog_ok">"Ok"</string>
    <string msgid="2454147715032376208" name="cast_tracks_chooser_dialog_subtitles">"Undertexter"</string>
    <string msgid="2913461521603516868" name="cast_unmute">"Slå på ljudet"</string>
</resources>


text:
<?php

interface f_valid_interface
{

    public function isValid($mValue);

}


text:
const { exec } = require('shelljs')
const { resolve } = require('path')
// ./node_modules/.bin/cross-env NODE_ENV=production ./node_modules/.bin/webpack --progress --config build/webpack.config.js"
const webpack = resolve(
  __dirname, '../node_modules/.bin/webpack'
)
const crossEnv = resolve(
  __dirname, '../node_modules/.bin/cross-env'
)
const conf = resolve(
  __dirname,
  '../build/webpack.config.js'
)
exec(`${crossEnv} NODE_ENV=production ${webpack} --progress --config ${conf}`)


text:
package com.popov.sqa.model;

public class Contact {
   public String firstname;
   public String lastname;
   public String address;
   public String homeNumber;
   public String email;

   public Contact(String firstname, String lastname, String address, String homeNumber, String email){
      this.firstname=firstname;
      this.lastname=lastname;
      this.address=address;
      this.homeNumber=homeNumber;
      this.email=email;
   }
}


text:
""" REST API Module """

import pytest

import ml_api.db as db

from pymongo import MongoClient

@pytest.fixture(scope="module")
def data_base(request):
    con = db.DatabaseConnector()
    yield con
    print ("Finalizing %s" % con)

@pytest.fixture(scope="function")
def client(request):
    client = MongoClient()
    yield client
    print ("Finalizing %s" % client)

@pytest.fixture(scope="function")
def item(request):
    con = db.DatabaseConnector()
    con.set_db("test")
    con.set_collection("test_collection")
    item = con.insert_item({"value": 12345})
    yield (item, con)
    print ("Finalizing %s and %s" % (item, con))

@pytest.fixture(scope="function")
def items(request):
    con = db.DatabaseConnector()
    con.set_db("test")
    con.set_collection("test_collection")
    yield con
    print ("Finalizing %s" % con)

# content of test_class.py
class TestDataBaseModule(object):
    """ Class used to test ML REST API """

    def test_connector_class(self, data_base):
        assert isinstance(data_base, type(db.DatabaseConnector()))

    def test_active_connection(self, client):
        inst = db.DatabaseConnector(conn=client)
        assert inst.client == client

    def test_database_set_get(self, data_base):
        data_base.set_db("Tox")
        db = data_base.get_db()
        assert db.name == "Tox"

    def test_none_database(self, data_base):
        data_base.db = None
        db = data_base.get_db()
        assert db == None

    def test_collection_set_get(self, data_base):
        data_base.set_db("test_database")
        data_base.set_collection("documents")
        col = data_base.get_collection()
        assert col.name == "documents"

    def test_none_collection(self, data_base):
        data_base.collection = None
        col = data_base.get_collection()
        assert col == None

    def test_get_item(self, data_base):
        data_base.set_db("test_database")
        data_base.set_collection("documents")
        item = data_base.get_item()
        assert item is not None

    def test_get_item_by_id(self, item):
        id_ = item[0]
        db = item[1]
        item = db.get_item(id_)
        assert item is not None

    def test_get_all(self, item):
        result = item[1].get_all_items()
        assert len(result) > 0

    def test_get_item_none(self, data_base):
        data_base.collection = None
        item = data_base.get_item()
        assert item == None

    def test_error_insert(self, data_base):
        assert data_base.insert_item("aaaaa") is None

    def test_bulk_insert(self, items):
        vals = items.bulk_insert_items([{"value": 12345}, {"value": 67890}, {"value": 54321}])
        assert len(vals) > 0

    def test_bulk_insert_error(self, data_base):
        assert data_base.bulk_insert_items("aaaaa") is None

    def test_delete_by_id(self, item):
        id_ = item[0]
        con = item[1]
        result = con.delete_by_id(id_)
        assert result > 0

    def test_delete_by_id_error(self, item):
        id_ = item[0]
        con = item[1]
        result = con.delete_by_id("aaaaa")
        assert result is None

    def test_conn_close(self, data_base):
        data_base.close_connection()


text:
package com.haulmont.cuba.gui.xml.layout.loaders;

import com.haulmont.cuba.gui.components.RadioButtonGroup;

public class RadioButtonGroupLoader extends AbstractOptionsBaseLoader<RadioButtonGroup> {

    @Override
    public void createComponent() {
        resultComponent = factory.create(RadioButtonGroup.NAME);
        loadId(resultComponent, element);
    }

    @Override
    public void loadComponent() {
        super.loadComponent();

        loadOrientation(resultComponent, element);
        loadCaptionProperty(resultComponent, element);

        loadOptionsEnum(resultComponent, element);
        loadTabIndex(resultComponent, element);
    }
}


text:
[![Build Status](https://api.travis-ci.org/markrwilliams/txdarn.svg?branch=master)](https://travis-ci.org/markrwilliams/txdarn)
[![Coverage Status](https://codecov.io/github/markrwilliams/txdarn/coverage.svg?branch=master)](https://codecov.io/github/markrwilliams/txdarn)

### SockJS for modern Twisted

#### What is it?
`txdarn` is a [SockJS](http://sockjs.org) [0.3.4](https://github.com/sockjs/sockjs-client) library for Twisted.  It runs on Python 2 and 3 and aims for a simple API.  **This is a work in progress!  Stay tuned for more features and documentation.**

#### How do I use it?

Create a `Protocol` and `Factory`, determine your options and create a `TxDarn` instance:

````python
from twisted.internet import protocol, endpoints, reactor
from twisted.web import server
from txdarn.resources import TxDarn

class SimpleProtocol(protocol.Protocol):

    def dataReceived(self, data):
        self.transport.write(["Here's what you said: {}'".format(data)])

SOCKJS_URL = ('https://cdnjs.cloudflare.com'
              '/ajax/libs/sockjs-client/1.0.3/sockjs.js')

txdarnResource = TxDarn(protocol.Factory.forPortocol(SimpleProtocol),
                        sockJSURL=SOCKJS_URL)
site = server.Site(txdarnResource)
endpoints.serverFromString(reactor, 'tcp:8080').listen(site)
reactor.run()
````


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

namespace GrottoPress\Jentil\Setups\Views;

use GrottoPress\Jentil\Setups\AbstractSetup;

final class Author extends AbstractSetup
{
    public function run()
    {
        \add_action('jentil_before_title', [$this, 'renderAvatar']);
    }

    /**
     * @action jentil_before_title
     */
    public function renderAvatar()
    {
        if (!$this->app->utilities->page->is('author')) {
            return;
        }

        echo \get_avatar(\get_query_var('author'), 60);
    }
}


text:
/*

@deftypefn Extension {const char*} make_relative_prefix (const char *@var{progname}, const char *@var{bin_prefix}, const char *@var{prefix})

Given three paths @var{progname}, @var{bin_prefix}, @var{prefix},
return the path that is in the same position relative to
@var{progname}'s directory as @var{prefix} is relative to
@var{bin_prefix}.  That is, a string starting with the directory
portion of @var{progname}, followed by a relative pathname of the
difference between @var{bin_prefix} and @var{prefix}.

If @var{progname} does not contain any directory separators,
@code{make_relative_prefix} will search @env{PATH} to find a program
named @var{progname}.  Also, if @var{progname} is a symbolic link,
the symbolic link will be resolved.

For example, if @var{bin_prefix} is @code{/alpha/beta/gamma/gcc/delta},
@var{prefix} is @code{/alpha/beta/gamma/omega/}, and @var{progname} is
@code{/red/green/blue/gcc}, then this function will return
@code{/red/green/blue/../../omega/}.

The return value is normally allocated via @code{malloc}.  If no
relative prefix can be found, return @code{NULL}.

@end deftypefn

*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <string.h>

#include "ansidecl.h"
#include "libiberty.h"

#ifndef R_OK
#define R_OK 4
#define W_OK 2
#define X_OK 1
#endif

#ifndef DIR_SEPARATOR
#  define DIR_SEPARATOR '/'
#endif

#if defined (_WIN32) || defined (__MSDOS__) \
    || defined (__DJGPP__) || defined (__OS2__)
#  define HAVE_DOS_BASED_FILE_SYSTEM
#  define HAVE_HOST_EXECUTABLE_SUFFIX
#  define HOST_EXECUTABLE_SUFFIX ".exe"
#  ifndef DIR_SEPARATOR_2
#    define DIR_SEPARATOR_2 '\\'
#  endif
#  define PATH_SEPARATOR ';'
#else
#  define PATH_SEPARATOR ':'
#endif

#ifndef DIR_SEPARATOR_2
#  define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
#else
#  define IS_DIR_SEPARATOR(ch) \
	(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
#endif

#define DIR_UP ".."

static char *save_string (const char *, int);
static char **split_directories	(const char *, int *);
static void free_split_directories (char **);

static char *
save_string (const char *s, int len)
{
  char *result = (char *) malloc (len + 1);

  memcpy (result, s, len);
  result[len] = 0;
  return result;
}

/* Split a filename into component directories.  */

static char **
split_directories (const char *name, int *ptr_num_dirs)
{
  int num_dirs = 0;
  char **dirs;
  const char *p, *q;
  int ch;

  /* Count the number of directories.  Special case MSDOS disk names as part
     of the initial directory.  */
  p = name;
#ifdef HAVE_DOS_BASED_FILE_SYSTEM
  if (name[1] == ':' && IS_DIR_SEPARATOR (name[2]))
    {
      p += 3;
      num_dirs++;
    }
#endif /* HAVE_DOS_BASED_FILE_SYSTEM */

  while ((ch = *p++) != '\0')
    {
      if (IS_DIR_SEPARATOR (ch))
	{
	  num_dirs++;
	  while (IS_DIR_SEPARATOR (*p))
	    p++;
	}
    }

  dirs = (char **) malloc (sizeof (char *) * (num_dirs + 2));
  if (dirs == NULL)
    return NULL;

  /* Now copy the directory parts.  */
  num_dirs = 0;
  p = name;
#ifdef HAVE_DOS_BASED_FILE_SYSTEM
  if (name[1] == ':' && IS_DIR_SEPARATOR (name[2]))
    {
      dirs[num_dirs++] = save_string (p, 3);
      if (dirs[num_dirs - 1] == NULL)
	{
	  free (dirs);
	  return NULL;
	}
      p += 3;
    }
#endif /* HAVE_DOS_BASED_FILE_SYSTEM */

  q = p;
  while ((ch = *p++) != '\0')
    {
      if (IS_DIR_SEPARATOR (ch))
	{
	  while (IS_DIR_SEPARATOR (*p))
	    p++;

	  dirs[num_dirs++] = save_string (q, p - q);
	  if (dirs[num_dirs - 1] == NULL)
	    {
	      dirs[num_dirs] = NULL;
	      free_split_directories (dirs);
	      return NULL;
	    }
	  q = p;
	}
    }

  if (p - 1 - q > 0)
    dirs[num_dirs++] = save_string (q, p - 1 - q);
  dirs[num_dirs] = NULL;

  if (dirs[num_dirs - 1] == NULL)
    {
      free_split_directories (dirs);
      return NULL;
    }

  if (ptr_num_dirs)
    *ptr_num_dirs = num_dirs;
  return dirs;
}

/* Release storage held by split directories.  */

static void
free_split_directories (char **dirs)
{
  int i = 0;

  if (dirs != NULL)
    {
      while (dirs[i] != NULL)
	free (dirs[i++]);

      free ((char *) dirs);
    }
}

/* Given three strings PROGNAME, BIN_PREFIX, PREFIX, return a string that gets
   to PREFIX starting with the directory portion of PROGNAME and a relative
   pathname of the difference between BIN_PREFIX and PREFIX.

   For example, if BIN_PREFIX is /alpha/beta/gamma/gcc/delta, PREFIX is
   /alpha/beta/gamma/omega/, and PROGNAME is /red/green/blue/gcc, then this
   function will return /red/green/blue/../../omega/.

   If no relative prefix can be found, return NULL.  */

static char *
make_relative_prefix_1 (const char *progname, const char *bin_prefix,
			const char *prefix, const int resolve_links)
{
  char **prog_dirs = NULL, **bin_dirs = NULL, **prefix_dirs = NULL;
  int prog_num, bin_num, prefix_num;
  int i, n, common;
  int needed_len;
  char *ret = NULL, *ptr, *full_progname;

  if (progname == NULL || bin_prefix == NULL || prefix == NULL)
    return NULL;

  /* If there is no full pathname, try to find the program by checking in each
     of the directories specified in the PATH environment variable.  */
  if (lbasename (progname) == progname)
    {
      char *temp;

      temp = getenv ("PATH");
      if (temp)
	{
	  char *startp, *endp, *nstore;
	  size_t prefixlen = strlen (temp) + 1;
	  if (prefixlen < 2)
	    prefixlen = 2;

	  nstore = (char *) alloca (prefixlen + strlen (progname) + 1);

	  startp = endp = temp;
	  while (1)
	    {
	      if (*endp == PATH_SEPARATOR || *endp == 0)
		{
		  if (endp == startp)
		    {
		      nstore[0] = '.';
		      nstore[1] = DIR_SEPARATOR;
		      nstore[2] = '\0';
		    }
		  else
		    {
		      strncpy (nstore, startp, endp - startp);
		      if (! IS_DIR_SEPARATOR (endp[-1]))
			{
			  nstore[endp - startp] = DIR_SEPARATOR;
			  nstore[endp - startp + 1] = 0;
			}
		      else
			nstore[endp - startp] = 0;
		    }
		  strcat (nstore, progname);
		  if (! access (nstore, X_OK)
#ifdef HAVE_HOST_EXECUTABLE_SUFFIX
                      || ! access (strcat (nstore, HOST_EXECUTABLE_SUFFIX), X_OK)
#endif
		      )
		    {
		      progname = nstore;
		      break;
		    }

		  if (*endp == 0)
		    break;
		  endp = startp = endp + 1;
		}
	      else
		endp++;
	    }
	}
    }

  if (resolve_links)
    full_progname = lrealpath (progname);
  else
    full_progname = strdup (progname);
  if (full_progname == NULL)
    return NULL;

  prog_dirs = split_directories (full_progname, &prog_num);
  free (full_progname);
  if (prog_dirs == NULL)
    return NULL;

  bin_dirs = split_directories (bin_prefix, &bin_num);
  if (bin_dirs == NULL)
    goto bailout;

  /* Remove the program name from comparison of directory names.  */
  prog_num--;

  /* If we are still installed in the standard location, we don't need to
     specify relative directories.  Also, if argv[0] still doesn't contain
     any directory specifiers after the search above, then there is not much
     we can do.  */
  if (prog_num == bin_num)
    {
      for (i = 0; i < bin_num; i++)
	{
	  if (strcmp (prog_dirs[i], bin_dirs[i]) != 0)
	    break;
	}

      if (prog_num <= 0 || i == bin_num)
	goto bailout;
    }

  prefix_dirs = split_directories (prefix, &prefix_num);
  if (prefix_dirs == NULL)
    goto bailout;

  /* Find how many directories are in common between bin_prefix & prefix.  */
  n = (prefix_num < bin_num) ? prefix_num : bin_num;
  for (common = 0; common < n; common++)
    {
      if (strcmp (bin_dirs[common], prefix_dirs[common]) != 0)
	break;
    }

  /* If there are no common directories, there can be no relative prefix.  */
  if (common == 0)
    goto bailout;

  /* Two passes: first figure out the size of the result string, and
     then construct it.  */
  needed_len = 0;
  for (i = 0; i < prog_num; i++)
    needed_len += strlen (prog_dirs[i]);
  needed_len += sizeof (DIR_UP) * (bin_num - common);
  for (i = common; i < prefix_num; i++)
    needed_len += strlen (prefix_dirs[i]);
  needed_len += 1; /* Trailing NUL.  */

  ret = (char *) malloc (needed_len);
  if (ret == NULL)
    goto bailout;

  /* Build up the pathnames in argv[0].  */
  *ret = '\0';
  for (i = 0; i < prog_num; i++)
    strcat (ret, prog_dirs[i]);

  /* Now build up the ..'s.  */
  ptr = ret + strlen(ret);
  for (i = common; i < bin_num; i++)
    {
      strcpy (ptr, DIR_UP);
      ptr += sizeof (DIR_UP) - 1;
      *(ptr++) = DIR_SEPARATOR;
    }
  *ptr = '\0';

  /* Put in directories to move over to prefix.  */
  for (i = common; i < prefix_num; i++)
    strcat (ret, prefix_dirs[i]);

 bailout:
  free_split_directories (prog_dirs);
  free_split_directories (bin_dirs);
  free_split_directories (prefix_dirs);

  return ret;
}

/* Do the full job, including symlink resolution.
   This path will find files installed in the same place as the
   program even when a soft link has been made to the program
   from somwhere else. */

char *
make_relative_prefix (const char *progname, const char *bin_prefix,
		      const char *prefix)
{
  return make_relative_prefix_1 (progname, bin_prefix, prefix, 1);
}

/* Make the relative pathname without attempting to resolve any links.
   '..' etc may also be left in the pathname.
   This will find the files the user meant the program to find if the
   installation is patched together with soft links. */

char *
make_relative_prefix_ignore_links (const char *progname,
				   const char *bin_prefix,
				   const char *prefix)
{
  return make_relative_prefix_1 (progname, bin_prefix, prefix, 0);
}


text:
#include "config.h"

#include <unistd.h>

#include "logging.h"
#include "miner.h"

bool opt_debug = false;
bool opt_log_output = false;

/* per default priorities higher than LOG_NOTICE are logged */
int opt_log_level = LOG_NOTICE;

static void my_log_curses(int prio, const char *datetime, const char *str, bool force)
{
	if (opt_quiet && prio != LOG_ERR)
		return;

	/* Mutex could be locked by dead thread on shutdown so forcelog will
	 * invalidate any console lock status. */
	if (force) {
		mutex_trylock(&console_lock);
		mutex_unlock(&console_lock);
	}
#ifdef HAVE_CURSES
	extern bool use_curses;
	if (use_curses && log_curses_only(prio, datetime, str))
		;
	else
#endif
	{
		mutex_lock(&console_lock);
		printf("%s%s%s", datetime, str, "                    \n");
		mutex_unlock(&console_lock);
	}
}

/* high-level logging function, based on global opt_log_level */

/*
 * log function
 */
void _applog(int prio, const char *str, bool force)
{
#ifdef HAVE_SYSLOG_H
	if (use_syslog) {
		syslog(LOG_LOCAL0 | prio, "%s", str);
	}
#else
	if (0) {}
#endif
	else {
		char datetime[64];
		struct timeval tv = {0, 0};
		struct tm *tm;

		cgtime(&tv);

		const time_t tmp_time = tv.tv_sec;
		int ms = (int)(tv.tv_usec / 1000);
		tm = localtime(&tmp_time);

		snprintf(datetime, sizeof(datetime), " [%d-%02d-%02d %02d:%02d:%02d.%03d] ",
			tm->tm_year + 1900,
			tm->tm_mon + 1,
			tm->tm_mday,
			tm->tm_hour,
			tm->tm_min,
			tm->tm_sec, ms);

		/* Only output to stderr if it's not going to the screen as well */
		if (!isatty(fileno((FILE *)stderr))) {
			fprintf(stderr, "%s%s\n", datetime, str);	/* atomic write to stderr */
			fflush(stderr);
		}

		my_log_curses(prio, datetime, str, force);
	}
}

void _simplelog(int prio, const char *str, bool force)
{
#ifdef HAVE_SYSLOG_H
	if (use_syslog) {
		syslog(LOG_LOCAL0 | prio, "%s", str);
	}
#else
	if (0) {}
#endif
	else {
		/* Only output to stderr if it's not going to the screen as well */
		if (!isatty(fileno((FILE *)stderr))) {
			fprintf(stderr, "%s\n", str);	/* atomic write to stderr */
			fflush(stderr);
		}

		my_log_curses(prio, "", str, force);
	}
}


text:
Buyers

				Posted on

				by

    	No Buyers yet, why don't you create one?


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="emailConfirm_subject">Stadfest lichess.org-kontoen din, %s</string>
  <string name="emailConfirm_click" comment="emailConfirm_click

Part of the confirmation email upon registering for a Lichess account.

The unique reset link is presented just after this string.">Trykk på lenkja for å aktivere Lichess-kontoen:</string>
  <string name="emailConfirm_ignore">Om du ikkje har registrert deg på Lichess, kan du trygt sjå bort frå denne meldinga.</string>
  <string name="passwordReset_subject">Attendestill lichess.org-passordet ditt, %s</string>
  <string name="passwordReset_intro">Me har mottatt ein førespurnad om å attendestilla passordet for kontoen din.</string>
  <string name="passwordReset_clickOrIgnore">Klikk på lenka nedanfor om det er du som står bak denne førespurnaden. Sjå bort frå denne e-posten om det ikkje var du.</string>
  <string name="emailChange_subject">Stadfest ny e-postadresse, %s</string>
  <string name="emailChange_intro">Du har bede om å få endra e-postadressen din.</string>
  <string name="emailChange_click">Klikk på lenka nedanfor for å stadfeste at du har tilgang til denne e-posten:</string>
  <string name="welcome_subject">Velkomen til lichess.org, %s</string>
  <string name="welcome_text">Du har oppretta ein konto hos https://lichess.org.

Her finn du profilsida di: %1$s. Du kan tilpasse den på %2$s.

Ha det kjekt, og må brikkene dine alltid finne vegen til motspelarens konge!</string>
  <string name="logInToLichess">Logg inn på lichess.org, %s</string>
  <string name="common_orPaste">(Fungerar det ikkje å klikke? Prøv å lime den inn i nettlesaren!)</string>
  <string name="common_note">Dette er ein service-e-post i samband med bruken din av %s.</string>
  <string name="common_contact">Bruk %s om du vil ta kontakt med oss.</string>
</resources>


text:
"""FFI APIs for tvm.tir.usmp.analysis"""
import tvm._ffi

tvm._ffi._init_api("tir.usmp.analysis", __name__)


text:
package org.apache.lucene.util.automaton;

import java.util.*;

import org.apache.lucene.util.*;
import org.apache.lucene.util.fst.Util;

import com.carrotsearch.randomizedtesting.generators.RandomInts;

import static org.apache.lucene.util.automaton.Operations.DEFAULT_MAX_DETERMINIZED_STATES;

public class TestOperations extends LuceneTestCase {
  /** Test string union. */
  public void testStringUnion() {
    List<BytesRef> strings = new ArrayList<>();
    for (int i = RandomInts.randomIntBetween(random(), 0, 1000); --i >= 0;) {
      strings.add(new BytesRef(TestUtil.randomUnicodeString(random())));
    }

    Collections.sort(strings);
    Automaton union = Automata.makeStringUnion(strings);
    assertTrue(union.isDeterministic());
    assertFalse(Operations.hasDeadStatesFromInitial(union));

    Automaton naiveUnion = naiveUnion(strings);
    assertTrue(naiveUnion.isDeterministic());
    assertFalse(Operations.hasDeadStatesFromInitial(naiveUnion));

    assertTrue(Operations.sameLanguage(union, naiveUnion));
  }

  private static Automaton naiveUnion(List<BytesRef> strings) {
    Automaton[] eachIndividual = new Automaton[strings.size()];
    int i = 0;
    for (BytesRef bref : strings) {
      eachIndividual[i++] = Automata.makeString(bref.utf8ToString());
    }
    return Operations.determinize(Operations.union(Arrays.asList(eachIndividual)),
      DEFAULT_MAX_DETERMINIZED_STATES);
  }

  /** Test concatenation with empty language returns empty */
  public void testEmptyLanguageConcatenate() {
    Automaton a = Automata.makeString("a");
    Automaton concat = Operations.concatenate(a, Automata.makeEmpty());
    assertTrue(Operations.isEmpty(concat));
  }

  /** Test optimization to concatenate() with empty String to an NFA */
  public void testEmptySingletonNFAConcatenate() {
    Automaton singleton = Automata.makeString("");
    Automaton expandedSingleton = singleton;
    // an NFA (two transitions for 't' from initial state)
    Automaton nfa = Operations.union(Automata.makeString("this"),
        Automata.makeString("three"));
    Automaton concat1 = Operations.concatenate(expandedSingleton, nfa);
    Automaton concat2 = Operations.concatenate(singleton, nfa);
    assertFalse(concat2.isDeterministic());
    assertTrue(Operations.sameLanguage(Operations.determinize(concat1, 100),
                                       Operations.determinize(concat2, 100)));
    assertTrue(Operations.sameLanguage(Operations.determinize(nfa, 100),
                                       Operations.determinize(concat1, 100)));
    assertTrue(Operations.sameLanguage(Operations.determinize(nfa, 100),
                                       Operations.determinize(concat2, 100)));
  }

  public void testGetRandomAcceptedString() throws Throwable {
    final int ITER1 = atLeast(100);
    final int ITER2 = atLeast(100);
    for(int i=0;i<ITER1;i++) {

      final RegExp re = new RegExp(AutomatonTestUtil.randomRegexp(random()), RegExp.NONE);
      //System.out.println("TEST i=" + i + " re=" + re);
      final Automaton a = Operations.determinize(re.toAutomaton(), DEFAULT_MAX_DETERMINIZED_STATES);
      assertFalse(Operations.isEmpty(a));

      final AutomatonTestUtil.RandomAcceptedStrings rx = new AutomatonTestUtil.RandomAcceptedStrings(a);
      for(int j=0;j<ITER2;j++) {
        //System.out.println("TEST: j=" + j);
        int[] acc = null;
        try {
          acc = rx.getRandomAcceptedString(random());
          final String s = UnicodeUtil.newString(acc, 0, acc.length);
          //a.writeDot("adot");
          assertTrue(Operations.run(a, s));
        } catch (Throwable t) {
          System.out.println("regexp: " + re);
          if (acc != null) {
            System.out.println("fail acc re=" + re + " count=" + acc.length);
            for(int k=0;k<acc.length;k++) {
              System.out.println("  " + Integer.toHexString(acc[k]));
            }
          }
          throw t;
        }
      }
    }
  }
  /**
   * tests against the original brics implementation.
   */
  public void testIsFinite() {
    int num = atLeast(200);
    for (int i = 0; i < num; i++) {
      Automaton a = AutomatonTestUtil.randomAutomaton(random());
      assertEquals(AutomatonTestUtil.isFiniteSlow(a), Operations.isFinite(a));
    }
  }

  /** Pass false for testRecursive if the expected strings
   *  may be too long */
  private Set<IntsRef> getFiniteStrings(Automaton a, int limit, boolean testRecursive) {
    Set<IntsRef> result = Operations.getFiniteStrings(a, limit);
    if (testRecursive) {
      assertEquals(AutomatonTestUtil.getFiniteStringsRecursive(a, limit), result);
    }
    return result;
  }

  /**
   * Basic test for getFiniteStrings
   */
  public void testFiniteStringsBasic() {
    Automaton a = Operations.union(Automata.makeString("dog"), Automata.makeString("duck"));
    a = MinimizationOperations.minimize(a, DEFAULT_MAX_DETERMINIZED_STATES);
    Set<IntsRef> strings = getFiniteStrings(a, -1, true);
    assertEquals(2, strings.size());
    IntsRefBuilder dog = new IntsRefBuilder();
    Util.toIntsRef(new BytesRef("dog"), dog);
    assertTrue(strings.contains(dog.get()));
    IntsRefBuilder duck = new IntsRefBuilder();
    Util.toIntsRef(new BytesRef("duck"), duck);
    assertTrue(strings.contains(duck.get()));
  }

  public void testFiniteStringsEatsStack() {
    char[] chars = new char[50000];
    TestUtil.randomFixedLengthUnicodeString(random(), chars, 0, chars.length);
    String bigString1 = new String(chars);
    TestUtil.randomFixedLengthUnicodeString(random(), chars, 0, chars.length);
    String bigString2 = new String(chars);
    Automaton a = Operations.union(Automata.makeString(bigString1), Automata.makeString(bigString2));
    Set<IntsRef> strings = getFiniteStrings(a, -1, false);
    assertEquals(2, strings.size());
    IntsRefBuilder scratch = new IntsRefBuilder();
    Util.toUTF32(bigString1.toCharArray(), 0, bigString1.length(), scratch);
    assertTrue(strings.contains(scratch.get()));
    Util.toUTF32(bigString2.toCharArray(), 0, bigString2.length(), scratch);
    assertTrue(strings.contains(scratch.get()));
  }

  public void testRandomFiniteStrings1() {

    int numStrings = atLeast(100);
    if (VERBOSE) {
      System.out.println("TEST: numStrings=" + numStrings);
    }

    Set<IntsRef> strings = new HashSet<IntsRef>();
    List<Automaton> automata = new ArrayList<>();
    IntsRefBuilder scratch = new IntsRefBuilder();
    for(int i=0;i<numStrings;i++) {
      String s = TestUtil.randomSimpleString(random(), 1, 200);
      automata.add(Automata.makeString(s));
      Util.toUTF32(s.toCharArray(), 0, s.length(), scratch);
      strings.add(scratch.toIntsRef());
      if (VERBOSE) {
        System.out.println("  add string=" + s);
      }
    }

    // TODO: we could sometimes use
    // DaciukMihovAutomatonBuilder here

    // TODO: what other random things can we do here...
    Automaton a = Operations.union(automata);
    if (random().nextBoolean()) {
      a = MinimizationOperations.minimize(a, 1000000);
      if (VERBOSE) {
        System.out.println("TEST: a.minimize numStates=" + a.getNumStates());
      }
    } else if (random().nextBoolean()) {
      if (VERBOSE) {
        System.out.println("TEST: a.determinize");
      }
      a = Operations.determinize(a, 1000000);
    } else if (random().nextBoolean()) {
      if (VERBOSE) {
        System.out.println("TEST: a.removeDeadStates");
      }
      a = Operations.removeDeadStates(a);
    }

    Set<IntsRef> actual = getFiniteStrings(a, -1, true);
    if (strings.equals(actual) == false) {
      System.out.println("strings.size()=" + strings.size() + " actual.size=" + actual.size());
      List<IntsRef> x = new ArrayList<>(strings);
      Collections.sort(x);
      List<IntsRef> y = new ArrayList<>(actual);
      Collections.sort(y);
      int end = Math.min(x.size(), y.size());
      for(int i=0;i<end;i++) {
        System.out.println("  i=" + i + " string=" + toString(x.get(i)) + " actual=" + toString(y.get(i)));
      }
      fail("wrong strings found");
    }
  }

  // ascii only!
  private static String toString(IntsRef ints) {
    BytesRef br = new BytesRef(ints.length);
    for(int i=0;i<ints.length;i++) {
      br.bytes[i] = (byte) ints.ints[i];
    }
    br.length = ints.length;
    return br.utf8ToString();
  }

  public void testWithCycle() throws Exception {
    try {
      Operations.getFiniteStrings(new RegExp("abc.*", RegExp.NONE).toAutomaton(), -1);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
  }

  public void testRandomFiniteStrings2() {
    // Just makes sure we can run on any random finite
    // automaton:
    int iters = atLeast(100);
    for(int i=0;i<iters;i++) {
      Automaton a = AutomatonTestUtil.randomAutomaton(random());
      try {
        // Must pass a limit because the random automaton
        // can accept MANY strings:
        Operations.getFiniteStrings(a, TestUtil.nextInt(random(), 1, 1000));
        // NOTE: cannot do this, because the method is not
        // guaranteed to detect cycles when you have a limit
        //assertTrue(Operations.isFinite(a));
      } catch (IllegalArgumentException iae) {
        assertFalse(Operations.isFinite(a));
      }
    }
  }

  public void testInvalidLimit() {
    Automaton a = AutomatonTestUtil.randomAutomaton(random());
    try {
      Operations.getFiniteStrings(a, -7);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
  }

  public void testInvalidLimit2() {
    Automaton a = AutomatonTestUtil.randomAutomaton(random());
    try {
      Operations.getFiniteStrings(a, 0);
      fail("did not hit exception");
    } catch (IllegalArgumentException iae) {
      // expected
    }
  }

  public void testSingletonNoLimit() {
    Set<IntsRef> result = Operations.getFiniteStrings(Automata.makeString("foobar"), -1);
    assertEquals(1, result.size());
    IntsRefBuilder scratch = new IntsRefBuilder();
    Util.toUTF32("foobar".toCharArray(), 0, 6, scratch);
    assertTrue(result.contains(scratch.get()));
  }

  public void testSingletonLimit1() {
    Set<IntsRef> result = Operations.getFiniteStrings(Automata.makeString("foobar"), 1);
    assertEquals(1, result.size());
    IntsRefBuilder scratch = new IntsRefBuilder();
    Util.toUTF32("foobar".toCharArray(), 0, 6, scratch);
    assertTrue(result.contains(scratch.get()));
  }
}


text:
<?php

namespace PharIo\Version;

class ExactVersionConstraint extends AbstractVersionConstraint {
    /**
     * @param Version $version
     *
     * @return bool
     */
    public function complies(Version $version) {
        return $this->asString() == $version->getVersionString();
    }
}


text:
function showLoadingMessage(message, icon, position)
{
	if (icon === undefined) {
		icon = 'glyphicon-off';
	}

	if (position === undefined) {
		position = 'left';
	}

	var iconClass = icon;
	if (icon.substring(0, 3) == 'mdi') {
		iconClass = 'mdi ' + icon;
	} else if (icon.substring(0, 9) == 'glyphicon') {
		iconClass = 'glyphicon ' + icon;
	}

	var iconLeft = '';
	var iconRight = '';

	if (position === 'left') {
		iconLeft = '';
	} else if (position === 'right') {
		iconRight = '';
	}

	var tpl = '' + iconLeft + '%text%' + iconRight + '';

	jQuery.isLoading({
		'text': message,
		'class': iconClass,
		'tpl': tpl
	})
}

function hideLoadingMessage()
{
	jQuery.isLoading('hide');
}


text:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router';

import { ICustomer } from '../shared/interfaces';
import { DataService } from '../shared/services/data.service';
import { CapitalizePipe } from '../shared/pipes/capitalize.pipe';

@Component({
  moduleId: module.id,
  selector: 'customer-details',
  templateUrl: 'customerDetails.component.html',
  directives: [ ROUTER_DIRECTIVES ],
  pipes: [ CapitalizePipe ]
})
export class CustomerDetailsComponent implements OnInit {

  customer: ICustomer;

  constructor(private router: Router, private route: ActivatedRoute, private dataService: DataService) { }

  ngOnInit() {
      const id = +this.router.routerState.parent(this.route).snapshot.params['id'];
      this.dataService.getCustomer(id)
          .subscribe((customer: ICustomer) => this.customer = customer);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@color/blueLove"/>
    <item android:state_checked="false" android:drawable="@color/whiteLove"/>

</selector>


text:
package com.mixer.api.http.ws;

import com.mixer.api.MixerAPI;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Map;

public class MixerWebsocketClient extends WebSocketClient {
    protected final MixerAPI mixer;

    public MixerWebsocketClient(MixerAPI mixer, URI uri) {
        super(uri, new CookieDraft_6455(mixer.http));

        this.mixer = mixer;
    }

    public MixerWebsocketClient(MixerAPI mixer, URI uri, Map<String, String> httpHeaders) {
        super(uri, new CookieDraft_6455(mixer.http), httpHeaders, 0);

        this.mixer = mixer;
    }

    @Override public void onOpen(ServerHandshake serverHandshake) { }
    @Override public void onMessage(String s) { }
    @Override public void onClose(int i, String s, boolean b) { }
    @Override public void onError(Exception e) { }
}


text:
            <input class="form-control"
                   ng-model="model.description"
                   ng-if="!isReadOnly"
                   placeholder="Quick Description" />

               Change

               Delete


text:
'use strict';
const fs = require('fs');
let adWhitelist = ['tsunami'];
let adRegex = new RegExp("(play.pokemonshowdown.com\\/~~)(?!(" + adWhitelist.join('|') + "))", "g");
Config.chatfilter = function (message, user, room, connection, targetUser) {
	user.lastActiveTime = Date.now();
	if (!room && !Users(targetUser)) targetUser = {name: 'unknown user'};
	let pre_matches = (message.match(/psim|psim.us|psim us/g) || []).length;
	let final_check = (pre_matches >= 1 ? adWhitelist.filter(server => ~message.indexOf(server)).length : 0);
	if (!user.can('lock') && (pre_matches >= 1 && final_check === 0 || pre_matches >= 2 && final_check >= 1 || message.match(adRegex))) {
		if (user.locked) return false;
		if (!user.advWarns) user.advWarns = 0;
		user.advWarns++;
		if (user.advWarns > 1) {
			Punishments.lock(user, Date.now() + 7 * 24 * 60 * 60 * 1000, null, "Advertising");
			fs.appendFile('logs/modlog/modlog_staff.txt', '[' + (new Date().toJSON()) + '] (staff) ' + user.name + ' was locked from talking by the Server. (Advertising) (' + connection.ip + ')\n');
			connection.sendTo(room, '|raw|You have been locked for attempting to advertise.');
			Monitor.log("[AdMonitor] " + user.name + " has been locked for attempting to advertise" + (room ? ". **Room:** " + room.id : " in a private message to " + targetUser.name + ".") + " **Message:** " + message);
			return false;
		}
		Monitor.log("[AdMonitor] " + user.name + " has attempted to advertise" + (room ? ". **Room:** " + room.id : " in a private message to " + targetUser.name + ".") + " **Message:** " + message);
		connection.sendTo(room, '|raw|Advertising detected, your message has not been sent and Tsunami global authorities have been notified.' + '
Further attempts to advertise in a chat OR PMs will result in being locked.');
		connection.user.popup("|modal|Advertising detected, your message has not been sent and Tsunami global authorities have been notified.\n" + "Further attempts to advertise in a chat OR in PMs will result in being locked.");
		return false;
	}
	return message;
};


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_01.c
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close.label.xml
Template File: source-sinks-01.tmpl.c
*/
/*
 * @description
 * CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
 * BadSource:  Open a file using CreateFile()
 * Sinks:
 *    GoodSink: Close the file using CloseHandle()
 *    BadSink : Do not close file
 * Flow Variant: 01 Baseline
 *
 * */

#include "std_testcase.h"

#include <windows.h>

#ifndef OMITBAD

void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_01_bad()
{
    HANDLE data;
    /* Initialize data */
    data = INVALID_HANDLE_VALUE;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    /* FLAW: No attempt to close the file */
    ; /* empty statement needed for some flow variants */
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
    HANDLE data;
    /* Initialize data */
    data = INVALID_HANDLE_VALUE;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    /* FIX: If the file is still opened, close it */
    if (data != INVALID_HANDLE_VALUE)
    {
        CloseHandle(data);
    }
}

void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_01_good()
{
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_01_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_01_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
class MembersController < ApplicationController
  ################################################################################
  require_authorization(:can_edit_users, :except => [:index, :list, :redraw_position_table])
  before_filter(:public_member_list)

  ################################################################################
  table_for(Position, :url => lambda {|c| {:project => c.send(:project)}}, :partial => 'table')

  ################################################################################
  def index
    list
    render(:action => 'list')
  end

  ################################################################################
  def list
  end

  ################################################################################
  def new
  end

  ################################################################################
  def create
    @create_errors = []

    person = User.find_by_email(params[:email])
    @create_errors << 'No user with that email address could be found' if person.nil?

    all_roles = current_user.role_list_for(@project)
    role = all_roles.find {|r| r.position == params[:role].to_i}
    @create_errors << 'You cannot assign that role to this project' if role.nil?

    if @create_errors.blank?
      person.positions.create(:role => role, :project => @project)
      redirect_to(:action => 'index', :project => @project)
    else
      render(:action => 'new')
    end
  end

  ################################################################################
  def edit
    @position = @project.positions.find(params[:id])
    @my_position = current_user.positions.find_by_project_id(@project.id)
    when_authorized(:condition => @position.role.position >= @my_position.role.position)
  end

  ################################################################################
  def update
    @position = @project.positions.find(params[:id])
    @my_position = current_user.positions.find_by_project_id(@project.id)

    when_authorized(:condition => @position.role.position >= @my_position.role.position) do
      role = current_user.role_list_for(@project).find {|r| r.id == params[:position][:role_id].to_i}
      @position.role = role unless role.blank?
      @position.save
      redirect_to(:action => 'index', :project => @project)
    end
  end

  ################################################################################
  def destroy
    @position = @project.positions.find(params[:id])
    @my_position = current_user.positions.find_by_project_id(@project.id)

    when_authorized(:condition => @position.role.position >= @my_position.role.position) do
      # XXX Why is this failing?
      @position.destroy
      redirect_to(:action => 'index', :project => @project)
    end
  end

  ################################################################################
  def public_member_list
    return true if current_user.projects.include?(@project)
    @project.policies.check(:members_are_public)
  end

end
################################################################################


text:
<?php

namespace OpenCloud\Compute\Exception;

class KeyPairException extends \Exception
{
}


text:
{-# LANGUAGE RecordWildCards #-}

module SDL.Run
    ( ScreenInfo(..)
    , Context(..)
    , MilliDelta
    , InitialState
    , FinishedPlaying(..)
    , IterateStateFunc
    , runWithContext
    ) where

import Data.Word (Word32)
import           Control.Monad          (unless, when)
import qualified Linear                 as L
import           SDL                    (($=))
import qualified SDL
import qualified Foreign.C.Types        as Foreign
import qualified Data.Text              as Text

data ScreenInfo = ScreenInfo { width  :: Foreign.CInt
                             , height :: Foreign.CInt
                             , title  :: Text.Text
                             }

data Context = Context { renderer :: SDL.Renderer
                       , window   :: SDL.Window
                       , events   :: [SDL.Event]
                       }

type MilliDelta = Word32
type InitialState state = state
data FinishedPlaying = StillPlaying
                     | DonePlaying
                       deriving (Eq, Ord, Show, Enum, Bounded)

type IterateStateFunc m state = Context -> MilliDelta -> state -> m (state, FinishedPlaying)

runWithContext :: ScreenInfo -> InitialState a -> IterateStateFunc IO a -> IO ()
runWithContext ScreenInfo{..} initialState iterator =
    let initialize = SDL.initialize [SDL.InitVideo]

        setupRenderQuality = do SDL.HintRenderScaleQuality $= SDL.ScaleLinear
                                renderQuality <- SDL.get SDL.HintRenderScaleQuality
                                when (renderQuality /= SDL.ScaleLinear) $
                                    putStrLn "Warning: Linear texture filtering not enabled"

        winArg = SDL.defaultWindow {SDL.windowInitialSize = L.V2 width height}
        createWindow = do win <- SDL.createWindow title winArg
                          SDL.showWindow win
                          pure win

        renConf = SDL.RendererConfig { SDL.rendererType = SDL.AcceleratedRenderer
                                     , SDL.rendererTargetTexture = False
                                     }
        createRenderer win = SDL.createRenderer win (-1) renConf

    in do initialize
          setupRenderQuality
          window   <- createWindow
          renderer <- createRenderer window
          SDL.rendererDrawColor renderer $= black
          loopOn initialState iterator $ Context renderer window []
          SDL.destroyRenderer renderer
          SDL.destroyWindow window
          SDL.quit
    where black = let m = minBound in L.V4 m m m m

loopOn :: InitialState state -> IterateStateFunc IO state -> Context -> IO ()
loopOn initial f context = iterateWithTime initial $ \dt a' ->
                                  do events <- collectEvents
                                     SDL.clear (renderer context)
                                     (a'', done) <- f context{events = events} dt a'
                                     SDL.present (renderer context)
                                     pure (a'', done ||: quit events)
    where quit = elem SDL.QuitEvent . map SDL.eventPayload

          collectEvents = do ev <- SDL.pollEvent
                             maybe (return []) (\e -> (e:) <$> collectEvents) ev

          (||:) :: FinishedPlaying -> Bool -> FinishedPlaying
          DonePlaying ||: _    = DonePlaying
          _           ||: True = DonePlaying
          _           ||: _    = StillPlaying

iterateWithTime :: InitialState state -> (MilliDelta -> state -> IO (state, FinishedPlaying)) -> IO ()
iterateWithTime initial f = go initial 0 =<< SDL.ticks
  where go a dt t = do (a',stop) <- f dt a
                       keepPlaying stop $ SDL.ticks >>= \t' -> go a' (t' - t) t'
        keepPlaying x = unless (x == DonePlaying)