text:
extern "C" {
#endif

NPY_NO_EXPORT void
BOOL_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
          void *NPY_UNUSED(func));
NPY_NO_EXPORT void
BYTE_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
          void *NPY_UNUSED(func));
NPY_NO_EXPORT void
UBYTE_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
           void *NPY_UNUSED(func));
NPY_NO_EXPORT void
SHORT_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
           void *NPY_UNUSED(func));
NPY_NO_EXPORT void
USHORT_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
            void *NPY_UNUSED(func));
NPY_NO_EXPORT void
INT_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
         void *NPY_UNUSED(func));
NPY_NO_EXPORT void
UINT_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
          void *NPY_UNUSED(func));
NPY_NO_EXPORT void
LONG_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
          void *NPY_UNUSED(func));
NPY_NO_EXPORT void
ULONG_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
           void *NPY_UNUSED(func));
NPY_NO_EXPORT void
LONGLONG_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
              void *NPY_UNUSED(func));
NPY_NO_EXPORT void
ULONGLONG_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
               void *NPY_UNUSED(func));
NPY_NO_EXPORT void
HALF_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
          void *NPY_UNUSED(func));
NPY_NO_EXPORT void
FLOAT_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
           void *NPY_UNUSED(func));
NPY_NO_EXPORT void
DOUBLE_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
            void *NPY_UNUSED(func));
NPY_NO_EXPORT void
LONGDOUBLE_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
                void *NPY_UNUSED(func));
NPY_NO_EXPORT void
CFLOAT_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
            void *NPY_UNUSED(func));
NPY_NO_EXPORT void
CDOUBLE_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
             void *NPY_UNUSED(func));
NPY_NO_EXPORT void
CLONGDOUBLE_clip(char **args, npy_intp const *dimensions,
                 npy_intp const *steps, void *NPY_UNUSED(func));
NPY_NO_EXPORT void
DATETIME_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
              void *NPY_UNUSED(func));
NPY_NO_EXPORT void
TIMEDELTA_clip(char **args, npy_intp const *dimensions, npy_intp const *steps,
               void *NPY_UNUSED(func));

#ifdef __cplusplus
}
#endif

#endif


text:
@interface NSString (iTunes)
// To determine whether it is open appstore method
- (BOOL)isiTunesURL;
@end

redpajama_set_name: RedPajamaGithub


text:
from Quality.AtomicComputation.BlackHole import BlackHoleSink
from Quality.AtomicComputation.CSVSink import CSVSink
from Quality.AtomicComputation.generic_qoi_age import Age
from Quality.AtomicComputation.generic_qoi_completeness import Completeness
from Quality.AtomicComputation.generic_qoi_correctness import Correctness
from Quality.AtomicComputation.generic_qoi_frequency import Frequency
from Quality.AtomicComputation.generic_qoi_latency import Latency
from Quality.AtomicComputation.reputationsystem.repsys import ReputationSystem
from virtualisation.misc.jsonobject import JSONObject
from virtualisation.misc.log import Log as L

__author__ = 'Thorben Iggena (t.iggena@hs-osnabrueck.de)'

# from Quality.AtomicComputation.VirtuosoSink import VirtuosoSink
# from Quality.AtomicComputation.TerminalSink import TerminalSink

class SensorQueueElement(object):
    def __init__(self, description, data):
        self.sensorDescription = description
        self.sensorData = data

class CpQoiSystem(object):

    def __init__(self):
        self.initialised = False
        self.reputationSystem = None
        self.messageBusQueue = None
        L.d2("CpQoiSystem started")

    def getObservationIds(self, data):
        return [data[field].observationID for field in data.fields]

    def addData(self, description, data, clock):
        if not self.initialised:
            self.initialise(description, clock)
        self.reputationSystem.setClock(clock)
        self.reputationSystem.setDescription(description)
        # send data to reputationsystem
        qoiInformation = self.reputationSystem.update(data)
        # persist calculated qoi
        # get list of observationIds for virtuoso sink
        self.reputationSystem.persist(self.getObservationIds(data))
        return qoiInformation

    # initialise reputationsystem with values from sensor description, add qoi metrics and sinks
    def initialise(self, description, clock):
        self.reputationSystem = ReputationSystem(description, clock)
        # self.reputationSystem.addSink(CSVSink())
        # self.reputationSystem.addSink(VirtuosoSink(self.messageBusQueue))
        # self.reputationSystem.addSink(TerminalSink())
        self.reputationSystem.addSink(BlackHoleSink())
        self.reputationSystem.addQoIMetric(Frequency())
        self.reputationSystem.addQoIMetric(Completeness())
        self.reputationSystem.addQoIMetric(Age())
        self.reputationSystem.addQoIMetric(Latency())
        self.reputationSystem.addQoIMetric(Correctness())
        self.initialised = True
        L.d2("CpQoiSystem initialised")

    def setMessageBusQueue(self, messageBusQueue):
        self.messageBusQueue = messageBusQueue

    def getLastQoI(self, types=None, avg=None, minimum=None, maximum=None):
        qoiData = JSONObject()
        for metric in self.reputationSystem.metrics:
            q = JSONObject()
            currentValues = JSONObject()
            currentValues.absoluteValue = metric.absoluteValue
            currentValues.ratedValue = metric.ratedValue
            q.unit = metric.unit
            qoiData[metric.name] = q
            q.CURRENT = currentValues
            if types:
                self.reputationSystem.avgQoIManager.getValues(q, metric.name, types, avg, minimum, maximum)
        return qoiData


text:
Im Folgenden: Mensch = *Klara*

Zeitraffer: Duma, Parlament, usw, manche Stellen ruhig & Gerede hörbar, "zeitungsstapel" von mitteilungen über verschiedene "Verbesserungsversuche", Kongresstreffen und normalen Balast

Sprecher: Es schien, dass die Menschen alles taten, um etwas zu verändern, um einer Katastrophe zu entgehen, um etwas zu verbessern
Plastik einsammeln Kampange, Greenpeace, etc.

…. doch es geschah nichts.

Denn es waren nicht die Gesetzestexte die geändert werden mussten, sondern nur ein Wandel der Lebensweise konnte etwas bewirken.

- Black -

Großstadt, Nacht, Zeitraffer, Himmelskörperbewegungen zu sehen (HDR[?]), Autos und Menschen eilen / wimmeln umher

Dunkelheit (fadein). Zeitraffer von Sonnenaufgang über stadt. Ein Schlafzimmer in einer Wohnung. Man sieht durch irgendein "Guckloch" (z.B Fenster) die Sonnenstrahlen auftauchen, sieht den Wecker / die Uhr wie wild weitergehen, der Wecker klingelt, nach wiederholtem Klingeln haut der Mensch auf den Wecker (snooze) ohne die Augen aufzumachen, sinkt wieder zusammen.

// Möglichkeit: Die "Sicht" mit mehreren solcher Schlafzimmern auszufüllen, immer bisschen anders, aber doch gleich.

Zweites Weckerklingeln. Mensch schlägt die Augen auf und schaltet den Wecker aus. Setzt sich stönend, die Augen reibend, auf.

M: Aufregende / gehetzte Musik durch ganzen Alltag, ganze Szene sollte < 3min sein.

Eine Darstellung des eiligen und gehetzten Alltags. Eventuell darstellen, wie sich alles Tag für Tag, Jahr für Jahr, Mensch für Mensch wiederhohlt [?].

Mensch steht aus dem Bett auf, zieht sich an (oder ist plötzlich angezogen), kocht Kaffee, isst frühstück, etc, nimmt seine Umgebung kaum wahr (Handy, Fernseher, Zeitung, etc. nehmen die gesamte Aufmerksammkeit), macht "Morgenritual" fertig, Verlangsammung, schaut auf die Uhr.

Mensch: Scheiße, jetzt ist's schon wieder so spät. (Verdammt, ) Hoffentlich verpass' ich nicht den Bus(/Zug)

Beschleunigung, rennt hinaus und zur Haltestelle, schafft es gerade noch das Verkehrsmittel zu erreichen, im Verkehrsmittel sitzt er wieder am Handy. Man sieht, wie die Umgebung (durch die fenster [?]) weiterzieht.

[Von außen] Verkehrsmittel stoppt, Mensch steigt aus, geht zur Arbeit/ Uni. Hat dort wenig Umgang mit Kollegen und sitzt hauptsächlich am Computer. Wird dort die ganze Zeit von Jungs umzingelt, will aber hauptsächliche mal etwas allein sein, sich sammeln und seine ruhe haben. Ganzer Unitag / Arbeitstag dargestellt, aber wahnsinnig beschleunigt. Im Blickfeld sollte es einen Ausblick geben, wo man vieles vorbeiziehen sieht (Ampel, Kreuzung, Straße, etc).

Nach dem Arbeitstag kommt Mensch erschöpft nach Hause, setzt sich vor den Fernseher und isst unterwegsgekauftes Fastfood. Macht administrative Aufgaben. Währen dem ganzen Alltag sollten die himmelskörper oder ähnliches ab und zu dargestellt werden. Geht voller Sorgen viel zu spät ins Bett.

// Alltag wiederholt sich, irgendwie demonstrieren wie es in verschiedenen Städten gleich ist? (Moskau, Berlin, Stockholm, New York, etc)

Eine diese schöne junge Frau sitzt, die Hände in Handschellen, auf einem still in einen schallisolierten Zimmer. Vor ihr steht eine Frau mit einer Waffe in der Hand.

Frau mit waffe (geschrien): ENTWEDER, DU ZIEHST AUS DIESER VERFLUCHTEN WOHNUNG DEINES BRUDERS AUS, ODER DU LANDEST, ETWAS VON BLEI BESCHWEHRT AUF DER STRAßE, IN EINEM VIERTEL IN DEM SCHON DIE GEIER AUF DICH WARTEN! Hinterhältig/Spöttisch/Voller Hohn Das willt die kleine süße Dame doch nicht, oder? So wie du auf deine Figur achtest….

(Gefesselte) Frau: Bitte tun sie mir nichts! Aber, schluchtzt, aber, mein guter Bruder hat sich so sehr dafür eingesetzt das ich da wohnen kann! Eine Träne rinnt ihr über die Wange

Frau mit Waffe: Hah, dein Bruder also! Und wehe du sagst ihm auch etwas!

Gibt *Klara* eine Ohrfeige, black.

*Klara* (weinend, in einer sehr kleinen wohnung mit ihrem Bruder (*Ivan*) zusammen): DU du du

du du du drecksspatz

du du du gemeinüztiger kerl

dein, *seuftz* deine eine träne rinnt ihr über die wange möglichkeit zu studieren nimmst du dir sie "reist sich zusammen" und wirkt wütender Nur um so einer hässlichen schlampe wie mich so eine schöne wohnung zu bescheren? Und all das Geld was du von unseren armen eltern geerbst hast, stellst du ihr auch noch zur verfügung?!?!

HA! Mein Bruder versucht sich also an mich ranzumachen! Wenn ich das der ganzen Uni erzähle, die werden aber stimmung ändert sich auf traurig lachen schluchtz

*Ivan*: Aber das hat doch überhaupt niemand gesagt

*Klara*: Ha! Das ist mir egal. Auf jeden fall kannst du diese bude sofort kündigen.

Geht. Lehnt sich draußen an einen Laternenpfahl und weint. Touching music. Von innen gefilmt: *Alvin* sieht sie. greift nach einem fernglas was am fensterbrett liegt, und schaut zu *Klara*. Sieht ihr weinendes Gesicht. Lässt das fernglas sinken.

Von außen: er hält sich die hände vors gesicht und weint

----------------------------------------------------------------------------------------------------------------------------

Bruder hat ihr extra diese wohnung besorgt, die sehr schön und erreichbar ist, aber eben auch billig. Die Immobilienhaiin will an die wohnung ran - oder sie tötet die Frau - da sie ihre eigene wohnung ausbauen will. Der bruder tut extra nicht studieren - die zwei kinder sind waisen - sondern gibt sein teil des erbes für's studium von *Klara* aus, und arbeitet zusätzlich beim bäcker um ihr diese wohnung zu finanzieren.

----------------------------------------------------------------------------------------------------------------------------


text:
package com.dptest.behavioralpattern.chainofresponsibility;

public class NegativeProcessor implements IChain {

	private IChain nextInChain;

	public void setNext(IChain c) {
		nextInChain = c;
	}

	public void process(int number) {
		if (number < 0) {
			System.out.println("NegativeProcessor : " + number);
		} else {
			nextInChain.process(number);
		}
	}
}


text:
import {Stats, StatsBuilder} from "../common/Stats";
import {BattleParticipant} from "../common/BattleParticipant";
import {GameState} from "../../../states/GameState";
import {Enemy} from "../enemies/Enemy";
import {Inventory} from "./inventory/Inventory";
import {Potion} from "./inventory/Potion";
import {AngelicShield} from "./inventory/AngelicShield";
import {InventoryItem} from "./inventory/InventoryItem";
import {EncounterState} from "../../../states/encounterstate/EncounterState";
import {NotificationMessageWithCallback} from "../common/NotificationMessageWithCallback";
export class Player extends Phaser.Sprite implements BattleParticipant {

    idlePoses: Map<string, number>;
    lastDirection: string;
    playerStats: Stats;
    attacks: any[];
    inventory: Inventory = new Inventory();

    constructor(public state: GameState, public x: number, public y: number, public imageRef: string) {
        super(state.game, x, y, imageRef);

        this.state = state;

        this.animations.add('left', [0, 1, 2], 10, true);
        this.animations.add('right', [3, 4, 5], 10, true);
        this.animations.add('down', [6, 7, 8], 10, true);
        this.animations.add('up', [9, 10, 11], 10, true);
        this.state.physics.arcade.enable(this);
        this.createIdlePoses();
        this.createPlayerStats();
        this.attacks = [{name: "Bite", power: 10}, {name: "Scratch", power: 15}, {name: "Weep", power: 0}];

        this.fillInventory();
        // this.items = [
        //     {name: "Potion", amount: 5},
        //     {name: "Smoke bomb", amount: 2},
        //     {name: "X marker", amount: 1},
        //     {name: "X attacker", amount: 1},
        //     {name: "X defender", amount: 1},
        //     {name: "Pokéball", amount: 1},
        //     {name: "Link's sword", amount: 1},
        //     {name: "???", amount: 1},
        //     {name: "Mattress", amount: 1},
        //     {name: "Bowl of pee", amount: 1},
        //     {name: "Eleven", amount: 1}
        // ];
        // this.orderItems();
    }

    private createPlayerStats() {
        this.playerStats = new StatsBuilder().stats()
            .withLevel(1)
            .withAttack(10)
            .withDefense(10)
            .withSpeed(10)
            .withMaxhealth(100)
            .withMaxmana(10)
            .build();
    }

    createIdlePoses() {
        this.idlePoses = new Map();
        this.idlePoses.set("left", 1);
        this.idlePoses.set("right", 4);
        this.idlePoses.set("down", 7);
        this.idlePoses.set("up", 10);
    }

    update() {
        this.body.velocity.x = 0;
        this.body.velocity.y = 0;

        if (!this.state.displayingText) {
            if (this.state.cursors.left.isDown) {
                this.body.velocity.x -= 600;
                this.animations.play("left");
                this.lastDirection = "left";
            } else if (this.state.cursors.right.isDown) {
                this.body.velocity.x += 600;
                this.animations.play("right");
                this.lastDirection = "right";
            } else if (this.state.cursors.up.isDown) {
                this.body.velocity.y -= 600;
                this.animations.play("up");
                this.lastDirection = "up";
            } else if (this.state.cursors.down.isDown) {
                this.body.velocity.y += 600;
                this.animations.play("down");
                this.lastDirection = "down";
            } else {
                this.animations.stop();
                this.frame = this.lastDirection ? this.idlePoses.get(this.lastDirection) : 7;
            }
        }
    }

    hasAttackInSlot(index: number) {
        return this.attacks.length - 1 >= index;
    };

    attack(index: number, enemy: Enemy) {
        let playerAttacks = this.attacks;
        enemy.processAttacked(playerAttacks[index].power);
    }

    // private orderItems() {
    //     this.items.sort(function (item, item2) {
    //         return item.name > item2.name ? 1 : -1;
    //     });
    // }

    public isPlayerControlled(): boolean {
        return true;
    }

    getStats(): Stats {
        return this.playerStats;
    }

    //TODO: temp, until player can acquire items
    private fillInventory() {
        this.inventory.addItem(new Potion());
        this.inventory.addItem(new Potion());
        this.inventory.addItem(new Potion());
        this.inventory.addItem(new AngelicShield());
    }

    useItem(item: InventoryItem, encounterState: EncounterState): NotificationMessageWithCallback {
        return this.inventory.useItem(item, encounterState);
    }
}


text:
#ifndef Header_SuperpoweredNBandEQ
#define Header_SuperpoweredNBandEQ

#include "SuperpoweredFX.h"
struct nbeqInternals;

/**
 @brief N-band equalizer.

 It doesn't allocate any internal buffers and needs just a few bytes of memory.

 @param decibels Gain for each frequency band in decibels. Bandwidths are automatically calculated.
 @param enabled True if the effect is enabled (processing audio). Read only. Use the enable() method to set.
 */
class SuperpoweredNBandEQ: public SuperpoweredFX {
public:
	float *decibels; // READ-ONLY parameter.

/**
 @brief Sets the gain for a frequency band.

 @param index The index of the frequency band.
 @param gainDecibels The gain of the frequency band in decibels.
 */
	void setBand(unsigned int index, float gainDecibels);

/**
 @brief Turns the effect on/off.
 */
	void enable(bool flag);

/**
 @brief Create an eq instance.

 Enabled is false by default, use enable(true) to enable. Example: SuperpoweredNBandEQ eq = new SuperpoweredNBandEQ(44100);

 @param samplerate 44100, 48000, etc.
 @param frequencies 0-terminated list of frequency bands.
*/
	SuperpoweredNBandEQ(unsigned int samplerate, float *frequencies);
	~SuperpoweredNBandEQ();

/**
 @brief Sets the sample rate.

 @param samplerate 44100, 48000, etc.
 */
	void setSamplerate(unsigned int samplerate);
/**
 @brief Reset all internals, sets the instance as good as new and turns it off.
 */
	void reset();

/**
 @brief Processes the audio.

 It's not locked when you call other methods from other threads, and they not interfere with process() at all.

 @return Put something into output or not.

 @param input 32-bit interleaved stereo input buffer. Can point to the same location with output (in-place processing).
 @param output 32-bit interleaved stereo output buffer. Can point to the same location with input (in-place processing).
 @param numberOfSamples Should be 32 minimum.
*/
	bool process(float *input, float *output, unsigned int numberOfSamples);

private:
	nbeqInternals *internals;
	SuperpoweredNBandEQ(const SuperpoweredNBandEQ&);
	SuperpoweredNBandEQ& operator=(const SuperpoweredNBandEQ&);
};

#endif


text:
package leasepool

import (
	"net"
)

/*
 * Lease.IP is the Key.
 */
type LeasePool interface {
	//Add A Lease To The Pool
	AddLease(Lease) error

	//Remove
	RemoveLease(net.IP) error

	//Remove All Leases from the Pool (Required for Persistant LeaseManagers)
	PurgeLeases() error

	/*
	 * Get the Lease
	 * -Found
	 * -Copy Of the Lease
	 * -Any Error
	 */
	GetLease(net.IP) (bool, Lease, error)

	//Get the lease already in use by that hardware address and/or client identifier.
	GetLeaseForClient(net.HardwareAddr, []byte) (bool, Lease, error)

	/*
	 * -Lease Available
	 * -Lease
	 * -Error
	 */
	GetNextFreeLease() (bool, Lease, error)

	/*
	 * Return All Leases
	 */
	GetLeases() ([]Lease, error)

	/*
	 * Update Lease
	 * - Has Updated
	 * - Error
	 */
	UpdateLease(Lease) (bool, error)
}


text:
"""Boolean operation description"""
import ast

_DEFAULT_FORMAT = "{left} {operation} {right}"

class BooleanOperationDesc:
    """Binary operation description"""

    OPERATION = {
        ast.And: {
            "value": "and",
            "format": _DEFAULT_FORMAT,
        },
        ast.Or: {
            "value": "or",
            "format": _DEFAULT_FORMAT,
        },
    }


text:
<?php

namespace EventSnoozer\Tests\EventStorage;

use EventSnoozer\EventStorage\MemoryEventStorage;
use EventSnoozer\StoredEvent\StoredEvent;
use PHPUnit\Framework\TestCase;
use EventSnoozer\Tests\Mocks\TestEvent;

class MemoryEventStorageTest extends TestCase
{
    public function testSaveEvent()
    {
        $storedEvent = new StoredEvent();
        $storedEvent->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('+1 day'))
            ->setPriority(123)
            ->setId(456);

        $memoryEventStorage = new MemoryEventStorage();
        $memoryEventStorage->saveEvent($storedEvent);

        $reflectionClass = new \ReflectionClass($memoryEventStorage);
        $reflectionProperty = $reflectionClass->getProperty('storedEvents');
        $reflectionProperty->setAccessible(true);
        $storedEvents = $reflectionProperty->getValue($memoryEventStorage);

        self::assertSame([$storedEvent], $storedEvents);
    }

    public function testFetchEvent()
    {
        $futureEvent = new StoredEvent();
        $futureEvent->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('+1 day'))
            ->setPriority(123)
            ->setId(456);
        $pastEvent = new StoredEvent();
        $pastEvent->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-1 day'))
            ->setPriority(123)
            ->setId(654);

        $memoryEventStorage = new MemoryEventStorage();
        $reflectionClass = new \ReflectionClass($memoryEventStorage);
        $reflectionProperty = $reflectionClass->getProperty('storedEvents');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($memoryEventStorage, [$futureEvent, $pastEvent]);

        $fetchedEvent = $memoryEventStorage->fetchEvent();
        self::assertSame($pastEvent, $fetchedEvent);
    }

    public function testFetchMultipleEvents()
    {
        $futureEvent = new StoredEvent();
        $futureEvent->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('+1 day'))
            ->setPriority(123)
            ->setId(234);
        $pastEvent1 = new StoredEvent();
        $pastEvent1->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-1 day'))
            ->setPriority(123)
            ->setId(345);
        $pastEvent2 = new StoredEvent();
        $pastEvent2->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-2 day'))
            ->setPriority(10)
            ->setId(456);

        $memoryEventStorage = new MemoryEventStorage();
        $reflectionClass = new \ReflectionClass($memoryEventStorage);
        $reflectionProperty = $reflectionClass->getProperty('storedEvents');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($memoryEventStorage, [$futureEvent, $pastEvent1, $pastEvent2]);

        $fetchedEvents = $memoryEventStorage->fetchMultipleEvents(1);
        self::assertSame([$pastEvent1], $fetchedEvents);

        $fetchedEvents = $memoryEventStorage->fetchMultipleEvents(2);
        self::assertSame([$pastEvent1, $pastEvent2], $fetchedEvents);

        $fetchedEvents = $memoryEventStorage->fetchMultipleEvents(3);
        self::assertSame([$pastEvent1, $pastEvent2], $fetchedEvents);
    }

    public function testRemoveEvent()
    {
        $futureEvent = new StoredEvent();
        $futureEvent->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('+1 day'))
            ->setPriority(123)
            ->setId(234);
        $pastEvent = new StoredEvent();
        $pastEvent->setEventName(TestEvent::NAME)
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-1 day'))
            ->setPriority(123)
            ->setId(345);

        $memoryEventStorage = new MemoryEventStorage();
        $reflectionClass = new \ReflectionClass($memoryEventStorage);
        $reflectionProperty = $reflectionClass->getProperty('storedEvents');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($memoryEventStorage, [$futureEvent, $pastEvent]);

        $memoryEventStorage->removeEvent($pastEvent);
        $leftEvents = $reflectionProperty->getValue($memoryEventStorage);
        self::assertSame([$futureEvent], $leftEvents);

        $memoryEventStorage->removeEvent($futureEvent);
        $leftEvents = $reflectionProperty->getValue($memoryEventStorage);
        self::assertSame([], $leftEvents);
    }

    public function testWhitelistRestrictions()
    {
        $pastEvent1 = new StoredEvent();
        $pastEvent1->setEventName('test.event1')
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-1 day'))
            ->setPriority(123)
            ->setId(345);
        $pastEvent2 = new StoredEvent();
        $pastEvent2->setEventName('test.event2')
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-2 day'))
            ->setPriority(10)
            ->setId(456);

        $memoryEventStorage = new MemoryEventStorage();
        $reflectionClass = new \ReflectionClass($memoryEventStorage);
        $reflectionProperty = $reflectionClass->getProperty('storedEvents');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($memoryEventStorage, [$pastEvent1, $pastEvent2]);
        $memoryEventStorage->setWhitelistEvents(['test.event2']);

        $fetchedEvents = $memoryEventStorage->fetchMultipleEvents(2);
        self::assertSame([$pastEvent2], $fetchedEvents);
    }

    public function testBlacklistRestrictions()
    {
        $pastEvent1 = new StoredEvent();
        $pastEvent1->setEventName('test.event1')
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-1 day'))
            ->setPriority(123)
            ->setId(345);
        $pastEvent2 = new StoredEvent();
        $pastEvent2->setEventName('test.event2')
            ->setEventClass(TestEvent::class)
            ->setAdditionalData(['key' => 'value'])
            ->setRuntime(new \DateTime('-2 day'))
            ->setPriority(10)
            ->setId(456);

        $memoryEventStorage = new MemoryEventStorage();
        $reflectionClass = new \ReflectionClass($memoryEventStorage);
        $reflectionProperty = $reflectionClass->getProperty('storedEvents');
        $reflectionProperty->setAccessible(true);
        $reflectionProperty->setValue($memoryEventStorage, [$pastEvent1, $pastEvent2]);
        $memoryEventStorage->setBlacklistEvents(['test.event2']);

        $fetchedEvents = $memoryEventStorage->fetchMultipleEvents(2);
        self::assertSame([$pastEvent1], $fetchedEvents);
    }
}


text:
package rune_tree

import (
	"fmt"

	"github.com/kentik/patricia"
)

// this is IPv6 tree code that's not very copy/paste friendly for when we transfer IPv4 code to IPv6

// create a new node in the tree, return its index
func (t *TreeV6) newNode(address patricia.IPv6Address, prefixLength uint) uint {
	availCount := len(t.availableIndexes)
	if availCount > 0 {
		index := t.availableIndexes[availCount-1]
		t.availableIndexes = t.availableIndexes[:availCount-1]
		t.nodes[index] = treeNodeV6{prefixLeft: address.Left, prefixRight: address.Right, prefixLength: prefixLength}
		return index
	}

	t.nodes = append(t.nodes, treeNodeV6{prefixLeft: address.Left, prefixRight: address.Right, prefixLength: prefixLength})
	return uint(len(t.nodes) - 1)
}

// Address returns the current IP address for the iterator.
func (iter *TreeIteratorV6) Address() patricia.IPv6Address {
	var prefixLeft, prefixRight uint64
	var prefixLength uint
	for _, i := range iter.nodeHistory {
		prefixLeft, prefixRight, prefixLength = patricia.MergePrefixes64(prefixLeft, prefixRight, prefixLength,
			iter.t.nodes[i].prefixLeft, iter.t.nodes[i].prefixRight, iter.t.nodes[i].prefixLength)
	}
	prefixLeft, prefixRight, prefixLength = patricia.MergePrefixes64(prefixLeft, prefixRight, prefixLength,
		iter.t.nodes[iter.nodeIndex].prefixLeft, iter.t.nodes[iter.nodeIndex].prefixRight,
		iter.t.nodes[iter.nodeIndex].prefixLength)
	return patricia.IPv6Address{
		Left:   prefixLeft,
		Right:  prefixRight,
		Length: prefixLength,
	}
}

//nolint
func (t *TreeV6) print() {
	buf := make([]rune, 0)
	for i := range t.nodes {
		buf = buf[:0]
		fmt.Printf("%d: \tleft: %d, right: %d, prefix: %032b %032b (%d), tags: (%d): %v\n", i, int(t.nodes[i].Left), int(t.nodes[i].Right), int(t.nodes[i].prefixLeft), int(t.nodes[i].prefixRight), int(t.nodes[i].prefixLength), t.nodes[i].TagCount, t.tagsForNode(buf, uint(i), nil))
	}
}


text:
!----------------------------------------------------------------------------
! Copyright 2012 SINTEF
!
! 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.
!----------------------------------------------------------------------------

!> @brief QTestLib API for Fortran2003
!!
!! @details
!! The QTestLib framework, provided by Nokia, is a tool for unit testing Qt
!! based applications and libraries. QTestLib provides all the functionality
!! commonly found in unit testing frameworks as well as extensions for testing
!! graphical user interfaces.
!!
!! The class_QTest provides a simplified wrapper layer to the QTestLib. It
!! implements all public member functions as PURE or ELEMENTAL
!!
!! @author Thomas F. Hagelien
MODULE class_qtest
  USE, INTRINSIC :: ISO_C_BINDING
  IMPLICIT NONE

  PUBLIC :: check_c_binding, qwarn, qfail, qexpect_fail, qverify, qcompare
  PUBLIC :: qcompare_expect_fail
  PUBLIC :: abort, perdue
  !
  PRIVATE
  !
  SAVE
  !

  !! Module constants
  INTEGER, PARAMETER :: Abort = 1  !< Aborts the execution of the test.
                                   !! Use this mode when it doesn't make
                                   !! sense to execute the test any further
                                   !! after the expected failure.
  INTEGER, PARAMETER :: Perdue = 2 !< Continues execution of the test after
                                   !!the expected failure.

  !> @interface qcompare
  !! qcompare is a set of subroutines to compare 2 values of different datatypes
  !! in addition to the two values to be compared, a third @a tolerance argument can
  !! be given to define a maximum distance for the values to be close enough.
  INTERFACE qcompare
     MODULE PROCEDURE qcompare_int
     MODULE PROCEDURE qcompare_real
     MODULE PROCEDURE qcompare_double
     MODULE PROCEDURE qcompare_string
  END INTERFACE qcompare

   INTERFACE qcompare_expect_fail
      MODULE PROCEDURE qcompare_expect_fail_int
      MODULE PROCEDURE qcompare_expect_fail_real
      MODULE PROCEDURE qcompare_expect_fail_double
      MODULE PROCEDURE qcompare_expect_fail_string
   END INTERFACE qcompare_expect_fail
  !> @interface
  !! QCOMPARE (expect fail)

  INTERFACE
     PURE SUBROUTINE qtest_qcompare_int_expect_fail(actual,expected, dataIndex, comment) &
          & BIND(C, NAME='qtest_qcompare_int_expect_fail')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_int, c_char
       IMPLICIT NONE
       INTEGER(kind=c_int),    INTENT(IN), VALUE  :: actual
       INTEGER(kind=c_int),    INTENT(IN), VALUE  :: expected
       CHARACTER(kind=c_char), INTENT(IN)         :: dataIndex(*)
       CHARACTER(kind=c_char), INTENT(IN)         :: comment(*)
     END SUBROUTINE qtest_qcompare_int_expect_fail

     PURE SUBROUTINE qtest_qcompare_real_expect_fail(actual,expected, dataIndex, comment) &
          & BIND(C, NAME='qtest_qcompare_float_expect_fail')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_float, c_char
       IMPLICIT NONE
       REAL(kind=c_float),    INTENT(IN), VALUE   :: actual
       REAL(kind=c_float),    INTENT(IN), VALUE   :: expected
       CHARACTER(kind=c_char), INTENT(IN)         :: dataIndex(*)
       CHARACTER(kind=c_char), INTENT(IN)         :: comment(*)
     END SUBROUTINE qtest_qcompare_real_expect_fail

     PURE SUBROUTINE qtest_qcompare_double_expect_fail(actual,expected, dataIndex, comment) &
          & BIND(C, NAME='qtest_qcompare_double_expect_fail')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_double, c_char
       IMPLICIT NONE
       REAL(kind=c_double),    INTENT(IN), VALUE  :: actual
       REAL(kind=c_double),    INTENT(IN), VALUE  :: expected
       CHARACTER(kind=c_char), INTENT(IN)         :: dataIndex(*)
       CHARACTER(kind=c_char), INTENT(IN)         :: comment(*)
     END SUBROUTINE qtest_qcompare_double_expect_fail

     PURE SUBROUTINE qtest_qcompare_string_expect_fail(actual,expected, dataIndex, comment) &
          & BIND(C, NAME='qtest_qcompare_string_expect_fail')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_char
       IMPLICIT NONE
       CHARACTER(kind=c_char), INTENT(IN)         :: actual(*)
       CHARACTER(kind=c_char), INTENT(IN)         :: expected(*)
       CHARACTER(kind=c_char), INTENT(IN)         :: dataIndex(*)
       CHARACTER(kind=c_char), INTENT(IN)         :: comment(*)
     END SUBROUTINE qtest_qcompare_string_expect_fail
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qwarn(message) BIND(C, NAME='qtest_qwarn')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_char
       IMPLICIT NONE
       CHARACTER(kind=c_char), INTENT(in)         :: message(*)
     END SUBROUTINE qtest_qwarn
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qfail(message) BIND(C, NAME='qtest_qfail')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_char
       IMPLICIT NONE
       CHARACTER(kind=c_char), INTENT(IN)         :: message(*)
     END SUBROUTINE qtest_qfail
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qexpect_fail(dataIndex, comment, mode) &
          & BIND(C, NAME='qtest_qexpect_fail')
       USE, INTRINSIC :: ISO_C_BINDING, only : c_char, c_int
       IMPLICIT NONE
       CHARACTER(kind=c_char), INTENT(in)         :: dataIndex(*)
       CHARACTER(kind=c_char), INTENT(in)         :: comment(*)
       INTEGER(kind=c_int),    INTENT(in), VALUE  :: mode
     END SUBROUTINE qtest_qexpect_fail
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qverify(cond) BIND(C, NAME='qtest_qverify')
       USE, INTRINSIC :: ISO_C_BINDING
       IMPLICIT NONE
       INTEGER(kind=c_int),    INTENT(in), VALUE  :: cond
     END SUBROUTINE qtest_qverify
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qverify2(cond, message) BIND(C, NAME='qtest_qverify2')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_char, c_int
       IMPLICIT NONE
       INTEGER(c_int), INTENT(in), VALUE          :: cond
       CHARACTER(kind=c_char), INTENT(in)         :: message(*)
     END SUBROUTINE qtest_qverify2
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qcompare_int(actual, expected) BIND(C, name='qtest_qcompare_int')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_int
       IMPLICIT NONE
       INTEGER(c_int), INTENT(in), VALUE          :: actual
       INTEGER(c_int), INTENT(in), VALUE          :: expected
     END SUBROUTINE qtest_qcompare_int
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qcompare_float(actual, expected) BIND(C, name='qtest_qcompare_float')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_float
       IMPLICIT NONE
       REAL(kind=c_float), INTENT(in), VALUE      :: actual
       REAL(kind=c_float), INTENT(in), VALUE      :: expected
     END SUBROUTINE qtest_qcompare_float
  END INTERFACE

  INTERFACE
     PURE SUBROUTINE qtest_qcompare_double(actual, expected) BIND(C, name='qtest_qcompare_double')
       USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_double
       IMPLICIT NONE
       REAL(kind=c_double), INTENT(in), VALUE     :: actual
       REAL(kind=c_double), INTENT(in), VALUE     :: expected
     END SUBROUTINE qtest_qcompare_double
  END INTERFACE

 INTERFACE
    PURE SUBROUTINE qtest_qcompare_string(actual, expected) BIND(C, name='qtest_qcompare_string')
      USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_char
      IMPLICIT NONE
      CHARACTER(kind=c_char), INTENT(in)          :: actual(*)
      CHARACTER(kind=c_char), INTENT(in)          :: expected(*)
    END SUBROUTINE qtest_qcompare_string
 END INTERFACE

CONTAINS

  !> Checks the current compiler for compatible bindings used by this test-library
  !! @section Example
  !! @verbatim
  !! CALL check_c_binding
  !! @endverbatim
  PURE SUBROUTINE check_c_binding
    USE, INTRINSIC :: ISO_C_BINDING, ONLY : c_int, c_float, c_double, c_char, c_int
    IMPLICIT NONE
    !
    CALL check(c_int, KIND(1), 'integer/int ')
    CALL check(c_float, KIND(1.0e0), 'real/float ')
    CALL check(c_double, KIND(1.0d0), 'double precision/double' )
    CALL check(c_char, KIND('A'), 'character/char')
    CALL check(c_int, KIND(.true.), 'int/logical')

  END SUBROUTINE check_c_binding

  !> @internal
  PURE SUBROUTINE check(ckind, fkind, vartype)
    INTEGER, INTENT(IN)                           :: ckind    !> C datatype
    INTEGER, INTENT(IN)                           :: fkind    !> Fortran datatype
    CHARACTER(LEN=*), INTENT(IN)                  :: vartype  !> Description

    CALL qverify(ckind == fkind, TRIM(vartype)//c_null_char)
  END SUBROUTINE check

  !> Appends message as a warning to the test log. This macro can be used
  !! anywhere in your tests.
  !! @param[in] message The message to be displayed
  PURE SUBROUTINE qwarn(message)
    CHARACTER(*),INTENT(in)                       :: message
    CALL qtest_qwarn(TRIM(message)//c_null_char)
  END SUBROUTINE qwarn

  !> This subroutine can be used to force a test failure.
  !! The test stops executing and the failure message is appended to the test log.
  !! @param[in] message The message to be displayed
  PURE SUBROUTINE qfail(message)
    CHARACTER(*),INTENT(in)                       :: message
    CALL qtest_qfail(TRIM(message)//c_null_char)
  END SUBROUTINE qfail

  !> The QEXPECT_FAIL subroutine marks the next QCOMPARE() or QVERIFY() as an expected
  !! failure. Instead of adding a failure to the test log, an expected failure will
  !! be reported. If a QVERIFY() or QCOMPARE() is marked as an expected failure, but
  !! passes instead, an unexpected pass (XPASS) is written to the test log.
  !!
  !! The parameter dataIndex is not currently used in FQUnit. Pass an empty character ('')
  !! @section Example
  !! @verbatim
  !! CALL qexpect_fail( '', 'this test should fail', perdue )
  !! CALL qcompare(1,2)
  !! @endverbatim
  !
  ELEMENTAL SUBROUTINE qexpect_fail(dataIndex, comment, mode)
    CHARACTER(*),INTENT(in)                       :: dataIndex
    CHARACTER(*),INTENT(in)                       :: comment
    INTEGER,     INTENT(in)                       :: mode
    !
    CALL qtest_qexpect_fail(TRIM(dataIndex)//c_null_char, &
         & TRIM(comment)//c_null_char, INT(mode, KIND(c_int)))
  END SUBROUTINE qexpect_fail

  !> The QVERIFY() subroutine checks whether the condition is true or not.
  !! If it is true, execution continues. If not, a failure is recorded in
  !! the test log and the test won't be executed further.
  !! @param[in] cond A LOGICAL conditio
  !! @param[in,optional] message A message that will be displayed when the condition is false
  !!
  !! @section Example
  !! @verbatim
  !! CALL qverify(2 == 1+1)
  !! @endverbatim
  !! Since QVERIFY is declared as ELEMENTAL (Fortran2003), the subroutine
  !! will be called for each element if given an array of logical arguments
  !! @section Example
  !! @verbatim
  !! CALL qverify((/2 == 1+1, 3 == 2+1, 5==2+3/))
  !! @endverbatim
  !!
  !! Optionally, an argument @a message can be given to specify a verbose message
  !! that will be displayed when the condition is false.
  !
  ELEMENTAL SUBROUTINE qverify(cond, message)
    LOGICAL, INTENT(in)                           :: cond
    CHARACTER(*), INTENT(in), OPTIONAL            :: message
    !
    INTEGER(c_int)     :: i
    if( cond ) then
       i = 1
    else
       i = 0
    endif

    IF (PRESENT(message) ) THEN
       CALL qtest_qverify2(i, TRIM(message)//c_null_char)
    ELSE
       CALL qtest_qverify(i)
    END IF
  END SUBROUTINE qverify

  !> qcompare_integers
  ELEMENTAL SUBROUTINE qcompare_int(actual, expected, tolerance)
    INTEGER, INTENT(in)                           :: actual
    INTEGER, INTENT(in)                           :: expected
    INTEGER, INTENT(in), OPTIONAL                 :: tolerance
    !
    IF (PRESENT(tolerance)) THEN
       CALL qverify(ABS(actual - expected) < ABS(tolerance))
    ELSE
       CALL qtest_qcompare_int(INT(actual, KIND(c_int)),INT(expected, KIND(c_int)))
    END IF
  END SUBROUTINE qcompare_int

  !> qcompare_real
  ELEMENTAL SUBROUTINE qcompare_real(actual, expected,tolerance)
    REAL, INTENT(in)                              :: actual
    REAL, INTENT(in)                              :: expected
    REAL, INTENT(in), OPTIONAL                    :: tolerance
    !
    IF (PRESENT(tolerance)) THEN
       CALL qverify(ABS(actual - expected) < ABS(tolerance))
    ELSE
       CALL qtest_qcompare_float(REAL(actual, KIND(1.0e0)), REAL(expected, KIND(1.0e0)))
    END IF
  END SUBROUTINE qcompare_real

  !> compare double
  ELEMENTAL SUBROUTINE qcompare_double(actual, expected,tolerance)
    DOUBLE PRECISION, INTENT(in)                  :: actual
    DOUBLE PRECISION, INTENT(in)                  :: expected
    DOUBLE PRECISION, INTENT(in), optional        :: tolerance
    !
    IF (PRESENT(tolerance)) THEN
       CALL qverify(ABS(actual - expected) < ABS(tolerance))
    ELSE
       CALL qtest_qcompare_double(REAL(actual,KIND(1.0d0)),REAL(expected,KIND(1.0d0)))
    END IF
  END SUBROUTINE qcompare_double

  !> qcompare_strings
  ELEMENTAL SUBROUTINE qcompare_string(actual, expected)
    CHARACTER(*), INTENT(in)                      :: actual
    CHARACTER(*), INTENT(in)                      :: expected
    CALL qtest_qcompare_string(TRIM(actual)//c_null_char, TRIM(expected)//c_null_char)
  END SUBROUTINE qcompare_string

  !> qcompare_expect_fail
  !! This subroutine is especially handy if you need to take advantage of the ELEMENTAL
  !! declaration, and every call to this function is expected to fail.
  !! @param[in] actual  The value to compare
  !! @param[in] expected  The expected value to compare @a actual with
  !!
  !! @section Example
  !! @verbatim
  !!  INTEGER, DIMENSION(50) :: iarray_a = (/ (i, i=1,50) /)
  !!  INTEGER, DIMENSION(50) :: iarray_b = (/ (i*2, i=1,50) /)
  !!  CALL qcompare_expect_fail( iarray_a, iarray_b, '', 'This should fail' )
  !! @endverbatim
  ELEMENTAL SUBROUTINE qcompare_expect_fail_int(actual, expected, index, message)
    INTEGER, INTENT(in)                           :: actual
    INTEGER, INTENT(in)                           :: expected
    CHARACTER(*), INTENT(in)                      :: index
    CHARACTER(*), INTENT(in)                      :: message
    !
    CALL qtest_qcompare_int_expect_fail(INT(actual, KIND(c_int)), &
         & INT(expected, KIND(c_int)), &
         & TRIM(index)//c_null_char, TRIM(message)//c_null_char)
  END SUBROUTINE qcompare_expect_fail_int

  ELEMENTAL SUBROUTINE qcompare_expect_fail_real(actual, expected, index, message)
    REAL, INTENT(in)                              :: actual
    REAL, INTENT(in)                              :: expected
    CHARACTER(*), INTENT(in)                      :: index
    CHARACTER(*), INTENT(in)                      :: message
    !
    CALL qtest_qcompare_real_expect_fail(REAL(actual, KIND(1.0e0)), &
         & REAL(expected, KIND(1.0e0)), &
         & TRIM(index)//c_null_char, TRIM(message)//c_null_char)
  END SUBROUTINE qcompare_expect_fail_real

  ELEMENTAL SUBROUTINE qcompare_expect_fail_double(actual, expected, index, message)
    DOUBLE PRECISION, INTENT(in)                  :: actual
    DOUBLE PRECISION, INTENT(in)                  :: expected
    CHARACTER(*), INTENT(in)                      :: index
    CHARACTER(*), INTENT(in)                      :: message
    !
    CALL qtest_qcompare_double_expect_fail(REAL(actual, KIND(1.0d0)), &
         & REAL(expected, KIND(1.0d0)), &
         & TRIM(index)//c_null_char, TRIM(message)//c_null_char)
  END SUBROUTINE qcompare_expect_fail_double

  ELEMENTAL SUBROUTINE qcompare_expect_fail_string(actual, expected, index, message)
    CHARACTER(*), INTENT(in)                      :: actual
    CHARACTER(*), INTENT(in)                      :: expected
    CHARACTER(*), INTENT(in)                      :: index
    CHARACTER(*), INTENT(in)                      :: message
    !
    CALL qtest_qcompare_string_expect_fail( &
         & TRIM(actual)//c_null_char, &
         & TRIM(expected)// c_null_char, &
         & TRIM(index)//c_null_char, &
         & TRIM(message)//c_null_char)
  END SUBROUTINE qcompare_expect_fail_string

END MODULE class_qtest


text:
import { IDataProvider } from "../interfaces/IDataProvider";
import { ProviderEventType } from "./ProviderEventType";

/**
 * Interface for general provider events.
 */
export interface ProviderEvent {
    /**
     * Data provider target that emitted the event.
     */
    target: IDataProvider;

    /**
     * Provider event type.
     */
    type: ProviderEventType;
}


text:
package org.apache.sis.internal.storage.xml.stream;

import java.io.Writer;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stax.StAXResult;
import org.xml.sax.ContentHandler;
import org.w3c.dom.Node;

/**
 * Creates {@link XMLStreamWriter} from a given output. This enumeration allows to analyze the output type
 * only once before to create as many instances of {@link XMLStreamWriter} as needed for that output.
 * The enumeration order is the preference order (i.e. we will test if the object already implements the
 * {@link XMLStreamWriter} interface before to test for {@link OutputStream}, {@link Writer}, etc.).
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.8
 * @since   0.8
 * @module
 */
enum OutputType {
    /**
     * The output is already an instance of {@link XMLStreamWriter}.
     * That output is returned directly.
     */
    STAX(XMLStreamWriter.class, InputType.STAX) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) {
            return (XMLStreamWriter) s;
        }
    },

    /**
     * The output is an instance of Java I/O {@link OutputStream}.
     * Encoding depends on the {@linkplain StaxDataStore#encoding data store character encoding}.
     */
    STREAM(OutputStream.class, InputType.STREAM) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException {
            final XMLOutputFactory f = ds.outputFactory();
            return (ds.encoding != null) ? f.createXMLStreamWriter((OutputStream) s, ds.encoding.name())
                                         : f.createXMLStreamWriter((OutputStream) s);
        }
        @Override Closeable snapshot(final Object s) {
            if (s instanceof ByteArrayOutputStream) {
                return new ByteArrayInputStream(((ByteArrayOutputStream) s).toByteArray());
            }
            return super.snapshot(s);
        }
    },

    /**
     * The output is an instance of Java I/O {@link Writer}.
     */
    CHARACTERS(Writer.class, InputType.CHARACTERS) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException {
            return ds.outputFactory().createXMLStreamWriter((Writer) s);
        }
        @Override Closeable snapshot(final Object s) {
            if (s instanceof StringWriter) {
                return new StringReader(s.toString());
            }
            return super.snapshot(s);
        }
    },

    /**
     * The output is an instance of XML {@link Result}, which is itself a wrapper around another kind of result.
     */
    RESULT(Result.class, InputType.SOURCE) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException {
            return ds.outputFactory().createXMLStreamWriter((Result) s);
        }
    },

    /**
     * The output is an instance of DOM {@link Node}.
     */
    NODE(Node.class, InputType.NODE) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException {
            return ds.outputFactory().createXMLStreamWriter(new DOMResult((Node) s));
        }
    },

    /**
     * The output is an instance of SAX {@link ContentHandler}.
     */
    SAX(ContentHandler.class, InputType.SAX) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException {
            return ds.outputFactory().createXMLStreamWriter(new SAXResult((ContentHandler) s));
        }
    },

    /**
     * The output is an instance of STAX {@link XMLEventWriter}.
     */
    EVENT(XMLEventWriter.class, InputType.EVENT) {
        @Override XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException {
            return ds.outputFactory().createXMLStreamWriter(new StAXResult((XMLEventWriter) s));
        }
    };

    /**
     * The kind of output that this enumeration can handle.
     */
    private final Class<?> outputType;

    /**
     * The input type from the same framework (StAX, DOM, etc) than this output type.
     */
    final InputType inputType;

    /**
     * Creates a new enumeration for the given type of output.
     */
    private OutputType(final Class<?> outputType, final InputType inputType) {
        this.inputType  = inputType;
        this.outputType = outputType;
    }

    /**
     * Creates a XML writer for the given output.
     *
     * @param  ds  the data store for which to create writer instances.
     * @param  s   the output stream or the storage object (URL, etc).
     * @return the XML writer.
     * @throws XMLStreamException if the XML writer creation failed.
     */
    abstract XMLStreamWriter create(StaxDataStore ds, Object s) throws XMLStreamException;

    /**
     * Returns a reader for the data written by the given writer, or {@code null} if we cannot read the data.
     * If non-null, the value returned by this method is a snapshot of the given stream content, i.e. changes
     * in the output stream will not affect the returned input stream or reader. In particular, contrarily to
     * {@link org.apache.sis.internal.storage.io.IOUtilities#toInputStream(AutoCloseable)} this method does not
     * invalidate the output stream.
     *
     *
The returned input can be used by {@link #inputType}.

     *
     * @param  s  the output from which to get the data that we wrote.
     * @return the input for the data written by the given stream, or {@code null} if none.
     */
    Closeable snapshot(final Object s) {
        return null;
    }

    /**
     * Returns a {@code WriterFactory} for the given output type. The {@code type} argument given to this method
     * shall be the class of the {@code s} argument to be given in {@link #create(StaxDataStore, Object)} calls.
     *
     * @param  type  the type of the output stream or storage object (URL, etc).
     * @return a factory for the given stream or storage type, or {@code null} if the given type is not recognized.
     */
    static OutputType forType(final Class<?> type) {
        for (final OutputType c : values()) {
            if (c.outputType.isAssignableFrom(type)) {
                return c;
            }
        }
        return null;
    }
}


text:
FROM smebberson/alpine-base:1.2.0

#Build script installs sshd
COPY build.sh /build.sh
RUN chmod 755 /build.sh
RUN /build.sh
RUN rm build.sh

#Die a bit faster on exit:
ENV S6_KILL_GRACETIME=500

#Script to generate host keys on startup:
COPY keygen.sh /etc/cont-init.d/keygen
RUN chmod 755 /etc/cont-init.d/keygen

EXPOSE 22

#-D = don't detach, -e = output to stderr, -f = config file
CMD [ "/usr/sbin/sshd", "-D", "-e", "-f", "/etc/ssh/sshd_config"]


text:
package org.apache.flink.runtime.resourcemanager.slotmanager;

import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.instance.InstanceID;
import org.apache.flink.runtime.resourcemanager.registration.TaskExecutorConnection;
import org.apache.flink.util.Preconditions;

import java.util.Collection;
import java.util.HashSet;

public class TaskManagerRegistration {

    private final TaskExecutorConnection taskManagerConnection;

    private final ResourceProfile defaultSlotResourceProfile;

    private final ResourceProfile totalResource;

    private final HashSet<SlotID> slots;

    private int numberFreeSlots;

    /** Timestamp when the last time becoming idle. Otherwise Long.MAX_VALUE. */
    private long idleSince;

    public TaskManagerRegistration(
            TaskExecutorConnection taskManagerConnection,
            Collection<SlotID> slots,
            ResourceProfile totalResourceProfile,
            ResourceProfile defaultSlotResourceProfile) {

        this.taskManagerConnection =
                Preconditions.checkNotNull(taskManagerConnection, "taskManagerConnection");
        Preconditions.checkNotNull(slots, "slots");

        this.totalResource = Preconditions.checkNotNull(totalResourceProfile);
        this.defaultSlotResourceProfile = Preconditions.checkNotNull(defaultSlotResourceProfile);

        this.slots = new HashSet<>(slots);

        this.numberFreeSlots = slots.size();

        idleSince = System.currentTimeMillis();
    }

    public TaskExecutorConnection getTaskManagerConnection() {
        return taskManagerConnection;
    }

    public InstanceID getInstanceId() {
        return taskManagerConnection.getInstanceID();
    }

    public int getNumberRegisteredSlots() {
        return slots.size();
    }

    public int getNumberFreeSlots() {
        return numberFreeSlots;
    }

    public ResourceProfile getDefaultSlotResourceProfile() {
        return defaultSlotResourceProfile;
    }

    public ResourceProfile getTotalResource() {
        return totalResource;
    }

    public void freeSlot() {
        Preconditions.checkState(
                numberFreeSlots < slots.size(),
                "The number of free slots cannot exceed the number of registered slots. This indicates a bug.");
        numberFreeSlots++;

        if (numberFreeSlots == getNumberRegisteredSlots() && idleSince == Long.MAX_VALUE) {
            idleSince = System.currentTimeMillis();
        }
    }

    public void occupySlot() {
        Preconditions.checkState(
                numberFreeSlots > 0, "There are no more free slots. This indicates a bug.");
        numberFreeSlots--;

        idleSince = Long.MAX_VALUE;
    }

    public Iterable<SlotID> getSlots() {
        return slots;
    }

    public long getIdleSince() {
        return idleSince;
    }

    public boolean isIdle() {
        return idleSince != Long.MAX_VALUE;
    }

    public void markUsed() {
        idleSince = Long.MAX_VALUE;
    }

    public boolean containsSlot(SlotID slotId) {
        return slots.contains(slotId);
    }
}


text:
""" Websocket client module """

import socket
import asyncio
import websockets

from smserver.smutils import smconn

class WebSocketClient(smconn.StepmaniaConn):
    ENCODING = "json"

    def __init__(self, serv, ip, port, websocket, _path, loop):
        smconn.StepmaniaConn.__init__(self, serv, ip, port)
        self.websocket = websocket
        self.task = None
        self.loop = loop

    @asyncio.coroutine
    def run(self):
        while True:
            try:
                data = yield from self.websocket.recv()
            except websockets.ConnectionClosed:
                break
            self._on_data(data)

        self.close()

    def send_data(self, data):
        self.loop.create_task(self.websocket.send(data))

    def close(self):
        self._serv.on_disconnect(self)
        self.websocket.close()

class WebSocketServer(smconn.SMThread):
    def __init__(self, server, ip, port, loop=None):
        smconn.SMThread.__init__(self, server, ip, port)

        self.loop = loop or asyncio.new_event_loop()

        self._serv = None
        self.server = server
        self.daemon = True
        self.ip = ip
        self.port = port

    @asyncio.coroutine
    def _accept_client(self, websocket, path=""):
        ip, port = websocket.remote_address
        client = WebSocketClient(self.server, ip, port, websocket, path, self.loop)

        self.server.add_connection(client)
        try:
            yield from client.run()
        except Exception:
            client.close()
            raise

    def run(self):
        self.start_server()
        self.loop.run_forever()
        smconn.SMThread.run(self)

    def start_server(self):
        """ Start the websocket server """

        self._serv = self.loop.run_until_complete(
            websockets.serve(
                self._accept_client,
                host=self.ip,
                port=self.port,
                loop=self.loop,
            )
        )
        return self._serv

    def stop_server(self):
        """ Stop the server in the given loop """

        if self._serv is None:
            return

        sockets = self._serv.server.sockets
        if sockets:
            for sock in sockets:
                try:
                    sock.shutdown(socket.SHUT_RDWR)
                except OSError:
                    pass

        self._serv.close()
        self.loop.run_until_complete(
            asyncio.wait_for(self._serv.wait_closed(), timeout=1)
        )

    def stop(self):
        smconn.SMThread.stop(self)
        self.stop_server()
        self.loop.stop()


text:
package org.springframework.boot.web.embedded.jetty;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EventListener;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration.Dynamic;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.awaitility.Awaitility;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.webapp.AbstractConfiguration;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;

import org.springframework.boot.web.server.GracefulShutdownResult;
import org.springframework.boot.web.server.Shutdown;
import org.springframework.boot.web.server.Ssl;
import org.springframework.boot.web.server.WebServerException;
import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory;
import org.springframework.util.ReflectionUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link JettyServletWebServerFactory}.
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author Andy Wilkinson
 * @author Henri Kerola
 */
class JettyServletWebServerFactoryTests extends AbstractJettyServletWebServerFactoryTests {

	@Test
	protected void correctVersionOfJettyUsed() {
		String jettyVersion = ErrorHandler.class.getPackage().getImplementationVersion();
		Matcher matcher = Pattern.compile("[0-9]+.[0-9]+.([0-9]+)[\\.-].*").matcher(jettyVersion);
		assertThat(matcher.find()).isTrue();
		assertThat(Integer.valueOf(matcher.group(1))).isGreaterThan(19);
	}

	@Test
	protected void jettyConfigurations() throws Exception {
		JettyServletWebServerFactory factory = getFactory();
		Configuration[] configurations = new Configuration[4];
		Arrays.setAll(configurations, (i) -> mock(Configuration.class));
		factory.setConfigurations(Arrays.asList(configurations[0], configurations[1]));
		factory.addConfigurations(configurations[2], configurations[3]);
		this.webServer = factory.getWebServer();
		InOrder ordered = inOrder((Object[]) configurations);
		for (Configuration configuration : configurations) {
			ordered.verify(configuration).configure(any(WebAppContext.class));
		}
	}

	@Test
	void jettyCustomizations() {
		JettyServletWebServerFactory factory = getFactory();
		JettyServerCustomizer[] configurations = new JettyServerCustomizer[4];
		Arrays.setAll(configurations, (i) -> mock(JettyServerCustomizer.class));
		factory.setServerCustomizers(Arrays.asList(configurations[0], configurations[1]));
		factory.addServerCustomizers(configurations[2], configurations[3]);
		this.webServer = factory.getWebServer();
		InOrder ordered = inOrder((Object[]) configurations);
		for (JettyServerCustomizer configuration : configurations) {
			ordered.verify(configuration).customize(any(Server.class));
		}
	}

	@Test
	void sessionTimeout() {
		JettyServletWebServerFactory factory = getFactory();
		factory.getSession().setTimeout(Duration.ofSeconds(10));
		assertTimeout(factory, 10);
	}

	@Test
	void sessionTimeoutInMinutes() {
		JettyServletWebServerFactory factory = getFactory();
		factory.getSession().setTimeout(Duration.ofMinutes(1));
		assertTimeout(factory, 60);
	}

	@Test
	void sslCiphersConfiguration() {
		Ssl ssl = new Ssl();
		ssl.setKeyStore("src/test/resources/test.jks");
		ssl.setKeyStorePassword("secret");
		ssl.setKeyPassword("password");
		ssl.setCiphers(new String[] { "ALPHA", "BRAVO", "CHARLIE" });

		JettyServletWebServerFactory factory = getFactory();
		factory.setSsl(ssl);

		this.webServer = factory.getWebServer();
		this.webServer.start();

		JettyWebServer jettyWebServer = (JettyWebServer) this.webServer;
		ServerConnector connector = (ServerConnector) jettyWebServer.getServer().getConnectors()[0];
		SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class);
		SslContextFactory sslContextFactory = extractSslContextFactory(connectionFactory);
		assertThat(sslContextFactory.getIncludeCipherSuites()).containsExactly("ALPHA", "BRAVO", "CHARLIE");
		assertThat(sslContextFactory.getExcludeCipherSuites()).isEmpty();
	}

	@Test
	void stopCalledWithoutStart() {
		JettyServletWebServerFactory factory = getFactory();
		this.webServer = factory.getWebServer(exampleServletRegistration());
		this.webServer.stop();
		Server server = ((JettyWebServer) this.webServer).getServer();
		assertThat(server.isStopped()).isTrue();
	}

	@Test
	void sslEnabledMultiProtocolsConfiguration() {
		JettyServletWebServerFactory factory = getFactory();
		factory.setSsl(getSslSettings("TLSv1.1", "TLSv1.2"));
		this.webServer = factory.getWebServer();
		this.webServer.start();
		JettyWebServer jettyWebServer = (JettyWebServer) this.webServer;
		ServerConnector connector = (ServerConnector) jettyWebServer.getServer().getConnectors()[0];
		SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class);
		SslContextFactory sslContextFactory = extractSslContextFactory(connectionFactory);
		assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.1", "TLSv1.2");
	}

	@Test
	void sslEnabledProtocolsConfiguration() {
		JettyServletWebServerFactory factory = getFactory();
		factory.setSsl(getSslSettings("TLSv1.1"));
		this.webServer = factory.getWebServer();
		this.webServer.start();
		JettyWebServer jettyWebServer = (JettyWebServer) this.webServer;
		ServerConnector connector = (ServerConnector) jettyWebServer.getServer().getConnectors()[0];
		SslConnectionFactory connectionFactory = connector.getConnectionFactory(SslConnectionFactory.class);
		SslContextFactory sslContextFactory = extractSslContextFactory(connectionFactory);
		assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.1");
	}

	private SslContextFactory extractSslContextFactory(SslConnectionFactory connectionFactory) {
		try {
			return connectionFactory.getSslContextFactory();
		}
		catch (NoSuchMethodError ex) {
			Method getSslContextFactory = ReflectionUtils.findMethod(connectionFactory.getClass(),
					"getSslContextFactory");
			return (SslContextFactory) ReflectionUtils.invokeMethod(getSslContextFactory, connectionFactory);
		}
	}

	@Test
	void whenServerIsShuttingDownGracefullyThenNewConnectionsCannotBeMade() throws Exception {
		AbstractServletWebServerFactory factory = getFactory();
		factory.setShutdown(Shutdown.GRACEFUL);
		BlockingServlet blockingServlet = new BlockingServlet();
		this.webServer = factory.getWebServer((context) -> {
			Dynamic registration = context.addServlet("blockingServlet", blockingServlet);
			registration.addMapping("/blocking");
			registration.setAsyncSupported(true);
		});
		this.webServer.start();
		int port = this.webServer.getPort();
		Future<Object> request = initiateGetRequest(port, "/blocking");
		blockingServlet.awaitQueue();
		this.webServer.shutDownGracefully((result) -> {
		});
		Future<Object> unconnectableRequest = initiateGetRequest(port, "/");
		blockingServlet.admitOne();
		Object response = request.get();
		assertThat(response).isInstanceOf(HttpResponse.class);
		assertThat(unconnectableRequest.get()).isInstanceOf(HttpHostConnectException.class);
		this.webServer.stop();
	}

	@Test
	void whenServerIsShuttingDownGracefullyThenResponseToRequestOnIdleConnectionWillHaveAConnectionCloseHeader()
			throws Exception {
		AbstractServletWebServerFactory factory = getFactory();
		factory.setShutdown(Shutdown.GRACEFUL);
		BlockingServlet blockingServlet = new BlockingServlet();
		this.webServer = factory.getWebServer((context) -> {
			Dynamic registration = context.addServlet("blockingServlet", blockingServlet);
			registration.addMapping("/blocking");
			registration.setAsyncSupported(true);
		});
		this.webServer.start();
		int port = this.webServer.getPort();
		HttpClient client = HttpClients.createMinimal();
		Future<Object> request = initiateGetRequest(client, port, "/blocking");
		blockingServlet.awaitQueue();
		blockingServlet.admitOne();
		Object response = request.get();
		assertThat(response).isInstanceOf(HttpResponse.class);
		assertThat(((HttpResponse) response).getStatusLine().getStatusCode()).isEqualTo(200);
		assertThat(((HttpResponse) response).getFirstHeader("Connection")).isNull();
		this.webServer.shutDownGracefully((result) -> {
		});
		request = initiateGetRequest(client, port, "/blocking");
		blockingServlet.awaitQueue();
		blockingServlet.admitOne();
		response = request.get();
		assertThat(response).isInstanceOf(HttpResponse.class);
		assertThat(((HttpResponse) response).getStatusLine().getStatusCode()).isEqualTo(200);
		assertThat(((HttpResponse) response).getFirstHeader("Connection")).isNotNull().extracting(Header::getValue)
				.isEqualTo("close");
		this.webServer.stop();
	}

	@Test
	void whenARequestCompletesAfterGracefulShutdownHasBegunThenItHasAConnectionCloseHeader()
			throws InterruptedException, ExecutionException {
		AbstractServletWebServerFactory factory = getFactory();
		factory.setShutdown(Shutdown.GRACEFUL);
		BlockingServlet blockingServlet = new BlockingServlet();
		this.webServer = factory.getWebServer((context) -> {
			Dynamic registration = context.addServlet("blockingServlet", blockingServlet);
			registration.addMapping("/blocking");
			registration.setAsyncSupported(true);
		});
		this.webServer.start();
		int port = this.webServer.getPort();
		Future<Object> request = initiateGetRequest(port, "/blocking");
		blockingServlet.awaitQueue();
		AtomicReference<GracefulShutdownResult> result = new AtomicReference<>();
		this.webServer.shutDownGracefully(result::set);
		blockingServlet.admitOne();
		Awaitility.await().atMost(Duration.ofSeconds(5)).until(() -> GracefulShutdownResult.IDLE == result.get());
		Object requestResult = request.get();
		assertThat(requestResult).isInstanceOf(HttpResponse.class);
		assertThat(((HttpResponse) requestResult).getFirstHeader("Connection").getValue()).isEqualTo("close");
	}

	private Ssl getSslSettings(String... enabledProtocols) {
		Ssl ssl = new Ssl();
		ssl.setKeyStore("src/test/resources/test.jks");
		ssl.setKeyStorePassword("secret");
		ssl.setKeyPassword("password");
		ssl.setCiphers(new String[] { "ALPHA", "BRAVO", "CHARLIE" });
		ssl.setEnabledProtocols(enabledProtocols);
		return ssl;
	}

	private void assertTimeout(JettyServletWebServerFactory factory, int expected) {
		this.webServer = factory.getWebServer();
		JettyWebServer jettyWebServer = (JettyWebServer) this.webServer;
		WebAppContext webAppContext = findWebAppContext(jettyWebServer);
		int actual = webAppContext.getSessionHandler().getMaxInactiveInterval();
		assertThat(actual).isEqualTo(expected);
	}

	@Test
	void wrappedHandlers() throws Exception {
		JettyServletWebServerFactory factory = getFactory();
		factory.setServerCustomizers(Collections.singletonList((server) -> {
			Handler handler = server.getHandler();
			HandlerWrapper wrapper = new HandlerWrapper();
			wrapper.setHandler(handler);
			HandlerCollection collection = new HandlerCollection();
			collection.addHandler(wrapper);
			server.setHandler(collection);
		}));
		this.webServer = factory.getWebServer(exampleServletRegistration());
		this.webServer.start();
		assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World");
	}

	@Test
	void basicSslClasspathKeyStore() throws Exception {
		testBasicSslWithKeyStore("classpath:test.jks");
	}

	@Test
	void useForwardHeaders() throws Exception {
		JettyServletWebServerFactory factory = getFactory();
		factory.setUseForwardHeaders(true);
		assertForwardHeaderIsUsed(factory);
	}

	@Test
	void defaultThreadPool() {
		JettyServletWebServerFactory factory = getFactory();
		factory.setThreadPool(null);
		assertThat(factory.getThreadPool()).isNull();
		this.webServer = factory.getWebServer();
		assertThat(((JettyWebServer) this.webServer).getServer().getThreadPool()).isNotNull();
	}

	@Test
	void customThreadPool() {
		JettyServletWebServerFactory factory = getFactory();
		ThreadPool threadPool = mock(ThreadPool.class);
		factory.setThreadPool(threadPool);
		this.webServer = factory.getWebServer();
		assertThat(((JettyWebServer) this.webServer).getServer().getThreadPool()).isSameAs(threadPool);
	}

	@Test
	void startFailsWhenThreadPoolIsTooSmall() {
		JettyServletWebServerFactory factory = getFactory();
		factory.addServerCustomizers((server) -> {
			QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
			threadPool.setMaxThreads(2);
			threadPool.setMinThreads(2);
		});
		assertThatExceptionOfType(WebServerException.class).isThrownBy(factory.getWebServer()::start)
				.withCauseInstanceOf(IllegalStateException.class);
	}

	@Test
	void specificIPAddressNotReverseResolved() throws Exception {
		JettyServletWebServerFactory factory = getFactory();
		InetAddress localhost = InetAddress.getLocalHost();
		factory.setAddress(InetAddress.getByAddress(localhost.getAddress()));
		this.webServer = factory.getWebServer();
		this.webServer.start();
		Connector connector = ((JettyWebServer) this.webServer).getServer().getConnectors()[0];
		assertThat(((ServerConnector) connector).getHost()).isEqualTo(localhost.getHostAddress());
	}

	@Test
	void specificIPAddressWithSslIsNotReverseResolved() throws Exception {
		JettyServletWebServerFactory factory = getFactory();
		InetAddress localhost = InetAddress.getLocalHost();
		factory.setAddress(InetAddress.getByAddress(localhost.getAddress()));
		Ssl ssl = new Ssl();
		ssl.setKeyStore("src/test/resources/test.jks");
		ssl.setKeyStorePassword("secret");
		ssl.setKeyPassword("password");
		factory.setSsl(ssl);
		this.webServer = factory.getWebServer();
		this.webServer.start();
		Connector connector = ((JettyWebServer) this.webServer).getServer().getConnectors()[0];
		assertThat(((ServerConnector) connector).getHost()).isEqualTo(localhost.getHostAddress());
	}

	@Test
	void faultyListenerCausesStartFailure() throws Exception {
		JettyServletWebServerFactory factory = getFactory();
		factory.addServerCustomizers((JettyServerCustomizer) (server) -> {
			Collection<WebAppContext> contexts = server.getBeans(WebAppContext.class);
			EventListener eventListener = new ServletContextListener() {

				@Override
				public void contextInitialized(ServletContextEvent event) {
					throw new RuntimeException();
				}

				@Override
				public void contextDestroyed(ServletContextEvent event) {
				}
			};
			WebAppContext context = contexts.iterator().next();
			try {
				context.addEventListener(eventListener);
			}
			catch (NoSuchMethodError ex) {
				// Jetty 10
				Method addEventListener = ReflectionUtils.findMethod(context.getClass(), "addEventListener",
						EventListener.class);
				ReflectionUtils.invokeMethod(addEventListener, context, eventListener);
			}
		});
		assertThatExceptionOfType(WebServerException.class).isThrownBy(() -> {
			JettyWebServer jettyWebServer = (JettyWebServer) factory.getWebServer();
			try {
				jettyWebServer.start();
			}
			finally {
				QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer.getServer().getThreadPool();
				assertThat(threadPool.isRunning()).isFalse();
			}
		});
	}

	@Test
	void errorHandlerCanBeOverridden() {
		JettyServletWebServerFactory factory = getFactory();
		factory.addConfigurations(new AbstractConfiguration() {

			@Override
			public void configure(WebAppContext context) throws Exception {
				context.setErrorHandler(new CustomErrorHandler());
			}

		});
		JettyWebServer jettyWebServer = (JettyWebServer) factory.getWebServer();
		WebAppContext context = findWebAppContext(jettyWebServer);
		assertThat(context.getErrorHandler()).isInstanceOf(CustomErrorHandler.class);
	}

	private static class CustomErrorHandler extends ErrorPageErrorHandler {

	}

}


text:
#ifndef SRC_OPERATORS_EQ_H_
#define SRC_OPERATORS_EQ_H_

#include <string>

#include "src/operators/operator.h"

namespace modsecurity {
namespace operators {

class Eq : public Operator {
 public:
    /** @ingroup ModSecurity_Operator */
    Eq(std::string op, std::string param, bool negation)
        : Operator(op, param, negation) { }
    explicit Eq(std::string param)
        : Operator("Eq", param) { }
    bool evaluate(Transaction *transaction, const std::string &input) override;
};

}  // namespace operators
}  // namespace modsecurity

#endif  // SRC_OPERATORS_EQ_H_


text:
RESERVED = 0  # reserved for invalid segments, do not use
REQUEST = 1
REPLY = 2
ERROR = 5     # reply segment containing error


text:
import React from 'react';
import gql from 'graphql-tag';
import { map, isEmpty } from 'lodash';
import { format, parseISO } from 'date-fns';
import { useQuery } from '@apollo/react-hooks';

import TextBlock from '../utilities/TextBlock';
import Action, { ActionFragment } from '../Action';
import EntityLabel from '../utilities/EntityLabel';
import RogueClient from '../../utilities/RogueClient';

import './campaign.scss';

const SHOW_CAMPAIGN_ACTIONS_QUERY = gql`
  query ShowCampaignActionsQuery($id: Int!, $idString: String!) {
    campaign(id: $id) {
      actions {
        ...ActionFragment
      }
      causes {
        id
        name
      }
      createdAt
      endDate
      id
      contentfulCampaignId
      impactDoc
      internalTitle
      startDate
      updatedAt
      groupTypeId
      groupType {
        id
        name
      }
    }
    campaignWebsiteByCampaignId(campaignId: $idString) {
      title
      url
    }
  }
  ${ActionFragment}
`;

const Campaign = ({ id }) => {
  const apiClient = new RogueClient(window.location.origin, {
    headers: {
      Authorization: `Bearer ${window.AUTH.token}`,
    },
  });

  const { loading, error, data } = useQuery(SHOW_CAMPAIGN_ACTIONS_QUERY, {
    variables: { id, idString: `${id}` },
  });

  if (error) {
    return <TextBlock title="Error" content={JSON.stringify(error)} />;
  }

  if (loading) {
    return <TextBlock title="Loading actions..." />;
  }

  function deleteAction(action, event) {
    event.preventDefault();

    const confirmed = confirm(
      `🚨🔥🚨 Are you sure you want to delete Action ID ${action.id}? 🚨🔥🚨`,
    );

    if (confirmed) {
      // Make API request to Rogue to delete the action.
      apiClient
        .delete(`/admin/actions/${action.id}`)
        .then(() => {
          window.location.href = `/admin/campaigns/${id}`;
          alert(`Deleted Action ID ${action.id}`);
        })
        .catch(error =>
          alert(
            `Cannot delete Action ID ${action.id}: ${JSON.stringify(error)}`,
          ),
        );
    }
  }

  const { campaign, campaignWebsiteByCampaignId } = data;

  return (

Campaign Information

        <a
          className="button -secondary"
          href={`/admin/campaigns/${campaign.id}/pending`}
        >
          Campaign Inbox

Internal Campaign Name

{campaign.internalTitle}

Campaign ID

{campaign.id}

Contentful Campaign ID

        {campaign.contentfulCampaignId ? (

{campaign.contentfulCampaignId}

        ) : (

–

        )}

Group Type

          {campaign.groupType ? (
            <EntityLabel
              id={campaign.groupType.id}
              name={campaign.groupType.name}
              path="admin/group-types"
            />
          ) : (
            '–'
          )}

URL

          {campaignWebsiteByCampaignId ? (

              {campaignWebsiteByCampaignId.title}

          ) : (
            '–'
          )}

Cause Area

          {campaign.causes.length
            ? campaign.causes.map(cause => cause.name).join(', ')
            : '–'}

Proof of Impact

        {campaign.impactDoc ? (

              {campaign.impactDoc}

        ) : (

–

        )}

Start Date

{format(parseISO(campaign.startDate), 'MM/dd/yyyy')}

End Date

          {campaign.endDate
            ? format(parseISO(campaign.endDate), 'MM/dd/yyyy')
            : '–'}

        <a className="button" href={`/admin/campaigns/${campaign.id}/edit`}>
          Edit this campaign

          Last updated: {campaign.updatedAt}

          Created: {campaign.createdAt}

Campaign Actions

          Each action in your campaign requires a different set of metadata, to
          determine how it will be treated by Rogue. Use this Action ID in
          Contentful to link user submissions in Rogue.

        {!isEmpty(campaign.actions)
          ? map(campaign.actions, (action, key) => {
              return (
                <Action key={key} action={action} deleteAction={deleteAction} />
              );
            })
          : null}

          <a
            className="button -secondary"
            href={`/admin/campaigns/${campaign.id}/actions/create`}
          >
            Add Action

  );
};

export default Campaign;


text:
Psychobunnies
============

Psychobunnies is a two-player cooperative platformer with, well, psycho bunnies. They're crazy. Seriously. Try them out for yourself.

To play, download the Psychobunnies at http://psychobunnies.github.com/, extract its contents and and run the executable appropriate for your OS.


text:
package unimelb.mf.client.util;

import arc.xml.XmlDoc;
import arc.xml.XmlStringWriter;
import unimelb.mf.client.session.MFSession;

public class AssetUtils {

    public static XmlDoc.Element getAssetMeta(MFSession session, String assetId) throws Throwable {
        XmlStringWriter w = new XmlStringWriter();
        w.add("id", assetId);
        return session.execute("asset.get", w.document()).element("asset");
    }

    public static XmlDoc.Element getAssetMetaByPath(MFSession session, String assetPath) throws Throwable {
        return getAssetMeta(session, "path=" + assetPath);
    }
}


text:
namespace Web.Services
{
    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Linq;
    using System.Web.Caching;
    using System.Web;

    using AutoMapper.QueryableExtensions;
    using Gma.DataStructures.StringSearch;

    using Data;

    public class CacheService : ICacheService
    {
        private const string SubtitleSearchCacheKey = "subtitleSearch";
        private const string UserCacheDropDownFormat = "users:{0}:{1}";

        public CacheService(IApplicationData data)
        {
            this.Data = data;
        }

        protected IApplicationData Data { get; set; }
    }
}


text:
route-optimizer
===============

Forio's Route Optimizer combines linear optimization in Julia with Google Maps. The completed project runs on Forio's Epicenter platform [here](https://forio.com/app/showcase/route-optimizer/).

The Route Optimizer [model](https://github.com/forio/route-optimizer/tree/master/model) is licensed under [LGPL](https://github.com/forio/route-optimizer/tree/master/LGPL_LICENSE.txt) and the [interface](https://github.com/forio/route-optimizer/tree/master/src) is licensed under [Apache v2](https://github.com/forio/route-optimizer/tree/master/Apache_LICENSE.txt).

##To run on Epicenter
Before running the project, a Google Maps API Key is required

- Copy the 'public' folder into your Epicenter project. Tutorial [here.](https://forio.com/epicenter/docs/public/project_admin/#upload)
- Verify from your project settings that your project is set to 'public'. Tutorial [here.](https://forio.com/epicenter/docs/public/updating_your_settings/#general-settings)
- Change YOUR_KEY_HERE in index.html to reference your Google Maps API key.

## To run locally
- npm install
- bower install
- grunt production or grunt server

### Configuration
- Copy the 'configure.default.json' file into the same folder and name the new file 'config.json'
- Change the "YOUR_API_KEY" value to your API Key

##Background

Additional details on our methods and motivation are in our [blog post](http://forio.com/about/blog/route-optimizer-julia-google-maps-epicenter/).

© Forio Corporation, 2014. All rights reserved.


text:
/*global require: false, QUnit: false */

(function () {
	'use strict';

	require.config({
		waitSeconds: 0
	});

	require([
		'UtilTest.js',
		'LatLngTest.js',
		'GeolocationCodeTest.js',
		'BoundingBoxTest.js',
		'GpxTrackTest.js',
		'TrackPointTest.js',
		'TrackSegmentTest.js',
		'WebResourcesTest.js'
	], QUnit.start);

}());


text:
package org.chromium;

import android.app.Activity;
import android.content.ComponentName;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class GcmReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}


text:
OBS Remote UI optimised for tablets, but really it works with any

## Building instructions

* Clone the repository
* Install dependencies `npm install`
* Build it! `npm run build -- --homepage /`

Note: By default the build script assumes deployment to the main URL. `--homepage <url>` lets you specifiy the base URL the assets will follow.

## Developing

* Clone
* Install dependencies
* `npm run dev`