text:
export BrickletCO2V2AllValues
struct BrickletCO2V2AllValues
    co2_concentration::Integer
    temperature::Integer
    humidity::Integer
end

export BrickletCO2V2AllValuesCallbackConfiguration
struct BrickletCO2V2AllValuesCallbackConfiguration
    period::Integer
    value_has_to_change::Bool
end

export BrickletCO2V2CO2ConcentrationCallbackConfiguration
struct BrickletCO2V2CO2ConcentrationCallbackConfiguration
    period::Integer
    value_has_to_change::Bool
    option::Char
    min::Integer
    max::Integer
end

export BrickletCO2V2TemperatureCallbackConfiguration
struct BrickletCO2V2TemperatureCallbackConfiguration
    period::Integer
    value_has_to_change::Bool
    option::Char
    min::Integer
    max::Integer
end

export BrickletCO2V2HumidityCallbackConfiguration
struct BrickletCO2V2HumidityCallbackConfiguration
    period::Integer
    value_has_to_change::Bool
    option::Char
    min::Integer
    max::Integer
end

export BrickletCO2V2SPITFPErrorCount
struct BrickletCO2V2SPITFPErrorCount
    error_count_ack_checksum::Integer
    error_count_message_checksum::Integer
    error_count_frame::Integer
    error_count_overflow::Integer
end

export BrickletCO2V2Identity
struct BrickletCO2V2Identity
    uid::String
    connected_uid::String
    position::Char
    hardware_version::Vector{Integer}
    firmware_version::Vector{Integer}
    device_identifier::Integer
end

export BrickletCO2V2
"""
Measures CO2 concentration, temperature and humidity
"""
mutable struct BrickletCO2V2 <: TinkerforgeDevice
    ipcon::IPConnection
    deviceInternal::PyObject

    """
    Creates an object with the unique device ID *uid* and adds it to
    the IP Connection *ipcon*.
    """
    function BrickletCO2V2(uid::String, ipcon::IPConnection)
        package = pyimport("tinkerforge.bricklet_co2_v2")
        deviceInternal = package.BrickletCO2V2(uid, ipcon.ipconInternal)

        return new(ipcon, deviceInternal)
    end
end

export get_all_values
"""
    $(SIGNATURES)

Returns all values measured by the CO2 Bricklet 2.0.

If you want to get the values periodically, it is recommended to use the
:cb:`All Values` callback. You can set the callback configuration
with :func:`Set All Values Callback Configuration`.

.. note::
 The sensor is able to messure up to 120 °C. However it is only specified up to 70 °C.
 Exposing the Bricklet to higher temperatures might result in permanent damage.
"""
function get_all_values(device::BrickletCO2V2)
    return device.deviceInternal.get_all_values()
end

export set_air_pressure
"""
    $(SIGNATURES)

The CO2 concentration depends (among other things) on the ambient air pressure.

To increase the accuracy of the CO2 Bricklet 2.0 you can set the current air pressure.
You use the :ref:`Barometer Bricklet 2.0 <barometer_v2_bricklet>` or the
:ref:`Air Quality Bricklet <air_quality_bricklet>` to get the current air pressure.

By default air pressure compensation is disabled. Once you set a value it
will be used for compensation. You can turn the compensation off again by
setting the value to 0.

It is sufficient to update the value every few minutes.
"""
function set_air_pressure(device::BrickletCO2V2, air_pressure)
    device.deviceInternal.set_air_pressure(air_pressure)
end

export get_air_pressure
"""
    $(SIGNATURES)

Returns the ambient air pressure as set by :func:`Set Air Pressure`.
"""
function get_air_pressure(device::BrickletCO2V2)
    return device.deviceInternal.get_air_pressure()
end

export set_temperature_offset
"""
    $(SIGNATURES)

Sets a temperature offset. A offset of 10 will decrease
the measured temperature by 0.1 °C.

If you install this Bricklet into an enclosure and you want to measure the ambient
temperature, you may have to decrease the measured temperature by some value to
compensate for the error because of the heating inside of the enclosure.

We recommend that you leave the parts in the enclosure running for at least
24 hours such that a temperature equilibrium can be reached. After that you can measure
the temperature directly outside of enclosure and set the difference as offset.

This temperature offset is used to calculate the relative humidity and
CO2 concentration. In case the Bricklet is installed in an enclosure, we
recommend to measure and set the temperature offset to improve the accuracy of
the measurements.

It is sufficient to set the temperature offset once. The offset is saved in
non-volatile memory and is applied again after a power loss.
"""
function set_temperature_offset(device::BrickletCO2V2, offset)
    device.deviceInternal.set_temperature_offset(offset)
end

export get_temperature_offset
"""
    $(SIGNATURES)

Returns the temperature offset as set by
:func:`Set Temperature Offset`.
"""
function get_temperature_offset(device::BrickletCO2V2)
    return device.deviceInternal.get_temperature_offset()
end

export set_all_values_callback_configuration
"""
    $(SIGNATURES)

The period is the period with which the :cb:`All Values`
callback is triggered periodically. A value of 0 turns the callback off.

If the `value has to change`-parameter is set to true, the callback is only
triggered after at least one of the values has changed. If the values didn't
change within the period, the callback is triggered immediately on change.

If it is set to false, the callback is continuously triggered with the period,
independent of the value.
"""
function set_all_values_callback_configuration(device::BrickletCO2V2, period, value_has_to_change)
    device.deviceInternal.set_all_values_callback_configuration(period, value_has_to_change)
end

export get_all_values_callback_configuration
"""
    $(SIGNATURES)

Returns the callback configuration as set by
:func:`Set All Values Callback Configuration`.
"""
function get_all_values_callback_configuration(device::BrickletCO2V2)
    return device.deviceInternal.get_all_values_callback_configuration()
end

export get_co2_concentration
"""
    $(SIGNATURES)

Returns CO2 concentration.

If you want to get the value periodically, it is recommended to use the
:cb:`CO2 Concentration` callback. You can set the callback configuration
with :func:`Set CO2 Concentration Callback Configuration`.
"""
function get_co2_concentration(device::BrickletCO2V2)
    return device.deviceInternal.get_co2_concentration()
end

export set_co2_concentration_callback_configuration
"""
    $(SIGNATURES)

The period is the period with which the :cb:`CO2 Concentration` callback is triggered
periodically. A value of 0 turns the callback off.

If the `value has to change`-parameter is set to true, the callback is only
triggered after the value has changed. If the value didn't change
within the period, the callback is triggered immediately on change.

If it is set to false, the callback is continuously triggered with the period,
independent of the value.

It is furthermore possible to constrain the callback with thresholds.

The `option`-parameter together with min/max sets a threshold for the :cb:`CO2 Concentration` callback.

The following options are possible:

.. csv-table::
 :header: "Option", "Description"
 :widths: 10, 100

 "'x'",    "Threshold is turned off"
 "'o'",    "Threshold is triggered when the value is *outside* the min and max values"
 "'i'",    "Threshold is triggered when the value is *inside* or equal to the min and max values"
 "'<'",    "Threshold is triggered when the value is smaller than the min value (max is ignored)"
 "'>'",    "Threshold is triggered when the value is greater than the min value (max is ignored)"

If the option is set to 'x' (threshold turned off) the callback is triggered with the fixed period.
"""
function set_co2_concentration_callback_configuration(device::BrickletCO2V2, period, value_has_to_change, option, min, max)
    device.deviceInternal.set_co2_concentration_callback_configuration(period, value_has_to_change, option, min, max)
end

export get_co2_concentration_callback_configuration
"""
    $(SIGNATURES)

Returns the callback configuration as set by :func:`Set CO2 Concentration Callback Configuration`.
"""
function get_co2_concentration_callback_configuration(device::BrickletCO2V2)
    return device.deviceInternal.get_co2_concentration_callback_configuration()
end

export get_temperature
"""
    $(SIGNATURES)

Returns temperature.

.. note::
 The sensor is able to messure up to 120 °C. However it is only specified up to 70 °C.
 Exposing the Bricklet to higher temperatures might result in permanent damage.

If you want to get the value periodically, it is recommended to use the
:cb:`Temperature` callback. You can set the callback configuration
with :func:`Set Temperature Callback Configuration`.
"""
function get_temperature(device::BrickletCO2V2)
    return device.deviceInternal.get_temperature()
end

export set_temperature_callback_configuration
"""
    $(SIGNATURES)

The period is the period with which the :cb:`Temperature` callback is triggered
periodically. A value of 0 turns the callback off.

If the `value has to change`-parameter is set to true, the callback is only
triggered after the value has changed. If the value didn't change
within the period, the callback is triggered immediately on change.

If it is set to false, the callback is continuously triggered with the period,
independent of the value.

It is furthermore possible to constrain the callback with thresholds.

The `option`-parameter together with min/max sets a threshold for the :cb:`Temperature` callback.

The following options are possible:

.. csv-table::
 :header: "Option", "Description"
 :widths: 10, 100

 "'x'",    "Threshold is turned off"
 "'o'",    "Threshold is triggered when the value is *outside* the min and max values"
 "'i'",    "Threshold is triggered when the value is *inside* or equal to the min and max values"
 "'<'",    "Threshold is triggered when the value is smaller than the min value (max is ignored)"
 "'>'",    "Threshold is triggered when the value is greater than the min value (max is ignored)"

If the option is set to 'x' (threshold turned off) the callback is triggered with the fixed period.
"""
function set_temperature_callback_configuration(device::BrickletCO2V2, period, value_has_to_change, option, min, max)
    device.deviceInternal.set_temperature_callback_configuration(period, value_has_to_change, option, min, max)
end

export get_temperature_callback_configuration
"""
    $(SIGNATURES)

Returns the callback configuration as set by :func:`Set Temperature Callback Configuration`.
"""
function get_temperature_callback_configuration(device::BrickletCO2V2)
    return device.deviceInternal.get_temperature_callback_configuration()
end

export get_humidity
"""
    $(SIGNATURES)

Returns relative humidity.

If you want to get the value periodically, it is recommended to use the
:cb:`Humidity` callback. You can set the callback configuration
with :func:`Set Humidity Callback Configuration`.
"""
function get_humidity(device::BrickletCO2V2)
    return device.deviceInternal.get_humidity()
end

export set_humidity_callback_configuration
"""
    $(SIGNATURES)

The period is the period with which the :cb:`Humidity` callback is triggered
periodically. A value of 0 turns the callback off.

If the `value has to change`-parameter is set to true, the callback is only
triggered after the value has changed. If the value didn't change
within the period, the callback is triggered immediately on change.

If it is set to false, the callback is continuously triggered with the period,
independent of the value.

It is furthermore possible to constrain the callback with thresholds.

The `option`-parameter together with min/max sets a threshold for the :cb:`Humidity` callback.

The following options are possible:

.. csv-table::
 :header: "Option", "Description"
 :widths: 10, 100

 "'x'",    "Threshold is turned off"
 "'o'",    "Threshold is triggered when the value is *outside* the min and max values"
 "'i'",    "Threshold is triggered when the value is *inside* or equal to the min and max values"
 "'<'",    "Threshold is triggered when the value is smaller than the min value (max is ignored)"
 "'>'",    "Threshold is triggered when the value is greater than the min value (max is ignored)"

If the option is set to 'x' (threshold turned off) the callback is triggered with the fixed period.
"""
function set_humidity_callback_configuration(device::BrickletCO2V2, period, value_has_to_change, option, min, max)
    device.deviceInternal.set_humidity_callback_configuration(period, value_has_to_change, option, min, max)
end

export get_humidity_callback_configuration
"""
    $(SIGNATURES)

Returns the callback configuration as set by :func:`Set Humidity Callback Configuration`.
"""
function get_humidity_callback_configuration(device::BrickletCO2V2)
    return device.deviceInternal.get_humidity_callback_configuration()
end

export get_spitfp_error_count
"""
    $(SIGNATURES)

Returns the error count for the communication between Brick and Bricklet.

The errors are divided into

* ACK checksum errors,
* message checksum errors,
* framing errors and
* overflow errors.

The errors counts are for errors that occur on the Bricklet side. All
Bricks have a similar function that returns the errors on the Brick side.
"""
function get_spitfp_error_count(device::BrickletCO2V2)
    return device.deviceInternal.get_spitfp_error_count()
end

export set_bootloader_mode
"""
    $(SIGNATURES)

Sets the bootloader mode and returns the status after the requested
mode change was instigated.

You can change from bootloader mode to firmware mode and vice versa. A change
from bootloader mode to firmware mode will only take place if the entry function,
device identifier and CRC are present and correct.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_bootloader_mode(device::BrickletCO2V2, mode)
    return device.deviceInternal.set_bootloader_mode(mode)
end

export get_bootloader_mode
"""
    $(SIGNATURES)

Returns the current bootloader mode, see :func:`Set Bootloader Mode`.
"""
function get_bootloader_mode(device::BrickletCO2V2)
    return device.deviceInternal.get_bootloader_mode()
end

export set_write_firmware_pointer
"""
    $(SIGNATURES)

Sets the firmware pointer for :func:`Write Firmware`. The pointer has
to be increased by chunks of size 64. The data is written to flash
every 4 chunks (which equals to one page of size 256).

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function set_write_firmware_pointer(device::BrickletCO2V2, pointer)
    device.deviceInternal.set_write_firmware_pointer(pointer)
end

export write_firmware
"""
    $(SIGNATURES)

Writes 64 Bytes of firmware at the position as written by
:func:`Set Write Firmware Pointer` before. The firmware is written
to flash every 4 chunks.

You can only write firmware in bootloader mode.

This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program.
"""
function write_firmware(device::BrickletCO2V2, data)
    return device.deviceInternal.write_firmware(data)
end

export set_status_led_config
"""
    $(SIGNATURES)

Sets the status LED configuration. By default the LED shows
communication traffic between Brick and Bricklet, it flickers once
for every 10 received data packets.

You can also turn the LED permanently on/off or show a heartbeat.

If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.
"""
function set_status_led_config(device::BrickletCO2V2, config)
    device.deviceInternal.set_status_led_config(config)
end

export get_status_led_config
"""
    $(SIGNATURES)

Returns the configuration as set by :func:`Set Status LED Config`
"""
function get_status_led_config(device::BrickletCO2V2)
    return device.deviceInternal.get_status_led_config()
end

export get_chip_temperature
"""
    $(SIGNATURES)

Returns the temperature as measured inside the microcontroller. The
value returned is not the ambient temperature!

The temperature is only proportional to the real temperature and it has bad
accuracy. Practically it is only useful as an indicator for
temperature changes.
"""
function get_chip_temperature(device::BrickletCO2V2)
    return device.deviceInternal.get_chip_temperature()
end

export reset
"""
    $(SIGNATURES)

Calling this function will reset the Bricklet. All configurations
will be lost.

After a reset you have to create new device objects,
calling functions on the existing ones will result in
undefined behavior!
"""
function reset(device::BrickletCO2V2)
    device.deviceInternal.reset()
end

export write_uid
"""
    $(SIGNATURES)

Writes a new UID into flash. If you want to set a new UID
you have to decode the Base58 encoded UID string into an
integer first.

We recommend that you use Brick Viewer to change the UID.
"""
function write_uid(device::BrickletCO2V2, uid)
    device.deviceInternal.write_uid(uid)
end

export read_uid
"""
    $(SIGNATURES)

Returns the current UID as an integer. Encode as
Base58 to get the usual string version.
"""
function read_uid(device::BrickletCO2V2)
    return device.deviceInternal.read_uid()
end

export get_identity
"""
    $(SIGNATURES)

Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port).
A Bricklet connected to an :ref:`Isolator Bricklet <isolator_bricklet>` is always at
position 'z'.

The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant|
"""
function get_identity(device::BrickletCO2V2)
    return device.deviceInternal.get_identity()
end

export register_callback
"""
Registers the given *function* with the given *callback_id*.
"""
function register_callback(device::BrickletCO2V2, callback_id, function_)
    if isnothing(function_)
        device.registered_callbacks.pop(callback_id, None)
    else
        device.registered_callbacks[callback_id] = function_
    end
end


text:
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:hydrogen
#     text_representation:
#       extension: .jl
#       format_name: hydrogen
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: Julia 1.8.0-DEV
#     language: julia
#     name: julia-1.8
# ---

# %%
using SymPy
@syms z
@syms x::real
@syms a::positive

# %%
expr = cos(z)^2 + sin(z)^2

# %%
expr.simplify()

# %%
Eq(expr, expr.simplify())

# %%
G = sympy.Integral(exp(-x^2/a), (x, -oo, oo))

# %%
Eq(G, G.doit())

# %%

ext: jl

max_stars_repo_path: 0013/SymPy example.jl

max_stars_repo_name: genkuroki/public

max_issues_repo_path: 0013/SymPy example.jl

max_issues_repo_name: genkuroki/public

max_forks_repo_path: 0013/SymPy example.jl

max_forks_repo_name: genkuroki/public


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

using Test, SparseArrays
@test detect_ambiguities(SparseArrays; imported=true, recursive=true) == []

max_stars_repo_name: TimoLarson/julia

max_issues_repo_name: AsForMe/julia

max_forks_repo_name: AsForMe/julia


text:
using CamJulia
using MLStyle

rmlines = @λ begin
    Expr(head, args...) -> Expr(head, filter(x -> x !== nothing, map(rmlines, args))...)
    ::LineNumberNode -> nothing
    a -> a
end

macro load_cam(path)
    aeson = CamJulia.ReadIR.load_aeson(path);
    ir = CamJulia.ReadIR.aeson_to_ir(aeson)
    x = CamJulia.CAM.ir_to_julia(ir)
    # @info rmlines(x)
    esc(x)
end

# @load_cam "./test.cam"
@load_cam "/tmp/idris19309-1"

max_stars_repo_name: thautwarm/idris-cam

max_issues_repo_name: thautwarm/idris-cam

max_forks_repo_name: thautwarm/idris-cam


text:
export TRKOp

function TRKOp(nlp 		:: AbstractNLPModel,
               nlpstop 	:: NLPStopping;
							 kwargs...
               )

	return TRARC2(nlp,
				  nlpstop;
				  TR = TrustRegion(10.0),
				  c = Combi(hessian_operator, PDataK{eltype(nlp.meta.x0)}, solve_modelKTR, preprocessKTR, decreaseKTR, TparamsKTR{eltype(nlp.meta.x0)}()),
				  kwargs...
				  )
end


text:
"""
    semi_elementary_polynomial{N}

A polynomial with integer coefficient, where each term is a semi elementary monomial.
Internally it's represented as a sorted dict, which allows fast lookup of the term
with the highest order, and fast insertion.
"""
struct semi_elementary_polynomial{N}
    terms::SortedDict{semi_elementary_monomial{N},Int128,Base.Order.ForwardOrdering}
    semi_elementary_polynomial(N) = new{N}(SortedDict{semi_elementary_monomial{N},Int128}())
end

function to_polynomial(x::semi_elementary_monomial{N}) where {N}
    k = semi_elementary_polynomial(N)
    k.terms[x]=1
    return k
end

function Base.push!(x::semi_elementary_polynomial{N},k::semi_elementary_monomial{N},v::Union{Integer,Rational}) where {N}
    if !haskey(x.terms,k)
        x.terms[k] = v
    elseif x.terms[k] != -v
        x.terms[k] += v
    else
        pop!(x.terms,k)
    end
end

Base.:(==)(x::semi_elementary_polynomial,y::semi_elementary_polynomial) = x.terms == y.terms

"""
    lower_order_representation(p,x)

Rewrite an admissible symmetric polynomial (as explained in the documentation for decompose)
In lower order terms, and add them to polynomial p.

For example, we want to write ``S(0,1,3)=x^3(y+z)+y^3(x+z)+z^3(x+y)`` into an equivalent representation,
but with terms of lower order. We would take an initial guess, ``S(0,1,3)\\approx S(0,1,2)S(0,0,1)``.

It turns out ``S(0,1,2)S(0,0,1)=S(0,1,3)+2S(0,2,2)+2S(1,1,1)(0,0,1)``, so if we rewrite it as
``S(0,1,3)=S(0,1,2)S(0,0,1)-2S(0,2,2)-2S(1,1,1)(0,0,1)`` every term has lower order.
"""
function lower_order_representation(polynomial::semi_elementary_polynomial{N},x::semi_elementary_monomial{N}) where {N}
    is_elementary(x) && return
    sp = x.sp_term
    original_coefficient = polynomial.terms[x]
    num_highest = N - findfirst(i->i==sp[end],sp) + 1
    factor = ntuple(i->i > N - num_highest ? sp[i] - 1 : sp[i],N)

    f_keys,f_values = count_occurrences(factor)
    distribution_ways = ways_place_contain
push!(LOAD_PATH,"../src/")ers(f_values,num_highest)

    for j=1:size(distribution_ways,1)
        way = view(distribution_ways,j,:)
        representative = canonical_placement(f_values,way)
        new_term = TupleTools.sort(ntuple(i->factor[i] + representative[i],N))
        coeff = 1
        for i=2:length(f_keys)
            if f_keys[i-1]==f_keys[i]-1
                coeff *= binomial(f_values[i] - way[i] + way[i-1],way[i-1])
            end
        end
        push!(polynomial,semi_elementary_monomial(new_term,x.powers),-coeff * original_coefficient)
    end
    tmp = ntuple(i->i==num_highest ? x.powers[i] + 1 : x.powers[i],N)
    push!(polynomial,semi_elementary_monomial(factor,tmp),original_coefficient)
end

"""
    decompose(x)

Rewrites a symmetric polynomial as a polynomial of elementary symmetric polynomials.
This function only factors symmetric polynomials where every term has the same order
and the powers has the same partition.
For example, ``x^3(y+z)+y^3(x+z)+z^3(x+y)`` is ok. Because the power of every term
is ``(0,1,3)``.

``(x^2+y^2+z^2)+(x^3+y^3+z^3)`` on the other hand is not ok, because some terms' power
are ``(0,0,2)`` while others are ``(0,0,3)``.
"""
function decompose(x::semi_elementary_monomial{N}) where {N}
    polynomial = semi_elementary_polynomial(N)
    polynomial.terms[x] = 1
    highest_term = last(polynomial.terms).first
    while !is_elementary(highest_term)
        #println("highest term is "*string(highest_term))
        lower_order_representation(polynomial,highest_term)
        highest_term = last(polynomial.terms).first
    end
    return polynomial
end

function to_string(x::semi_elementary_polynomial)
    head = ""
    for (i,j) in x.terms
        if j>0
            head *= "+"
        end
        head *= string(j)
        head *= "*"
        head *= to_string(i)
    end
    return head
end
Base.show(io::IO, ::MIME{Symbol("text/plain")}, x::semi_elementary_polynomial) = join(io,to_string(x))

max_stars_repo_path: src/semi elementary polynomial.jl

max_stars_repo_name: yushoteke/SymmetricPolynomials

max_issues_repo_path: src/semi elementary polynomial.jl

max_issues_repo_name: yushoteke/SymmetricPolynomials

max_forks_repo_path: src/semi elementary polynomial.jl

max_forks_repo_name: yushoteke/SymmetricPolynomials


text:
### A Pluto.jl notebook ###
# v0.14.7

using Markdown
using InteractiveUtils

# ╔═╡ 28dec7bc-c846-11eb-2576-0d28a2569db6
begin
	using Pkg
	Pkg.activate(mktempdir())
end

# ╔═╡ bcdf3958-9a53-437f-8c0e-529b37e3e833
begin
	Pkg.add(["Plots", "PlutoUI","StatsBase", "DataStructures", "Unitful", "UnitfulRecipes", "PhysicalConstants", "UnitfulEquivalences", "DataFrames", "CSV", "Dates", "TimeZones", "StatsPlots", "ImageFiltering", "OffsetArrays", "FileIO", "StaticArrays", "FastIOBuffers", "TranscodingStreams", "CodecBzip2", "Tokenize", "DataInterpolations", "GR"])
	Pkg.develop(["RobotOSData"])

	using Plots
	gr()
	# plotly()
	using PlutoUI
	using StatsBase
	using DataStructures
	using Unitful
	using PhysicalConstants.CODATA2018: c_0, h, ħ
	using UnitfulEquivalences
	using UnitfulRecipes
	using DataFrames
	using CSV
	using TimeZones
	using Dates
	using StatsPlots
	using ImageFiltering
	using OffsetArrays
	using RobotOSData
	using FileIO
	using StaticArrays
	using DataInterpolations
end

# ╔═╡ c13e43d4-b7d6-4d65-996d-b2568d43b9f4
module ExtraMessages
    module tf2_msgs
        using RobotOSData.Messages # imports Readable, Header
        using RobotOSData.StdMsgs
        using RobotOSData.CommonMsgs # for sensor_msgs
        struct TFMessage <: Readable
	        transforms::Vector{geometry_msgs.TransformStamped}
        end
    end
end

# ╔═╡ ebbe541a-7ae5-4b18-b079-239bd733c5fb
bag = load("/home/kris/learning/robotont/bagfiles/straight-movement2.bag", ExtraMessages)

# ╔═╡ 433f3fe3-45c6-43c4-84f1-7b54178ed34a
bag.topic_map

# ╔═╡ 977dbaf0-ed9b-4582-9378-8e1eabd1a1c1
time_range = ROSTime("2021-06-10T11:08:50"):ROSTime("2021-06-10T11:09:21")

# ╔═╡ 10e08ba1-6e48-4d6c-8949-83e0c8ee82e7
tfs = [tf for msg ∈ bag[RobotOSData.ConnectionFilter(2), time_range] for tf ∈ msg.data.transforms ]

# ╔═╡ 0df647f5-340f-4b8a-9826-4ee55ea66890
countmap([tf.child_frame_id for tf ∈ tfs])

# ╔═╡ bf83571f-c7f5-45d9-87a9-23c2bcff04fe
zs = [(convert(DateTime, tf.header.time), tf.transform.translation.z) for tf ∈ tfs if tf.child_frame_id ∈ ("tag_5","tag_6")]

# ╔═╡ 8f96e1d2-32e4-46d8-998c-7728f4204fda
df = DataFrame(NamedTuple{(:time, :pos)}.(zs))

# ╔═╡ 79d2d3ed-d65d-44b2-aa6c-6964785a044a
mzs = combine(groupby(df, [:time]), :pos => mean => :mpos)

# ╔═╡ d42aa9df-4991-494e-a30d-24351ede8a0a
@df mzs plot(:time, [:mpos], ticks=:native)

# ╔═╡ fa2f217f-0184-4947-b161-191feba95d42
dist = mzs[!, :mpos] .* u"m" # add units

# ╔═╡ accbb017-a1c4-4122-b2ce-7711a946312a
time = mzs[!, :time] - mzs[1, :time]

# ╔═╡ 02e4c44e-42d7-4064-b522-1384122eee5e
plot(time[2:end], diff(dist) * u"1/s", title="Not smoothed", ylabel="speed")

# ╔═╡ 854e8a1a-3caa-4661-ba85-d0542f1489bb
begin
	smooth_range = -10:10
	n_ = size(smooth_range)[1]
	kernel = OffsetArray(fill(1/n_, n_), smooth_range)
end;

# ╔═╡ 4ae7323d-be6b-45c8-b16f-52c27968efc8
plot(time[2:end], diff(imfilter(dist, kernel)) * u"1/s", title="Smoothed with uniform kernel", ylabel="velocity")

# ╔═╡ c4054e36-b8a9-4743-8b36-bba84f29ec1b
velocity_gauss = diff(imfilter(dist, KernelFactors.gaussian(3))) * u"1/s"

# ╔═╡ faeb3515-b797-4920-b3ff-5672e47b1a51
plot(time[2:end], velocity_gauss, title="Smoothed with gaussian kernel", ylabel="velocity")

# ╔═╡ eb19d479-d778-4f9f-89b7-6825163769aa
acceleration_gauss = diff(imfilter(velocity_gauss, KernelFactors.gaussian(3))) * u"1/s"

# ╔═╡ cfe4a5f3-5d70-467b-9706-bebd17b55305
plot(time[3:end], acceleration_gauss, title="Smoothed with gaussian kernel", ylabel="acceleration")

# ╔═╡ 53699f51-6295-4f3e-8376-0891e4f3afd2
odom = bag["/robotont/odom", time_range]

# ╔═╡ 14101c1e-f328-487b-a8a9-570e54fe7aa9
ox = [(convert(DateTime, o.data.header.time), o.data.twist.twist.linear.y, o.data.pose.pose.position.x) for o = odom]

# ╔═╡ 88f25939-55ba-4c26-9976-7f9e733f6966
odf = DataFrame(NamedTuple{(:time, :vel, :pos)}.(ox))

# ╔═╡ 9dfa7cda-1a14-43bf-9b0e-ca2fe8f0dcac
otime = odf[!, :time] - odf[1, :time]

# ╔═╡ 3c548f42-982c-49f7-9768-5f75771f28a7
plot(otime[1:end], odf[!, :vel])

# ╔═╡ 5f003d0a-f6ae-4bb9-8b8e-a1f7be829385
mean(odf[!,:vel])

# ╔═╡ eb52fa86-4c01-4100-91f4-eb94f4ad15d8
begin
	start = mzs[1,:mpos]

	plot(time, mzs[!, :mpos], ticks=:native, label="camera")
	plot!(otime, start .- odf[!, :pos], ticks=:native, label="odom")
end

# ╔═╡ d1929e40-a617-4577-a875-0b7e2f8878e6

# ╔═╡ Cell order:
# ╠═28dec7bc-c846-11eb-2576-0d28a2569db6
# ╠═bcdf3958-9a53-437f-8c0e-529b37e3e833
# ╠═ebbe541a-7ae5-4b18-b079-239bd733c5fb
# ╠═433f3fe3-45c6-43c4-84f1-7b54178ed34a
# ╠═977dbaf0-ed9b-4582-9378-8e1eabd1a1c1
# ╠═10e08ba1-6e48-4d6c-8949-83e0c8ee82e7
# ╠═0df647f5-340f-4b8a-9826-4ee55ea66890
# ╠═c13e43d4-b7d6-4d65-996d-b2568d43b9f4
# ╠═bf83571f-c7f5-45d9-87a9-23c2bcff04fe
# ╠═8f96e1d2-32e4-46d8-998c-7728f4204fda
# ╠═79d2d3ed-d65d-44b2-aa6c-6964785a044a
# ╠═d42aa9df-4991-494e-a30d-24351ede8a0a
# ╠═fa2f217f-0184-4947-b161-191feba95d42
# ╠═accbb017-a1c4-4122-b2ce-7711a946312a
# ╠═02e4c44e-42d7-4064-b522-1384122eee5e
# ╠═854e8a1a-3caa-4661-ba85-d0542f1489bb
# ╠═4ae7323d-be6b-45c8-b16f-52c27968efc8
# ╠═c4054e36-b8a9-4743-8b36-bba84f29ec1b
# ╠═faeb3515-b797-4920-b3ff-5672e47b1a51
# ╠═eb19d479-d778-4f9f-89b7-6825163769aa
# ╠═cfe4a5f3-5d70-467b-9706-bebd17b55305
# ╠═53699f51-6295-4f3e-8376-0891e4f3afd2
# ╠═14101c1e-f328-487b-a8a9-570e54fe7aa9
# ╠═88f25939-55ba-4c26-9976-7f9e733f6966
# ╠═9dfa7cda-1a14-43bf-9b0e-ca2fe8f0dcac
# ╠═3c548f42-982c-49f7-9768-5f75771f28a7
# ╠═5f003d0a-f6ae-4bb9-8b8e-a1f7be829385
# ╠═eb52fa86-4c01-4100-91f4-eb94f4ad15d8
# ╠═d1929e40-a617-4577-a875-0b7e2f8878e6


text:
# How to constrain the weights ? Upper limit only, or sum strictly equal to
# target ?
abstract type HeterosynapticConstraint end
# Whether to consider the sum over  outgoing weights, incoming weights, or both
abstract type HeterosynapticTarget end
# Additive or multiplicative
abstract type HeterosynapticMethod end

struct HetUpperLimit <: HeterosynapticConstraint
  wsum_max::Float64
  wmin::Float64
  wmax::Float64
  tolerance::Float64
end
struct HetStrictSum <: HeterosynapticConstraint
  wsum_max::Float64
  wmin::Float64
  wmax::Float64
  tolerance::Float64
end

@inline function hardbounds(x::Float64,hc::HeterosynapticConstraint)
  hardbounds(x,hc.wmin,hc.wmax)
end

function _hetconstraint_vs_sum(sums::Vector{Float64},c::HetUpperLimit)
  _lim  =  c.wsum_max + c.tolerance
  return sums .> _lim
end
function _hetconstraint_vs_sum(sums::Vector{Float64},c::HetStrictSum)
  return .!isapprox.(sums,c.wsum_max;atol=c.tolerance)
end

struct HetIncoming <: HeterosynapticTarget end
struct HetOutgoing <: HeterosynapticTarget end
struct HetBoth <: HeterosynapticTarget end

struct HetAdditive <: HeterosynapticMethod end
struct HetMultiplicative <: HeterosynapticMethod end

struct PlasticityHeterosynapticApprox{
    HC<:HeterosynapticConstraint,
    HM<:HeterosynapticMethod,
    HT<:HeterosynapticTarget} <:PlasticityRule
  constraint::HC
  method::HM
  target::HT
  Δt_update::Float64
  _tcounter::Ref{Float64}
  alloc_incoming::Vector{Float64} # preallocate, for sums
  alloc_Nincoming::Vector{Int64}  # and count synapses too
  alloc_outgoing::Matrix{Float64}
  alloc_Noutgoing::Matrix{Int64}
  function PlasticityHeterosynapticApprox(
      Npost::Int64,Npre::Int64,
      Δt_update::Float64,
      hc::HC,hm::HM,ht::HT) where {
        HC <: HeterosynapticConstraint,
        HM <: HeterosynapticMethod,
        HT <: HeterosynapticTarget }
    _tcounter = Ref(0.0)
    alloc_incoming = fill(0.0,Npost)
    alloc_Nincoming = fill(0,Npost)
    alloc_outgoing = fill(0.0,1,Npre) # row!
    alloc_Noutgoing = fill(0,Npre)
    return new{HC,HM,HT}(hc,hm,ht,
      Δt_update,_tcounter,Nel_rows,Nel_cols,
      alloc_incoming,alloc_Nincoming,alloc_outgoing,alloc_Noutgoing)
  end
end

function reset!(plast::PlasticityHeterosynapticApprox)
  plast._tcounter[] = zero(Float64)
  # just in case...
  fill!(plast.alloc_incoming,0.0)
  fill!(plast.alloc_Nincoming,0)
  fill!(plast.alloc_outgoing,0.0)
  fill!(plast.alloc_Noutgoing,0)
  return nothing
end

function plasticity_update!(t_spike::Real,::Integer,::Integer,
    ::AbstractPopulationState,conn::Connection,::AbstractPopulationState,
    plast::PlasticityHeterosynapticApprox)
  # time since previous spike
  if (t_spike-plast._tcounter[]) < plast.Δt_update
    return nothing
  end
  # reset timer
  plast._tcounter[] = t_spike
  # find correction values at col/row , depending on target
  _het_plasticity_fix_incoming!(plast.alloc_incoming,plast.Nel_incoming,
    conn.weights,plast.constraint,plast.method,plast.target)
  _het_plasticity_fix_outgoing!(plast.alloc_outgoing,plast.Nel_outgoing,
    conn.weights,plast.constraint,plast.method,plast.target)
  # apply the fix
  _het_plasticity_apply_fix!(
      plast.alloc_incoming,plast.alloc_outgoing,
      conn.weights,
      plast.constraint,plast.method,plast.target)
  return nothing
end

function _het_plasticity_fix_incoming!(alloc_sum::Vector{Float64},Nel::Vector{Int64},
    weights::Matrix{Float64},
    constraint::HetStrictSum,
    ::HetAdditive,::Union{HetBoth,HetIncoming})
  sum!(alloc_sum,weights)
  for (k,row) in eachrow(weights)
    Nel[k]=count(!=(0.0),row)
  end
  sum_max = constraint.wsum_max
  @. alloc_sum = (sum_max - alloc_sum )/ Nel
  return nothing
end
function _het_plasticity_fix_incoming!(::Vector{Float64},::Vector{Int64},
    ::Matrix,::HeterosynapticConstraint,
    ::HeterosynapticMethod,::HetOutgoing)
  return nothing
end
function _het_plasticity_fix_outgoing!(alloc_sum::Matrix{Float64},nel::Vector{Int64},
    weights::Matrix,
    constraint::HetStrictSum,
    ::HetAdditive,::Union{HetBoth,HetOutgoing})
  sum!(alloc_sum,weights)
  for (k,col) in eachcol(weights)
    Nel[k]=count(!=(0.0),col)
  end
  sum_max = constraint.wsum_max
  @. alloc_sum = (sum_max - alloc_sum )/ Nel
  return nothing
end
function _het_plasticity_fix_outgoing!(::Vector{Float64},::Vector{Int64},
    ::Matrix,::HeterosynapticConstraint,::HeterosynapticMethod,::HetIncoming)
  return nothing
end

# returns mean if both nonzero
@inline function _mean_nonzero(a::R,b::R) where R
  if iszero(a)
    return b
  elseif iszero(b)
    return a
  else
    return 0.5*(a+b)
  end
end

function _het_plasticity_apply_fix!(
    fixrows::Vector{Float64},fixcols::Vector{Float64},
    weights::Matrix{Float64},constraint::HeterosynapticConstraint,
    ::HetAdditive,::HetBoth)
  @inbounds for ij in CartesianIndices(weights)
    wij = weights[ik]
    if iszero(wij) # skip missing connections
      continue
    end
    wij += _mean_nonzero(fixrows[ij[1]],fixcols[ij[2]])
    weights[ij] = hardbounds(wij,constraint)
  end
  return nothing
end


text:
# ---
# title: 997. Find the Town Judge
# id: problem997
# author: Indigo
# date: 2021-05-31
# difficulty: Easy
# categories: Graph
# link: <https://leetcode.com/problems/find-the-town-judge/description/>
# hidden: true
# ---
#
# In a town, there are `N` people labelled from `1` to `N`.  There is a rumor
# that one of these people is secretly the town judge.
#
# If the town judge exists, then:
#
#   1. The town judge trusts nobody.
#   2. Everybody (except for the town judge) trusts the town judge.
#   3. There is exactly one person that satisfies properties 1 and 2.
#
# You are given `trust`, an array of pairs `trust[i] = [a, b]` representing that
# the person labelled `a` trusts the person labelled `b`.
#
# If the town judge exists and can be identified, return the label of the town
# judge.  Otherwise, return `-1`.
#
#
#
# **Example 1:**
#
#
#
#     Input: N = 2, trust = [[1,2]]
#     Output: 2
#
#
# **Example 2:**
#
#
#
#     Input: N = 3, trust = [[1,3],[2,3]]
#     Output: 3
#
#
# **Example 3:**
#
#
#
#     Input: N = 3, trust = [[1,3],[2,3],[3,1]]
#     Output: -1
#
#
# **Example 4:**
#
#
#
#     Input: N = 3, trust = [[1,2],[2,3]]
#     Output: -1
#
#
# **Example 5:**
#
#
#
#     Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
#     Output: 3
#
#
#
#
# **Constraints:**
#
#   * `1 <= N <= 1000`
#   * `0 <= trust.length <= 10^4`
#   * `trust[i].length == 2`
#   * `trust[i]` are all different
#   * `trust[i][0] != trust[i][1]`
#   * `1 <= trust[i][0], trust[i][1] <= N`
#
#
## @lc code=start
using LeetCode

function find_judge(N::Int, trust::Vector{Vector{Int}})
    cnt = fill(0, N)
    for t in trust
        cnt[t[1]] -= 1
        cnt[t[2]] += 1
    end
    res = findfirst(==(N - 1), cnt)
    return isnothing(res) ? -1 : res
end
## @lc code=end


text:
@testset "process.jl" begin

    @testset "Process fields" begin
        @process helloWorld() begin
            return "Goodbye world"
        end

        @test typeof(helloWorld()) == Process
        @test helloWorld().name == "helloWorld()"
        @test helloWorld().state == :created
        @test helloWorld().task.state == :runnable
        @test typeof(helloWorld().notice.element) == Process
        @test typeof(helloWorld().queue) == Array{SimLynx.AbstractMessage,1}
        @test helloWorld().acceptors == SimLynx.Acceptor[]
        @test helloWorld().response === nothing
        @test helloWorld().storage == IdDict{Symbol, Any}()
    end

    @testset "discrete process states" begin
        stateList = []
        shared = nothing

        @process control() begin
            @with_resource shared begin
                add!(proc_list, current_process())

                delayedProcess = testProcess(1)
                @schedule now delayedProcess # due to control() taking resource
                @schedule now suspendProcess()
                @schedule now testProcess(2)
                @schedule now interruptProcess()
                work(3)

                # :active
                push!(stateList, current_process().state)

                # :delayed
                push!(stateList, delayedProcess.state)

                remove!(proc_list, current_process())
            end

            wait(8) # XXX: make this number precise

            # :suspended
            push!(stateList, first(proc_list).state)

            notice = first(proc_list).notice
            notice.time = current_time() + 1.0
            resume(first(proc_list), notice)
        end

        @process testProcess(i::Integer) begin
            if current_process().name == "testProcess(1)"

                # :working
                push!(stateList, controlProcess.state)

                # current_process()'s state will mutate to :terminated
                push!(stateList, current_process())
            end
            @with_resource shared begin
                add!(proc_list, current_process())
                work(3)
                remove!(proc_list, current_process())
            end
        end

        @process interruptProcess() begin
            wait(4)
            other_proc = first(proc_list)
            notice = interrupt(other_proc)
            notice.time = current_time() + 2.0

            work(2)
            push!(stateList, other_proc.state)
            resume(other_proc, notice)
        end

        @process suspendProcess() begin
            @with_resource shared begin
                add!(proc_list, current_process())
                suspend()
            end
        end

        @simulation begin
            shared = Resource(1, "")
            global proc_list = Queue{Process}()
            global controlProcess = @schedule now control()
            start_simulation()
        end

        # :terminated
        stateList[2] = stateList[2].state

        # :created
        push!(stateList, testProcess(0).state)

        @test stateList[1] == :working
        @test stateList[2] == :terminated
        @test stateList[3] == :active
        @test stateList[4] == :delayed
        @test stateList[5] == :interrupted
        @test stateList[6] == :suspended
        @test stateList[7] == :created

    end

    @testset "Process Sig Error" begin
        @test_throws ArgumentError @m_throw @process foo :bar
    end

end


text:
module TestExamplesP4estMesh3D

using Test
using Trixi

include("test_trixi.jl")

EXAMPLES_DIR = joinpath(examples_dir(), "p4est_3d_dgsem")

# Start with a clean environment: remove Trixi output directory if it exists
outdir = "out"
isdir(outdir) && rm(outdir, recursive=true)

@testset "P4estMesh3D" begin
  @trixi_testset "elixir_advection_basic.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_basic.jl"),
      # Expected errors are exactly the same as with TreeMesh!
      l2   = [0.00016263963870641478],
      linf = [0.0014537194925779984])
  end

  @trixi_testset "elixir_advection_unstructured_curved.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_unstructured_curved.jl"),
      l2   = [0.0004750004258546538],
      linf = [0.026527551737137167])
  end

  @trixi_testset "elixir_advection_nonconforming.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_nonconforming.jl"),
      l2   = [0.00253595715323843],
      linf = [0.016486952252155795])
  end

  @trixi_testset "elixir_advection_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_amr.jl"),
      # Expected errors are exactly the same as with TreeMesh!
      l2   = [9.773852895157622e-6],
      linf = [0.0005853874124926162])
  end

  @trixi_testset "elixir_advection_amr_unstructured_curved.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_amr_unstructured_curved.jl"),
      l2   = [1.6236411810065552e-5],
      linf = [0.0010554006923731395],
      tspan = (0.0, 1.0))
  end

  @trixi_testset "elixir_advection_cubed_sphere.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_cubed_sphere.jl"),
      l2   = [0.002006918015656413],
      linf = [0.027655117058380085])
  end

  @trixi_testset "elixir_advection_restart.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_advection_restart.jl"),
      l2   = [0.002590388934758452],
      linf = [0.01840757696885409])
  end

  @trixi_testset "elixir_euler_source_terms_nonconforming_unstructured_curved.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_source_terms_nonconforming_unstructured_curved.jl"),
      l2   = [4.070355207909268e-5, 4.4993257426833716e-5, 5.10588457841744e-5, 5.102840924036687e-5, 0.00019986264001630542],
      linf = [0.0016987332417202072, 0.003622956808262634, 0.002029576258317789, 0.0024206977281964193, 0.008526972236273522],
      tspan = (0.0, 0.01))
  end

  @trixi_testset "elixir_euler_source_terms_nonperiodic.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_source_terms_nonperiodic.jl"),
      l2   = [0.0015106060984283647, 0.0014733349038567685, 0.00147333490385685, 0.001473334903856929, 0.0028149479453087093],
      linf = [0.008070806335238156, 0.009007245083113125, 0.009007245083121784, 0.009007245083102688, 0.01562861968368434],
      tspan = (0.0, 1.0))
  end

  @trixi_testset "elixir_euler_free_stream.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_free_stream.jl"),
      l2   = [5.162664597942288e-15, 1.941857343642486e-14, 2.0232366394187278e-14, 2.3381518645408552e-14, 7.083114561232324e-14],
      linf = [7.269740365245525e-13, 3.289868377720495e-12, 4.440087186807773e-12, 3.8686831516088205e-12, 9.412914891981927e-12],
      tspan = (0.0, 0.03))
  end

  @trixi_testset "elixir_euler_free_stream_extruded.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_free_stream_extruded.jl"),
      l2   = [8.444868392439035e-16, 4.889826056731442e-15, 2.2921260987087585e-15, 4.268460455702414e-15, 1.1356712092620279e-14],
      linf = [7.749356711883593e-14, 2.8792246364872653e-13, 1.1121659149182506e-13, 3.3228975127030935e-13, 9.592326932761353e-13],
      tspan=(0.0, 0.1))
  end

  @trixi_testset "elixir_euler_ec.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_ec.jl"),
      l2   = [0.010380390326164493, 0.006192950051354618, 0.005970674274073704, 0.005965831290564327, 0.02628875593094754],
      linf = [0.3326911600075694, 0.2824952141320467, 0.41401037398065543, 0.45574161423218573, 0.8099577682187109],
      tspan = (0.0, 0.2))
  end

  @trixi_testset "elixir_euler_sedov.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_euler_sedov.jl"),
      l2   = [7.82070951e-02, 4.33260474e-02, 4.33260474e-02, 4.33260474e-02, 3.75260911e-01],
      linf = [7.45329845e-01, 3.21754792e-01, 3.21754792e-01, 3.21754792e-01, 4.76151527e+00],
      tspan = (0.0, 0.3))
  end

  @trixi_testset "elixir_mhd_alfven_wave_nonconforming.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_alfven_wave_nonconforming.jl"),
      l2   = [0.00019018725889431733, 0.0006523517707148006, 0.0002401595437705759, 0.0007796920661427565,
              0.0007095787460334334, 0.0006558819731628876, 0.0003565026134076906, 0.0007904654548841712,
              9.437300326448332e-7],
      linf = [0.0012482306861187897, 0.006408776208178299, 0.0016845452099629663, 0.0068711236542984555,
              0.004626581522263695, 0.006614624811393632, 0.0030068344747734566, 0.008277825749754025,
              1.3475027166309006e-5],
      tspan = (0.0, 0.25))
  end

  @trixi_testset "elixir_mhd_shockcapturing_amr.jl" begin
    @test_trixi_include(joinpath(EXAMPLES_DIR, "elixir_mhd_shockcapturing_amr.jl"),
      l2   = [0.006298541670176575, 0.0064368506652601265, 0.007108729762852636, 0.006530420607206385,
              0.02061185869237284, 0.005562033787605515, 0.007571716276627825, 0.005571862660453231,
              3.909755063709152e-6],
      linf = [0.20904054009050665, 0.18622917151105936, 0.2347957890323218, 0.19432508025509926,
              0.6858860133405615, 0.15172116633332622, 0.22432820727833747, 0.16805989780225183,
              0.000535219040687628],
      tspan = (0.0, 0.04))
  end
end

# Clean up afterwards: delete Trixi output directory
@test_nowarn rm(outdir, recursive=true)

end # module


text:
using ApproxFun, Base.Test

single_sin = Fun(sin,Interval(0.f0,1.f0))
double_sin = Fun(sin,Interval(0.,1.))
big_sin = Fun(sin,Interval(parse(BigFloat,"0.0"), parse(BigFloat,"1.0")))

@test ncoefficients(single_sin) <= ncoefficients(double_sin)
@test ncoefficients(double_sin) <= ncoefficients(big_sin)

@test eltype(coefficients(single_sin)) == Float32
@test eltype(coefficients(double_sin)) == Float64
@test eltype(coefficients(big_sin)) == BigFloat

single_double_err = coefficients(single_sin-double_sin)[1:ncoefficients(single_sin)]
@test norm(single_double_err) < 10eps(Float32)

single_double_err = coefficients(double_sin-big_sin)[1:ncoefficients(double_sin)]
@test norm(single_double_err) < 10eps(Float64)


text:
# container variable for storing the results of simulations

function RunResults(net::SpikingLayersNet, settings::RunSettings)
    # storage for measurement variables
    # expressions for each layer
    T = settings.T
    names = Dict{Int64, ASCIIString}()
    N = Dict{Int64, Int64}()
    spikes = Dict{Int64, Vector{(Int64,Int64)}}()

    for (i,layer) in enumerate(net.l)
        names[i] = layer.name
        N[i] = layer.N
        spikes[i] = Array((Int64,Int64),0)
    end
    RunResults(names,N,spikes,dt,T)
end

function recordSpikes!(rec::RunResults, net::SpikingLayersNet, istep::Int64)
    for (i,layer) in enumerate(net.l)
        for ineuron in find(didSpike(layer))
            push!(rec.spikes[i], (istep,ineuron))
        end
    end
end


text:
using Celeste.Model: boxes_overlap, ImagePatch, box_from_catalog, find_neighbors
using Celeste.SDSSIO
using Base.Test

@testset "ImagePatch" begin
    @testset "boxes_overlap" begin
        @test boxes_overlap((1:0, 1:0), (1:0, 1:0)) == false
        @test boxes_overlap((1:1, 1:0), (1:2, 1:1)) == false
        @test boxes_overlap((1:2, 5:7), (2:3, 3:4)) == false
        @test boxes_overlap((1:2, 5:7), (2:3, 7:10)) == true
    end

    @testset "box_from_catalog: run it and check maxradius" begin
        images = SampleData.get_sdss_images(4114, 3, 127)
        catalog = SampleData.get_sdss_catalog(4114, 3, 127)

        patches = [ImagePatch(img, box_from_catalog(img, entry; max_radius=25))
                   for entry in catalog, img in images]

        patch_widths = [length(p.box[1]) for p in patches]

        # check that all obey maxradius
        @test all(patch_widths .<= 51)

        # check that some radii are smaller than 20 (fairly arbitrary number)
        @test sum(patch_widths .<= 40) > length(patch_widths) / 2
    end
end


text:
# Arvind Prasadan
# 2019 January
# DMF Package
# Creates an Autocorrelation Matrix at a given lag

"""
	autocorr_mat(X, lags = 1)

Creates an Autocorrelation Matrix at a set of given lags.

# Arguments
- `X`: Data matrix: p dimensions/sensors x n samples
- `lags`: list of lags (Integral)

# Outputs
- `R`: Data cube of autocorrelation matrices: # lags x p x p
- `lags`: Lags used
"""
function autocorr_mat(X, lags = 1)

    p, n = size(X)

    # Subtract Mean
    mu = mean(X; dims = 2)
    X = X .- mu

    # Get Standard Deviations
    sigma = std(X; dims = 2)

    # Sanity check lags
    lags = abs.(Int.(round.(lags)))
    if 1 == length(lags)
        lags = [lags]
    else
        lags = [min(x, n - 1) for x in lags]
        lags = sort(unique(lags))
    end

    R_unshaped = autocor(X', lags)
    R = zeros(length(lags), p, p)
    for l = 1:1:length(lags)
        R[l, :, :] = hcat([circshift(R_unshaped[l, :], t)[:] for t in 0:1:(p - 1)]...)
    end

    return R, lags
end


text:
import QuadratureRules: @big, _big
import QuadratureRules: scale_weights, shift_nodes, shift!, unshift!

@testset "$(rpad("Utility Functions",80))" begin

    @test _big(1)    == BigFloat(1)
    @test _big(1//1) == BigFloat(1)
    @test _big(1.0)  == BigFloat(1)
    @test _big("1")  == BigFloat(1)
    @test _big(:(1)) == BigFloat(1)

    x = @big [1  2.0  1//3]
    y = big.([1  2.0  1//3])
    z = [big(1)  big(2.0)  big(1//3)]

    @test x != y
    @test x == z

    b = rand(5); b̃ = copy(b)
    c = rand(5); c̃ = copy(c)

    shift!(b̃, c̃)

    @test b̃ ≈ scale_weights(b)  atol=1E-14
    @test c̃ ≈ shift_nodes(c)    atol=1E-14

    unshift!(b̃, c̃)

    @test b̃ ≈ b  atol=1E-14
    @test c̃ ≈ c  atol=1E-14

end


text:
function rows2sparse(table; col_user = :userid, col_item = :itemid, col_rating = :rating)
    U = Int[]
    I = Int[]
    R = Float64[]

    for row in Tables.rows(table)
        push!(U, row[col_user])
        push!(I, row[col_item])
        push!(R, row[col_rating])
    end

    return sparse(U, I, R)
end

function reindex_id_column(table, col_id::Symbol)
    col = table |> TableOperations.select(col_id) |> Tables.columntable |> collect
    col = col[1]
    id2index = Dict(id => index for (index, id) in enumerate(unique(col)))
    reindexed_table = table |> TableOperations.transform(Dict(col_id => x -> id2index[x]))
    return Tables.materializer(table)(reindexed_table), id2index
end

function make_u2i_dataset(table; col_user = :userid, col_item = :itemid)
    user_actioned_items =
        Dict{Union{AbstractString,Int},Vector{Union{AbstractString,Int}}}()
    for row in Tables.rows(table)
        uid = row[col_user]
        iid = row[col_item]
        if uid in keys(user_actioned_items)
            push!(user_actioned_items[uid], iid)
        else
            user_actioned_items[uid] = [iid]
        end
    end
    xs = collect(keys(user_actioned_items))
    ys = collect(values(user_actioned_items))
    return xs, ys
end


text:
using NQCDynamics
using Test
using StatsBase: mean

b = RingPolymerArray(rand(2,3,4), quantum=[2])
beads = RingPolymers.RingPolymerParameters{Float64}(4, 1.0, [2])

@testset "transform!" begin
    b_original = deepcopy(b)
    RingPolymers.transform!(beads, b)
    @test !(b ≈ b_original)
    RingPolymers.transform!(beads, b)
    @test b ≈ b_original
end

@testset "setindex!" begin
    b[1,1,1] = 1.0
    @test all(b[1,1,:] .≈ 1.0) # Test all classical atoms set to 1
    b[1,2,1] = 1.0
    !(b[1,2,2] ≈ 1.0) # Test quantum atoms not all 1
end

@testset "similar" begin
    c = similar(b)
    @test c.quantum_atoms == b.quantum_atoms
    @test c.classical_atoms == b.classical_atoms
    @test c.normal == b.normal
end

@testset "get_centroid" begin
    b_original = deepcopy(b)
    centroid_original = RingPolymers.get_centroid(b)
    RingPolymers.transform!(beads, b)
    @test !(b ≈ b_original)
    centroid_middle = RingPolymers.get_centroid(b)
    RingPolymers.transform!(beads, b)
    @test b ≈ b_original
    centroid_final = RingPolymers.get_centroid(b)

    @test centroid_original ≈ centroid_middle ≈ centroid_final

    R = rand(size(b)...)
    centroid = dropdims(mean(R; dims=3); dims=3)
    @test centroid ≈ RingPolymers.get_centroid(R)
    out = similar(centroid) .+ 10
    RingPolymers.get_centroid!(out, R)
    @test centroid ≈ out
end

@testset "broadcasting" begin
    data = rand(2,3,4)
    A = RingPolymerArray(data, quantum=[2])

    test_data = copy(data)
    RingPolymers.constrain_classical_atoms!(test_data, A.classical_atoms)

    B = A ./ 10
    @test test_data ./ 10 ≈ B.data

    A ./= 10
    @test test_data ./ 10 ≈ A.data
end


text:
# Test name methods
@testset "Basics" begin
    # setup data
    m = InfiniteModel()
    @infinite_parameter(m, a in [0, 1])
    @infinite_parameter(m, b[1:3] in [0, 1], independent = true)
    @infinite_parameter(m, c[1:2] in [0, 1])
    @infinite_parameter(m, d in [0, 1])
    idx = InfiniteVariableIndex(1)
    num = Float64(0)
    func = (x) -> NaN
    func2 = (x...) -> 1
    info = VariableInfo(false, num, false, num, false, num, false, func, false, false)
    new_info = VariableInfo(true, 0., true, 0., true, 0., true, func2, true, false)
    var = InfiniteVariable(info, IC.VectorTuple(a, b[1:2], c, [b[3], d]),
                           [1:7...], [1:6...], true)
    var2 = InfiniteVariable(new_info, IC.VectorTuple(a, b[1:2], c, [b[3], d]),
                            [1:7...], [1:6...], true)
    object = VariableData(var, "var")
    vref = InfiniteVariableRef(m, idx)
    gvref = GeneralVariableRef(m, 1, InfiniteVariableIndex)
    bad_vref = InfiniteVariableRef(m, InfiniteVariableIndex(-1))
    # JuMP.owner_model
    @testset "JuMP.owner_model" begin
        @test owner_model(vref) === m
        @test owner_model(gvref) === m
    end
    # JuMP.index
    @testset "JuMP.index" begin
        @test index(vref) == idx
        @test index(gvref) == idx
    end
    # dispatch_variable_ref
    @testset "dispatch_variable_ref" begin
        @test dispatch_variable_ref(m, idx) == vref
        @test dispatch_variable_ref(gvref) == vref
    end
    # _add_data_object
    @testset "_add_data_object" begin
        @test InfiniteOpt._add_data_object(m, object) == idx
    end
    # _data_dictionary
    @testset "_data_dictionary" begin
        @test InfiniteOpt._data_dictionary(m, InfiniteVariable) === m.infinite_vars
        @test InfiniteOpt._data_dictionary(vref) === m.infinite_vars
        @test InfiniteOpt._data_dictionary(gvref) === m.infinite_vars
    end
    # JuMP.is_valid
    @testset "JuMP.is_valid" begin
        @test is_valid(m, vref)
        @test is_valid(m, gvref)
    end
    # _data_object
    @testset "_data_object" begin
        @test InfiniteOpt._data_object(vref) === object
        @test InfiniteOpt._data_object(gvref) === object
        @test_throws ErrorException InfiniteOpt._data_object(bad_vref)
    end
    # _core_variable_object
    @testset "_core_variable_object" begin
        @test InfiniteOpt._core_variable_object(vref) === var
        @test InfiniteOpt._core_variable_object(gvref) === var
    end
    # _set_core_variable_object
    @testset "_set_core_variable_object" begin
        @test InfiniteOpt._set_core_variable_object(vref, var) isa Nothing
        @test InfiniteOpt._set_core_variable_object(vref, var2) isa Nothing
        @test InfiniteOpt._set_core_variable_object(vref, var) isa Nothing
    end
    # _object_numbers
    @testset "_object_numbers" begin
        @test InfiniteOpt._object_numbers(vref) == [1:6...]
    end
    # _parameter_numbers
    @testset "_parameter_numbers" begin
        @test InfiniteOpt._parameter_numbers(vref) == [1:7...]
    end
    # test _variable_info
    @testset "_variable_info" begin
        @test InfiniteOpt._variable_info(vref) == info
    end
    # test _is_vector_start
    @testset "_is_vector_start" begin
        @test InfiniteOpt._is_vector_start(vref)
    end
    # _update_variable_info
    @testset "_update_variable_info" begin
        @test isa(InfiniteOpt._update_variable_info(vref, new_info), Nothing)
        @test InfiniteOpt._variable_info(vref) == new_info
    end
    # _measure_dependencies
    @testset "_measure_dependencies" begin
        @test InfiniteOpt._measure_dependencies(vref) == MeasureIndex[]
        @test InfiniteOpt._measure_dependencies(gvref) == MeasureIndex[]
    end
    # _constraint_dependencies
    @testset "_constraint_dependencies" begin
        @test InfiniteOpt._constraint_dependencies(vref) == InfOptConstraintIndex[]
        @test InfiniteOpt._constraint_dependencies(gvref) == InfOptConstraintIndex[]
    end
    # _semi_infinite_variable_dependencies
    @testset "_semi_infinite_variable_dependencies" begin
        @test InfiniteOpt._semi_infinite_variable_dependencies(vref) == SemiInfiniteVariableIndex[]
        @test InfiniteOpt._semi_infinite_variable_dependencies(gvref) == SemiInfiniteVariableIndex[]
    end
    # _point_variable_dependencies
    @testset "_point_variable_dependencies" begin
        @test InfiniteOpt._point_variable_dependencies(vref) == PointVariableIndex[]
        @test InfiniteOpt._point_variable_dependencies(gvref) == PointVariableIndex[]
    end
    # _derivative_dependencies
    @testset "_derivative_dependencies" begin
        @test InfiniteOpt._derivative_dependencies(vref) == DerivativeIndex[]
        @test InfiniteOpt._derivative_dependencies(gvref) == DerivativeIndex[]
    end
    # JuMP.name
    @testset "JuMP.name" begin
        @test name(vref) == "var"
        @test name(gvref) == "var"
        @test name(bad_vref) == ""
    end
    # raw_parameter_refs
    @testset "raw_parameter_refs" begin
        @test raw_parameter_refs(vref) == IC.VectorTuple(a, b[1:2], c, [b[3], d])
        @test raw_parameter_refs(gvref) == IC.VectorTuple(a, b[1:2], c, [b[3], d])
    end
    # parameter_refs
    @testset "parameter_refs" begin
        @test parameter_refs(vref) == (a, b[1:2], c, [b[3], d])
        @test parameter_refs(gvref) == (a, b[1:2], c, [b[3], d])
    end
    # parameter_list
    @testset "parameter_list" begin
        @test parameter_list(vref) == [a; b[1:2]; c; [b[3], d]]
        @test parameter_list(gvref) == [a; b[1:2]; c; [b[3], d]]
        @test parameter_list(raw_parameter_refs(vref)) == [a; b[1:2]; c; [b[3], d]]
    end
    # JuMP.set_name
    @testset "JuMP.set_name" begin
        # test default
        @test isa(set_name(vref, ""), Nothing)
        @test name(vref) == ""
        @test_throws ErrorException set_name(bad_vref, "")
        # test normal
        @test isa(set_name(gvref, "new"), Nothing)
        @test name(vref) == "new"
    end
    # _make_variable_ref
    @testset "_make_variable_ref" begin
        @test InfiniteOpt._make_variable_ref(m, idx) == gvref
    end
    # _var_name_dict
    @testset "_var_name_dict" begin
        @test InfiniteOpt._var_name_dict(m) isa Nothing
    end
    # _update_var_name_dict
    @testset "_update_var_name_dict" begin
        m.name_to_var = Dict{String, ObjectIndex}()
        dict = InfiniteOpt._data_dictionary(vref)
        @test InfiniteOpt._update_var_name_dict(m, dict) isa Nothing
        @test InfiniteOpt._var_name_dict(m) == Dict(name(vref) => idx)
        m.name_to_var = nothing
    end
    # parameter_by_name
    @testset "JuMP.variable_by_name" begin
        # test normal
        @test variable_by_name(m, "new") == gvref
        @test variable_by_name(m, "test") isa Nothing
        # prepare variable with same name
        idx2 = InfiniteVariableIndex(2)
        @test InfiniteOpt._add_data_object(m, object) == idx2
        vref2 = InfiniteVariableRef(m, idx2)
        @test set_name(vref2, "new") isa Nothing
        # test multiple name error
        @test_throws ErrorException variable_by_name(m, "new")
    end
    # _delete_data_object
    @testset "_delete_data_object" begin
        @test InfiniteOpt._delete_data_object(vref) isa Nothing
        @test length(InfiniteOpt._data_dictionary(vref)) == 1
        @test !is_valid(m, vref)
    end
end

# Test variable definition methods
@testset "Definition" begin
    # initialize model and infinite variable info
    m = InfiniteModel()
    @infinite_parameter(m, pref in [0, 1])
    @infinite_parameter(m, pref2 in [0, 1])
    @infinite_parameter(m, prefs[1:2] in [0, 1])
    @finite_parameter(m, fin == 42)
    num = Float64(0)
    func1 = (a) -> 2
    info = VariableInfo(false, num, false, num, false, num, false, NaN, false, false)
    info2 = VariableInfo(true, num, true, num, true, num, true, func1, true, false)
    info3 = VariableInfo(true, num, true, num, true, num, true, 42, false, true)
    # test Infinite
    @testset "Infinite{VT}" begin
        @test Infinite(pref, prefs).parameter_refs isa IC.VectorTuple
        @test Infinite(pref).parameter_refs.values == [pref]
        @test Infinite(pref, prefs, pref2).parameter_refs.values == [pref, prefs..., pref2]
    end
    # _check_tuple_element (IndependentParameterRefs)
    @testset "_check_tuple_element (IndependentParameterRefs)" begin
        iprefs = dispatch_variable_ref.([pref, pref2])
        @test InfiniteOpt._check_tuple_element(error, iprefs) isa Nothing
    end
    # _check_tuple_element (DependentParameterRefs)
    @testset "_check_tuple_element (DependentParameterRefs)" begin
        dprefs = dispatch_variable_ref.(prefs)
        @test InfiniteOpt._check_tuple_element(error, dprefs) isa Nothing
        @test_throws ErrorException InfiniteOpt._check_tuple_element(error, dprefs[1:1])
    end
    # _check_tuple_element (Fallback)
    @testset "_check_tuple_element (Fallback)" begin
        refs = dispatch_variable_ref.([fin, pref])
        @test_throws ErrorException InfiniteOpt._check_tuple_element(error, refs)
    end
    # _check_parameter_tuple
    @testset "_check_parameter_tuple" begin
        # test normal
        tuple = IC.VectorTuple((pref, prefs, pref2))
        @test InfiniteOpt._check_parameter_tuple(error, tuple) isa Nothing
        tuple = IC.VectorTuple(([pref, pref2], prefs))
        @test InfiniteOpt._check_parameter_tuple(error, tuple) isa Nothing
        # test bad
        tuple = IC.VectorTuple((pref, pref))
        @test_throws ErrorException InfiniteOpt._check_parameter_tuple(error, tuple)
        tuple = IC.VectorTuple((pref, [prefs[1], pref2]))
        @test_throws ErrorException InfiniteOpt._check_parameter_tuple(error, tuple)
        tuple = IC.VectorTuple(fin)
        @test_throws ErrorException InfiniteOpt._check_parameter_tuple(error, tuple)
        tuple = IC.VectorTuple(2)
        @test_throws ErrorException InfiniteOpt._check_parameter_tuple(error, tuple)
    end
    # _check_and_format_infinite_info (Real)
    @testset "_check_and_format_infinite_info (Real)" begin
        tuple = IC.VectorTuple((pref, prefs, pref2))
        @test !InfiniteOpt._check_and_format_infinite_info(error, info, tuple)[1].has_start
        @test InfiniteOpt._check_and_format_infinite_info(error, info, tuple)[1].start isa Function
        @test InfiniteOpt._check_and_format_infinite_info(error, info, tuple)[2]
        @test InfiniteOpt._check_and_format_infinite_info(error, info3, tuple)[1].has_start
        @test InfiniteOpt._check_and_format_infinite_info(error, info3, tuple)[1].start isa Function
        @test InfiniteOpt._check_and_format_infinite_info(error, info3, tuple)[2]
    end
    # _check_and_format_infinite_info (Function)
    @testset "_check_and_format_infinite_info (Function)" begin
        tuple = IC.VectorTuple((pref,))
        # test normal
        @test InfiniteOpt._check_and_format_infinite_info(error, info2, tuple)[1].has_start
        @test InfiniteOpt._check_and_format_infinite_info(error, info2, tuple)[1].start == func1
        @test !InfiniteOpt._check_and_format_infinite_info(error, info2, tuple)[2]
        # test multiple methods
        mult_func(a,b,c) = 2
        mult_func(a) = 2
        mult_info = VariableInfo(true, num, true, num, true, num, true, mult_func, true, false)
        @test InfiniteOpt._check_and_format_infinite_info(error, mult_info, tuple)[1] isa VariableInfo
        # test bad method
        bad_func(a, b) = 2
        bad_info = VariableInfo(true, num, true, num, true, num, true, bad_func, true, false)
        @test_throws ErrorException InfiniteOpt._check_and_format_infinite_info(error, bad_info, tuple)
        # test bad args
        func = (a, b) -> a + sum(b)
        bad_info = VariableInfo(true, num, true, num, true, num, true, func, true, false)
        @test_throws ErrorException InfiniteOpt._check_and_format_infinite_info(error, bad_info, tuple)
    end
    # _check_and_format_infinite_info (Fallback)
    @testset "_check_and_format_infinite_info (Fallback)" begin
        tuple = IC.VectorTuple((pref, prefs, pref2))
        bad_info = VariableInfo(true, num, true, num, true, num, true, Complex(1), true, false)
        @test_throws ErrorException InfiniteOpt._check_and_format_infinite_info(error, bad_info, tuple)
    end
    # build_variable
    @testset "JuMP.build_variable" begin
        # test for each error message
        @test_throws ErrorException build_variable(error, info, Infinite(pref),
                                                   bob = 42)
        @test_throws ErrorException build_variable(error, info, Infinite())
        @test_throws ErrorException build_variable(error, info, Infinite(pref, fin))
        @test_throws ErrorException build_variable(error, info, Infinite(pref, pref))
        # test for expected output
        @test build_variable(error, info, Infinite(pref)).info isa JuMP.VariableInfo{Float64, Float64, Float64, <:Function}
        @test build_variable(error, info, Infinite(pref)).parameter_refs == IC.VectorTuple(pref)
        # test various types of param tuples
        tuple = IC.VectorTuple(pref, prefs)
        @test build_variable(error, info, Infinite(pref, prefs)).parameter_refs == tuple
        tuple = IC.VectorTuple(prefs)
        @test build_variable(error, info, Infinite(prefs)).parameter_refs == tuple
        @test build_variable(error, info, Infinite(prefs)).parameter_nums == [3, 4]
        @test build_variable(error, info, Infinite(prefs)).object_nums == [3]
    end
    # _check_parameters_valid
    @testset "_check_parameters_valid" begin
        # prepare param tuple
        @infinite_parameter(InfiniteModel(), pref3 in [0, 1])
        tuple = IC.VectorTuple((pref, prefs, pref3))
        # test that catches error
        @test_throws VariableNotOwned{GeneralVariableRef} InfiniteOpt._check_parameters_valid(m, tuple)
        # test normal
        tuple = IC.VectorTuple(pref, pref2)
        @test InfiniteOpt._check_parameters_valid(m, tuple) isa Nothing
    end
    # _update_param_var_mapping
    @testset "_update_param_var_mapping" begin
        # prepare tuple
        tuple = IC.VectorTuple(pref, prefs)
        idx = InfiniteVariableIndex(1)
        ivref = InfiniteVariableRef(m, idx)
        # test normal
        @test InfiniteOpt._update_param_var_mapping(ivref, tuple) isa Nothing
        @test InfiniteOpt._infinite_variable_dependencies(pref) == [idx]
        @test InfiniteOpt._infinite_variable_dependencies(prefs[1]) == [idx]
        @test InfiniteOpt._infinite_variable_dependencies(prefs[2]) == [idx]
        # undo changes
        empty!(InfiniteOpt._infinite_variable_dependencies(pref))
        empty!(InfiniteOpt._infinite_variable_dependencies(prefs[1]))
        empty!(InfiniteOpt._infinite_variable_dependencies(prefs[2]))
    end
    # _check_and_make_variable_ref
    @testset "_check_and_make_variable_ref" begin
        # prepare secondary model and parameter and variable
        m2 = InfiniteModel()
        @infinite_parameter(m2, pref3 in [0, 1])
        v = build_variable(error, info, Infinite(pref3))
        # test for error of invalid variable
        @test_throws VariableNotOwned{GeneralVariableRef} InfiniteOpt._check_and_make_variable_ref(m, v, "")
        # test normal
        idx = InfiniteVariableIndex(1)
        vref = InfiniteVariableRef(m2, idx)
        @test InfiniteOpt._check_and_make_variable_ref(m2, v, "") == vref
        @test InfiniteOpt._infinite_variable_dependencies(pref3) == [idx]
        # test with other variable object
        @test_throws ArgumentError InfiniteOpt._check_and_make_variable_ref(m, :bad, "")
    end
    # add_variable
    @testset "JuMP.add_variable" begin
        # prepare secondary model and parameter and variable
        m2 = InfiniteModel()
        @infinite_parameter(m2, pref3 in [0, 1])
        v = build_variable(error, info, Infinite(pref3))
        # test for error of invalid variable
        @test_throws VariableNotOwned{GeneralVariableRef} add_variable(m, v)
        # prepare normal variable
        v = build_variable(error, info, Infinite(pref))
        # test normal
        idx = InfiniteVariableIndex(1)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test add_variable(m, v, "name") == gvref
        @test haskey(InfiniteOpt._data_dictionary(vref), idx)
        @test InfiniteOpt._core_variable_object(vref) == v
        @test InfiniteOpt._infinite_variable_dependencies(pref) == [idx]
        @test name(vref) == "name"
        # prepare infinite variable with all the possible info additions
        v = build_variable(error, info2, Infinite(pref))
        # test info addition functions
        idx = InfiniteVariableIndex(2)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test add_variable(m, v, "name") == gvref
        @test !optimizer_model_ready(m)
        @test !InfiniteOpt._is_vector_start(vref)
        @test InfiniteOpt._variable_info(vref).start == func1
        # lower bound
        cindex = InfOptConstraintIndex(1)
        cref = InfOptConstraintRef(m, cindex)
        @test has_lower_bound(vref)
        @test InfiniteOpt._lower_bound_index(vref) == cindex
        @test constraint_object(cref) isa ScalarConstraint{GeneralVariableRef,
                                                           MOI.GreaterThan{Float64}}
        @test InfiniteOpt._data_object(cref).is_info_constraint
        # upper bound
        cindex = InfOptConstraintIndex(2)
        cref = InfOptConstraintRef(m, cindex)
        @test has_upper_bound(vref)
        @test InfiniteOpt._upper_bound_index(vref) == cindex
        @test constraint_object(cref) isa ScalarConstraint{GeneralVariableRef,
                                                           MOI.LessThan{Float64}}
        @test InfiniteOpt._data_object(cref).is_info_constraint
        # fix
        cindex = InfOptConstraintIndex(3)
        cref = InfOptConstraintRef(m, cindex)
        @test is_fixed(vref)
        @test InfiniteOpt._fix_index(vref) == cindex
        @test constraint_object(cref) isa ScalarConstraint{GeneralVariableRef,
                                                           MOI.EqualTo{Float64}}
        @test InfiniteOpt._data_object(cref).is_info_constraint
        # binary
        cindex = InfOptConstraintIndex(4)
        cref = InfOptConstraintRef(m, cindex)
        @test is_binary(vref)
        @test InfiniteOpt._binary_index(vref) == cindex
        @test constraint_object(cref) isa ScalarConstraint{GeneralVariableRef,
                                                           MOI.ZeroOne}
        @test InfiniteOpt._data_object(cref).is_info_constraint
        @test InfiniteOpt._constraint_dependencies(vref) == [InfOptConstraintIndex(i)
                                                             for i = 1:4]
        # prepare infinite variable with integer info addition
        v = build_variable(error, info3, Infinite(pref))
        # test integer addition functions
        idx = InfiniteVariableIndex(3)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test add_variable(m, v, "name") == gvref
        @test !optimizer_model_ready(m)
        @test InfiniteOpt._is_vector_start(vref)
        @test InfiniteOpt._variable_info(vref).start isa Function
        cindex = InfOptConstraintIndex(8)
        cref = InfOptConstraintRef(m, cindex)
        @test is_integer(vref)
        @test InfiniteOpt._integer_index(vref) == cindex
        @test constraint_object(cref) isa ScalarConstraint{GeneralVariableRef,
                                                           MOI.Integer}
        @test InfiniteOpt._data_object(cref).is_info_constraint
        @test InfiniteOpt._constraint_dependencies(vref) == [InfOptConstraintIndex(i)
                                                             for i = 5:8]
    end
end

# Test the infinite variable macro
@testset "Macro Definition" begin
    # initialize model and infinite parameters
    m = InfiniteModel()
    @infinite_parameter(m, t in [0, 1])
    @infinite_parameter(m, x[1:2] in [-1, 1])
    # test single variable definition
    @testset "Single" begin
        # test basic defaults
        idx = InfiniteVariableIndex(1)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, variable_type = Infinite(t)) == gvref
        @test name(vref) == ""
        # test more tuple input and variable details
        idx = InfiniteVariableIndex(2)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, variable_type = Infinite(t, x), base_name = "test",
                        binary = true) == gvref
        @test name(vref) == "test"
        @test is_binary(vref)
        # test nonanonymous with simple single arg
        idx = InfiniteVariableIndex(3)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, a, Infinite(x)) == gvref
        @test name(vref) == "a"
        # test nonanonymous with complex single arg
        idx = InfiniteVariableIndex(4)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, 0 <= b <= 1, Infinite(x)) == gvref
        @test name(vref) == "b"
        @test lower_bound(vref) == 0
        @test upper_bound(vref) == 1
        # test nonanonymous with reversed single arg
        idx = InfiniteVariableIndex(5)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, 0 <= c, Infinite(t)) == gvref
        @test name(vref) == "c"
        @test lower_bound(vref) == 0
        # test multi-argument expr 1
        idx = InfiniteVariableIndex(6)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, d == 0, Infinite(t), Int, base_name = "test") == gvref
        @test name(vref) == "test"
        @test fix_value(vref) == 0
        # test single start value
        idx = InfiniteVariableIndex(7)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        @test @variable(m, aa, Infinite(t), Int, start = 42) == gvref
        @test name(vref) == "aa"
        @test start_value_function(vref) isa Function
        @test start_value_function(vref)([0]) == 42
        @test_throws MethodError start_value_function(vref)(0)
        # test function start value
        idx = InfiniteVariableIndex(8)
        vref = InfiniteVariableRef(m, idx)
        gvref = InfiniteOpt._make_variable_ref(m, idx)
        func = (a) -> a
        @test @variable(m, ab, Infinite(t), Int, start = func) == gvref
        @test name(vref) == "ab"
        @test start_value_function(vref) isa Function
        @test start_value_function(vref)(0) == 0
    end
    # test array variable definition
    @testset "Array" begin
        # test anonymous array
        idxs = [InfiniteVariableIndex(9), InfiniteVariableIndex(10)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        @test @variable(m, [1:2], variable_type = Infinite(t)) == gvrefs
        @test name(vrefs[1]) == ""
        # test basic param expression
        idxs = [InfiniteVariableIndex(11), InfiniteVariableIndex(12)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        @test @variable(m, e[1:2], variable_type = Infinite(t, x)) == gvrefs
        @test name(vrefs[2]) == "e[2]"
        # test comparison without params
        idxs = [InfiniteVariableIndex(13), InfiniteVariableIndex(14)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        @test @variable(m, 0 <= f[1:2] <= 1, Infinite(t, x)) == gvrefs
        @test name(vrefs[2]) == "f[2]"
        @test lower_bound(vrefs[1]) == 0
        @test upper_bound(vrefs[2]) == 1
        # test comparison with call
        idxs = [InfiniteVariableIndex(15), InfiniteVariableIndex(16)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        @test @variable(m, 0 <= g[1:2] <= 1, Infinite(t)) == gvrefs
        @test name(vrefs[1]) == "g[1]"
        @test lower_bound(vrefs[1]) == 0
        @test upper_bound(vrefs[2]) == 1
        # test fixed
        idxs = [InfiniteVariableIndex(17), InfiniteVariableIndex(18)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        @test @variable(m, h[i = 1:2] == ones(2)[i], Infinite(t)) == gvrefs
        @test name(vrefs[1]) == "h[1]"
        @test fix_value(vrefs[1]) == 1
        # test containers
        idxs = [InfiniteVariableIndex(19), InfiniteVariableIndex(20)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        svrefs = convert(JuMP.Containers.SparseAxisArray, gvrefs)
        @test @variable(m, [1:2], Infinite(t),
                        container = SparseAxisArray) isa JuMPC.SparseAxisArray
        @test name(vrefs[1]) == ""
        # test scalar starts
        idxs = [InfiniteVariableIndex(21), InfiniteVariableIndex(22)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        starts = [2, 5]
        @test @variable(m, w[i = 1:2], Infinite(t), start = starts[i]) == gvrefs
        @test start_value_function(vrefs[1])([0]) == 2
        @test start_value_function(vrefs[2])([0]) == 5
        # test mixed starts
        idxs = [InfiniteVariableIndex(23), InfiniteVariableIndex(24)]
        vrefs = [InfiniteVariableRef(m, idx) for idx in idxs]
        gvrefs = [InfiniteOpt._make_variable_ref(m, idx) for idx in idxs]
        starts = [(a) -> 2, 5]
        @test @variable(m, cat[i = 1:2], Infinite(t),
                        start = starts[i]) == gvrefs
        @test start_value_function(vrefs[1])(0) == 2
        @test start_value_function(vrefs[2])([0]) == 5
    end
    # test errors
    @testset "Errors" begin
        # test deprecation
        @test_macro_throws ErrorException @infinite_variable(m, z(t))
        # test invalid keyword arguments
        @test_macro_throws ErrorException @variable(m, i, Infinite(t),
                                                    parameter_values = 1)
        # test name duplication
        @test_macro_throws ErrorException @variable(m, a, Infinite(t), Int)
        # test bad start function
        @test_macro_throws ErrorException @variable(m, zz, Infinite(t),
                                                    start = (a, b) -> 2)
    end
end

# Test variable(s) constrained on creation
@testset "Creation Constraints" begin
    # initialize model and stuff
    m = InfiniteModel()
    @infinite_parameter(m, t in [0, 1])
    @infinite_parameter(m, x[1:2] in [-1, 1])
    info = VariableInfo(false, NaN, false, NaN, false, NaN, false, NaN, false, false)
    v1 = build_variable(error, info, Infinite(t))
    v2 = build_variable(error, info, Infinite(t, x))
    # test add_variable with VariableConstrainedOnCreation
    @testset "Adding VariableConstrainedOnCreation" begin
        v = VariableConstrainedOnCreation(v1, MOI.Integer())
        vref = GeneralVariableRef(m, 1, InfiniteVariableIndex)
        @test add_variable(m, v, "test") == vref
        @test name(vref) == "test"
        @test num_constraints(m, MOI.Integer) == 1
    end
    # test add_variable with VariablesConstrainedOnCreation
    @testset "Adding VariablesConstrainedOnCreation" begin
        v = VariablesConstrainedOnCreation([v1, v2, v1], MOI.SecondOrderCone(3),
                                           VectorShape())
        vrefs = [GeneralVariableRef(m, i, InfiniteVariableIndex) for i in 2:4]
        names = ["test[$i]" for i in 1:3]
        @test add_variable(m, v, names) == vrefs
        @test name.(vrefs) == names
        @test num_constraints(m, MOI.SecondOrderCone) == 1
    end
end

# test usage methods
@testset "Usage" begin
    # initialize model and stuff
    m = InfiniteModel()
    @infinite_parameter(m, t in [0, 1])
    @infinite_parameter(m, x[1:2] in [-1, 1])
    @variable(m, y, Infinite(t, x))
    vref = dispatch_variable_ref(y)
    # test used_by_semi_infinite_variable
    @testset "used_by_semi_infinite_variable" begin
        @test !used_by_semi_infinite_variable(vref)
        push!(InfiniteOpt._semi_infinite_variable_dependencies(vref),
              SemiInfiniteVariableIndex(1))
        @test used_by_semi_infinite_variable(y)
        @test used_by_semi_infinite_variable(vref)
        empty!(InfiniteOpt._semi_infinite_variable_dependencies(vref))
    end
    # test used_by_point_variable
    @testset "used_by_point_variable" begin
        @test !used_by_point_variable(vref)
        push!(InfiniteOpt._point_variable_dependencies(vref), PointVariableIndex(1))
        @test used_by_point_variable(y)
        @test used_by_point_variable(vref)
        empty!(InfiniteOpt._point_variable_dependencies(vref))
    end
    # test used_by_derivative
    @testset "used_by_derivative" begin
        @test !used_by_derivative(vref)
        push!(InfiniteOpt._derivative_dependencies(vref), DerivativeIndex(1))
        @test used_by_derivative(y)
        @test used_by_derivative(vref)
        empty!(InfiniteOpt._derivative_dependencies(vref))
    end
    # test used_by_measure
    @testset "used_by_measure" begin
        @test !used_by_measure(vref)
        push!(InfiniteOpt._measure_dependencies(vref), MeasureIndex(1))
        @test used_by_measure(y)
        @test used_by_measure(vref)
        empty!(InfiniteOpt._measure_dependencies(vref))
    end
    # test used_by_constraint
    @testset "used_by_constraint" begin
        @test !used_by_constraint(vref)
        push!(InfiniteOpt._constraint_dependencies(vref), InfOptConstraintIndex(1))
        @test used_by_constraint(y)
        @test used_by_constraint(vref)
        empty!(InfiniteOpt._constraint_dependencies(vref))
    end
    # test used_by_objective
    @testset "used_by_objective" begin
        @test !used_by_objective(y)
        @test !used_by_objective(vref)
    end
    # test is_used
    @testset "is_used" begin
        # test not used
        @test !is_used(vref)
        # test used by constraint and/or measure
        push!(InfiniteOpt._constraint_dependencies(vref), InfOptConstraintIndex(1))
        @test is_used(y)
        empty!(InfiniteOpt._constraint_dependencies(vref))
        # test used by point variable
        num = Float64(0)
        info = VariableInfo(false, num, false, num, false, num, false, num, false, false)
        var = PointVariable(info, y, [0., 0., 0.])
        object = VariableData(var, "var")
        idx = PointVariableIndex(1)
        pvref = PointVariableRef(m, idx)
        @test InfiniteOpt._add_data_object(m, object) == idx
        push!(InfiniteOpt._point_variable_dependencies(vref), idx)
        @test !is_used(vref)
        push!(InfiniteOpt._constraint_dependencies(pvref), InfOptConstraintIndex(2))
        @test is_used(vref)
        empty!(InfiniteOpt._point_variable_dependencies(vref))
        # test used by semi-infinite variable
        eval_supps = Dict{Int, Float64}(1 => 0.5, 3 => 1)
        var = SemiInfiniteVariable(y, eval_supps, [2], [2])
        object = VariableData(var, "var")
        idx = SemiInfiniteVariableIndex(1)
        rvref = SemiInfiniteVariableRef(m, idx)
        @test InfiniteOpt._add_data_object(m, object) == idx
        push!(InfiniteOpt._semi_infinite_variable_dependencies(vref), idx)
        @test !is_used(vref)
        push!(InfiniteOpt._constraint_dependencies(rvref), InfOptConstraintIndex(2))
        @test is_used(vref)
        empty!(InfiniteOpt._semi_infinite_variable_dependencies(vref))
        # test used by derivative
        func = (x) -> NaN
        num = 0.
        info = VariableInfo{Float64, Float64, Float64, Function}(true, num, true,
                                         num, true, num, false, func, true, true)
        deriv = Derivative(info, true, y, t)
        object = VariableData(deriv)
        idx = DerivativeIndex(1)
        dref = DerivativeRef(m, idx)
        @test InfiniteOpt._add_data_object(m, object) == idx
        push!(InfiniteOpt._derivative_dependencies(vref), idx)
        @test !is_used(vref)
        push!(InfiniteOpt._constraint_dependencies(dref), InfOptConstraintIndex(2))
        @test is_used(vref)
        empty!(InfiniteOpt._derivative_dependencies(vref))
    end
end


text:
module MirroredArrayViews

import Base: size, getindex, setindex!, similar

export MirroredArrayView

"""
`MirroredArrayView(arr::AbstractArray, dims...)`

Construct a view of array `arr` mirrored along each dimension in `dims`.
Repeated dimensions will be ignored. The mirrored dimensions become part of
the type of the view and no data is copied.
"""
struct MirroredArrayView{D, N, T, ARR} <: AbstractArray{T, N}
    data::ARR

    function MirroredArrayView(arr::AbstractArray{T, N},
                               dims::Int...;
                               checkdims::Val{B}=Val(true)) where {T, N, B}
        if B
            for dim in dims
                if !(dim >= 1 && dim <= N)
                    throw(BoundsError(arr, "Expect dim <= N; dim = $dim, N = $N"))
                end
            end
        end
        new{(dims...,), N, T, typeof(arr)}(arr)
    end
end

size(A::MirroredArrayView) = size(A.data)

# This generates an expression consisting of tuple broadcasting to
# convert a cartesian index into its mirrored version in a manner the
# compiler can optimize away as much as possible.
@generated function mirror_indices(A::MirroredArrayView{D, N},
                                   indices::NTuple{N, I}
                                  ) where {D, N} where I <: Integer
    dim_mask = ( (i in D for i ∈ 1:N)..., )
    mult_mask = -2 .* dim_mask .+ 1

    quote
        indices .* $mult_mask .+ (size(A) .+ 1) .* $dim_mask
    end
end

function getindex(A::MirroredArrayView{D, N}, indices::Vararg{I, N}
                 ) where {D, N} where I <: Integer
    A.data[mirror_indices(A, indices)...]
end

function setindex!(A::MirroredArrayView{D, N}, v, indices::Vararg{I, N}
                  ) where {D, N} where I <: Integer
    A.data[mirror_indices(A, indices)...] = v
end

function similar(A::MirroredArrayView{D}) where D
    # Use the checkdims keyword to skip overhead of checking dimensions
    # when calling similar.
    MirroredArrayView(similar(A.data), D..., checkdims=Val(false))
end

end # module

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
using Test

@testset "Galois field tests" begin
    include("galois_fields.jl")
end

@testset "Elliptic curve primitive tests" begin
    include("elliptic_curves.jl")
end

@testset "Testing NIST elliptic curves" begin
    include("curve_specs.jl")
end

@testset "Testing external fields" begin
    include("../examples/external_fields.jl")
end

@testset "Testing Specs module" begin
    include("spec.jl")
    include("primitives.jl")
    include("gbasis.jl")
    include("gecbasis.jl")
    include("conversions.jl")
    include("ecdsa/ecdsa_prime.jl")
    include("ecdsa/ecdsa_pb.jl")
    # It would be great to have a gaussian normal basis
end

@testset "Testing groups and ElGamal" begin
    include("groups.jl")
    include("elgamal.jl")
end