text:
"""Tests for zero-padding layers."""

import numpy as np
import tensorflow.compat.v2 as tf
from absl.testing import parameterized

import keras
from keras.testing_infra import test_combinations
from keras.testing_infra import test_utils

@test_combinations.run_all_keras_modes
class ZeroPaddingTest(test_combinations.TestCase):
    def test_zero_padding_1d(self):
        num_samples = 2
        input_dim = 2
        num_steps = 5
        shape = (num_samples, num_steps, input_dim)
        inputs = np.ones(shape)

        with self.cached_session():
            # basic test
            test_utils.layer_test(
                keras.layers.ZeroPadding1D,
                kwargs={"padding": 2},
                input_shape=inputs.shape,
            )
            test_utils.layer_test(
                keras.layers.ZeroPadding1D,
                kwargs={"padding": (1, 2)},
                input_shape=inputs.shape,
            )

            # correctness test
            layer = keras.layers.ZeroPadding1D(padding=2)
            layer.build(shape)
            output = layer(keras.backend.variable(inputs))
            if tf.executing_eagerly():
                np_output = output.numpy()
            else:
                np_output = keras.backend.eval(output)
            for offset in [0, 1, -1, -2]:
                np.testing.assert_allclose(np_output[:, offset, :], 0.0)
            np.testing.assert_allclose(np_output[:, 2:-2, :], 1.0)

            layer = keras.layers.ZeroPadding1D(padding=(1, 2))
            layer.build(shape)
            output = layer(keras.backend.variable(inputs))
            if tf.executing_eagerly():
                np_output = output.numpy()
            else:
                np_output = keras.backend.eval(output)
            for left_offset in [0]:
                np.testing.assert_allclose(np_output[:, left_offset, :], 0.0)
            for right_offset in [-1, -2]:
                np.testing.assert_allclose(np_output[:, right_offset, :], 0.0)
            np.testing.assert_allclose(np_output[:, 1:-2, :], 1.0)
            layer.get_config()

        # test incorrect use
        with self.assertRaises(ValueError):
            keras.layers.ZeroPadding1D(padding=(1, 1, 1))
        with self.assertRaises(ValueError):
            keras.layers.ZeroPadding1D(padding=None)

    @parameterized.named_parameters(
        ("channels_first", "channels_first"), ("channels_last", "channels_last")
    )
    def test_zero_padding_2d(self, data_format):
        num_samples = 2
        stack_size = 2
        input_num_row = 4
        input_num_col = 5
        if data_format == "channels_first":
            inputs = np.ones(
                (num_samples, stack_size, input_num_row, input_num_col)
            )
        elif data_format == "channels_last":
            inputs = np.ones(
                (num_samples, input_num_row, input_num_col, stack_size)
            )

        # basic test
        with self.cached_session():
            test_utils.layer_test(
                keras.layers.ZeroPadding2D,
                kwargs={"padding": (2, 2), "data_format": data_format},
                input_shape=inputs.shape,
            )
            test_utils.layer_test(
                keras.layers.ZeroPadding2D,
                kwargs={
                    "padding": ((1, 2), (3, 4)),
                    "data_format": data_format,
                },
                input_shape=inputs.shape,
            )

        # correctness test
        with self.cached_session():
            layer = keras.layers.ZeroPadding2D(
                padding=(2, 2), data_format=data_format
            )
            layer.build(inputs.shape)
            output = layer(keras.backend.variable(inputs))
            if tf.executing_eagerly():
                np_output = output.numpy()
            else:
                np_output = keras.backend.eval(output)
            if data_format == "channels_last":
                for offset in [0, 1, -1, -2]:
                    np.testing.assert_allclose(np_output[:, offset, :, :], 0.0)
                    np.testing.assert_allclose(np_output[:, :, offset, :], 0.0)
                np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.0)
            elif data_format == "channels_first":
                for offset in [0, 1, -1, -2]:
                    np.testing.assert_allclose(np_output[:, :, offset, :], 0.0)
                    np.testing.assert_allclose(np_output[:, :, :, offset], 0.0)
                np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.0)

            layer = keras.layers.ZeroPadding2D(
                padding=((1, 2), (3, 4)), data_format=data_format
            )
            layer.build(inputs.shape)
            output = layer(keras.backend.variable(inputs))
            if tf.executing_eagerly():
                np_output = output.numpy()
            else:
                np_output = keras.backend.eval(output)
            if data_format == "channels_last":
                for top_offset in [0]:
                    np.testing.assert_allclose(
                        np_output[:, top_offset, :, :], 0.0
                    )
                for bottom_offset in [-1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, bottom_offset, :, :], 0.0
                    )
                for left_offset in [0, 1, 2]:
                    np.testing.assert_allclose(
                        np_output[:, :, left_offset, :], 0.0
                    )
                for right_offset in [-1, -2, -3, -4]:
                    np.testing.assert_allclose(
                        np_output[:, :, right_offset, :], 0.0
                    )
                np.testing.assert_allclose(np_output[:, 1:-2, 3:-4, :], 1.0)
            elif data_format == "channels_first":
                for top_offset in [0]:
                    np.testing.assert_allclose(
                        np_output[:, :, top_offset, :], 0.0
                    )
                for bottom_offset in [-1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, :, bottom_offset, :], 0.0
                    )
                for left_offset in [0, 1, 2]:
                    np.testing.assert_allclose(
                        np_output[:, :, :, left_offset], 0.0
                    )
                for right_offset in [-1, -2, -3, -4]:
                    np.testing.assert_allclose(
                        np_output[:, :, :, right_offset], 0.0
                    )
                np.testing.assert_allclose(np_output[:, :, 1:-2, 3:-4], 1.0)

        # test incorrect use
        with self.assertRaises(ValueError):
            keras.layers.ZeroPadding2D(padding=(1, 1, 1))
        with self.assertRaises(ValueError):
            keras.layers.ZeroPadding2D(padding=None)

    @parameterized.named_parameters(
        ("channels_first", "channels_first"), ("channels_last", "channels_last")
    )
    def test_zero_padding_3d(self, data_format):
        num_samples = 2
        stack_size = 2
        input_len_dim1 = 4
        input_len_dim2 = 5
        input_len_dim3 = 3

        if data_format == "channels_first":
            inputs = np.ones(
                (
                    num_samples,
                    stack_size,
                    input_len_dim1,
                    input_len_dim2,
                    input_len_dim3,
                )
            )
        elif data_format == "channels_last":
            inputs = np.ones(
                (
                    num_samples,
                    input_len_dim1,
                    input_len_dim2,
                    input_len_dim3,
                    stack_size,
                )
            )

        with self.cached_session():
            # basic test
            test_utils.layer_test(
                keras.layers.ZeroPadding3D,
                kwargs={"padding": (2, 2, 2), "data_format": data_format},
                input_shape=inputs.shape,
            )
            test_utils.layer_test(
                keras.layers.ZeroPadding3D,
                kwargs={
                    "padding": ((1, 2), (3, 4), (0, 2)),
                    "data_format": data_format,
                },
                input_shape=inputs.shape,
            )

        with self.cached_session():
            # correctness test
            layer = keras.layers.ZeroPadding3D(
                padding=(2, 2, 2), data_format=data_format
            )
            layer.build(inputs.shape)
            output = layer(keras.backend.variable(inputs))
            if tf.executing_eagerly():
                np_output = output.numpy()
            else:
                np_output = keras.backend.eval(output)
            if data_format == "channels_last":
                for offset in [0, 1, -1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, offset, :, :, :], 0.0
                    )
                    np.testing.assert_allclose(
                        np_output[:, :, offset, :, :], 0.0
                    )
                    np.testing.assert_allclose(
                        np_output[:, :, :, offset, :], 0.0
                    )
                np.testing.assert_allclose(
                    np_output[:, 2:-2, 2:-2, 2:-2, :], 1.0
                )
            elif data_format == "channels_first":
                for offset in [0, 1, -1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, :, offset, :, :], 0.0
                    )
                    np.testing.assert_allclose(
                        np_output[:, :, :, offset, :], 0.0
                    )
                    np.testing.assert_allclose(
                        np_output[:, :, :, :, offset], 0.0
                    )
                np.testing.assert_allclose(
                    np_output[:, :, 2:-2, 2:-2, 2:-2], 1.0
                )

            layer = keras.layers.ZeroPadding3D(
                padding=((1, 2), (3, 4), (0, 2)), data_format=data_format
            )
            layer.build(inputs.shape)
            output = layer(keras.backend.variable(inputs))
            if tf.executing_eagerly():
                np_output = output.numpy()
            else:
                np_output = keras.backend.eval(output)
            if data_format == "channels_last":
                for offset in [0]:
                    np.testing.assert_allclose(
                        np_output[:, offset, :, :, :], 0.0
                    )
                for offset in [-1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, offset, :, :, :], 0.0
                    )
                for offset in [0, 1, 2]:
                    np.testing.assert_allclose(
                        np_output[:, :, offset, :, :], 0.0
                    )
                for offset in [-1, -2, -3, -4]:
                    np.testing.assert_allclose(
                        np_output[:, :, offset, :, :], 0.0
                    )
                for offset in [-1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, :, :, offset, :], 0.0
                    )
                np.testing.assert_allclose(
                    np_output[:, 1:-2, 3:-4, 0:-2, :], 1.0
                )
            elif data_format == "channels_first":
                for offset in [0]:
                    np.testing.assert_allclose(
                        np_output[:, :, offset, :, :], 0.0
                    )
                for offset in [-1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, :, offset, :, :], 0.0
                    )
                for offset in [0, 1, 2]:
                    np.testing.assert_allclose(
                        np_output[:, :, :, offset, :], 0.0
                    )
                for offset in [-1, -2, -3, -4]:
                    np.testing.assert_allclose(
                        np_output[:, :, :, offset, :], 0.0
                    )
                for offset in [-1, -2]:
                    np.testing.assert_allclose(
                        np_output[:, :, :, :, offset], 0.0
                    )
                np.testing.assert_allclose(
                    np_output[:, :, 1:-2, 3:-4, 0:-2], 1.0
                )

        # test incorrect use
        with self.assertRaises(ValueError):
            keras.layers.ZeroPadding3D(padding=(1, 1))
        with self.assertRaises(ValueError):
            keras.layers.ZeroPadding3D(padding=None)

if __name__ == "__main__":
    tf.test.main()


text:
<?php

namespace Mage\Checkout\Test\Constraint;

use Mage\Catalog\Test\Fixture\CatalogProductSimple;
use Mage\Checkout\Test\Fixture\Cart;
use Mage\Checkout\Test\Fixture\Cart\Items;
use Mage\Cms\Test\Page\CmsIndex;
use Magento\Mtf\Constraint\AbstractAssertForm;
use Magento\Mtf\Fixture\FixtureInterface;

/**
 * Assert that product quantity in the mini shopping cart is equals to expected quantity from data set.
 */
class AssertProductQtyInMiniShoppingCart extends AbstractAssertForm
{
    /* tags */
    const SEVERITY = 'low';
    /* end tags */

    /**
     * Assert that product quantity in the mini shopping cart is equals to expected quantity from data set.
     *
     * @param CmsIndex $cmsIndex
     * @param Cart $cart
     * @return void
     */
    public function processAssert(CmsIndex $cmsIndex, Cart $cart)
    {
        $cmsIndex->open()->getTopLinksBlock()->openMiniCart();
        /** @var Items $sourceProducts */
        $products = $cart->getDataFieldConfig('items')['source']->getProducts();
        $items = $cart->getItems();
        $productsData = [];
        $miniCartData = [];

        foreach ($items as $key => $item) {
            /** @var CatalogProductSimple $product */
            $product = $products[$key];
            $productName = $product->getName();
            /** @var FixtureInterface $item */
            $checkoutItem = $item->getData();

            $productsData[$productName] = ['qty' => $checkoutItem['qty']];
            $miniCartData[$productName] = ['qty' => $cmsIndex->getCartSidebarBlock()->getCartItem($product)->getQty()];
        }

        $error = $this->verifyData($productsData, $miniCartData, true);
        \PHPUnit_Framework_Assert::assertEmpty($error, $error);
    }

    /**
     * Returns a string representation of the object.
     *
     * @return string
     */
    public function toString()
    {
        return 'Quantity in the mini shopping cart equals to expected quantity from data set.';
    }
}

redpajama_set_name: RedPajamaGithub


text: export { locationHistory, router } from './router';


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include "visitor.h"

namespace storage {

/**
 * A visitor instance that is intended to be used for background reindexing.
 * Only meant to be run alongside distributor-level bucket locking support
 * that prevents concurrent writes to documents in the visited bucket.
 *
 * The bucket lock is explicitly bypassed by the Puts sent by the visitor
 * by having all these be augmented with a special TaS string that is
 * recognized by the distributor.
 */
class ReindexingVisitor : public Visitor {
public:
    explicit ReindexingVisitor(StorageComponent& component);
    ~ReindexingVisitor() override = default;

private:
    void handleDocuments(const document::BucketId&, DocEntryList&, HitCounter&) override;
    bool remap_docapi_message_error_code(api::ReturnCode& in_out_code) override;
    vespalib::string make_lock_access_token() const;
};

struct ReindexingVisitorFactory : public VisitorFactory {
    VisitorEnvironment::UP makeVisitorEnvironment(StorageComponent&) override {
        return std::make_unique<VisitorEnvironment>();
    };

    Visitor* makeVisitor(StorageComponent& c, VisitorEnvironment&, const vdslib::Parameters&) override {
        return new ReindexingVisitor(c);
    }
};

}


text:
//
//  UCVideoServiceUstream.h
//  Flashless
//
//  Created by Christoph on 04.09.09.
//  Copyright Useless Coding 2009.

#import <Cocoa/Cocoa.h>
#import "UCVideoService.h"

@interface UCVideoServiceUstream : UCVideoService
{
}
@end


text:
package client

type (
	// EndpointsInterface has methods to work with Endpoints resources.
	EndpointsInterface interface {
		CreateEndpoints(namespace string, item *Endpoints) (*Endpoints, error)
		GetEndpoints(namespace, name string) (result *Endpoints, err error)
		ListEndpoints(namespace string, opts *ListOptions) (*EndpointsList, error)
		DeleteEndpoints(namespace, name string) error
		UpdateEndpoints(namespace string, item *Endpoints) (*Endpoints, error)
	}

	// Endpoints is a collection of endpoints that implement the actual service.
	Endpoints struct {
		TypeMeta   `json:",inline"`
		ObjectMeta `json:"metadata,omitempty"`

		// The set of all endpoints is the union of all subsets.
		// Addresses are placed into subsets according to the IPs they share.
		// A single address with multiple ports, some of which are ready and some of which are not
		// (because they come from different containers) will result in the address being displayed in different
		// subsets for the different ports.
		// No address will appear in both Addresses and NotReadyAddresses in the same subset.
		// Sets of addresses and ports that comprise a service
		Subsets []EndpointSubset `json:"subsets,omitempty"`
	}

	// EndpointSubset is a group of addresses with a common set of ports.
	// The expanded set of endpoints is the Cartesian product of Addresses x Ports.
	EndpointSubset struct {
		// IP addresses which offer the related ports that are marked as ready.
		// These endpoints should be considered safe for load balancers and clients to utilize.
		Addresses []EndpointAddress `json:"addresses,omitempty"`

		// IP addresses which offer the related ports but are not currently marked as ready because
		// they have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.
		NotReadyAddresses []EndpointAddress `json:"notReadyAddresses,omitempty"`

		// Port numbers available on the related IP addresses
		Ports []EndpointPort `json:"ports,omitempty"`
	}

	EndpointAddress struct {
		// The IP of this endpoint.
		// May not be loopback (127.0.0.0/8), link-local (169.254.0.0/16), or link-local multicast ((224.0.0.0/24).
		// IPv6 is also accepted but not fully supported on all platforms.
		// Also, certain kubernetes components, like kube-proxy, are not IPv6 ready.
		IP string `json:"ip,omitempty"`
		// The Hostname of this endpoint
		Hostname string `json:"hostname,omitempty"`
		// Optional: Node hosting this endpoint. This can be used to determine endpoints local to a node.
		NodeName string `json:"nodeName,omitempty"`
		// Reference to object providing the endpoint.
		TargetRef *ObjectReference `json:"targetRef,omitempty"`
	}

	EndpointPort struct {
		// The name of this port (corresponds to ServicePort.Name). Must be a DNS_LABEL.
		// Optional only if one port is defined.
		Name string `json:"name,omitempty"`
		// The port number of the endpoint.
		Port int32 `json:"port"`
		// The IP protocol for this port. Must be UDP or TCP. Default is TCP.
		Protocol string `json:"protocol,omitempty"`
	}

	// EndpointsList holds a list of endpoints.
	EndpointsList struct {
		TypeMeta `json:",inline"`
		ListMeta `json:"metadata,omitempty"`

		Items []Endpoints `json:"items"`
	}
)


text:
#pragma once

#include "targetver.h"
#include <Windows.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <tchar.h>
#include <memory>
#include <functional>

extern "C" {
#include <libavutil\avutil.h>
#include <libavcodec\avcodec.h>
#include <libavformat\avformat.h>
#include <libavfilter\avfilter.h>
}


text:
"""Runs the aggregate interference code under profiler.

This script creates several profile output:
  profile-<idx>.out
where idx:
  0 is the main process
  1-N: for each workers

Note: script derived from the aggregate_interference_example.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import os
import time
import cProfile

from reference_models.common import data
from reference_models.common import mpool
from reference_models.interference import interference as interf
from reference_models.interference import aggregate_interference
from reference_models.tools import profpool

# Number of parallel processes
NUM_PROCESS = 4

def json_load(fname):
  with open(fname) as fd:
    return json.load(fd)

def CvtToList(data):
  """Convert interf to a sorted list suitable for comparison."""
  out_dict = {}
  for k0, v0 in data.items():
    for k1, v1 in v0.items():
      out_dict[(k0, k1)] = v1

  out_list = list(out_dict.items())
  out_list.sort()
  return out_list

if __name__ == '__main__':

  #=======================================
  # Decrease resolution of GWPZ/PPA for reducing time
  aggregate_interference.GWPZ_GRID_RES_ARCSEC = 10
  aggregate_interference.PPA_GRID_RES_ARCSEC = 10

  #=======================================
  # Configure the multiprocess pool with profiler enabled
  pool = profpool.PoolWithProfiler(NUM_PROCESS)
  mpool.Configure(pool=pool)
  prof0 = cProfile.Profile()

  #=======================================
  # Data directory
  _BASE_DATA_DIR = os.path.join(os.path.dirname(__file__),
                                '../../interference/test_data')

  # Populate a list of CBSD registration requests
  cbsd_filename = ['cbsd_0.json',
                   'cbsd_1.json', 'cbsd_2.json', 'cbsd_3.json',
                   'cbsd_4.json', 'cbsd_5.json', 'cbsd_6.json',
                   'cbsd_7.json', 'cbsd_8.json', 'cbsd_9.json',
                   'cbsd_10.json', 'cbsd_11.json', 'cbsd_12.json',
                   'cbsd_13.json', 'cbsd_14.json', 'cbsd_15.json',
                   'cbsd_16.json', 'cbsd_17.json', 'cbsd_18.json',
                   'cbsd_19.json', 'cbsd_20.json', 'cbsd_21.json',
                   'cbsd_22.json', 'cbsd_23.json'
                   ]
  cbsd_list = []
  for cbsd_file in cbsd_filename:
    cbsd_record = json_load(os.path.join(_BASE_DATA_DIR, cbsd_file))
    cbsd_list.append(cbsd_record)

  # Populate FSS
  fss_filename = ['fss_0.json', 'fss_1.json']
  fss_list = []
  for fss_file in fss_filename:
    fss_record = json_load(os.path.join(_BASE_DATA_DIR, fss_file))
    fss_list.append(fss_record)

  # Populate ESC
  esc_filename = ['esc_0.json']
  esc_list = []
  for esc_file in esc_filename:
    esc_record = json_load(
        os.path.join(_BASE_DATA_DIR, esc_file))
    esc_list.append(esc_record)

  # Populate GWPZ
  gwpz_filename = ['gwpz_0.json', 'gwpz_1.json']
  gwpz_list = []
  for gwpz_file in gwpz_filename:
    gwpz_record = json_load(
        os.path.join(_BASE_DATA_DIR, gwpz_file))
    gwpz_list.append(gwpz_record)

  # Populate PPA/PAL
  ppa_filename = ['ppa_0.json', 'ppa_1.json', 'ppa_2.json', 'ppa_3.json']
  ppa_list = []
  for ppa_file in ppa_filename:
    # load and inject PPA data with Overlapping Frequency of CBSD
    ppa_record = json_load(os.path.join(_BASE_DATA_DIR, ppa_file))
    ppa_list.append(ppa_record)

  pal_filename = ['pal_0.json', 'pal_1.json', 'pal_2.json', 'pal_3.json']
  ppa_filename = []
  pal_list = []
  for pal_file in pal_filename:
    pal_record = json_load(os.path.join(_BASE_DATA_DIR, pal_file))
    pal_list.append(pal_record)

  #=======================================
  # Determine aggregate interference caused by the grants in the neighborhood
  start_time = time.time()
  prof0.enable()

  #--- FSS ---
  for fss_record in fss_list:
    # Get the frequency range of the FSS
    fss_freq_range = fss_record['record']['deploymentParam'][0]\
        ['operationParam']['operationFrequencyRange']
    fss_low_freq = fss_freq_range['lowFrequency']
    fss_high_freq = fss_freq_range['highFrequency']

    # Get FSS T&C Flag value
    fss_ttc_flag = fss_record['ttc']

    # FSS Passband is between 3600 and 4200
    if (fss_low_freq >= interf.FSS_LOW_FREQ_HZ and
        fss_low_freq < interf.CBRS_HIGH_FREQ_HZ):
      fss_cochannel_aggr_interference = aggregate_interference.\
        calculateAggregateInterferenceForFssCochannel(
            fss_record, data.getAllGrantInfoFromCbsdDataDump(cbsd_list))
      print('Aggregate Interference (mW) output at FSS co-channel: %s\n'
            % (CvtToList(fss_cochannel_aggr_interference)))
      fss_blocking_aggr_interference = aggregate_interference.\
        calculateAggregateInterferenceForFssBlocking(
            fss_record, data.getAllGrantInfoFromCbsdDataDump(cbsd_list))
      print('\nAggregate Interference (mW) output at FSS blocking: %s\n'
            % (CvtToList(fss_blocking_aggr_interference)))

    # FSS Passband is between 3700 and 4200 and TT&C flag is set to TRUE
    elif (fss_low_freq >= interf.FSS_TTC_LOW_FREQ_HZ and
          fss_high_freq <= interf.FSS_TTC_HIGH_FREQ_HZ and
          fss_ttc_flag is True):
      fss_blocking_aggr_interference = aggregate_interference.\
        calculateAggregateInterferenceForFssBlocking(
            fss_record, data.getAllGrantInfoFromCbsdDataDump(cbsd_list))
      print('\nAggregate Interference (mW) output at FSS blocking: %s\n'
            % (CvtToList(fss_blocking_aggr_interference)))

  #--- ESC ---
  for esc_record in esc_list:
    esc_aggr_interference = aggregate_interference.\
      calculateAggregateInterferenceForEsc(
          esc_record, data.getAllGrantInfoFromCbsdDataDump(cbsd_list))
    print('\nAggregate Interference (mW) output at ESC: %s\n'
          % (CvtToList(esc_aggr_interference)))

  #--- GWPZ ---
  for gwpz_record in gwpz_list:
    gwpz_aggr_interference = aggregate_interference.\
      calculateAggregateInterferenceForGwpz(
          gwpz_record, data.getAllGrantInfoFromCbsdDataDump(cbsd_list))
    print('\nAggregate Interference (mW) output at GWPZ: \n' +
          str(CvtToList(gwpz_aggr_interference))[0:400])

  #--- PPA ---
  for ppa_record in ppa_list:
    ppa_aggr_interference = aggregate_interference.\
      calculateAggregateInterferenceForPpa(
          ppa_record, pal_list,
          data.getAllGrantInfoFromCbsdDataDump(cbsd_list, ppa_record=ppa_record))
    print('\nAggregate Interference (mW) output at PPA: \n' +
          str(CvtToList(gwpz_aggr_interference))[0:400])

  prof0.disable()
  end_time = time.time()
  #=======================================
  print('\nComputation time: %.4f\n' % (end_time - start_time))
  print('Saving profile')
  prof0.dump_stats('profile-0m.out')
  pool.dump_stats()

  #=======================================
  # Print on screen basic data
  import pstats
  print('******* Profiling on main process *******')
  p0 = pstats.Stats('profile-0m.out')
  p0.sort_stats('cumulative')
  p0.print_stats(20)
  print('******* Profiling on worker1 *******')
  p1 = pstats.Stats('profile-1.out')
  p1.sort_stats('cumulative')
  p1.print_stats(20)


text:
package com.intellij.java.slicer;

import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.execution.filters.ExceptionAnalysisProvider;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.slicer.*;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.util.ArrayUtil;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class SliceBackwardTest extends SliceTestCase {
  @Override
  protected Sdk getTestProjectJdk() {
    return PsiTestUtil.addJdkAnnotations(IdeaTestUtil.getMockJdk11());
  }

  private void doTest() throws Exception {
    doTest("");
  }

  private void doTest(@NotNull String filter) throws Exception {
    doTest(filter, ArrayUtil.EMPTY_STRING_ARRAY);
  }

  @Override
  protected @NotNull LanguageLevel getProjectLanguageLevel() {
    return LanguageLevel.JDK_16;
  }

  private void doTest(@NotNull String filter, @NotNull String @NotNull... stack) throws Exception {
    configureByFile("/codeInsight/slice/backward/"+getTestName(false)+".java");
    Map<String, RangeMarker> sliceUsageName2Offset = SliceTestUtil.extractSliceOffsetsFromDocument(getEditor().getDocument());
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    PsiElement element = SliceHandler.create(true).getExpressionAtCaret(getEditor(), getFile());
    assertNotNull(element);
    SliceTestUtil.Node tree = SliceTestUtil.buildTree(element, sliceUsageName2Offset);
    Collection<HighlightInfo> errors = highlightErrors();
    assertEmpty(errors);
    SliceAnalysisParams params = new SliceAnalysisParams();
    params.scope = new AnalysisScope(getProject());
    params.dataFlowToThis = true;
    SliceLanguageSupportProvider provider = LanguageSlicing.getProvider(element);
    params.valueFilter = filter.isEmpty() ? JavaValueFilter.ALLOW_EVERYTHING : provider.parseFilter(element, filter);
    List<ExceptionAnalysisProvider.StackLine> lines = StreamEx.of(stack).map(line -> {
      String[] parts = line.split(":");
      return new ExceptionAnalysisProvider.StackLine(parts[0], parts[1], null);
    }).toList();
    assertTrue(params.valueFilter instanceof JavaValueFilter);
    params.valueFilter = ((JavaValueFilter)params.valueFilter).withStack(lines);

    SliceUsage usage = provider.createRootUsage(element, params);
    SliceTestUtil.checkUsages(usage, tree);
  }

  public void testSimple() throws Exception { doTest();}
  public void testLocalVar() throws Exception { doTest();}
  public void testInterMethod() throws Exception { doTest();}
  public void testConditional() throws Exception { doTest();}
  public void testConditional2() throws Exception { doTest();}
  public void testMethodReturn() throws Exception { doTest();}
  public void testVarUse() throws Exception { doTest();}
  public void testWeirdCaretPosition() throws Exception { doTest();}
  public void testAnonClass() throws Exception { doTest();}
  public void testPostfix() throws Exception { doTest();}
  public void testMethodCall() throws Exception { doTest();}
  public void testEnumConst() throws Exception { doTest();}
  public void testTypeAware() throws Exception { doTest();}
  public void testTypeAware2() throws Exception { doTest();}
  public void testViaParameterizedMethods() throws Exception { doTest();}
  public void testTypeErased() throws Exception { doTest();}
  public void testComplexTypeErasure() throws Exception { doTest();}
  public void testGenericsSubst() throws Exception { doTest();}
  public void testOverrides() throws Exception { doTest();}
  public void testGenericBoxing() throws Exception { doTest();}
  public void testAssignment() throws Exception { doTest();}
  public void testGenericImplement() throws Exception { doTest();}
  public void testGenericImplement2() throws Exception { doTest();}
  public void testOverloadConstructor() throws Exception { doTest();}
  public void testArrayElements() throws Exception { doTest();}
  public void testAnonArray() throws Exception { doTest();}
  public void testVarArgs() throws Exception { doTest();}
  public void testVarArgsAsAWhole() throws Exception { doTest();}
  public void testVarArgsPartial() throws Exception { doTest();}

  public void testListTrackToArray() throws Exception { doTest();}
  public void testTryCatchFinally() throws Exception { doTest();}
  public void testFinalVarAssignedBeforePassingToAnonymous() throws Exception { doTest();}
  public void testLocalVarDeclarationAndAssignment() throws Exception { doTest();}
  public void testSearchOverriddenMethodsInThisClassHierarchy() throws Exception { doTest();}
  public void testSearchOverriddenMethodsInThisClassHierarchyParam() throws Exception { doTest();}
  public void testSearchOverriddenMethodsInThisClassHierarchyParamDfa() throws Exception { doTest();}
  public void testAppend() throws Exception { doTest();}
  public void testRequireNonNull() throws Exception { doTest();}
  public void testBackAndForward() throws Exception { doTest();}

  public void testFilterIntRange() throws Exception { doTest(">=0");}
  public void testFilterIntRangeArray() throws Exception { doTest(">=0");}
  public void testFilterNull() throws Exception { doTest("null");}
  public void testNarrowFilter() throws Exception { doTest();}
  public void testFilterPropagateMath() throws Exception { doTest("-8");}
  public void testFilterPropagateBoolean() throws Exception { doTest("true");}
  public void testFilterPropagateBoolean2() throws Exception { doTest("false");}
  public void testFilterAssertionViolation() throws Exception { doTest("-1");}
  public void testReturnParameter() throws Exception { doTest(); }
  public void testFilterLongByInt() throws Exception { doTest("<=0"); }
  public void testFilterDoubleByInt() throws Exception { doTest("0.0"); }

  public void testStackFilterSimple() throws Exception {
    doTest("null", "MainTest:test", "MainTest:foo", "MainTest:main");
  }

  public void testStackFilterBridgeMethod() throws Exception {
    doTest("null", "MainTest$Bar:get", "MainTest$Bar:get", "MainTest:bar", "MainTest:main");
  }

  public void testStackFilterBridgeMethod2() throws Exception {
    doTest("null", "MainTest$Bar:get", "MainTest$Bar:get", "MainTest:bar", "MainTest:main");
  }

  public void testRecordComponent() throws Exception { doTest();}
  public void testRecordComponent2() throws Exception { doTest();}
  public void testRecordComponent3() throws Exception { doTest();}
  public void testOptionalAsContainer() throws Exception { doTest();}
  public void testUnmodifiableList() throws Exception { doTest();}
}


text:
<?php

namespace RK\HelperModule\Form\Handler\Common\Base;

use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Zikula\Bundle\CoreBundle\HttpKernel\ZikulaHttpKernelInterface;
use Zikula\Bundle\HookBundle\Category\FormAwareCategory;
use Zikula\Bundle\HookBundle\Category\UiHooksCategory;
use Zikula\Common\Translator\TranslatorInterface;
use Zikula\Common\Translator\TranslatorTrait;
use Zikula\Core\Doctrine\EntityAccess;
use Zikula\Core\RouteUrl;
use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
use Zikula\PageLockModule\Api\ApiInterface\LockingApiInterface;
use Zikula\PermissionsModule\Api\ApiInterface\PermissionApiInterface;
use Zikula\UsersModule\Api\ApiInterface\CurrentUserApiInterface;
use RK\HelperModule\Entity\Factory\EntityFactory;
use RK\HelperModule\Helper\FeatureActivationHelper;
use RK\HelperModule\Helper\ControllerHelper;
use RK\HelperModule\Helper\HookHelper;
use RK\HelperModule\Helper\ModelHelper;
use RK\HelperModule\Helper\TranslatableHelper;
use RK\HelperModule\Helper\WorkflowHelper;

/**
 * This handler class handles the page events of editing forms.
 * It collects common functionality required by different object types.
 */
abstract class AbstractEditHandler
{
    use TranslatorTrait;

    /**
     * Name of treated object type.
     *
     * @var string
     */
    protected $objectType;

    /**
     * Name of treated object type starting with upper case.
     *
     * @var string
     */
    protected $objectTypeCapital;

    /**
     * Lower case version.
     *
     * @var string
     */
    protected $objectTypeLower;

    /**
     * Permission component based on object type.
     *
     * @var string
     */
    protected $permissionComponent;

    /**
     * Reference to treated entity instance.
     *
     * @var EntityAccess
     */
    protected $entityRef = null;

    /**
     * Name of primary identifier field.
     *
     * @var string
     */
    protected $idField = null;

    /**
     * Identifier of treated entity.
     *
     * @var integer
     */
    protected $idValue = 0;

    /**
     * Code defining the redirect goal after command handling.
     *
     * @var string
     */
    protected $returnTo = null;

    /**
     * Whether a create action is going to be repeated or not.
     *
     * @var boolean
     */
    protected $repeatCreateAction = false;

    /**
     * Url of current form with all parameters for multiple creations.
     *
     * @var string
     */
    protected $repeatReturnUrl = null;

    /**
     * List of identifiers for predefined relationships.
     *
     * @var mixed
     */
    protected $relationPresets = [];

    /**
     * Full prefix for related items.
     *
     * @var string
     */
    protected $idPrefix = '';

    /**
     * Whether the PageLock extension is used for this entity type or not.
     *
     * @var boolean
     */
    protected $hasPageLockSupport = false;

    /**
     * Whether the entity has translatable fields or not.
     *
     * @var boolean
     */
    protected $hasTranslatableFields = false;

    /**
     * @var ZikulaHttpKernelInterface
     */
    protected $kernel;

    /**
     * @var FormFactoryInterface
     */
    protected $formFactory;

    /**
     * The current request.
     *
     * @var Request
     */
    protected $request;

    /**
     * The router.
     *
     * @var RouterInterface
     */
    protected $router;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var PermissionApiInterface
     */
    protected $permissionApi;

    /**
     * @var VariableApiInterface
     */
    protected $variableApi;

    /**
     * @var CurrentUserApiInterface
     */
    protected $currentUserApi;

    /**
     * @var EntityFactory
     */
    protected $entityFactory;

    /**
     * @var ControllerHelper
     */
    protected $controllerHelper;

    /**
     * @var HookHelper
     */
    protected $hookHelper;

    /**
     * @var ModelHelper
     */
    protected $modelHelper;

    /**
     * @var WorkflowHelper
     */
    protected $workflowHelper;

    /**
     * @var TranslatableHelper
     */
    protected $translatableHelper;

    /**
     * @var FeatureActivationHelper
     */
    protected $featureActivationHelper;

    /**
     * Reference to optional locking api.
     *
     * @var LockingApiInterface
     */
    protected $lockingApi = null;

    /**
     * The handled form type.
     *
     * @var AbstractType
     */
    protected $form;

    /**
     * Template parameters.
     *
     * @var array
     */
    protected $templateParameters = [];

    /**
     * EditHandler constructor.
     *
     * @param ZikulaHttpKernelInterface $kernel           Kernel service instance
     * @param TranslatorInterface       $translator       Translator service instance
     * @param FormFactoryInterface      $formFactory      FormFactory service instance
     * @param RequestStack              $requestStack     RequestStack service instance
     * @param RouterInterface           $router           Router service instance
     * @param LoggerInterface           $logger           Logger service instance
     * @param PermissionApiInterface    $permissionApi    PermissionApi service instance
     * @param VariableApiInterface      $variableApi      VariableApi service instance
     * @param CurrentUserApiInterface   $currentUserApi   CurrentUserApi service instance
     * @param EntityFactory             $entityFactory    EntityFactory service instance
     * @param ControllerHelper          $controllerHelper ControllerHelper service instance
     * @param ModelHelper               $modelHelper      ModelHelper service instance
     * @param WorkflowHelper            $workflowHelper   WorkflowHelper service instance
     * @param HookHelper                $hookHelper       HookHelper service instance
     * @param TranslatableHelper        $translatableHelper TranslatableHelper service instance
     * @param FeatureActivationHelper   $featureActivationHelper FeatureActivationHelper service instance
     */
    public function __construct(
        ZikulaHttpKernelInterface $kernel,
        TranslatorInterface $translator,
        FormFactoryInterface $formFactory,
        RequestStack $requestStack,
        RouterInterface $router,
        LoggerInterface $logger,
        PermissionApiInterface $permissionApi,
        VariableApiInterface $variableApi,
        CurrentUserApiInterface $currentUserApi,
        EntityFactory $entityFactory,
        ControllerHelper $controllerHelper,
        ModelHelper $modelHelper,
        WorkflowHelper $workflowHelper,
        HookHelper $hookHelper,
        TranslatableHelper $translatableHelper,
        FeatureActivationHelper $featureActivationHelper
    ) {
        $this->kernel = $kernel;
        $this->setTranslator($translator);
        $this->formFactory = $formFactory;
        $this->request = $requestStack->getCurrentRequest();
        $this->router = $router;
        $this->logger = $logger;
        $this->permissionApi = $permissionApi;
        $this->variableApi = $variableApi;
        $this->currentUserApi = $currentUserApi;
        $this->entityFactory = $entityFactory;
        $this->controllerHelper = $controllerHelper;
        $this->modelHelper = $modelHelper;
        $this->workflowHelper = $workflowHelper;
        $this->hookHelper = $hookHelper;
        $this->translatableHelper = $translatableHelper;
        $this->featureActivationHelper = $featureActivationHelper;
    }

    /**
     * Sets the translator.
     *
     * @param TranslatorInterface $translator Translator service instance
     */
    public function setTranslator(/*TranslatorInterface */$translator)
    {
        $this->translator = $translator;
    }

    /**
     * Initialise form handler.
     *
     * This method takes care of all necessary initialisation of our data and form states.
     *
     * @param array $templateParameters List of preassigned template variables
     *
     * @return boolean False in case of initialisation errors, otherwise true
     *
     * @throws RuntimeException Thrown if the workflow actions can not be determined
     */
    public function processForm(array $templateParameters)
    {
        $this->templateParameters = $templateParameters;
        $this->templateParameters['inlineUsage'] = $this->request->query->getBoolean('raw', false);

        $this->idPrefix = $this->request->query->get('idp', '');

        // initialise redirect goal
        $this->returnTo = $this->request->query->get('returnTo', null);
        // default to referer
        $refererSessionVar = 'rkhelpermodule' . $this->objectTypeCapital . 'Referer';
        if (null === $this->returnTo && $this->request->headers->has('referer')) {
            $currentReferer = $this->request->headers->get('referer');
            if ($currentReferer != $this->request->getUri()) {
                $this->returnTo = $currentReferer;
                $this->request->getSession()->set($refererSessionVar, $this->returnTo);
            }
        }
        if (null === $this->returnTo && $this->request->getSession()->has($refererSessionVar)) {
            $this->returnTo = $this->request->getSession()->get($refererSessionVar);
        }
        // store current uri for repeated creations
        $this->repeatReturnUrl = $this->request->getSchemeAndHttpHost() . $this->request->getBasePath() . $this->request->getPathInfo();

        $this->permissionComponent = 'RKHelperModule:' . $this->objectTypeCapital . ':';

        $this->idField = $this->entityFactory->getIdField($this->objectType);

        // retrieve identifier of the object we wish to edit
        $routeParams = $this->request->get('_route_params', []);
        if (empty($this->idValue)) {
            if (array_key_exists($this->idField, $routeParams)) {
                $this->idValue = (int) !empty($routeParams[$this->idField]) ? $routeParams[$this->idField] : 0;
            }
            if (0 === $this->idValue) {
                $this->idValue = $this->request->query->getInt($this->idField, 0);
            }
            if (0 === $this->idValue && $this->idField != 'id') {
                $this->idValue = $this->request->query->getInt('id', 0);
            }
        }

        $entity = null;
        $this->templateParameters['mode'] = !empty($this->idValue) ? 'edit' : 'create';

        if ($this->templateParameters['mode'] == 'edit') {
            if (!$this->permissionApi->hasPermission($this->permissionComponent, $this->idValue . '::', ACCESS_EDIT)) {
                throw new AccessDeniedException();
            }

            $entity = $this->initEntityForEditing();
            if (null !== $entity) {
                if (true === $this->hasPageLockSupport && $this->kernel->isBundle('ZikulaPageLockModule') && null !== $this->lockingApi) {
                    // try to guarantee that only one person at a time can be editing this entity
                    $lockName = 'RKHelperModule' . $this->objectTypeCapital . $entity->getKey();
                    $this->lockingApi->addLock($lockName, $this->getRedirectUrl(null));
                    // reload entity as the addLock call above has triggered the preUpdate event
                    $this->entityFactory->getObjectManager()->refresh($entity);
                }
            }
        } else {
            $permissionLevel = ACCESS_EDIT;
            if (!$this->permissionApi->hasPermission($this->permissionComponent, '::', $permissionLevel)) {
                throw new AccessDeniedException();
            }

            $entity = $this->initEntityForCreation();

            // set default values from request parameters
            foreach ($this->request->query->all() as $key => $value) {
                if (strlen($key) < 5 || substr($key, 0, 4) != 'set_') {
                    continue;
                }
                $fieldName = str_replace('set_', '', $key);
                $setterName = 'set' . ucfirst($fieldName);
                if (!method_exists($entity, $setterName)) {
                    continue;
                }
                $entity[$fieldName] = $value;
            }
        }

        if (null === $entity) {
            $this->request->getSession()->getFlashBag()->add('error', $this->__('No such item found.'));

            return new RedirectResponse($this->getRedirectUrl(['commandName' => 'cancel']), 302);
        }

        // save entity reference for later reuse
        $this->entityRef = $entity;

        if (true === $this->hasTranslatableFields) {
            $this->initTranslationsForEditing();
        }

        $this->initRelationPresets();

        $actions = $this->workflowHelper->getActionsForObject($entity);
        if (false === $actions || !is_array($actions)) {
            $this->request->getSession()->getFlashBag()->add('error', $this->__('Error! Could not determine workflow actions.'));
            $logArgs = ['app' => 'RKHelperModule', 'user' => $this->currentUserApi->get('uname'), 'entity' => $this->objectType, 'id' => $entity->getKey()];
            $this->logger->error('{app}: User {user} tried to edit the {entity} with id {id}, but failed to determine available workflow actions.', $logArgs);
            throw new \RuntimeException($this->__('Error! Could not determine workflow actions.'));
        }

        $this->templateParameters['actions'] = $actions;

        $this->form = $this->createForm();
        if (!is_object($this->form)) {
            return false;
        }

        if ($entity->supportsHookSubscribers()) {
            // Call form aware display hooks
            $formHook = $this->hookHelper->callFormDisplayHooks($this->form, $entity, FormAwareCategory::TYPE_EDIT);
            $this->templateParameters['formHookTemplates'] = $formHook->getTemplates();
        }

        // handle form request and check validity constraints of edited entity
        if ($this->form->handleRequest($this->request) && $this->form->isSubmitted()) {
            if ($this->form->isValid()) {
                $result = $this->handleCommand();
                if (false === $result) {
                    $this->templateParameters['form'] = $this->form->createView();
                }

                return $result;
            }
            if ($this->form->get('cancel')->isClicked()) {
                return new RedirectResponse($this->getRedirectUrl(['commandName' => 'cancel']), 302);
            }
        }

        $this->templateParameters['form'] = $this->form->createView();

        // everything okay, no initialisation errors occured
        return true;
    }

    /**
     * Creates the form type.
     */
    protected function createForm()
    {
        // to be customised in sub classes
        return null;
    }

    /**
     * Initialises relationship presets.
     */
    protected function initRelationPresets()
    {
        // to be customised in sub classes
    }

    /**
     * Returns the template parameters.
     *
     * @return array
     */
    public function getTemplateParameters()
    {
        return $this->templateParameters;
    }

    /**
     * Initialise existing entity for editing.
     *
     * @return EntityAccess|null Desired entity instance or null
     */
    protected function initEntityForEditing()
    {
        return $this->entityFactory->getRepository($this->objectType)->selectById($this->idValue);
    }

    /**
     * Initialise new entity for creation.
     *
     * @return EntityAccess|null Desired entity instance or null
     */
    protected function initEntityForCreation()
    {
        $templateId = $this->request->query->getInt('astemplate', '');
        $entity = null;

        if (!empty($templateId)) {
            // reuse existing entity
            $entityT = $this->entityFactory->getRepository($this->objectType)->selectById($templateId);
            if (null === $entityT) {
                return null;
            }
            $entity = clone $entityT;
        }

        if (null === $entity) {
            $createMethod = 'create' . ucfirst($this->objectType);
            $entity = $this->entityFactory->$createMethod();
        }

        return $entity;
    }

    /**
     * Initialise translations.
     */
    protected function initTranslationsForEditing()
    {
        $translationsEnabled = $this->featureActivationHelper->isEnabled(FeatureActivationHelper::TRANSLATIONS, $this->objectType);
        $this->templateParameters['translationsEnabled'] = $translationsEnabled;

        $supportedLanguages = $this->translatableHelper->getSupportedLanguages($this->objectType);
        // assign list of installed languages for translatable extension
        $this->templateParameters['supportedLanguages'] = $supportedLanguages;

        if (!$translationsEnabled) {
            return;
        }

        if ($this->variableApi->getSystemVar('multilingual') != 1) {
            $this->templateParameters['translationsEnabled'] = false;

            return;
        }
        if (count($supportedLanguages) < 2) {
            $this->templateParameters['translationsEnabled'] = false;

            return;
        }

        $mandatoryFieldsPerLocale = $this->translatableHelper->getMandatoryFields($this->objectType);
        $localesWithMandatoryFields = [];
        foreach ($mandatoryFieldsPerLocale as $locale => $fields) {
            if (count($fields) > 0) {
                $localesWithMandatoryFields[] = $locale;
            }
        }
        if (!in_array($this->translatableHelper->getCurrentLanguage(), $localesWithMandatoryFields)) {
            $localesWithMandatoryFields[] = $this->translatableHelper->getCurrentLanguage();
        }
        $this->templateParameters['localesWithMandatoryFields'] = $localesWithMandatoryFields;

        // retrieve and assign translated fields
        $translations = $this->translatableHelper->prepareEntityForEditing($this->entityRef);
        foreach ($translations as $language => $translationData) {
            $this->templateParameters[$this->objectTypeLower . $language] = $translationData;
        }
    }

    /**
     * Get list of allowed redirect codes.
     *
     * @return string[] list of possible redirect codes
     */
    protected function getRedirectCodes()
    {
        $codes = [];

        // to be filled by subclasses

        return $codes;
    }

    /**
     * Command event handler.
     *
     * @param array $args List of arguments
     *
     * @return mixed Redirect or false on errors
     */
    public function handleCommand(array $args = [])
    {
        // build $args for BC (e.g. used by redirect handling)
        foreach ($this->templateParameters['actions'] as $action) {
            if ($this->form->get($action['id'])->isClicked()) {
                $args['commandName'] = $action['id'];
            }
        }
        if ($this->templateParameters['mode'] == 'create' && $this->form->get('submitrepeat')->isClicked()) {
            $args['commandName'] = 'submit';
            $this->repeatCreateAction = true;
        }
        if ($this->form->get('cancel')->isClicked()) {
            $args['commandName'] = 'cancel';
        }

        $action = $args['commandName'];
        $isRegularAction = !in_array($action, ['delete', 'cancel']);

        if ($isRegularAction || $action == 'delete') {
            $this->fetchInputData();
        }

        // get treated entity reference from persisted member var
        $entity = $this->entityRef;

        if ($entity->supportsHookSubscribers() && $action != 'cancel') {
            // Let any ui hooks perform additional validation actions
            $hookType = $action == 'delete' ? UiHooksCategory::TYPE_VALIDATE_DELETE : UiHooksCategory::TYPE_VALIDATE_EDIT;
            $validationErrors = $this->hookHelper->callValidationHooks($entity, $hookType);
            if (count($validationErrors) > 0) {
                $flashBag = $this->request->getSession()->getFlashBag();
                foreach ($validationErrors as $message) {
                    $flashBag->add('error', $message);
                }

                return false;
            }
        }

        if ($isRegularAction || $action == 'delete') {
            $success = $this->applyAction($args);
            if (!$success) {
                // the workflow operation failed
                return false;
            }

            if ($isRegularAction && true === $this->hasTranslatableFields) {
                if ($this->featureActivationHelper->isEnabled(FeatureActivationHelper::TRANSLATIONS, $this->objectType)) {
                    $this->processTranslationsForUpdate();
                }
            }

            if ($entity->supportsHookSubscribers()) {
                $routeUrl = null;
                if ($action != 'delete') {
                    $urlArgs = $entity->createUrlArgs();
                    $urlArgs['_locale'] = $this->request->getLocale();
                    $routeUrl = new RouteUrl('rkhelpermodule_' . $this->objectTypeLower . '_display', $urlArgs);
                }

                // Call form aware processing hooks
                $hookType = $action == 'delete' ? FormAwareCategory::TYPE_PROCESS_DELETE : FormAwareCategory::TYPE_PROCESS_EDIT;
                $this->hookHelper->callFormProcessHooks($this->form, $entity, $hookType, $routeUrl);

                // Let any ui hooks know that we have created, updated or deleted an item
                $hookType = $action == 'delete' ? UiHooksCategory::TYPE_PROCESS_DELETE : UiHooksCategory::TYPE_PROCESS_EDIT;
                $this->hookHelper->callProcessHooks($entity, $hookType, $routeUrl);
            }
        }

        if (true === $this->hasPageLockSupport && $this->templateParameters['mode'] == 'edit' && $this->kernel->isBundle('ZikulaPageLockModule') && null !== $this->lockingApi) {
            $lockName = 'RKHelperModule' . $this->objectTypeCapital . $entity->getKey();
            $this->lockingApi->releaseLock($lockName);
        }

        return new RedirectResponse($this->getRedirectUrl($args), 302);
    }

    /**
     * Prepare update of translations.
     */
    protected function processTranslationsForUpdate()
    {
        if (!$this->templateParameters['translationsEnabled']) {
            return;
        }

        // persist translated fields
        $this->translatableHelper->processEntityAfterEditing($this->entityRef, $this->form, $this->entityFactory->getObjectManager());
    }

    /**
     * Get success or error message for default operations.
     *
     * @param array   $args    arguments from handleCommand method
     * @param Boolean $success true if this is a success, false for default error
     *
     * @return String desired status or error message
     */
    protected function getDefaultMessage(array $args = [], $success = false)
    {
        $message = '';
        switch ($args['commandName']) {
            case 'create':
                if (true === $success) {
                    $message = $this->__('Done! Item created.');
                } else {
                    $message = $this->__('Error! Creation attempt failed.');
                }
                break;
            case 'update':
                if (true === $success) {
                    $message = $this->__('Done! Item updated.');
                } else {
                    $message = $this->__('Error! Update attempt failed.');
                }
                break;
            case 'delete':
                if (true === $success) {
                    $message = $this->__('Done! Item deleted.');
                } else {
                    $message = $this->__('Error! Deletion attempt failed.');
                }
                break;
        }

        return $message;
    }

    /**
     * Add success or error message to session.
     *
     * @param array   $args    arguments from handleCommand method
     * @param Boolean $success true if this is a success, false for default error
     *
     * @throws RuntimeException Thrown if executing the workflow action fails
     */
    protected function addDefaultMessage(array $args = [], $success = false)
    {
        $message = $this->getDefaultMessage($args, $success);
        if (empty($message)) {
            return;
        }

        $flashType = true === $success ? 'status' : 'error';
        $this->request->getSession()->getFlashBag()->add($flashType, $message);
        $logArgs = ['app' => 'RKHelperModule', 'user' => $this->currentUserApi->get('uname'), 'entity' => $this->objectType, 'id' => $this->entityRef->getKey()];
        if (true === $success) {
            $this->logger->notice('{app}: User {user} updated the {entity} with id {id}.', $logArgs);
        } else {
            $this->logger->error('{app}: User {user} tried to update the {entity} with id {id}, but failed.', $logArgs);
        }
    }

    /**
     * Input data processing called by handleCommand method.
     */
    public function fetchInputData()
    {
        // fetch posted data input values as an associative array
        $formData = $this->form->getData();

        if (method_exists($this->entityRef, 'getCreatedBy')) {
            if (isset($this->form['moderationSpecificCreator']) && null !== $this->form['moderationSpecificCreator']->getData()) {
                $this->entityRef->setCreatedBy($this->form['moderationSpecificCreator']->getData());
            }
            if (isset($this->form['moderationSpecificCreationDate']) && $this->form['moderationSpecificCreationDate']->getData() != '') {
                $this->entityRef->setCreatedDate($this->form['moderationSpecificCreationDate']->getData());
            }
        }

        // return remaining form data
        return $formData;
    }

    /**
     * This method executes a certain workflow action.
     *
     * @param array $args Arguments from handleCommand method
     *
     * @return bool Whether everything worked well or not
     */
    public function applyAction(array $args = [])
    {
        // stub for subclasses
        return false;
    }

    /**
     * Sets optional locking api reference.
     *
     * @param LockingApiInterface $lockingApi
     */
    public function setLockingApi(LockingApiInterface $lockingApi)
    {
        $this->lockingApi = $lockingApi;
    }
}


text:
var auth = require('./auth');

module.exports = function TokenCache() {

	var self = this;
	this._cache = {};

	TokenCache.prototype.get = function (options, callback) {

		var key = options.email + ':' + options.scopes.join(',');

		if (!self._cache[key]) {
			self._cache[key] = new TokenRequest(options);
		}

		self._cache[key].get(callback);

	};

	TokenCache.prototype.clear = function () {
		self._cache = {};
	};

};

function TokenRequest(options) {

	var self = this;
	this.status = 'expired';
	this.pendingCallbacks = [];

	this.get = function (callback) {

		if (this.status == 'expired') {

			this.status = 'pending';
			this.pendingCallbacks.push(callback);

			auth.authenticate(options, function (err, token) {

				if (err) return fireCallbacks(err, null);

				self.issued = new Date().getTime();
				self.duration = options.expiration || 60 * 60 * 1000;
				self.token = token;
				self.status = 'completed';
				return fireCallbacks(null, token);

			});

		} else if (this.status == 'pending') {
			this.pendingCallbacks.push(callback);
		} else if (this.status == 'completed') {

			if (this.issued + this.duration > new Date().getTime()) {
				this.status = 'expired';
				this.get(callback);
			} else {
				callback(null, this.token);
			}

		}
	};

	function fireCallbacks(err, token) {
		self.pendingCallbacks.forEach(function (callback) {
			callback(err, token);
		});
		self.pendingCallbacks = [];
	}
}


text:
#include <aws/ec2/model/PermissionGroup.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EC2
  {
    namespace Model
    {
      namespace PermissionGroupMapper
      {

        static const int all_HASH = HashingUtils::HashString("all");

        PermissionGroup GetPermissionGroupForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == all_HASH)
          {
            return PermissionGroup::all;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<PermissionGroup>(hashCode);
          }

          return PermissionGroup::NOT_SET;
        }

        Aws::String GetNameForPermissionGroup(PermissionGroup enumValue)
        {
          switch(enumValue)
          {
          case PermissionGroup::all:
            return "all";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace PermissionGroupMapper
    } // namespace Model
  } // namespace EC2
} // namespace Aws


text:
define([
    "geometria/GAnswerUtils",
    "geometria/GDictionary",
    "geometria/GFace",
    "geometria/GFiguresContainer",
    "geometria/GMath",
    "geometria/GNotepadContainer",
    "geometria/GPoint",
    "geometria/GUtils"
], function(answerUtils, dict, GFace, figuresContainer, math, notepadContainer, GPoint, utils) {

    var containsPoint = {
        id: "ContainsPoint",
        group: "Position",
        placeHolder: dict.get("EnterPoint"),
        invalidMessage: dict.get("EnterPoint"),
        validate: answerUtils.validatePoint,
        stringValueFromSelection: answerUtils.pointFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p = valuePs[0];
            var n = math.cross(ps[0], ps[1], ps[2]);
            return math.isInPlane(p, ps[0], n);
        }
    };

    var containsLine = {
        id: "ContainsLine",
        group: "Position",
        placeHolder: dict.get("Enter2Points"),
        invalidMessage: dict.get("Enter2CommaSeparatedPoints"),
        validate: answerUtils.validateLine,
        stringValueFromSelection: answerUtils.lineFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p1 = valuePs[0];
            var p2 = valuePs[1];
            var n = math.cross(ps[0], ps[1], ps[2]);
            return math.isInPlane(p1, ps[0], n) && math.isInPlane(p2, ps[0], n);
        }
    };

    var doesNotContainPoint = {
        id: "DoesNotContainPoint",
        group: "Position",
        placeHolder: dict.get("EnterPoint"),
        invalidMessage: dict.get("EnterPoint"),
        validate: answerUtils.validatePoint,
        stringValueFromSelection: answerUtils.pointFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p = valuePs[0];
            var n = math.cross(ps[0], ps[1], ps[2]);
            return !math.isInPlane(p, ps[0], n);
        }
    };

    var doesNotContainLine = {
        id: "DoesNotContainLine",
        group: "Position",
        placeHolder: dict.get("Enter2Points"),
        invalidMessage: dict.get("Enter2CommaSeparatedPoints"),
        validate: answerUtils.validateLine,
        stringValueFromSelection: answerUtils.lineFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p1 = valuePs[0];
            var p2 = valuePs[1];
            var n = math.cross(ps[0], ps[1], ps[2]);
            return !math.isInPlane(p1, ps[0], n) || !math.isInPlane(p2, ps[0], n);
        }
    };

    var containsNoVertex = {
        id: "ContainsNoVertex",
        group: "Position",
        verify: function(ps, targetSolid) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var valid = true;
            $.each(targetSolid.points, function(label, p) {
                if (p.isVertex && math.isInPlane(p.crds, ps[0], n)) {
                    valid = false;
                    return false;
                }
            });
            return valid;
        }
    };

    var containsNoEdge = {
        id: "ContainsNoEdge",
        group: "Position",
        verify: function(ps, targetSolid) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var valid = true;
            $.each(targetSolid.faces, function() {
                for (var lineIndex = 0; lineIndex < this.sideCount; lineIndex++) {
                    var line = this.lines[lineIndex];
                    var p1 = targetSolid.points[line.firstLabel()].crds;
                    var p2 = targetSolid.points[line.lastLabel()].crds;
                    if (math.isInPlane(p1, ps[0], n) && math.isInPlane(p2, ps[0], n)) {
                        valid = false;
                        return false;
                    }
                }
            });
            return valid;
        }
    };

    var parallelToLine = {
        id: "ParallelToLine",
        group: "Position",
        placeHolder: dict.get("Enter2Points"),
        invalidMessage: dict.get("Enter2CommaSeparatedPoints"),
        validate: answerUtils.validateLine,
        stringValueFromSelection: answerUtils.lineFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p1 = valuePs[0];
            var p2 = valuePs[1];
            var v = vec3.sub([], p2, p1);
            vec3.normalize(v, v);
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            return Math.abs(vec3.dot(v, n)) < math.EPSILON;
        }
    };

    var parallelToPlane = {
        id: "ParallelToPlane",
        group: "Position",
        placeHolder: dict.get("Enter3Points"),
        invalidMessage: dict.get("Enter3NonCollinearCommaSeparatedPoints"),
        validate: answerUtils.validatePlane,
        stringValueFromSelection: answerUtils.planeFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p1 = valuePs[0];
            var p2 = valuePs[1];
            var p3 = valuePs[2];
            var v = math.cross(p1, p2, p3)
            vec3.normalize(v, v);
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            return Math.abs(Math.abs(vec3.dot(v, n)) - 1) < math.EPSILON;
        }
    };

    var perpendicularToLine = {
        id: "PerpendicularToLine",
        group: "Position",
        placeHolder: dict.get("Enter2Points"),
        invalidMessage: dict.get("Enter2CommaSeparatedPoints"),
        validate: answerUtils.validateLine,
        stringValueFromSelection: answerUtils.lineFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p1 = valuePs[0];
            var p2 = valuePs[1];
            var v = vec3.sub([], p2, p1);
            vec3.normalize(v, v);
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            return Math.abs(Math.abs(vec3.dot(v, n)) - 1) < math.EPSILON;
        }
    };

    var perpendicularToPlane = {
        id: "PerpendicularToPlane",
        group: "Position",
        placeHolder: dict.get("Enter3Points"),
        invalidMessage: dict.get("Enter3NonCollinearCommaSeparatedPoints"),
        validate: answerUtils.validatePlane,
        stringValueFromSelection: answerUtils.planeFromSelection,
        verify: function(ps, targetSolid, value) {
            var valuePs = answerUtils.pointSetStringToCrds(value);
            var p1 = valuePs[0];
            var p2 = valuePs[1];
            var p3 = valuePs[2];
            var v = math.cross(p1, p2, p3)
            vec3.normalize(v, v);
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            return Math.abs(vec3.dot(v, n)) < math.EPSILON;
        }
    };

    var cutsVolumeInRatio = {
        id: "CutsVolumeInRatio",
        group: "Volume",
        placeHolder: dict.get("EnterRatio"),
        invalidMessage: dict.get("EnterPositiveExpression"),
        validate: function(props) {
            var outProps = { value: [null, null] };
            var scope = notepadContainer.getScope();
            var numerator = utils.eval(props.value[0], scope);
            var denominator = utils.eval(props.value[1], scope);
            if (numerator > 0) {
                outProps.value[0] = numerator.toString();
            }
            if (denominator > 0) {
                outProps.value[1] = denominator.toString();
            }
            return outProps;
        },
        verify: function(ps, targetSolid, value) {
            var ratio = utils.eval(value[0])/utils.eval(value[1]);
            var denominator = value[1];
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            if (!fragment.cutOff(ps[0], n)) {
                return false;
            }
            var v = fragment.computeVolume();
            var r = v / (targetSolid.computeVolume() - v);
            return Math.abs(r - ratio) < math.EPSILON || Math.abs(1 / r - ratio) < math.EPSILON;
        }
    };

    var isoscellesTriangle = {
        id: "IsoscellesTriangle",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isIsoscellesTriangle(fragment);
        }
    };

    var rightTriangle = {
        id: "RightTriangle",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isRightTriangle(fragment);
        }
    };

    var equilateralTriangle = {
        id: "EquilateralTriangle",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isEquilateralTriangle(fragment);
        }
    };

    var parallelogram = {
        id: "Parallelogram",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isParallelogram(fragment);
        }
    };

    var rhombus = {
        id: "Rhombus",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isRhombus(fragment);
        }
    };

    var rectangle = {
        id: "Rectangle",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isRectangle(fragment);
        }
    };

    var square = {
        id: "Square",
        group: "Shape",
        verify: function(ps, targetSolid, value) {
            var n = math.cross(ps[0], ps[1], ps[2]);
            vec3.normalize(n, n);
            var fragment = targetSolid.clone();
            var section = fragment.cutOff(ps[0], n);
            if (!section) {
                return false;
            }
            return section.isSquare(fragment);
        }
    };

    var conditions = {};
    $.each([
        containsPoint,
        containsLine,
        doesNotContainPoint,
        doesNotContainLine,
        containsNoVertex,
        containsNoEdge,
        parallelToLine,
        parallelToPlane,
        perpendicularToLine,
        perpendicularToPlane,
        cutsVolumeInRatio,
        isoscellesTriangle,
        rightTriangle,
        equilateralTriangle,
        parallelogram,
        rhombus,
        rectangle,
        square], function() {
            conditions[this.id] = this;
    });

    return conditions;
});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.can.CANTimeoutException;

/**
 *
 * @author David
 */
public class JagPair implements PIDOutput {

    CANJaguar jag1, jag2;
    public JagPair( int jag1In, int jag2In) {
        try{
            jag1 = new CANJaguar(jag1In);
            jag2 = new CANJaguar(jag2In);
        }catch(CANTimeoutException ex) {
            System.out.println("CAN issue");
        }
    }
    public void pidWrite(double output) {
        jag1.pidWrite(output);
        jag2.pidWrite(output);

    }

}


text:
package org.ovirt.engine.core.dao.network;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.ovirt.engine.core.common.businessentities.network.NetworkQoS;
import org.ovirt.engine.core.common.businessentities.qos.QosType;
import org.ovirt.engine.core.dao.qos.QosBaseDaoFacadeImpl;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;

public class NetworkQoSDaoFacadeImpl extends QosBaseDaoFacadeImpl<NetworkQoS> implements NetworkQoSDao {

    protected final RowMapper<NetworkQoS> mapper = createEntityRowMapper();

    public NetworkQoSDaoFacadeImpl(){
        super(QosType.NETWORK);
    }

    @Override
    protected MapSqlParameterSource createFullParametersMapper(NetworkQoS networkQos) {
        MapSqlParameterSource map = super.createFullParametersMapper(networkQos);
        map.addValue("inbound_average", networkQos.getInboundAverage());
        map.addValue("inbound_peak", networkQos.getInboundPeak());
        map.addValue("inbound_burst", networkQos.getInboundBurst());
        map.addValue("outbound_average", networkQos.getOutboundAverage());
        map.addValue("outbound_peak", networkQos.getOutboundPeak());
        map.addValue("outbound_burst", networkQos.getOutboundBurst());
        return map;
    }

    @Override
    protected RowMapper<NetworkQoS> createEntityRowMapper() {
        return NetworkQosDaoDbFacadaeImplMapper.MAPPER;
    }

    public static class NetworkQosDaoDbFacadaeImplMapper extends QosBaseDaoFacadaeImplMapper<NetworkQoS> {
        public static final NetworkQosDaoDbFacadaeImplMapper MAPPER = new NetworkQosDaoDbFacadaeImplMapper();

        @Override
        public NetworkQoS createQosEntity(ResultSet rs) throws SQLException {
            NetworkQoS entity = new NetworkQoS();
            entity.setInboundAverage(getInteger(rs, "inbound_average"));
            entity.setInboundPeak(getInteger(rs, "inbound_peak"));
            entity.setInboundBurst(getInteger(rs, "inbound_burst"));
            entity.setOutboundAverage(getInteger(rs, "outbound_average"));
            entity.setOutboundPeak(getInteger(rs, "outbound_peak"));
            entity.setOutboundBurst(getInteger(rs, "outbound_burst"));
            return entity;
        }
    }
}


text:
title: "Type-level unit testing in Haskell"
date: 2018-03-21T00:00:00-04:00
draft: false
tags:
- haskell
- type-level
- testing
---

> **Update 4/9/2022**: I created the library described in this post to
> learn the basics of type-level Haskell hacking. Reflecting on this
> post, the main thing the library provides is user-defined labels on
> tests. If you don't need these labels and/or are happy with GHC's
> built-in error messages, the built-in `(~)` can get you very far!

This post will assume some familiarity with type-level programming in
Haskell. I recommend this [blog post][] as an introduction to type-level
Haskell. Understanding the entirety of that post is not required to
continue reading this one, but I do recommend being slightly comfortable
with closed type families, data kinds, and type-level natural numbers.

## `tao`

The [`tao`][] package was released this week and we can use it do a sort
of type-level "unit testing". The package gives us type-level assertion
operators/functions. Here, we are using [Nats][] and asserting that `3`
is, in fact, `1 + 2`:

```haskell
unitTest :: Proxy '()
unitTest = Proxy :: Proxy (AssertEq "3 = 1 + 2" 3 (1 + 2))
```

`AssertEq` is a closed type family that takes three things:

* a message that is used on assertion failure
* the expected type
* the actual type

If the expected type and actual type are equal, the test passes and our
code compiles!  Otherwise, the code will not compile. We will see what
the use of [`Proxy`][] is all about, as well as why the proxy wraps the
promoted unit type later in this post.

This example could be written equivalently using [HUnit][]-inspired
operators:

```haskell
unitTest :: Proxy '()
unitTest = Proxy :: Proxy ("3 = 1 + 2" @<> 3 @=? 1 + 2)
```

In this post though, we will temporarily pretend the [`tao`][] package
does not exist. Instead, we will implement the core portion of `tao`
ourselves! Afterwards, we will get a feel for how to work with the
package like we have in the examples above.

## Type equality

A core usage of `tao` is asserting that types are equal using `AssertEq`
or the `(@=?)` operator version. The [base][] package conveniently
provides the [`(==)`][] type function in the `Data.Type.Equality`
module.

Let's play around with type-level equality! The `(==)` type function is
declared like this:

```haskell
type family (a :: k) == (b :: k) :: Bool
```

This means we can give the type function two types and the result will
be of kind `Bool`, so let's get to it. We can load the following script
directly into `GHCi` via `stack <script_name>.hs`:

```haskell
#!/usr/bin/env stack
-- stack --resolver lts-11.0 --install-ghc exec ghci

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}

import Data.Type.Equality (type (==))

type LooksEqual = Int == Int
type LooksNotEqual = Int == Bool
```

We will ask `GHCi` what the kinds of these two type synonyms are:

```text
ghci> :kind LooksEqual
LooksEqual :: Bool
ghci> :kind LooksNotEqual
LooksNotEqual :: Bool
```

This jives with the `(==)` type family declaration we saw above.  Both type
synonyms are of kind `Bool`.  Now we can ask GHCi to evaluate the types (using
`kind!` instead of `kind`):

```text
ghci> :kind! LooksEqual
LooksEqual :: Bool
= 'True
ghci> :kind! LooksNotEqual
LooksNotEqual :: Bool
= 'False
```

We are not stuck giving types of kind `*` (like `Bool`, `Char`, `(Int ->
String)`, etc.) to `(==)` though. We can throw `Nat`s, `Symbol`s, and
more at it!

```haskell
#!/usr/bin/env stack
-- stack --resolver lts-11.0 --install-ghc exec ghci

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}

import Data.Type.Equality (type (==))
import GHC.TypeNats (type (*))

type LooksEqual = 81 == 9 * 9
type LooksNotEqual = "haskell" == "Haskell"
```

Let's do our type evaluation again:

```text
ghci> :kind! LooksEqual
LooksEqual :: Bool
= 'True
ghci> :kind! LooksNotEqual
LooksNotEqual :: Bool
= 'False
```

## Implementing `AssertEq`

Now that we are familiar with the handy `(==)` type function, we can
offload the labor for asserting type equality to it as we implement
`AssertEq`:

```haskell
#!/usr/bin/env stack
-- stack --resolver lts-11.0 --install-ghc exec ghci

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Type.Equality (type (==))
import GHC.TypeLits (Symbol)

type family AssertEq (msg :: Symbol) (expected :: k) (actual :: k) :: () where
  AssertEq m e a = AssertEq' m e a (e == a)
```

Here we have created a type function called `AssertEq` that takes in a
`Symbol` (type-level string literal), an expected type, and an actual
type. The result type is of kind `()`. The implementation of our type
function passes its input parameters as well as the `(e == a)` equality
result type over to a yet-to-be-defined type function, `AssertEq'`. The
intent will be that users call `AssertEq` and `AssertEq'` is an
implementation detail.

Now we can define `AssertEq'`:

```haskell
#!/usr/bin/env stack
-- stack --resolver lts-11.0 --install-ghc exec ghci

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Type.Equality (type (==))
import GHC.TypeLits (Symbol)

type family AssertEq (msg :: Symbol) (expected :: k) (actual :: k) :: () where
  AssertEq m e a = AssertEq' m e a (e == a)

type family AssertEq' (msg :: Symbol) (expected :: k) (actual :: k) (result :: Bool) :: () where
  AssertEq' _ _ _ 'True  = '()
  AssertEq' m e a 'False = -- hmmm.....
```

From `AssertEq`, we are passing the result type of kind `Bool` from
the type equality check into the the `result` slot of `AssertEq'`. In
`AssertEq'`, we have "pattern matched" on the two possible types of kind
`Bool` - `'True` and `'False`.  On `'True`, this means the expected and
actual types are equal and we return promoted unit - the assertion has
passed!

The `'False` case is a bit trickier. When the types are not equal, we
want the assertion to fail at compile time. Fortunately, GHC provides
us with something that will perfectly suit our needs: user-defined
type errors via [`TypeError`][]! `TypeError` is implemented as a type
function and its declaration looks like this:

```haskell
type family TypeError (a :: ErrorMessage) :: b where
```

Think of this function sort of like type-level `undefined`. Hitting
`undefined` at runtime makes our program throw a nasty exception.
Hitting a `TypeError` at compile time causes GHC to stop doing its thing
and report the type error.

The input type we can pass to `TypeError` is of kind
[`ErrorMessage`][]. We can use the input type to build up a custom error
message when the expected and actual types are not equal in `AssertEq'`!

```haskell
#!/usr/bin/env stack
-- stack --resolver lts-11.0 --install-ghc exec ghci

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Type.Equality (type (==))
import GHC.TypeLits (ErrorMessage((:<>:), ShowType, Text), Symbol, type TypeError)

type family AssertEq (msg :: Symbol) (expected :: k) (actual :: k) :: () where
  AssertEq m e a = AssertEq' m e a (e == a)

type family AssertEq' (msg :: Symbol) (expected :: k) (actual :: k) (result :: Bool) :: () where
  AssertEq' _ _ _ 'True  = '()
  AssertEq' m e a 'False = TypeError ( 'Text m
                                 ':<>: 'Text ": expected ("
                                 ':<>: 'ShowType e
                                 ':<>: 'Text "), actual ("
                                 ':<>: 'ShowType a
                                 ':<>: 'Text ")"
                                     )
```

All of the new bits we are using here - `'Text`, `'ShowType`, and
`':<>:` - are the promoted constructors from `ErrorMessage`. We
create a `TypeError` that reports the user-supplied assertion failure
message as well as the expected and actual types (as pretty printed
by `'ShowType`).  The `':<>:` operator smooshes together pieces of
`ErrorMessage` on the same line.

## Using AssertEq

Let's put our new type function to work!

```haskell
type MustBeEqual = AssertEq "True is True" 'True 'True
```

Reloading this in GHCi gives us no errors.  Let's do the kind check:

```text
ghci> :kind! MustBeEqual
MustBeEqual :: ()
```

The types are in fact equal, so `AssertEq` has returned `'()`! Now we
will introduce a mismatching type:

```haskell
type MustBeEqual = AssertEq "True is False?" 'True 'False
```

Reloading this in GHCi does not give us any errors. This may be
surprising but just introducing the type synonym will not evaluate the
type! Let's do the kind check again:

```text
ghci> :kind! MustBeEqual
MustBeEqual :: ()
= (TypeError ...)
```

Hmm... two undesirable things have happened:

1. `GHCi` does not show our custom type error message
2. The assertion did not fail at compile time (reloading in `GHCi`)

We can address both of these problems by using a `Proxy` instead:

```haskell
import Data.Proxy (Proxy(Proxy))

-- ...

unitTest :: Proxy '()
unitTest = Proxy :: Proxy (AssertEq "True is False?" 'True 'False)
```

`unitTest`'s type is a proxy containing promoted unit. In the body of
the function, we have annotated the `Proxy` value we are constructing
using `AssertEq`, and `AssertEq` produces the promoted unit type. By
using a binding like this, we are telling GHC that the type of the proxy
value we are constructing should evaluate to the `Proxy '()` type we
have annotated the whole binding with.  GHC will then be forced to get
evaluation-happy and see if we are telling the truth!

We will reload in `GHCi` again:

```text
<script_name>.hs:28:12: error:
    • True is False?: expected ('True), actual ('False)
    • In the expression:
          Proxy :: Proxy (AssertEq "True is False?"  'True  'False)
      In an equation for 'unitTest':
          unitTest
            = Proxy :: Proxy (AssertEq "True is False?"  'True  'False)
   |
28 | unitTest = Proxy :: Proxy (AssertEq "True is False?" 'True 'False)
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
```

Much better! Now we see our custom-built type error message, and
it tells us what the expected/actual types are.  Woohoo - we have
implemented the backbone of `tao`! From this point on, we will use the
`tao` package directly.

## Infix assertion operators

`AssertEq` is the core type function in `tao`. The package also provides
infix variants of `AssertEq` via `(@=?)` when the expected type is
on the left and `(@?=)` when the expected type is on the right. They
offload the work straight to `AssertEq`, so we will not implement them
in this post.  Assertion messages can be attached via `@<>` or `<>@`.

```haskell
unitTestInfix :: Proxy '()
unitTestInfix = Proxy :: Proxy ("True is False?" @<> 'True @=? 'False)

unitTestInfix' :: Proxy '()
unitTestInfix' = Proxy :: Proxy ('False @?= 'True <>@ "True is False?")
```

We will use the infix versions from here on out.

## Improving usability

It is often the case that we do not just have a single unit test.  Our
examples so far have been of the form:

```haskell
unitTest :: Proxy '()
unitTest = -- stuff...
```

What if we have a couple tests? We could make multiple proxies:

```haskell

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}

import Data.Proxy (Proxy(Proxy))
import GHC.TypeNats (type (+), type (*))
import Tao

testAddingNats :: Proxy '()
testAddingNats = Proxy :: Proxy ("3 = 1 + 2" @<> 3 @=? 1 + 2)

testMultiplyingNats :: Proxy '()
testMultiplyingNats = Proxy :: Proxy ("3 = 1 * 3" @<> 3 @=? 1 * 3)
```

This works, but it is fairly heavy-handed. It would be nice to instead
just stuff all of our assertions in a type-level list.  A first attempt
might look like this:

```haskell
unitTests :: Proxy '[ '(), '() ]
unitTests = Proxy :: Proxy
  '["3 = 1 + 2" @<> 3 @=? 1 + 2
   ,"3 = 1 * 3" @<> 3 @=? 1 * 3
   ]
```

This is an improvement, but now we have to add a promoted unit to the
type-level list in `unitTests`'s type signature every time we add an
assertion.

A helper called `AssertAll` is provided for this case:

```haskell
unitTests :: Proxy '()
unitTests = Proxy :: Proxy (AssertAll
  '["3 = 1 + 2" @<> 3 @=? 1 + 2
   ,"3 = 1 * 3" @<> 3 @=? 1 * 3
   ])
```

`AssertAll` will squash down all the result units from assertions into
a single unit. This way, we can keep on adding assertions and never
have to fuss with `unitTests`'s type signature along the way. We can
implement `AssertAll` like this:

```haskell
type family AssertAll (xs :: [()]) :: () where
  AssertAll '[] = '()
  AssertAll ('() ': xs) = AssertAll xs
```

Here we have "pattern matched" on the promoted `'[]` and `':`
constructors to traverse the type-level list, ensuring that every value
is of type `'()`.

## Wrap up

Besides what has been shown in this post, `tao` also provides an
`AssertBool` type function (plus operators) for asserting on boolean
conditions. If anyone wants to get their feet wet with type-level
Haskell, I recommend taking a crack at `AssertBool` now that we have
learned how `AssertEq` works.

For more examples, there is a [`tao-example`][] package which
demonstrates testing a few more complicated type functions than the
type-level natural numbers examples shown here.

There is an interesting property when doing type-level "unit testing":
our tests run every time we build the library!

[blog post]: http://www.parsonsmatt.org/2017/04/26/basic_type_level_programming_in_haskell.html
[`tao`]: https://hackage.haskell.org/package/tao
[Nats]: https://www.stackage.org/haddock/lts-11.0/base-4.10.1.0/GHC-TypeNats.html#t:Nat
[`Proxy`]: https://www.stackage.org/haddock/lts-11.0/base-4.10.1.0/Data-Proxy.html#t:Proxy
[HUnit]: https://www.stackage.org/lts-11.0/package/HUnit-1.6.0.0
[base]: https://www.stackage.org/lts-11.0/package/base-4.10.1.0
[`(==)`]: https://www.stackage.org/haddock/lts-11.0/base-4.10.1.0/Data-Type-Equality.html#t:-61--61-
[`TypeError`]: https://www.stackage.org/haddock/lts-11.0/base-4.10.1.0/GHC-TypeLits.html#t:TypeError
[`ErrorMessage`]: https://www.stackage.org/haddock/lts-11.0/base-4.10.1.0/GHC-TypeLits.html#t:ErrorMessage
[`tao-example`]: https://hackage.haskell.org/package/tao-example-1.0.0/docs/Tao-Example.html


text:
def primes(limit):
    numbers = [True] * limit
    for i in range(2, limit):
        if not numbers[i]:
            continue
        for t in range(2 * i, limit, i):
            numbers[t] = False
    for i in range(2, limit):
        if numbers[i]:
            yield i

print sum(primes(2000000))