text:
package org.spongepowered.common.applaunch.config.core;

import static java.util.Objects.requireNonNull;

import io.leangen.geantyref.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.BasicConfigurationNode;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.NodePath;
import org.spongepowered.configurate.loader.ConfigurationLoader;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.transformation.ConfigurationTransformation;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

/**
 * A holder for load/save state of a configuration.
 */
public class ConfigHandle<T extends Config> {
    private static final Logger LOGGER = LogManager.getLogger();
    /**
     * Location where current version is stored
     */
    public static final NodePath VERSION_PATH = NodePath.path("version");
    private static final String VERSION_COMMENT = "Active configuration version\n"
            + "This has no relation to the current Sponge version, and will be updated automatically\n"
            + "Manual changes may cause unpredictable results.";

    // Save suppression
    // Temporary fix for IO spam -- just don't save during server load.
    private static boolean saveSuppressed = true;
    private static final Set<ConfigHandle<?>> saveQueue = ConcurrentHashMap.newKeySet();

    /**
     * Enable or disable save suppression.
     *
     *
Save on initial load will always be performed, no matter what this setting is.

     *
     * @implNote Default save suppression is {@code true}.
     * @param suppressed whether saves should be suppressed
     */
    public static void setSaveSuppressed(final boolean suppressed) {
        ConfigHandle.saveSuppressed = suppressed;
        if (!suppressed && !ConfigHandle.saveQueue.isEmpty()) {
            for (final Iterator<ConfigHandle<?>> it = ConfigHandle.saveQueue.iterator(); it.hasNext();) {
                try {
                    it.next().doSave();
                } catch (final ConfigurateException ex) {
                    ConfigHandle.LOGGER.error("Unable to save a Sponge configuration!", ex);
                }
                it.remove();
            }
        }
    }

    protected final @Nullable ConfigurationLoader<? extends CommentedConfigurationNode> loader;
    protected final Class<T> instanceType;
    protected volatile T instance;
    protected @MonotonicNonNull CommentedConfigurationNode node;
    private final @Nullable Supplier<ConfigurationTransformation> transformer;

    protected ConfigHandle(final Class<T> type) {
        try {
            this.instance = BasicConfigurationNode.root(SpongeConfigs.OPTIONS).get(type);
        } catch (final SerializationException ex) {
            throw new AssertionError(ex);
        }
        this.instanceType = type;
        this.loader = null;
        this.transformer = null;
    }

    protected ConfigHandle(final Class<T> instanceType, final @Nullable Supplier<ConfigurationTransformation> versionUpdater, final @Nullable ConfigurationLoader<? extends CommentedConfigurationNode> loader) {
        this.instanceType = instanceType;
        this.loader = loader;
        this.transformer = versionUpdater;
    }

    /**
     * If this configuration refers to a transient world or dimension type, it
     * will be marked as {@code detached}, meaning that it will not
     * be persisted.
     *
     * @return whether the node is attached, false if detached
     */
    public boolean isAttached() {
        return this.loader != null;
    }

    public T get() {
        return this.instance;
    }

    public CompletableFuture<T> updateAndSave(final UnaryOperator<T> updater) {
        final T updated = requireNonNull(updater, "updater").apply(this.instance);
        return ConfigHandle.asyncFailableFuture(() -> {
            // TODO: Force one save at a time
            this.save();
            return updated;
        }, ForkJoinPool.commonPool());
    }

    void load() throws ConfigurateException {
        if (this.loader == null) { // we are virtual
            return;
        }

        final CommentedConfigurationNode node = this.loader.load();
        this.doVersionUpdate(node);
        this.node = node;
        this.instance = node.get(this.instanceType);
        this.doSave();
    }

    protected final void doVersionUpdate(final CommentedConfigurationNode node) throws ConfigurateException {
        if (this.transformer != null) {
            final boolean wasEmpty = node.empty();
            final CommentedConfigurationNode versionNode = node.node(ConfigHandle.VERSION_PATH);
            final int existingVersion = versionNode.getInt(-1);
            this.transformer.get().apply(node);
            final int newVersion = versionNode.getInt(-1);
            if (!wasEmpty && newVersion > existingVersion) {
                ConfigHandle.LOGGER.info("Updated {} from version {} to {}", this.instance, existingVersion, newVersion);
            }
            versionNode.commentIfAbsent(ConfigHandle.VERSION_COMMENT);
            node.node(ConfigHandle.VERSION_PATH).set(versionNode);
        }
    }

    public CompletableFuture<?> reload() {
        // TODO: Something nicer?
        return ConfigHandle.asyncFailableFuture(() -> {
            this.load();
            return null;
        }, ForkJoinPool.commonPool());
    }

    public final void save() {
        if (ConfigHandle.saveSuppressed) {
            ConfigHandle.saveQueue.add(this);
        } else {
            try {
                this.doSave();
            } catch (final ConfigurateException ex) {
                ConfigHandle.LOGGER.error("Unable to save configuration to {}", this.loader, ex);
            }
        }
    }

    protected void doSave() throws ConfigurateException {
        if (this.loader == null) {
            return;
        }

        if (this.node == null) {
            this.node = this.loader.createNode();
        }

        final T instance = this.instance;
        final CommentedConfigurationNode node = this.node;
        if (instance != null && node != null) {
            node.set(this.instanceType, instance);
        }
        this.loader.save(node);
    }

    private @Nullable CommentedConfigurationNode getSetting(final String key) {
        if (key.equalsIgnoreCase("config-enabled")) {
            return this.node.node(key);
        } else if (!key.contains(".") || key.indexOf('.') == key.length() - 1) {
            return null;
        } else {
            final CommentedConfigurationNode node = this.node;
            final String[] split = key.split("\\.");
            return node.node((Object[]) split);
        }
    }

    public CompletableFuture<CommentedConfigurationNode> updateSetting(final String key, final Object value) {
        return ConfigHandle.asyncFailableFuture(() -> {
            final CommentedConfigurationNode upd = this.getSetting(key);
            upd.set(value);
            this.instance = this.node.get(this.instanceType);
            this.save();
            return upd;
        }, ForkJoinPool.commonPool());
    }

    public <V> CompletableFuture<CommentedConfigurationNode> updateSetting(final String key, final V value, final TypeToken<V> token) {
        return ConfigHandle.asyncFailableFuture(() -> {
            final CommentedConfigurationNode upd = this.getSetting(key);
            upd.set(token, value);
            this.instance = this.node.get(this.instanceType);
            this.save();
            return upd;
        }, ForkJoinPool.commonPool());
    }

    private static <T> CompletableFuture<T> asyncFailableFuture(final Callable<T> action, final Executor executor) {
        final CompletableFuture<T> future = new CompletableFuture<>();
        executor.execute(() -> {
            try {
                future.complete(action.call());
            } catch (final Exception ex) {
                future.completeExceptionally(ex);
            }
        });
        return future;
    }

    public ConfigurationNode getNode() {
        return this.node;
    }
}


text:
package model;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import org.apache.http.util.TextUtils;

public class EmailSender
{

    private final String username;
    private final String password;
    private final String host;
    private final String port;
    private final String starttlsEnable;
    private final String replyTo;

    public EmailSender(String username, String password, String host, String port, String starttlsEnable, String replyTo) throws Exception
    {
	if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(host) && !TextUtils.isEmpty(port) && !TextUtils.isEmpty(starttlsEnable))
	{
	    this.username = username;
	    this.password = password;
	    this.host = host;
	    this.port = port;
	    this.starttlsEnable = starttlsEnable;
	    this.replyTo = replyTo;
	}
	else
	{
	    throw new Exception("Missing parameters! Please check SMTP parameters.");
	}
    }

    public void send(String[] recipients, String subject, String body) throws Exception
    {
	try
	{
	    Properties props = new Properties();
	    props.put("mail.smtp.port", port);
	    props.put("mail.smtp.auth", "true");
	    props.put("mail.smtp.starttls.enable", starttlsEnable);

	    Session session = Session.getDefaultInstance(props);

	    Transport transport = session.getTransport("smtp");
	    transport.connect(host, username, password);

	    MimeMessage msg = new MimeMessage(session);
	    System.out.println("[i] List of recipients for e-mail notification:");
	    for (String recipient : recipients)
	    {
		System.out.println("[.] \t" + recipient);
		msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(recipient, recipient, "ISO-8859-9"));
	    }
	    msg.setFrom(new InternetAddress(username, username, "ISO-8859-9"));
	    if (!TextUtils.isEmpty(host))
	    {
		msg.setReplyTo(new Address[]
		{
		    new InternetAddress(replyTo, replyTo, "ISO-8859-9")
		});
	    }
	    msg.setSubject(subject, "ISO-8859-9");
	    msg.setHeader("X-Mailer", "heybot-relase-notification");

	    MimeBodyPart mbp1 = new MimeBodyPart();
	    mbp1.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html; charset=\"UTF-8\"")));

	    Multipart mp = new MimeMultipart();
	    mp.addBodyPart(mbp1);
	    msg.setContent(mp);

	    System.out.println("[i] Subject: " + subject);
	    transport.sendMessage(msg, msg.getAllRecipients());
	}
	catch (MessagingException | IOException ex)
	{
	    throw new Exception("Smtp sending error!" + ex.getMessage());
	}
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace os {

inline int kill(pid_t pid, int sig)
{
  return ::kill(pid, sig);
}

} // namespace os {

#endif // __STOUT_OS_POSIX_KILL_HPP__


text:
from __future__ import annotations

import pytest

from pre_commit.languages.golang import guess_go_dir

@pytest.mark.parametrize(
    ('url', 'expected'),
    (
        ('/im/a/path/on/disk', 'unknown_src_dir'),
        ('file:///im/a/path/on/disk', 'unknown_src_dir'),
        ('git@github.com:golang/lint', 'github.com/golang/lint'),
        ('git://github.com/golang/lint', 'github.com/golang/lint'),
        ('http://github.com/golang/lint', 'github.com/golang/lint'),
        ('https://github.com/golang/lint', 'github.com/golang/lint'),
        ('ssh://git@github.com/golang/lint', 'github.com/golang/lint'),
        ('git@github.com:golang/lint.git', 'github.com/golang/lint'),
    ),
)
def test_guess_go_dir(url, expected):
    assert guess_go_dir(url) == expected


text:
import { isMoment } from './constructor';
import { normalizeUnits } from '../units/aliases';
import { createLocal } from '../create/local';

export function isAfter (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(units) || 'millisecond';
    if (units === 'millisecond') {
        return this.valueOf() > localInput.valueOf();
    } else {
        return localInput.valueOf() < this.clone().startOf(units).valueOf();
    }
}

export function isBefore (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input);
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(units) || 'millisecond';
    if (units === 'millisecond') {
        return this.valueOf() < localInput.valueOf();
    } else {
        return this.clone().endOf(units).valueOf() < localInput.valueOf();
    }
}

export function isBetween (from, to, units, inclusivity) {
    var localFrom = isMoment(from) ? from : createLocal(from),
        localTo = isMoment(to) ? to : createLocal(to);
    if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
        return false;
    }
    inclusivity = inclusivity || '()';
    return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
        (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
}

export function isSame (input, units) {
    var localInput = isMoment(input) ? input : createLocal(input),
        inputMs;
    if (!(this.isValid() && localInput.isValid())) {
        return false;
    }
    units = normalizeUnits(units) || 'millisecond';
    if (units === 'millisecond') {
        return this.valueOf() === localInput.valueOf();
    } else {
        inputMs = localInput.valueOf();
        return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
    }
}

export function isSameOrAfter (input, units) {
    return this.isSame(input, units) || this.isAfter(input, units);
}

export function isSameOrBefore (input, units) {
    return this.isSame(input, units) || this.isBefore(input, units);
}


text:
<?php
/*
* @Author: ydk2 (me@ydk2.tk)
* @Date: 2017-01-21 16:22:09
* @Last Modified by: ydk2 (me@ydk2.tk)
* @Last Modified time: 2017-01-21 22:00:35
*/
namespace Library\Core;

class mainController
{
    public $array;
    public $disabled;
    public $enabled;
    public $layouts;
    public $layout_group;
    public $mode;
    public $access;
    public $current_group;
    public $access_groups;

    private $name;

    public $model;

    protected $data;
    protected $view;
    protected $error;

    public function __construct($theme = NULL)
    {
        $this->data = new Data();
        $this->name = get_class($this);

        if(class_exists('ReflectionClass')){
            $ref = new \ReflectionClass($this->name);
            $this->path = dirname($ref->getFileName());
        } else {
            $included_files = get_included_files();
            foreach ($included_files as $filename) {
                if( stripos( $filename, $this->name.'.php' ) !== false ){
                    $this->path = dirname($filename);
                    break;
                }
            }
        }

    $spath = str_replace(strtolower(ROOT), '', strtolower($this->name));
    $this->strip = explode(DIRECTORY_SEPARATOR, $spath);
    if(!is_array($this->strip)){
        $this->strip = explode("\\", $spath);
    }
    $vpath = array();
    foreach ($this->strip as $key => $value) {
        if ($value == 'controllers') {
            $vpath[] = 'views';
            if ($theme != NULL && $theme != "") {
                $vpath[] = $theme;
            }
        } else {
            $vpath[] = $value;
        }
    }
    $this->view = DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR,$vpath);
}

function View($view, $ext = ".php")
{
    try {
        ob_start();
        $filename = strtolower(str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, ROOT . $view) . $ext);
        if (file_exists($filename) && is_file($filename)) {
            require ($filename);
        }
        return ob_get_clean();
    } catch (\Exception $e) {
        return $e->getMessage();
    }
}

public function Show()
{
    echo $this->View($this->view, '.html');
}

/**
* Method return a new controller view
* @access public
* @param mixed $controller Can be XSLRender or PHPRender object or path
* @return Render object
**/
public final function newController($controller)
{
    if (is_object($controller)) {
        return $controller;
    }
    else {
        $ext = '.php';

        $path= strtolower(str_replace(array('\\', '/'), DIRECTORY_SEPARATOR,  $controller));
        $controller = strtolower(str_replace(array('\\', '/'), '\\',  $controller));
        if ($this->Inc($path,$ext)) {
            if (!class_exists($controller)) return NULL;
            $a = func_get_args();
            array_shift($a);
            $new = new \ReflectionClass($controller);
            $object = $new->newInstanceArgs($a);
            return $object;
        }
    }
}

/**
* Method return a new controller view
* @access public
* @param mixed $controller Can be XSLRender or PHPRender object or path
* @return Render object
**/
public final function newClass($class)
{
    if (is_object($class)) {
        return $class;
    }
    else {
        $ext = '.php';
        $path= strtolower(str_replace(array('\\', '/'), '\\',  $class));
        if ($this->Inc($path,$ext)) {
            if (!class_exists($class)) return NULL;
            $a = func_get_args();
            array_shift($a);
            $new = new \ReflectionClass($class);
            $object = $new->newInstanceArgs($a);
            return $object;
        }
    }
}

function Inc($class, $ext = ".php")
{
    $filename = strtolower(str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, ROOT . DIRECTORY_SEPARATOR . $class) . $ext);
    if (file_exists($filename) && is_file($filename)) {
        require_once ($filename);
        return TRUE;
    }
    return FALSE;
}

public function throwError($message = '', $code = 0)
{
    throw new \Exception($message, $code);
}

/**
* Get or Set data to views
* @access  protected
* @param string $name Name of element
* @param mixed $value Optional new value for given name
* @return mixed Value for name
**/
final protected function ViewData()
{
    $argsv = func_get_args();
    $argsc = func_num_args();

    if ($argsc == 1) {
        $name = $argsv[0];
        if ($name == '') {
            return '';
        }
        return (isset($this->data->$name)) ? $this->data->$name : '';
    }
    if ($argsc == 2) {
        $name = $argsv[0];
        $value = $argsv[1];
        if ($name == '') {
            return '';
        }
        $this->data->$name = $value;
        return (isset($this->data->$name)) ? $this->data->$name : '';
    }
    return '';
}

}
?>


text:
        </div>
          <script src="html/js/jquery.min.js"></script>
          <script src="html/js/bootstrap.min.js"></script>
          <script src="html/js/boothelp-demo.js"></script>
    </body>
</html>


text:
<?php
/**
 * Created by PhpStorm.
 * User: pt
 * Date: 05.05.16
 * Time: 17:40
 */

namespace bariew\yii2Tools\helpers;

use yii\base\Event;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\Html;
use yii\helpers\Inflector;

class ModelHelper
{
    /**
     * @param $data
     * @return Model
     */
    public static function initModel($data)
    {
        list($class, $attributes, $dirtyAttributes) = array_values($data);
        /** @var ActiveRecord $model */
        $model = new $class();
        if ($model instanceof ActiveRecord) {
            $model::populateRecord($model, $attributes);
            $model->oldAttributes = $model->primaryKey ? array_diff_key($attributes, $dirtyAttributes) : null;
        } else {
            $model->attributes = $attributes;
        }
        return $model;
    }

    /**
     * @param $class
     * @param $id
     * @param array $options
     * @return string
     */
    public static function getLink($class, $id, $options = [])
    {
        list($app, $module, $moduleName, $model, $modelName) = explode('\\', $class);
        list($modulePath, $modelPath)
            = [Inflector::camel2id($moduleName), Inflector::camel2id($modelName)];
        $modelName = ($modulePath == $modelPath || $modelPath == 'item')
            ? $moduleName
            :  "{$moduleName} {$modelName}";
        return $id
            ? Html::a("{$modelName}#{$id}", ["/{$modulePath}/{$modelPath}/view", 'id' => $id], $options)
            : Html::a("{$modelName}", ["/{$modulePath}/{$modelPath}/index"], $options);
    }

    public static function attributeDifference(Event $event)
    {
        /** @var ActiveRecord $model */
        $model = $event->sender;
        $diff = new \cogpowered\FineDiff\Diff();
        if (!isset($model->dirtyAttributes)) {
            $old = [];
            $new = $model->attributes;
        } else {
            $old = array_intersect_key($model->oldAttributes, $model->dirtyAttributes);
            $new = array_intersect_key($model->attributes, $model->dirtyAttributes);
        }
        unset($old['password'], $new['password']);
        return $diff->render(
            preg_replace(['#[\s\n]*\)#', '#Array[\s\n]*\(#'], ['', ''], print_r($old, true)),
            preg_replace(['#[\s\n]*\)#', '#Array[\s\n]*\(#'], ['', ''], print_r($new, true))
        );
    }
}


text:
{-|
Module: Flaw.Window.Win32
Description: Win32 window framework.
License: MIT
-}

{-# LANGUAGE GADTs, PatternSynonyms, TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-missing-pattern-synonym-signatures #-}

module Flaw.Window.Win32
  ( Win32WindowSystem()
  , Win32Window(..)
  , runWin32WindowSystem
  , createWin32Window
  , createLayeredWin32Window
  , updateLayeredWin32Window
  , invokeWin32WindowSystem
  , invokeWin32WindowSystem_
  , addWin32WindowCallback
  , chanWin32WindowMessages
  , getWin32WindowClientSize_unsafe
  ) where

import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import Control.Monad
import Control.Monad.Fix
import Data.IORef
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Foreign as T
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable

import Flaw.Exception
import Flaw.Window
import Flaw.FFI.Win32

newtype Win32WindowSystem = Win32WindowSystem
  { wsHandle :: Ptr () -- ^ Opaque handle for C side.
  }

data Win32Window = Win32Window
  { wWindowSystem :: !Win32WindowSystem
  , wHandle :: {-# UNPACK #-} !HWND
  , wCallback :: !(FunPtr WindowCallback)
  , wUserCallbacksRef :: {-# UNPACK #-} !(IORef [WindowCallback])
  , wMessagesChan :: {-# UNPACK #-} !(TChan (Word, WPARAM, LPARAM))
  , wEventsChan :: {-# UNPACK #-} !(TChan WindowEvent)
  }

instance Window Win32Window where
  setWindowTitle Win32Window { wWindowSystem = ws, wHandle = hwnd } title = invokeWin32WindowSystem_ ws $
    withCWString (T.unpack title) $ \titleCString ->
      c_setWin32WindowTitle hwnd titleCString
  getWindowClientSize window@Win32Window
    { wWindowSystem = ws
    } = invokeWin32WindowSystem ws $ getWin32WindowClientSize_unsafe window
  chanWindowEvents Win32Window
    { wEventsChan = eventsChan
    } = dupTChan eventsChan
  getWindowClipboardText Win32Window
    { wWindowSystem = ws
    , wHandle = hwnd
    } = invokeWin32WindowSystem ws $
    alloca $ \memPtr -> alloca $ \lenPtr -> do
      strPtr <- c_getClipboardTextBegin hwnd memPtr lenPtr
      if strPtr /= nullPtr then do
        len <- peek lenPtr
        text <- T.fromPtr strPtr $ fromIntegral len
        c_getClipboardTextEnd =<< peek memPtr
        return text
      else return T.empty
  setWindowClipboardText Win32Window
    { wWindowSystem = ws
    , wHandle = hwnd
    } text = invokeWin32WindowSystem ws $ do
    let len = T.lengthWord16 text
    allocaArray (len + 1) $ \ptr -> do
      T.unsafeCopyToPtr text ptr
      pokeElemOff ptr len 0
      c_setClipboardText hwnd ptr
  setWindowMouseCursor Win32Window
    { wWindowSystem = ws
    , wHandle = hwnd
    } mouseCursor = invokeWin32WindowSystem_ ws $ c_setMouseCursor hwnd $ fromIntegral $ fromEnum mouseCursor
  setWindowMouseLock Win32Window
    { wWindowSystem = ws
    , wHandle = hwnd
    } mouseLock = invokeWin32WindowSystem_ ws $ c_setMouseLock hwnd (if mouseLock then 1 else 0)

-- | Run Win32 window system.
runWin32WindowSystem :: MVar (Win32WindowSystem, IO ()) -> IO ()
runWin32WindowSystem resultVar = do
  -- initialize window system, get handle
  h <- c_initWin32WindowSystem
  -- create shutdown var
  shutdownVar <- newEmptyMVar
  -- return result in var
  let
    ws = Win32WindowSystem
      { wsHandle = h
      }
    shutdown = do
      -- send a message to stop window loop
      invokeWin32WindowSystem_ ws c_stopWin32WindowSystem
      -- wait for actual completion
      readMVar shutdownVar
  putMVar resultVar (ws, shutdown)
  -- run window system
  c_runWin32WindowSystem h
  -- free resources
  c_shutdownWin32WindowSystem h
  -- signal end
  putMVar shutdownVar ()

createWin32Window :: Win32WindowSystem -> T.Text -> Maybe (Int, Int) -> Maybe (Int, Int) -> IO (Win32Window, IO ())
createWin32Window ws title maybePosition maybeSize = internalCreateWin32Window ws title maybePosition maybeSize False

createLayeredWin32Window :: Win32WindowSystem -> T.Text -> Maybe (Int, Int) -> Maybe (Int, Int) -> IO (Win32Window, IO ())
createLayeredWin32Window ws title maybePosition maybeSize = internalCreateWin32Window ws title maybePosition maybeSize True

internalCreateWin32Window :: Win32WindowSystem -> T.Text -> Maybe (Int, Int) -> Maybe (Int, Int) -> Bool -> IO (Win32Window, IO ())
internalCreateWin32Window ws title maybePosition maybeSize layered = do
  w <- invokeWin32WindowSystem ws $ mfix $ \w -> do
    -- create callback
    userCallbacksRef <- newIORef []
    messagesChan <- newBroadcastTChanIO
    eventsChan <- newBroadcastTChanIO
    callback <- wrapWindowCallback $ \msg wParam lParam -> do
      -- run sync callbacks
      userCallbacks <- readIORef userCallbacksRef
      forM_ userCallbacks $ \callback -> callback msg wParam lParam
      -- dispatch raw message
      atomically $ writeTChan messagesChan (msg, wParam, lParam)
      -- dispatch event
      let
        maybeEvent = case msg of
          0x0002 {- WM_DESTROY -} -> Just DestroyWindowEvent
          0x0005 {- WM_SIZE -} -> Just $ ResizeWindowEvent (fromIntegral $ loWord lParam) (fromIntegral $ hiWord lParam)
          0x0010 {- WM_CLOSE -} -> Just CloseWindowEvent
          _ -> Nothing
      case maybeEvent of
        Just event -> atomically $ writeTChan eventsChan event
        Nothing -> return ()
      -- process some other messages
      case msg of
        0x0002 -> -- WM_DESTROY
          -- free callback
          freeHaskellFunPtr $ wCallback w
        _ -> return ()
    let
      (left, top) = fromMaybe (CW_USEDEFAULT, CW_USEDEFAULT) maybePosition
      (width, height) = fromMaybe (CW_USEDEFAULT, CW_USEDEFAULT) maybeSize
    -- create window
    hwnd <- withCWString (T.unpack title) $ \titleCString ->
      c_createWin32Window (wsHandle ws) titleCString left top width height callback (if layered then 1 else 0)
    when (hwnd == nullPtr) $ throwIO $ DescribeFirstException "cannot create Win32Window"
    return Win32Window
      { wWindowSystem = ws
      , wHandle = hwnd
      , wCallback = callback
      , wUserCallbacksRef = userCallbacksRef
      , wMessagesChan = messagesChan
      , wEventsChan = eventsChan
      }
  return (w, invokeWin32WindowSystem_ ws $ c_destroyWin32Window $ wHandle w)

updateLayeredWin32Window :: Win32Window -> IO ()
updateLayeredWin32Window w = invokeWin32WindowSystem_ (wWindowSystem w) $ c_updateLayeredWin32Window $ wHandle w

invokeWithMaybeResultVar :: Maybe (MVar (Either SomeException a)) -> Win32WindowSystem -> IO a -> IO ()
invokeWithMaybeResultVar maybeResultVar ws io = do
  -- create callback
  invokeCallback <- mfix $ \invokeCallback -> wrapInvokeCallback $ do
    -- run IO with exception propagation
    result <- try io
    case maybeResultVar of
      Just resultVar -> putMVar resultVar result
      Nothing -> return ()
    -- free fun ptr
    freeHaskellFunPtr invokeCallback
  -- do invoke
  c_invokeWin32WindowSystem (wsHandle ws) invokeCallback

-- | Invoke function in window system thread.
-- Do not wait for the result.
invokeWin32WindowSystem_ :: Win32WindowSystem -> IO () -> IO ()
invokeWin32WindowSystem_ = invokeWithMaybeResultVar Nothing

-- | Invoke function in window system thread.
-- Wait for the result.
invokeWin32WindowSystem :: Win32WindowSystem -> IO a -> IO a
invokeWin32WindowSystem ws io = do
  resultVar <- newEmptyMVar
  invokeWithMaybeResultVar (Just resultVar) ws io
  result <- takeMVar resultVar
  case result of
    Left e -> throwIO e
    Right r -> return r

addWin32WindowCallback :: Win32Window -> WindowCallback -> IO ()
addWin32WindowCallback Win32Window
  { wWindowSystem = ws
  , wUserCallbacksRef = userCallbacksRef
  } callback = invokeWin32WindowSystem ws $ do
  callbacks <- readIORef userCallbacksRef
  writeIORef userCallbacksRef $ callback : callbacks

chanWin32WindowMessages :: Win32Window -> STM (TChan (Word, WPARAM, LPARAM))
chanWin32WindowMessages Win32Window
  { wMessagesChan = messagesChan
  } = dupTChan messagesChan

-- | Get window size, no syncronization.
getWin32WindowClientSize_unsafe :: Win32Window -> IO (Int, Int)
getWin32WindowClientSize_unsafe Win32Window
  { wHandle = hwnd
  } = alloca $ \widthPtr -> alloca $ \heightPtr -> do
  c_getWin32WindowClientSize hwnd widthPtr heightPtr
  width <- peek widthPtr
  height <- peek heightPtr
  return (fromIntegral width, fromIntegral height)

-- foreign imports

foreign import ccall safe "initWin32WindowSystem" c_initWin32WindowSystem :: IO (Ptr ())
foreign import ccall safe "runWin32WindowSystem" c_runWin32WindowSystem :: Ptr () -> IO ()
foreign import ccall safe "shutdownWin32WindowSystem" c_shutdownWin32WindowSystem :: Ptr () -> IO ()
foreign import ccall safe "stopWin32WindowSystem" c_stopWin32WindowSystem :: IO ()
foreign import ccall safe "invokeWin32WindowSystem" c_invokeWin32WindowSystem :: Ptr () -> FunPtr InvokeCallback -> IO ()
foreign import ccall safe "createWin32Window" c_createWin32Window
  :: Ptr () -- window system handle
  -> LPWSTR -- title
  -> Int -> Int -- x y
  -> Int -> Int -- width height
  -> FunPtr WindowCallback -- callback
  -> Int -- layered
  -> IO HWND -- HWND
foreign import ccall unsafe "setWin32WindowTitle" c_setWin32WindowTitle :: HWND -> LPWSTR -> IO ()
foreign import ccall unsafe "getWin32WindowClientSize" c_getWin32WindowClientSize :: HWND -> Ptr CInt -> Ptr CInt -> IO ()
foreign import ccall safe "destroyWin32Window" c_destroyWin32Window :: HWND -> IO ()
foreign import ccall unsafe "getClipboardTextBegin" c_getClipboardTextBegin :: HWND -> Ptr HANDLE -> Ptr CInt -> IO (Ptr WCHAR)
foreign import ccall unsafe "getClipboardTextEnd" c_getClipboardTextEnd :: HANDLE -> IO ()
foreign import ccall unsafe "setClipboardText" c_setClipboardText :: HWND -> Ptr WCHAR -> IO ()
foreign import ccall unsafe "setWin32WindowMouseCursor" c_setMouseCursor :: HWND -> CInt -> IO ()
foreign import ccall unsafe "setWin32WindowMouseLock" c_setMouseLock :: HWND -> CInt -> IO ()
foreign import ccall safe "updateLayeredWin32Window" c_updateLayeredWin32Window :: HWND -> IO ()
foreign import ccall safe "getLayeredWin32WindowBitmapData" c_getLayeredWin32WindowBitmapData :: HWND -> Ptr (Ptr CUChar) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()

-- wrappers

type InvokeCallback = IO ()
foreign import ccall "wrapper" wrapInvokeCallback :: InvokeCallback -> IO (FunPtr InvokeCallback)

type WindowCallback = Word -> WPARAM -> LPARAM -> IO ()
foreign import ccall "wrapper" wrapWindowCallback :: WindowCallback -> IO (FunPtr WindowCallback)

-- constants

pattern CW_USEDEFAULT = 0x80000000


text:
/
public class HeaderTableModel extends AbstractTableModel {

	/**
	 *
	 */
	private static final long serialVersionUID = -5543254399018549428L;
	protected List<HttpHeader> headers;

	public static enum ColumnNames {
		Field, Value
	};

	public HeaderTableModel() {
		headers = new ArrayList<HeaderTableModel.HttpHeader>();
	}

	@Override
	public String getColumnName(int column) {
		return ColumnNames.values()[column].toString();
	}

	public int getColumnCount() {
		return ColumnNames.values().length;
	}

	public int getRowCount() {
		return headers.size();
	}

	public Object getValueAt(int row, int col) {
		if (row > -1) {
			HttpHeader header = headers.get(row);
			if (ColumnNames.Field.ordinal() == col) {
				return header.key;
			} else if (ColumnNames.Value.ordinal() == col) {
				return header.value;
			}
		}
		return null;
	}

	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		if (rowIndex > -1) {

			// do nothing to the key field
			if (ColumnNames.Field.ordinal() == columnIndex) {
				return;
			} else if (ColumnNames.Value.ordinal() == columnIndex) {
				HttpHeader header = headers.get(rowIndex);
				header.setValue((String) aValue);
				return;
			}
		}
		super.setValueAt(aValue, rowIndex, columnIndex);
	}

	public class HttpHeader {
		private String key;
		private String value;

		public HttpHeader(String key, String value) {
			this.key = key;
			this.value = value;
		}

		/**
		 * @return the key
		 */
		public String getKey() {
			return key;
		}

		/**
		 * @param key
		 *            the key to set
		 */
		public void setKey(String key) {
			this.key = key;
		}

		/**
		 * @return the value
		 */
		public String getValue() {
			return value;
		}

		/**
		 * @param value
		 *            the value to set
		 */
		public void setValue(String value) {
			this.value = value;
		}
	}

	/**
	 * Creates a set of header objects from a content string object.
	 *
	 * @param content
	 * @throws UnsupportedEncodingException
	 */
	public void setHeaders(AbstractPacketDO packet)
			throws UnsupportedEncodingException {
		headers.clear();

		String content = new String(packet.getData(), "UTF-8");
		List<String> headerList = HttpUtils.getHeaders(content);

		if (headerList != null) {
			if (headerList.size() >= 1) {
				if (HttpUtils.findRequestHeader(content) > -1) {
					packet.setType(MessageType.Request);
					HttpHeader requestHeader = new HttpHeader("Method",
							headerList.get(0));
					headers.add(requestHeader);
				} else if (HttpUtils.findResponseHeader(content) > -1) {
					packet.setType(MessageType.Response);
					HttpHeader responseHeader = new HttpHeader("Response",
							headerList.get(0));
					headers.add(responseHeader);
				}

				// iterate through remaining headers
				for (int i = 1; i < headerList.size(); i++) {
					String[] fields = headerList.get(i).split(":\\s");
					if (fields.length == 2) {
						HttpHeader h = new HttpHeader(fields[0], fields[1]);
						headers.add(h);
					}
				}
			}
		}

		fireTableDataChanged();
	}

	/**
	 * Returns the string representation of the header objects.
	 *
	 * @return
	 */
	public String getHeaders() {
		StringBuilder s = new StringBuilder();

		for (int i = 0; i < headers.size(); i++) {
			if (i == 0) {
				s.append(headers.get(i).getValue() + "\r\n");
			} else {
				s.append(headers.get(i).getKey() + ": "
						+ headers.get(i).getValue() + "\r\n");
			}
		}

		return s.toString();
	}

}


text:
tinyMCE.addToLang('',{
directionality_ltr_desc : 'Elhelyezkedés balról jobbra',
directionality_rtl_desc : 'Elhelyezkedés jobbról balra'
});


text:
<?php require_once('inc/init.php'); ?>
<!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Basic Example - KenticoCloud.Engage.PHP</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.4/foundation.css" />

  	<?php require('inc/topbar.php'); ?>

Engage, world!

    		<?php if(!$kceClient->getUserID()){ ?>

So, this is your first visit, eh?
It's nice to meet you. Refresh the page to engage.

			<?php }else if(!property_exists($loc = $kceClient->getCurrentLocation(), 'city')){ ?>

So...I'm only a day old. Try refreshing again.

FYI, this was the last response from the API:

<?php echo '(HTTP code '.$kceClient->lastResponse->code.') '. ($kceClient->lastResponse->raw_body) ?>

			<?php }else{ ?>

Hello again! How's the weather in <?php $loc = $kceClient->getCurrentLocation(); echo $loc->city ?>?

					Did you know that this is 	you've visited <?php echo count($kceClient->getCurrentSession()->getActions()) ?> pages in this session? Here's what else we know...

				User ID: <?php echo $kceClient->getUserID() ?>

    			Session ID: <?php echo $kceClient->getSessionID() ?>

    			Usual Location: <?php $loc = $kceClient->getUsualLocation(); echo $loc->city . ', ' . $loc->state . ', ' . $loc->country; ?>

    			First Visit: <?php echo date('F j, Y, g:i a', $kceClient->getFirstVisit()->visitDateTime) ?>

    			Last Visit: <?php echo date('F j, Y, g:i a', $kceClient->getLastVisit()->visitDateTime) ?>

    			Activity Summary: <?php echo $kceClient->getActivitySummary() ?>

    			Current Session: <?php echo $kceClient->getCurrentSession() ?>

			<?php } ?>

	<?php require('inc/footer.php'); ?>


text:
var path = require('path');
var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require(__dirname + '/app/config/config');
var log4js = require('log4js');

var app = express();

//日志模块
log4js.configure({
  appenders:[
    {type:'console'},//控制台输出
    {
      type:'file',//文件输出
      filename:'logs/access.log',
      maxLogSize:1024,
      backups:3,
      category:'normal'
    }
  ],
  replaceConsole:true
});

var logger = log4js.getLogger('normal');
logger.setLevel('INFO');

app.use(log4js.connectLogger(logger, {level: 'auto', format:':method :url'}));

app.use(express.static(__dirname + '/public'));

if (process.env.NODE_ENV === 'production') {
  app.enable('trust proxy');
  app.use(require('express-enforces-ssl')());
}

app.config = config;

// Database
require('./app/config/database')(app, mongoose);

var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
  if (~file.indexOf('.js')) require(models_path + '/' + file)
});

require('./app/config/passport')(app, passport);

// express settings
require('./app/config/express')(app, express, passport);

// create a server instance
// passing in express app as a request event handler
app.listen(app.get('port'), function () {
  console.log("\n✔ Express server listening on port %d in %s mode", app.get('port'), app.get('env'));
});

module.exports = app;


text:
/**
 *
 */
package org.treetank.revisioning;

import static com.google.common.base.Objects.toStringHelper;

import org.treetank.bucket.DataBucket;
import org.treetank.io.LogValue;

/**
 * FullDump versioning of {@link DataBucket}s.
 *
 * @author Sebastian Graf, University of Konstanz
 *
 */
public class FullDump implements IRevisioning {

    /**
     * {@inheritDoc}
     */
    @Override
    public DataBucket combineBuckets(DataBucket[] pBuckets) {
        final DataBucket returnVal =
            new DataBucket(pBuckets[0].getBucketKey(), pBuckets[0].getLastBucketPointer());
        for (int i = 0; i < pBuckets[0].getDatas().length; i++) {
            returnVal.setData(i, pBuckets[0].getData(i));
        }
        return returnVal;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LogValue combineBucketsForModification(int pRevisionsToRestore, long pNewBucketKey,
        DataBucket[] pBuckets, boolean fullDump) {
        final DataBucket[] returnVal =
            {
                new DataBucket(pBuckets[0].getBucketKey(), pBuckets[0].getLastBucketPointer()),
                new DataBucket(pNewBucketKey, pBuckets[0].getBucketKey())
            };

        for (int i = 0; i < pBuckets[0].getDatas().length; i++) {
            returnVal[0].setData(i, pBuckets[0].getData(i));
            returnVal[1].setData(i, pBuckets[0].getData(i));
        }

        return new LogValue(returnVal[0], returnVal[1]);

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return toStringHelper(this).toString();
    }

}


text:
/*
 *
 * Edit
 *
 */

import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import _ from 'lodash';

import { router } from 'app';
import { define } from 'i18n';

import Container from 'components/Container';
import EditForm from 'components/EditForm';
import { makeSelectSchema } from 'containers/App/selectors';
import EditFormRelations from 'components/EditFormRelations';

import {
  setInitialState,
  setCurrentModelName,
  setIsCreating,
  loadRecord,
  setRecordAttribute,
  editRecord,
  deleteRecord,
} from './actions';
import {
  makeSelectRecord,
  makeSelectLoading,
  makeSelectCurrentModelName,
  makeSelectEditing,
  makeSelectDeleting,
  makeSelectIsCreating,
} from './selectors';
import messages from './messages.json';

define(messages);

export class Edit extends React.Component {
  componentWillMount() {
    this.props.setInitialState();
    this.props.setCurrentModelName(this.props.routeParams.slug.toLowerCase());

    // Detect that the current route is the `create` route or not
    if (this.props.routeParams.id === 'create') {
      this.props.setIsCreating();
    } else {
      this.props.loadRecord(this.props.routeParams.id);
    }
  }

  render() {
    const PluginHeader = this.props.exposedComponents.PluginHeader;

    let content =
Loading...
;
    let relations;
    if (!this.props.loading && this.props.schema && this.props.currentModelName) {
      content = (
        <EditForm
          record={this.props.record}
          currentModelName={this.props.currentModelName}
          schema={this.props.schema}
          setRecordAttribute={this.props.setRecordAttribute}
          editRecord={this.props.editRecord}
          editing={this.props.editing}
        />
      );
      relations = (
        <EditFormRelations
          currentModelName={this.props.currentModelName}
          record={this.props.record}
          schema={this.props.schema}
          setRecordAttribute={this.props.setRecordAttribute}
        />
      );
    }

    // Define plugin header actions
    const pluginHeaderActions = [
      {
        label: messages.cancel,
        class: 'btn-default',
        onClick: () => {
          router.push(`/plugins/content-manager/${this.props.currentModelName}`);
        },
      },
      {
        label: this.props.editing ? messages.editing : messages.submit,
        class: 'btn-primary',
        onClick: this.props.editRecord,
        disabled: this.props.editing,
      },
    ];

    // Add the `Delete` button only in edit mode
    if (!this.props.isCreating) {
      pluginHeaderActions.push({
        label: messages.delete,
        class: 'btn-danger',
        onClick: this.props.deleteRecord,
        disabled: this.props.deleting,
      });
    }

    // Plugin header config
    const pluginHeaderTitle = _.get(this.props.schema, [this.props.currentModelName, 'label']) || 'Content Manager';
    const pluginHeaderDescription = this.props.isCreating
      ? 'New entry'
      : `#${this.props.record && this.props.record.get('id')}`;

    return (

          <PluginHeader
            title={{
              id: 'plugin-content-manager-title',
              defaultMessage: `${pluginHeaderTitle}`,
            }}
            description={{
              id: 'plugin-content-manager-description',
              defaultMessage: `${pluginHeaderDescription}`,
            }}
            actions={pluginHeaderActions}
          />
          <Container>

                {content}
                {relations}

          </Container>

    );
  }
}

Edit.propTypes = {
  currentModelName: React.PropTypes.oneOfType([
    React.PropTypes.bool,
    React.PropTypes.string,
  ]),
  deleteRecord: React.PropTypes.func.isRequired,
  deleting: React.PropTypes.bool.isRequired,
  editing: React.PropTypes.bool.isRequired,
  editRecord: React.PropTypes.func.isRequired,
  exposedComponents: React.PropTypes.object.isRequired,
  isCreating: React.PropTypes.bool.isRequired,
  loading: React.PropTypes.bool.isRequired,
  loadRecord: React.PropTypes.func.isRequired,
  record: React.PropTypes.oneOfType([
    React.PropTypes.object,
    React.PropTypes.bool,
  ]),
  routeParams: React.PropTypes.object.isRequired,
  schema: React.PropTypes.oneOfType([
    React.PropTypes.object,
    React.PropTypes.bool,
  ]),
  setCurrentModelName: React.PropTypes.func.isRequired,
  setInitialState: React.PropTypes.func.isRequired,
  setIsCreating: React.PropTypes.func.isRequired,
  setRecordAttribute: React.PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  record: makeSelectRecord(),
  loading: makeSelectLoading(),
  currentModelName: makeSelectCurrentModelName(),
  editing: makeSelectEditing(),
  deleting: makeSelectDeleting(),
  isCreating: makeSelectIsCreating(),
  schema: makeSelectSchema(),
});

function mapDispatchToProps(dispatch) {
  return {
    setInitialState: () => dispatch(setInitialState()),
    setCurrentModelName: currentModelName =>
      dispatch(setCurrentModelName(currentModelName)),
    setIsCreating: () => dispatch(setIsCreating()),
    loadRecord: id => dispatch(loadRecord(id)),
    setRecordAttribute: (key, value) =>
      dispatch(setRecordAttribute(key, value)),
    editRecord: () => dispatch(editRecord()),
    deleteRecord: () => {
      // TODO: improve confirmation UX.
      if (window.confirm('Are you sure ?')) {
        // eslint-disable-line no-alert
        dispatch(deleteRecord());
      }
    },
    dispatch,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Edit);


text:
import json
import subprocess
import time
import sys
import os
from testutils import run_efu, run_data_generator_timed, get_metrics

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from utils.efushell.EFUMetrics import Metrics

def get_stat(stat_name):
    return get_stats([stat_name])[stat_name]

def get_stats(stat_name_list):
    metrics = get_metrics()
    stats = {}
    for stat_name in stat_name_list:
        stats[stat_name] = metrics.return_metric(stat_name)
    return(stats)

def efu_drop_packets_check(efu, generator, module, throttle):
    time_s = 30
    readouts_per_packet = 100
    run_data_generator_timed(efu, generator, throttle, readouts_per_packet, time_s)
    time.sleep(5)
    new_packets_dropped = get_stat(f"efu.{module}.0.receive.dropped")
    return new_packets_dropped

def assess_performance(efu, generator, module, throttle):
    time_s = 30
    readouts_per_packet = 100
    stat_name_list = [f"efu.{module}.0.receive.packets", f"efu.{module}.0.readouts.count", f"efu.{module}.0.events.count"]
    stats = get_stats(stat_name_list)
    run_data_generator_timed(efu, generator, throttle, readouts_per_packet, time_s)
    new_stats = get_stats(stat_name_list)
    for stat_name in stat_name_list:
        stats[stat_name] = (new_stats[stat_name] - stats[stat_name]) / time_s
    print(f"the following stats are per second, calculated over {time_s} seconds")
    print(stats)

def bisect_throttle_settings(efu, generator, module, throttle):
    packets_dropped = 0
    min_throttle = 0
    max_throttle = 1000
    for x in range(10):
        new_packets_dropped = efu_drop_packets_check(efu, generator, module, throttle)
        if new_packets_dropped == packets_dropped:
            print(f"Passed at throttle: {throttle}")
            max_throttle = throttle
            throttle = (throttle + min_throttle) / 2
        else:
            print(f"Failed at throttle: {throttle}")
            min_throttle = throttle
            throttle = (throttle + max_throttle) / 2
        packets_dropped = new_packets_dropped
        if((max_throttle - min_throttle) < 1):
            break
        print(f"New throttle to test: {throttle}")
        print(f"Min throttle: {min_throttle}, Max throttle: {max_throttle}")
        print(f"Packets dropped: {packets_dropped}")
    print(f"Best throttle achieved: {max_throttle}")
    best_passing_throttle = max_throttle
    return best_passing_throttle

def run_performance_test():
    efu = "./event-formation-unit"

    with open('./test/performancetest.json') as f:
        data = json.load(f)

    for test in data['Tests']:
        efu_process = run_efu(efu, test['Module'], test['Config'])
        try:
            best_throttle = bisect_throttle_settings(efu, test['Generator'], test['Module'], test['InitThrottle'])
            assess_performance(efu, test['Generator'], test['Module'], best_throttle)
        except:
           efu_process.kill()
           raise
        efu_process.kill()
        time.sleep(5)

if __name__ == "__main__":
	run_performance_test()


text:
if __name__ == "__main__":
    numSetA = int(input())
    setA = set(map(int, input().split()))
    numSetB = int(input())
    setB = set(map(int, input().split()))
    print(len(setA.symmetric_difference(setB)))


text:
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

/**
 *
 * @brief Balanced binary tree
 *
 * The AVL tree structure is a balanced binary tree which stores
 * a collection of nodes (see @ref AVLTreeNode).  Each node has
 * a key and a value associated with it.  The nodes are sorted
 * within the tree based on the order of their keys. Modifications
 * to the tree are constructed such that the tree remains
 * balanced at all times (there are always roughly equal numbers
 * of nodes on either side of the tree).
 *
 * Balanced binary trees have several uses.  They can be used
 * as a mapping (searching for a value based on its key), or
 * as a set of keys which is always ordered.
 *
 * To create a new AVL tree, use @ref avl_tree_new.  To destroy
 * an AVL tree, use @ref avl_tree_free.
 *
 * To insert a new key-value pair into an AVL tree, use
 * @ref avl_tree_insert.  To remove an entry from an
 * AVL tree, use @ref avl_tree_remove or @ref avl_tree_remove_node.
 *
 * To search an AVL tree, use @ref avl_tree_lookup or
 * @ref avl_tree_lookup_node.
 *
 * Tree nodes can be queried using the
 * @ref avl_tree_node_child,
 * @ref avl_tree_node_parent,
 * @ref avl_tree_node_key and
 * @ref avl_tree_node_value functions.
 */

/**
 * An AVL tree balanced binary tree.
 *
 * @see avl_tree_new
 */

typedef struct _AVLTree AVLTree;

/**
 * A key for an @ref AVLTree.
 */

typedef void *AVLTreeKey;

/**
 * A value stored in an @ref AVLTree.
 */

typedef void *AVLTreeValue;

/**
 * A null @ref AVLTreeValue.
 */

#define AVL_TREE_NULL ((void *) 0)

/**
 * A node in an AVL tree.
 *
 * @see avl_tree_node_left_child
 * @see avl_tree_node_right_child
 * @see avl_tree_node_parent
 * @see avl_tree_node_key
 * @see avl_tree_node_value
 */

typedef struct _AVLTreeNode AVLTreeNode;

/**
 * An @ref AVLTreeNode can have left and right children.
 */

typedef enum {
	AVL_TREE_NODE_LEFT = 0,
	AVL_TREE_NODE_RIGHT = 1
} AVLTreeNodeSide;

/**
 * Type of function used to compare keys in an AVL tree.
 *
 * @param value1           The first key.
 * @param value2           The second key.
 * @return                 A negative number if value1 should be sorted
 *                         before value2, a positive number if value2 should
 *                         be sorted before value1, zero if the two keys
 *                         are equal.
 */

typedef int (*AVLTreeCompareFunc)(AVLTreeValue value1, AVLTreeValue value2);

int int_compare(void *vlocation1, void *vlocation2);

/**
 * Create a new AVL tree.
 *
 * @param compare_func    Function to use when comparing keys in the tree.
 * @return                A new AVL tree, or NULL if it was not possible
 *                        to allocate the memory.
 */

AVLTree *avl_tree_new(AVLTreeCompareFunc compare_func);

/**
 * Destroy an AVL tree.
 *
 * @param tree            The tree to destroy.
 */

void avl_tree_free(AVLTree *tree);

/**
 * Insert a new key-value pair into an AVL tree.
 *
 * @param tree            The tree.
 * @param key             The key to insert.
 * @param value           The value to insert.
 * @return                The newly created tree node containing the
 *                        key and value, or NULL if it was not possible
 *                        to allocate the new memory.
 */

AVLTreeNode *avl_tree_insert(AVLTree *tree, AVLTreeKey key, AVLTreeValue value);

/**
 * Remove a node from a tree.
 *
 * @param tree            The tree.
 * @param node            The node to remove
 */

void avl_tree_remove_node(AVLTree *tree, AVLTreeNode *node);

/**
 * Remove an entry from a tree, specifying the key of the node to
 * remove.
 *
 * @param tree            The tree.
 * @param key             The key of the node to remove.
 * @return                Zero (false) if no node with the specified key was
 *                        found in the tree, non-zero (true) if a node with
 *                        the specified key was removed.
 */

int avl_tree_remove(AVLTree *tree, AVLTreeKey key);

/**
 * Search an AVL tree for a node with a particular key.  This uses
 * the tree as a mapping.
 *
 * @param tree            The AVL tree to search.
 * @param key             The key to search for.
 * @return                The tree node containing the given key, or NULL
 *                        if no entry with the given key is found.
 */

AVLTreeNode *avl_tree_lookup_node(AVLTree *tree, AVLTreeKey key);

/**
 * Search an AVL tree for a value corresponding to a particular key.
 * This uses the tree as a mapping.  Note that this performs
 * identically to @ref avl_tree_lookup_node, except that the value
 * at the node is returned rather than the node itself.
 *
 * @param tree            The AVL tree to search.
 * @param key             The key to search for.
 * @return                The value associated with the given key, or
 *                        @ref AVL_TREE_NULL if no entry with the given key is
 *                        found.
 */

AVLTreeValue avl_tree_lookup(AVLTree *tree, AVLTreeKey key);

/**
 * Find the root node of a tree.
 *
 * @param tree            The tree.
 * @return                The root node of the tree, or NULL if the tree is
 *                        empty.
 */

AVLTreeNode *avl_tree_root_node(AVLTree *tree);

/**
 * Retrieve the key for a given tree node.
 *
 * @param node            The tree node.
 * @return                The key to the given node.
 */

AVLTreeKey avl_tree_node_key(AVLTreeNode *node);

/**
 * Retrieve the value at a given tree node.
 *
 * @param node            The tree node.
 * @return                The value at the given node.
 */

AVLTreeValue avl_tree_node_value(AVLTreeNode *node);

/**
 * Find the child of a given tree node.
 *
 * @param node            The tree node.
 * @param side            Which child node to get (left or right)
 * @return                The child of the tree node, or NULL if the
 *                        node has no child on the given side.
 */

AVLTreeNode *avl_tree_node_child(AVLTreeNode *node, AVLTreeNodeSide side);

/**
 * Find the parent node of a given tree node.
 *
 * @param node            The tree node.
 * @return                The parent node of the tree node, or NULL if
 *                        this is the root node.
 */

AVLTreeNode *avl_tree_node_parent(AVLTreeNode *node);

/**
 * Find the height of a subtree.
 *
 * @param node            The root node of the subtree.
 * @return                The height of the subtree.
 */

int avl_tree_subtree_height(AVLTreeNode *node);

/**
 * Convert the keys in an AVL tree into a C array.  This allows
 * the tree to be used as an ordered set.
 *
 * @param tree            The tree.
 * @return                A newly allocated C array containing all the keys
 *                        in the tree, in order.  The length of the array
 *                        is equal to the number of entries in the tree
 *                        (see @ref avl_tree_num_entries).
 */

AVLTreeValue *avl_tree_to_array(AVLTree *tree);

/**
 * Retrieve the number of entries in the tree.
 *
 * @param tree            The tree.
 * @return                The number of key-value pairs stored in the tree.
 */

int avl_tree_num_entries(AVLTree *tree);

/* AVL Tree (balanced binary search tree) */

struct _AVLTreeNode {
	AVLTreeNode *children[2];
	AVLTreeNode *parent;
	AVLTreeKey key;
	AVLTreeValue value;
	int height;
};

struct _AVLTree {
	AVLTreeNode *root_node;
	AVLTreeCompareFunc compare_func;
	int num_nodes;
};

AVLTree *avl_tree_new(AVLTreeCompareFunc compare_func)
{
	AVLTree *new_tree;

	new_tree = (AVLTree *) malloc(sizeof(AVLTree));

	if (new_tree == NULL) {
		return NULL;
	}

	new_tree->root_node = NULL;
	new_tree->compare_func = compare_func;
	new_tree->num_nodes = 0;

	return new_tree;
}

static void avl_tree_free_subtree(AVLTree *tree, AVLTreeNode *node)
{
	if (node == NULL) {
		return;
	}

	avl_tree_free_subtree(tree, node->children[AVL_TREE_NODE_LEFT]);
	avl_tree_free_subtree(tree, node->children[AVL_TREE_NODE_RIGHT]);

	free(node);
}

void avl_tree_free(AVLTree *tree)
{
	/* Destroy all nodes */

	avl_tree_free_subtree(tree, tree->root_node);

	/* Free back the main tree data structure */

	free(tree);
}

int avl_tree_subtree_height(AVLTreeNode *node)
{
	if (node == NULL) {
		return 0;
	} else {
		return node->height;
	}
}

/* Update the "height" variable of a node, from the heights of its
 * children.  This does not update the height variable of any parent
 * nodes. */

static void avl_tree_update_height(AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	int left_height, right_height;

	left_subtree = node->children[AVL_TREE_NODE_LEFT];
	right_subtree = node->children[AVL_TREE_NODE_RIGHT];
	left_height = avl_tree_subtree_height(left_subtree);
	right_height = avl_tree_subtree_height(right_subtree);

	if (left_height > right_height) {
		node->height = left_height + 1;
	} else {
		node->height = right_height + 1;
	}
}

/* Find what side a node is relative to its parent */

static AVLTreeNodeSide avl_tree_node_parent_side(AVLTreeNode *node)
{
	if (node->parent->children[AVL_TREE_NODE_LEFT] == node) {
		return AVL_TREE_NODE_LEFT;
	} else {
		return AVL_TREE_NODE_RIGHT;
	}
}

/* Replace node1 with node2 at its parent. */

static void avl_tree_node_replace(AVLTree *tree, AVLTreeNode *node1,
                                  AVLTreeNode *node2)
{
	int side;

	/* Set the node's parent pointer. */

	if (node2 != NULL) {
		node2->parent = node1->parent;
	}

	/* The root node? */

	if (node1->parent == NULL) {
		tree->root_node = node2;
	} else {
		side = avl_tree_node_parent_side(node1);
		node1->parent->children[side] = node2;

		avl_tree_update_height(node1->parent);
	}
}

/* Rotate a section of the tree.  'node' is the node at the top
 * of the section to be rotated.  'direction' is the direction in
 * which to rotate the tree: left or right, as shown in the following
 * diagram:
 *
 * Left rotation:              Right rotation:
 *
 *      B                             D
 *     / \                           / \
 *    A   D                         B   E
 *       / \                       / \
 *      C   E                     A   C

 * is rotated to:              is rotated to:
 *
 *        D                           B
 *       / \                         / \
 *      B   E                       A   D
 *     / \                             / \
 *    A   C                           C   E
 */

static AVLTreeNode *avl_tree_rotate(AVLTree *tree, AVLTreeNode *node,
                                    AVLTreeNodeSide direction)
{
	AVLTreeNode *new_root;

	/* The child of this node will take its place:
	   for a left rotation, it is the right child, and vice versa. */

	new_root = node->children[1-direction];

	/* Make new_root the root, update parent pointers. */

	avl_tree_node_replace(tree, node, new_root);

	/* Rearrange pointers */

	node->children[1-direction] = new_root->children[direction];
	new_root->children[direction] = node;

	/* Update parent references */

	node->parent = new_root;

	if (node->children[1-direction] != NULL) {
		node->children[1-direction]->parent = node;
	}

	/* Update heights of the affected nodes */

	avl_tree_update_height(new_root);
	avl_tree_update_height(node);

	return new_root;
}

/* Balance a particular tree node.
 *
 * Returns the root node of the new subtree which is replacing the
 * old one. */

static AVLTreeNode *avl_tree_node_balance(AVLTree *tree, AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	AVLTreeNode *child;
	int diff;

	left_subtree = node->children[AVL_TREE_NODE_LEFT];
	right_subtree = node->children[AVL_TREE_NODE_RIGHT];

	/* Check the heights of the child trees.  If there is an unbalance
	 * (difference between left and right > 2), then rotate nodes
	 * around to fix it */

	diff = avl_tree_subtree_height(right_subtree)
	     - avl_tree_subtree_height(left_subtree);

	if (diff >= 2) {

		/* Biased toward the right side too much. */

		child = right_subtree;

		if (avl_tree_subtree_height(child->children[AVL_TREE_NODE_RIGHT])
		  < avl_tree_subtree_height(child->children[AVL_TREE_NODE_LEFT])) {

			/* If the right child is biased toward the left
			 * side, it must be rotated right first (double
			 * rotation) */

			avl_tree_rotate(tree, right_subtree,
			                AVL_TREE_NODE_RIGHT);
		}

		/* Perform a left rotation.  After this, the right child will
		 * take the place of this node.  Update the node pointer. */

		node = avl_tree_rotate(tree, node, AVL_TREE_NODE_LEFT);

	} else if (diff <= -2) {

		/* Biased toward the left side too much. */

		child = node->children[AVL_TREE_NODE_LEFT];

		if (avl_tree_subtree_height(child->children[AVL_TREE_NODE_LEFT])
		  < avl_tree_subtree_height(child->children[AVL_TREE_NODE_RIGHT])) {

			/* If the left child is biased toward the right
			 * side, it must be rotated right left (double
			 * rotation) */

			avl_tree_rotate(tree, left_subtree,
			                AVL_TREE_NODE_LEFT);
		}

		/* Perform a right rotation.  After this, the left child will
		 * take the place of this node.  Update the node pointer. */

		node = avl_tree_rotate(tree, node, AVL_TREE_NODE_RIGHT);
	}

	/* Update the height of this node */

	avl_tree_update_height(node);

	return node;
}

/* Walk up the tree from the given node, performing any needed rotations */

static void avl_tree_balance_to_root(AVLTree *tree, AVLTreeNode *node)
{
	AVLTreeNode *rover;

	rover = node;

	while (rover != NULL) {

		/* Balance this node if necessary */

		rover = avl_tree_node_balance(tree, rover);

		/* Go to this node's parent */

		rover = rover->parent;
	}
}

AVLTreeNode *avl_tree_insert(AVLTree *tree, AVLTreeKey key, AVLTreeValue value)
{
	AVLTreeNode **rover;
	AVLTreeNode *new_node;
	AVLTreeNode *previous_node;

	/* Walk down the tree until we reach a NULL pointer */

	rover = &tree->root_node;
	previous_node = NULL;

	while (*rover != NULL) {
		previous_node = *rover;
		if (tree->compare_func(key, (*rover)->key) < 0) {
			rover = &((*rover)->children[AVL_TREE_NODE_LEFT]);
		} else {
			rover = &((*rover)->children[AVL_TREE_NODE_RIGHT]);
		}
	}

	/* Create a new node.  Use the last node visited as the parent link. */

	new_node = (AVLTreeNode *) malloc(sizeof(AVLTreeNode));

	if (new_node == NULL) {
		return NULL;
	}

	new_node->children[AVL_TREE_NODE_LEFT] = NULL;
	new_node->children[AVL_TREE_NODE_RIGHT] = NULL;
	new_node->parent = previous_node;
	new_node->key = key;
	new_node->value = value;
	new_node->height = 1;

	/* Insert at the NULL pointer that was reached */

	*rover = new_node;

	/* Rebalance the tree, starting from the previous node. */

	avl_tree_balance_to_root(tree, previous_node);

	/* Keep track of the number of entries */

	++tree->num_nodes;

	return new_node;
}

/* Find the nearest node to the given node, to replace it.
 * The node returned is unlinked from the tree.
 * Returns NULL if the node has no children. */

static AVLTreeNode *avl_tree_node_get_replacement(AVLTree *tree,
                                                  AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	AVLTreeNode *result;
	AVLTreeNode *child;
	int left_height, right_height;
	int side;

	left_subtree = node->children[AVL_TREE_NODE_LEFT];
	right_subtree = node->children[AVL_TREE_NODE_RIGHT];

	/* No children? */

	if (left_subtree == NULL && right_subtree == NULL) {
		return NULL;
	}

	/* Pick a node from whichever subtree is taller.  This helps to
	 * keep the tree balanced. */

	left_height = avl_tree_subtree_height(left_subtree);
	right_height = avl_tree_subtree_height(right_subtree);

	if (left_height < right_height) {
		side = AVL_TREE_NODE_RIGHT;
	} else {
		side = AVL_TREE_NODE_LEFT;
	}

	/* Search down the tree, back towards the center. */

	result = node->children[side];

	while (result->children[1-side] != NULL) {
		result = result->children[1-side];
	}

	/* Unlink the result node, and hook in its remaining child
	 * (if it has one) to replace it. */

	child = result->children[side];
	avl_tree_node_replace(tree, result, child);

	/* Update the subtree height for the result node's old parent. */

	avl_tree_update_height(result->parent);

	return result;
}

/* Remove a node from a tree */

void avl_tree_remove_node(AVLTree *tree, AVLTreeNode *node)
{
	AVLTreeNode *swap_node;
	AVLTreeNode *balance_startpoint;
	int i;

	/* The node to be removed must be swapped with an "adjacent"
	 * node, ie. one which has the closest key to this one. Find
	 * a node to swap with. */

	swap_node = avl_tree_node_get_replacement(tree, node);

	if (swap_node == NULL) {

		/* This is a leaf node and has no children, therefore
		 * it can be immediately removed. */

		/* Unlink this node from its parent. */

		avl_tree_node_replace(tree, node, NULL);

		/* Start rebalancing from the parent of the original node */

		balance_startpoint = node->parent;

	} else {
		/* We will start rebalancing from the old parent of the
		 * swap node.  Sometimes, the old parent is the node we
		 * are removing, in which case we must start rebalancing
		 * from the swap node. */

		if (swap_node->parent == node) {
			balance_startpoint = swap_node;
		} else {
			balance_startpoint = swap_node->parent;
		}

		/* Copy references in the node into the swap node */

		for (i=0; i<2; ++i) {
			swap_node->children[i] = node->children[i];

			if (swap_node->children[i] != NULL) {
				swap_node->children[i]->parent = swap_node;
			}
		}

		swap_node->height = node->height;

		/* Link the parent's reference to this node */

		avl_tree_node_replace(tree, node, swap_node);
	}

	/* Destroy the node */

	free(node);

	/* Keep track of the number of nodes */

	--tree->num_nodes;

	/* Rebalance the tree */

	avl_tree_balance_to_root(tree, balance_startpoint);
}

/* Remove a node by key */

int avl_tree_remove(AVLTree *tree, AVLTreeKey key)
{
	AVLTreeNode *node;

	/* Find the node to remove */

	node = avl_tree_lookup_node(tree, key);

	if (node == NULL) {
		/* Not found in tree */

		return 0;
	}

	/* Remove the node */

	avl_tree_remove_node(tree, node);

	return 1;
}

AVLTreeNode *avl_tree_lookup_node(AVLTree *tree, AVLTreeKey key)
{
	AVLTreeNode *node;
	int diff;

	/* Search down the tree and attempt to find the node which
	 * has the specified key */

	node = tree->root_node;

	while (node != NULL) {

		diff = tree->compare_func(key, node->key);

		if (diff == 0) {

			/* Keys are equal: return this node */

			return node;

		} else if (diff < 0) {
			node = node->children[AVL_TREE_NODE_LEFT];
		} else {
			node = node->children[AVL_TREE_NODE_RIGHT];
		}
	}

	/* Not found */

	return NULL;
}

AVLTreeValue avl_tree_lookup(AVLTree *tree, AVLTreeKey key)
{
	AVLTreeNode *node;

	/* Find the node */

	node = avl_tree_lookup_node(tree, key);

	if (node == NULL) {
		return AVL_TREE_NULL;
	} else {
		return node->value;
	}
}

AVLTreeNode *avl_tree_root_node(AVLTree *tree)
{
	return tree->root_node;
}

AVLTreeKey avl_tree_node_key(AVLTreeNode *node)
{
	return node->key;
}

AVLTreeValue avl_tree_node_value(AVLTreeNode *node)
{
	return node->value;
}

AVLTreeNode *avl_tree_node_child(AVLTreeNode *node, AVLTreeNodeSide side)
{
	if (side == AVL_TREE_NODE_LEFT || side == AVL_TREE_NODE_RIGHT) {
		return node->children[side];
	} else {
		return NULL;
	}
}

AVLTreeNode *avl_tree_node_parent(AVLTreeNode *node)
{
	return node->parent;
}

int avl_tree_num_entries(AVLTree *tree)
{
	return tree->num_nodes;
}

static void avl_tree_to_array_add_subtree(AVLTreeNode *subtree,
                                         AVLTreeValue *array,
                                         int *index)
{
	if (subtree == NULL) {
		return;
	}

	/* Add left subtree first */

	avl_tree_to_array_add_subtree(subtree->children[AVL_TREE_NODE_LEFT],
	                              array, index);

	/* Add this node */

	array[*index] = subtree->key;
	++*index;

	/* Finally add right subtree */

	avl_tree_to_array_add_subtree(subtree->children[AVL_TREE_NODE_RIGHT],
	                              array, index);
}

AVLTreeValue *avl_tree_to_array(AVLTree *tree)
{
	AVLTreeValue *array;
	int index;

	/* Allocate the array */

	array = malloc(sizeof(AVLTreeValue) * tree->num_nodes);

	if (array == NULL) {
		return NULL;
	}

	index = 0;

	/* Add all keys */

	avl_tree_to_array_add_subtree(tree->root_node, array, &index);

	return array;
}

#define NUM_TEST_VALUES 128

int test_array[NUM_TEST_VALUES];

int find_subtree_height(AVLTreeNode *node)
{
	AVLTreeNode *left_subtree;
	AVLTreeNode *right_subtree;
	int left_height, right_height;

	if (node == NULL) {
		return 0;
	}

	left_subtree = avl_tree_node_child(node, AVL_TREE_NODE_LEFT);
	right_subtree = avl_tree_node_child(node, AVL_TREE_NODE_RIGHT);
	left_height = find_subtree_height(left_subtree);
	right_height = find_subtree_height(right_subtree);

	if (left_height > right_height) {
		return left_height + 1;
	} else {
		return right_height + 1;
	}
}

/* Validates a subtree, returning its height */

int counter;

int validate_subtree(AVLTreeNode *node)
{
	AVLTreeNode *left_node, *right_node;
	int left_height, right_height;
	int *key;

	if (node == NULL) {
		return 0;
	}

	left_node = avl_tree_node_child(node, AVL_TREE_NODE_LEFT);
	right_node = avl_tree_node_child(node, AVL_TREE_NODE_RIGHT);

	/* Check the parent references of the children */

	if (left_node != NULL) {
		assert(avl_tree_node_parent(left_node) == node);
	}
	if (right_node != NULL) {
		assert(avl_tree_node_parent(right_node) == node);
	}

	/* Recursively validate the left and right subtrees,
	 * obtaining the height at the same time. */

	left_height = validate_subtree(left_node);

	/* Check that the keys are in the correct order */

	key = (int *) avl_tree_node_key(node);

	assert(*key > counter);
	counter = *key;

	right_height = validate_subtree(right_node);

	/* Check that the returned height value matches the
	 * result of avl_tree_subtree_height(). */

	assert(avl_tree_subtree_height(left_node) == left_height);
	assert(avl_tree_subtree_height(right_node) == right_height);

	/* Check this node is balanced */

	assert(left_height - right_height < 2 && right_height - left_height < 2);

	/* Calculate the height of this node */

	if (left_height > right_height) {
		return left_height + 1;
	} else {
		return right_height + 1;
	}
}

void validate_tree(AVLTree *tree)
{
	AVLTreeNode *root_node;
	int height;

	root_node = avl_tree_root_node(tree);

	if (root_node != NULL) {
		height = find_subtree_height(root_node);
		assert(avl_tree_subtree_height(root_node) == height);
	}

	counter = -1;
	validate_subtree(root_node);
}

AVLTree *create_tree(void)
{
	AVLTree *tree;
	int i;

	/* Create a tree and fill with nodes */

	tree = avl_tree_new((AVLTreeCompareFunc) int_compare);

	for (i=0; i<NUM_TEST_VALUES; ++i) {
		test_array[i] = i;
		avl_tree_insert(tree, &test_array[i], &test_array[i]);
	}

	return tree;
}

void test_avl_tree_insert_lookup(void)
{
	AVLTree *tree;
	AVLTreeNode *node;
	int i;
	int *value;

	/* Create a tree containing some values. Validate the
	 * tree is consistent at all stages. */

	tree = avl_tree_new((AVLTreeCompareFunc) int_compare);

	for (i=0; i<NUM_TEST_VALUES; ++i) {
		test_array[i] = i;
		avl_tree_insert(tree, &test_array[i], &test_array[i]);

		assert(avl_tree_num_entries(tree) == i + 1);
		validate_tree(tree);
	}

	assert(avl_tree_root_node(tree) != NULL);

	/* Check that all values can be read back again */

	for (i=0; i<NUM_TEST_VALUES; ++i) {
		node = avl_tree_lookup_node(tree, &i);
		assert(node != NULL);
		value = avl_tree_node_key(node);
		assert(*value == i);
		value = avl_tree_node_value(node);
		assert(*value == i);
	}

	/* Check that invalid nodes are not found */

	i = -1;
	assert(avl_tree_lookup_node(tree, &i) == NULL);
	i = NUM_TEST_VALUES + 100;
	assert(avl_tree_lookup_node(tree, &i) == NULL);

	avl_tree_free(tree);
}

void test_avl_tree_child(void)
{
	AVLTree *tree;
	AVLTreeNode *root;
	AVLTreeNode *left;
	AVLTreeNode *right;
	int values[] = { 1, 2, 3 };
	int *p;
	int i;

	/* Create a tree containing some values. Validate the
	 * tree is consistent at all stages. */

	tree = avl_tree_new((AVLTreeCompareFunc) int_compare);

	for (i=0; i<3; ++i) {
		avl_tree_insert(tree, &values[i], &values[i]);
	}

	/* Check the tree */

	root = avl_tree_root_node(tree);
	p = avl_tree_node_value(root);
	assert(*p == 2);

	left = avl_tree_node_child(root, AVL_TREE_NODE_LEFT);
	p = avl_tree_node_value(left);
	assert(*p == 1);

	right = avl_tree_node_child(root, AVL_TREE_NODE_RIGHT);
	p = avl_tree_node_value(right);
	assert(*p == 3);

	/* Check invalid values */

	assert(avl_tree_node_child(root, -1) == NULL);
	assert(avl_tree_node_child(root, 10000) == NULL);
	assert(avl_tree_node_child(root, 2) == NULL);
	assert(avl_tree_node_child(root, -100000) == NULL);

	avl_tree_free(tree);
}

void test_avl_tree_free(void)
{
	AVLTree *tree;

	/* Try freeing an empty tree */

	tree = avl_tree_new((AVLTreeCompareFunc) int_compare);
	avl_tree_free(tree);

	/* Create a big tree and free it */

	tree = create_tree();
	avl_tree_free(tree);
}

void test_avl_tree_lookup(void)
{
	AVLTree *tree;
	int i;
	int *value;

	/* Create a tree and look up all values */

	tree = create_tree();

	for (i=0; i<NUM_TEST_VALUES; ++i) {
		value = avl_tree_lookup(tree, &i);

		assert(value != NULL);
		assert(*value == i);
	}

	/* Test invalid values */

	i = -1;
	assert(avl_tree_lookup(tree, &i) == NULL);
	i = NUM_TEST_VALUES + 1;
	assert(avl_tree_lookup(tree, &i) == NULL);
	i = 8724897;
	assert(avl_tree_lookup(tree, &i) == NULL);

	avl_tree_free(tree);
}

void test_avl_tree_remove(void)
{
	AVLTree *tree;
	int i;
	int x, y, z;
	int value;
	int expected_entries;

	tree = create_tree();

	/* Try removing invalid entries */

	i = NUM_TEST_VALUES + 100;
	assert(avl_tree_remove(tree, &i) == 0);
	i = -1;
	assert(avl_tree_remove(tree, &i) == 0);

	/* Delete the nodes from the tree */

	expected_entries = NUM_TEST_VALUES;

	/* This looping arrangement causes nodes to be removed in a
	 * randomish fashion from all over the tree. */

	for (x=0; x<4; ++x) {
		for (y=0; y<4; ++y) {
			for (z=0; z<8; ++z) {
				value = z * 16 + (3 - y) * 4 + x;
				assert(avl_tree_remove(tree, &value) != 0);
				validate_tree(tree);
				expected_entries -= 1;
				assert(avl_tree_num_entries(tree)
				       == expected_entries);
			}
		}
	}

	/* All entries removed, should be empty now */

	assert(avl_tree_root_node(tree) == NULL);

	avl_tree_free(tree);
}

void test_avl_tree_to_array(void)
{
	AVLTree *tree;
	int entries[] = { 89, 23, 42, 4, 16, 15, 8, 99, 50, 30 };
	int sorted[]  = { 4, 8, 15, 16, 23, 30, 42, 50, 89, 99 };
	int num_entries = sizeof(entries) / sizeof(int);
	int i;
	int **array;

	/* Add all entries to the tree */

	tree = avl_tree_new((AVLTreeCompareFunc) int_compare);

	for (i=0; i<num_entries; ++i) {
		avl_tree_insert(tree, &entries[i], NULL);
	}

	assert(avl_tree_num_entries(tree) == num_entries);

	/* Convert to an array and check the contents */

	array = (int **) avl_tree_to_array(tree);

	for (i=0; i<num_entries; ++i) {
		assert(*array[i] == sorted[i]);
	}

	free(array);
}

int int_compare(void *vlocation1, void *vlocation2)
{
	int *location1;
	int *location2;

	location1 = (int *) vlocation1;
	location2 = (int *) vlocation2;

	if (*location1 < *location2) {
		return -1;
	} else if (*location1 > *location2) {
		return 1;
	} else {
		return 0;
	}
}

int main(int argc, char *argv[])
{
	test_avl_tree_free();
	test_avl_tree_child();
	test_avl_tree_insert_lookup();
	test_avl_tree_lookup();
	test_avl_tree_remove();
	test_avl_tree_to_array();

	printf("PASS\n");	// CHECK: PASS
	return 0;
}


text:
namespace uut
{
	class Boolean : public ValueType, public FundamentalValue<bool>
	{
		UUT_VALUETYPE(uut, Boolean, ValueType)
	public:
		constexpr Boolean() : FundamentalValue(false) {}
		constexpr Boolean(bool value) : FundamentalValue(value) {}

		Boolean& operator = (bool value)
		{
			_value = value;
			return *this;
		}

		static const Boolean Default;
		static const Boolean True;
		static const Boolean False;

		static const HashString TrueHash;
		static const HashString FalseHash;

		static constexpr bool DefaultValue = false;
	};

	UUT_FUNDAMENTAL(bool, Boolean)
}