text:
module FramesWrapper

using JavaCall

const AbsoluteDate = @jimport org.orekit.time.AbsoluteDate
const AbstractEopLoader = @jimport org.orekit.frames.AbstractEopLoader
const AbstractFrames = @jimport org.orekit.frames.AbstractFrames
const AngularCoordinates = @jimport org.orekit.utils.AngularCoordinates
const AngularDerivativesFilter = @jimport org.orekit.utils.AngularDerivativesFilter
const BodyShape = @jimport org.orekit.bodies.BodyShape
const BulletinAFilesLoader = @jimport org.orekit.frames.BulletinAFilesLoader
const BulletinBFilesLoader = @jimport org.orekit.frames.BulletinBFilesLoader
const CIRFProvider = @jimport org.orekit.frames.CIRFProvider
const CR3BPRotatingFrame = @jimport org.orekit.frames.CR3BPRotatingFrame
const CR3BPRotatingTransformProvider = @jimport org.orekit.frames.CR3BPRotatingTransformProvider
const CartesianDerivativesFilter = @jimport org.orekit.utils.CartesianDerivativesFilter
const CelestialBodies = @jimport org.orekit.bodies.CelestialBodies
const CelestialBody = @jimport org.orekit.bodies.CelestialBody
const Class = @jimport java.lang.Class
const Collection = @jimport java.util.Collection
const DataProvidersManager = @jimport org.orekit.data.DataProvidersManager
const EOPBasedTransformProvider = @jimport org.orekit.frames.EOPBasedTransformProvider
const EOPC04FilesLoader = @jimport org.orekit.frames.EOPC04FilesLoader
const EOPEntry = @jimport org.orekit.frames.EOPEntry
const EOPHistory = @jimport org.orekit.frames.EOPHistory
const EOPHistoryLoader = @jimport org.orekit.frames.EOPHistoryLoader
const EOPHistoryLoader_Parser = @jimport org.orekit.frames.EOPHistoryLoader$Parser
const EclipticProvider = @jimport org.orekit.frames.EclipticProvider
const Enum = @jimport java.lang.Enum
const EopParserLoader = @jimport org.orekit.frames.EopParserLoader
const FactoryManagedFrame = @jimport org.orekit.frames.FactoryManagedFrame
const Field = @jimport org.hipparchus.Field
const FieldAbsoluteDate = @jimport org.orekit.time.FieldAbsoluteDate
const FieldAngularCoordinates = @jimport org.orekit.utils.FieldAngularCoordinates
const FieldGeodeticPoint = @jimport org.orekit.bodies.FieldGeodeticPoint
const FieldLine = @jimport org.hipparchus.geometry.euclidean.threed.FieldLine
const FieldPVCoordinates = @jimport org.orekit.utils.FieldPVCoordinates
const FieldPoleCorrection = @jimport org.orekit.frames.FieldPoleCorrection
const FieldRotation = @jimport org.hipparchus.geometry.euclidean.threed.FieldRotation
const FieldTransform = @jimport org.orekit.frames.FieldTransform
const FieldTransformGenerator = @jimport org.orekit.frames.FieldTransformGenerator
const FieldVector3D = @jimport org.hipparchus.geometry.euclidean.threed.FieldVector3D
const FixedTransformProvider = @jimport org.orekit.frames.FixedTransformProvider
const Frame = @jimport org.orekit.frames.Frame
const Frames = @jimport org.orekit.frames.Frames
const FramesFactory = @jimport org.orekit.frames.FramesFactory
const GTODProvider = @jimport org.orekit.frames.GTODProvider
const GeodeticPoint = @jimport org.orekit.bodies.GeodeticPoint
const HelmertTransformation = @jimport org.orekit.frames.HelmertTransformation
const IERSConventions = @jimport org.orekit.utils.IERSConventions
const IERSConventions_NutationCorrectionConverter = @jimport org.orekit.utils.IERSConventions$NutationCorrectionConverter
const ITRFProvider = @jimport org.orekit.frames.ITRFProvider
const ITRFVersion = @jimport org.orekit.frames.ITRFVersion
const ITRFVersionLoader = @jimport org.orekit.frames.ITRFVersionLoader
const ITRFVersionLoader_ITRFVersionConfiguration = @jimport org.orekit.frames.ITRFVersionLoader$ITRFVersionConfiguration
const ITRFVersion_Converter = @jimport org.orekit.frames.ITRFVersion$Converter
const InputStream = @jimport java.io.InputStream
const InterpolatingTransformProvider = @jimport org.orekit.frames.InterpolatingTransformProvider
const ItrfVersionProvider = @jimport org.orekit.frames.ItrfVersionProvider
const JString = @jimport java.lang.String
const L1Frame = @jimport org.orekit.frames.L1Frame
const L1TransformProvider = @jimport org.orekit.frames.L1TransformProvider
const L2Frame = @jimport org.orekit.frames.L2Frame
const L2TransformProvider = @jimport org.orekit.frames.L2TransformProvider
const LOFType = @jimport org.orekit.frames.LOFType
const LazyLoadedEop = @jimport org.orekit.frames.LazyLoadedEop
const LazyLoadedFrames = @jimport org.orekit.frames.LazyLoadedFrames
const Line = @jimport org.hipparchus.geometry.euclidean.threed.Line
const List = @jimport java.util.List
const LocalOrbitalFrame = @jimport org.orekit.frames.LocalOrbitalFrame
const MODProvider = @jimport org.orekit.frames.MODProvider
const Object = @jimport java.lang.Object
const Optional = @jimport java.util.Optional
const OrphanFrame = @jimport org.orekit.frames.OrphanFrame
const PVCoordinates = @jimport org.orekit.utils.PVCoordinates
const PVCoordinatesProvider = @jimport org.orekit.utils.PVCoordinatesProvider
const PoleCorrection = @jimport org.orekit.frames.PoleCorrection
const Predefined = @jimport org.orekit.frames.Predefined
const RapidDataAndPredictionColumnsLoader = @jimport org.orekit.frames.RapidDataAndPredictionColumnsLoader
const RapidDataAndPredictionXMLLoader = @jimport org.orekit.frames.RapidDataAndPredictionXMLLoader
const RealFieldElement = @jimport org.hipparchus.RealFieldElement
const Rotation = @jimport org.hipparchus.geometry.euclidean.threed.Rotation
const ShiftingTransformProvider = @jimport org.orekit.frames.ShiftingTransformProvider
const SortedSet = @jimport java.util.SortedSet
const Stream = @jimport java.util.stream.Stream
const Supplier = @jimport java.util.function.Supplier
const TEMEProvider = @jimport org.orekit.frames.TEMEProvider
const TIRFProvider = @jimport org.orekit.frames.TIRFProvider
const TODProvider = @jimport org.orekit.frames.TODProvider
const TimeInterpolable = @jimport org.orekit.time.TimeInterpolable
const TimeScale = @jimport org.orekit.time.TimeScale
const TimeScales = @jimport org.orekit.time.TimeScales
const TimeStampedFieldPVCoordinates = @jimport org.orekit.utils.TimeStampedFieldPVCoordinates
const TimeStampedPVCoordinates = @jimport org.orekit.utils.TimeStampedPVCoordinates
const TopocentricFrame = @jimport org.orekit.frames.TopocentricFrame
const Transform = @jimport org.orekit.frames.Transform
const TransformGenerator = @jimport org.orekit.frames.TransformGenerator
const TransformProvider = @jimport org.orekit.frames.TransformProvider
const TransformProviderUtils = @jimport org.orekit.frames.TransformProviderUtils
const TwoBodiesBaryFrame = @jimport org.orekit.frames.TwoBodiesBaryFrame
const TwoBodiesBaryTransformProvider = @jimport org.orekit.frames.TwoBodiesBaryTransformProvider
const UpdatableFrame = @jimport org.orekit.frames.UpdatableFrame
const VEISProvider = @jimport org.orekit.frames.VEISProvider
const Vector3D = @jimport org.hipparchus.geometry.euclidean.threed.Vector3D
const VersionedITRF = @jimport org.orekit.frames.VersionedITRF
const VersionedITRFProvider = @jimport org.orekit.frames.VersionedITRFProvider

export AbstractEopLoader
export AbstractEopParser
export AbstractFrames
export BulletinAFilesLoader
export BulletinBFilesLoader
export CIRFProvider
export CR3BPRotatingFrame
export CR3BPRotatingTransformProvider
export EME2000Provider
export EOPBasedTransformProvider
export EOPC04FilesLoader
export EOPEntry
export EOPHistory
export EOPHistoryLoader
export EclipticProvider
export EopParserLoader
export FactoryManagedFrame
export FieldPoleCorrection
export FieldTransform
export FieldTransformGenerator
export FixedTransformProvider
export Frame
export Frames
export FramesFactory
export GTODProvider
export HelmertTransformation
export ITRFProvider
export ITRFVersion
export ITRFVersionLoader
export InterpolatingTransformProvider
export ItrfVersionProvider
export L1Frame
export L1TransformProvider
export L2Frame
export L2TransformProvider
export LOFType
export LazyLoadedEop
export LazyLoadedFrames
export LocalOrbitalFrame
export MODProvider
export OrphanFrame
export PoleCorrection
export Predefined
export RapidDataAndPredictionColumnsLoader
export RapidDataAndPredictionXMLLoader
export ShiftingTransformProvider
export TEMEProvider
export TIRFProvider
export TODProvider
export TopocentricFrame
export Transform
export TransformGenerator
export TransformProvider
export TransformProviderUtils
export TwoBodiesBaryFrame
export TwoBodiesBaryTransformProvider
export UpdatableFrame
export VEISProvider
export VersionedITRF
export VersionedITRFProvider
export add_child
export add_default_eop1980_history_loaders
export add_default_eop2000_history_loaders
export add_eop_history_loader
export attach_to
export check_eop_continuity
export clear_eop_history_loaders
export compare_to
export compute_limit_visibility_point
export describe_constable
export equals
export fill_history
export find_eop
export freeze
export generate
export get_acceleration
export get_ancestor
export get_angular
export get_azimuth
export get_cartesian
export get_children
export get_cirf
export get_class
export get_combined_provider
export get_configuration
export get_conventions
export get_converter
export get_data_providers_manager
export get_date
export get_dd_eps
export get_dd_psi
export get_declaring_class
export get_depth
export get_dx
export get_dy
export get_earth_rotation_angle
export get_east
export get_ecliptic
export get_elevation
export get_eme2000
export get_end_date
export get_entries
export get_eop
export get_eop_history
export get_epoch
export get_equinox_nutation_correction
export get_factory_key
export get_field_date
export get_frame
export get_frames
export get_frozen_frame
export get_gcrf
export get_grid_points
export get_gtod
export get_icrf
export get_identity
export get_inverse
export get_itrf
export get_itrf_equinox
export get_itrf_type
export get_itrf_version
export get_jacobian
export get_lod
export get_mjd
export get_mod
export get_nadir
export get_name
export get_non_interpolating_eop_history
export get_non_interpolating_provider
export get_non_interpolating_transform
export get_non_rotatin_origin_nutation_correction
export get_north
export get_parent
export get_parent_shape
export get_point
export get_pole_correction
export get_pv_coordinates
export get_pz9011
export get_range
export get_range_rate
export get_raw_provider
export get_reversed_provider
export get_root
export get_rotation
export get_rotation_acceleration
export get_rotation_rate
export get_south
export get_start_date
export get_step
export get_teme
export get_time_scales
export get_tirf
export get_tod
export get_transform
export get_transform_provider
export get_transform_to
export get_translation
export get_ut1_minus_utc
export get_veis1950
export get_velocity
export get_west
export get_x
export get_xp
export get_y
export get_year
export get_yp
export get_zenith
export hash_code
export interpolate
export is_child_of
export is_pseudo_inertial
export is_simple_eop
export load_data
export name
export notify
export notify_all
export of
export ordinal
export parse
export point_at_distance
export rotation_from_inertial
export set_eop_continuity_threshold
export shifted_by
export still_accepts_data
export to_string
export transform_from_inertial
export transform_line
export transform_position
export transform_pv_coordinates
export transform_vector
export update_transform
export uses_interpolation
export value_of
export values
export wait

include("abstract_eop_loader.jl")
include("abstract_eop_parser.jl")
include("abstract_frames.jl")
include("bulletin_a_files_loader.jl")
include("bulletin_b_files_loader.jl")
include("c_r3_bp_rotating_frame.jl")
include("c_r3_bp_rotating_transform_provider.jl")
include("cirf_provider.jl")
include("ecliptic_provider.jl")
include("em_e2000_provider.jl")
include("eop_based_transform_provider.jl")
include("eop_c04_files_loader.jl")
include("eop_entry.jl")
include("eop_history.jl")
include("eop_history_loader.jl")
include("eop_parser_loader.jl")
include("factory_managed_frame.jl")
include("field_pole_correction.jl")
include("field_transform.jl")
include("field_transform_generator.jl")
include("fixed_transform_provider.jl")
include("frame.jl")
include("frames.jl")
include("frames_factory.jl")
include("gtod_provider.jl")
include("helmert_transformation.jl")
include("interpolating_transform_provider.jl")
include("itrf_provider.jl")
include("itrf_version.jl")
include("itrf_version_loader.jl")
include("itrf_version_provider.jl")
include("l1_frame.jl")
include("l1_transform_provider.jl")
include("l2_frame.jl")
include("l2_transform_provider.jl")
include("lazy_loaded_eop.jl")
include("lazy_loaded_frames.jl")
include("local_orbital_frame.jl")
include("lof_type.jl")
include("mod_provider.jl")
include("orphan_frame.jl")
include("pole_correction.jl")
include("predefined.jl")
include("rapid_data_and_prediction_columns_loader.jl")
include("rapid_data_and_prediction_xml_loader.jl")
include("shifting_transform_provider.jl")
include("teme_provider.jl")
include("tirf_provider.jl")
include("tod_provider.jl")
include("topocentric_frame.jl")
include("transform.jl")
include("transform_generator.jl")
include("transform_provider.jl")
include("transform_provider_utils.jl")
include("two_bodies_bary_frame.jl")
include("two_bodies_bary_transform_provider.jl")
include("updatable_frame.jl")
include("veis_provider.jl")
include("versioned_itr_f.jl")
include("versioned_itrf_provider.jl")

end


text:
import KernelAbstractions: CPU

using ..Mesh.Grids
using ..MPIStateArrays
using ..DGMethods
using ..TicToc

"""
    writevtk(prefix, Q::MPIStateArray, dg::DGModel [, fieldnames])

Write a vtk file for all the fields in the state array `Q` using geometry and
connectivity information from `dg.grid`. The filename will start with `prefix`
which may also contain a directory path. The names used for each of the fields
in the vtk file can be specified through the collection of strings `fieldnames`;
if not specified the fields names will be `"Q1"` through `"Qk"` where `k` is the
number of states in `Q`, i.e., `k = size(Q,2)`.

"""
function writevtk(prefix, Q::MPIStateArray, dg::DGModel, fieldnames = nothing)
    vgeo = dg.grid.vgeo
    device = array_device(Q)
    (h_vgeo, h_Q) = device isa CPU ? (vgeo, Q.data) : (Array(vgeo), Array(Q))
    writevtk_helper(prefix, h_vgeo, h_Q, dg.grid, fieldnames)
    return nothing
end

"""
    writevtk(prefix, Q::MPIStateArray, dg::DGModel, fieldnames,
             state_auxiliary::MPIStateArray, auxfieldnames)

Write a vtk file for all the fields in the state array `Q` and auxiliary state
`state_auxiliary` using geometry and connectivity information from `dg.grid`. The
filename will start with `prefix` which may also contain a directory path. The
names used for each of the fields in the vtk file can be specified through the
collection of strings `fieldnames` and `auxfieldnames`.

If `fieldnames === nothing` then the fields names will be `"Q1"` through `"Qk"`
where `k` is the number of states in `Q`, i.e., `k = size(Q,2)`.

If `auxfieldnames === nothing` then the fields names will be `"aux1"` through
`"auxk"` where `k` is the number of states in `state_auxiliary`, i.e., `k =
size(state_auxiliary,2)`.

"""
function writevtk(
    prefix,
    Q::MPIStateArray,
    dg::DGModel,
    fieldnames,
    state_auxiliary,
    auxfieldnames,
)
    vgeo = dg.grid.vgeo
    device = array_device(Q)
    (h_vgeo, h_Q, h_aux) =
        device isa CPU ? (vgeo, Q.data, state_auxiliary.data) :
        (Array(vgeo), Array(Q), Array(state_auxiliary))
    writevtk_helper(
        prefix,
        h_vgeo,
        h_Q,
        dg.grid,
        fieldnames,
        h_aux,
        auxfieldnames,
    )
    return nothing
end

"""
    writevtk_helper(prefix, vgeo::Array, Q::Array, grid, fieldnames)

Internal helper function for `writevtk`
"""
function writevtk_helper(
    prefix,
    vgeo::Array,
    Q::Array,
    grid,
    fieldnames,
    state_auxiliary = nothing,
    auxfieldnames = nothing,
)

    dim = dimensionality(grid)
    N = polynomialorder(grid)
    Nq = N + 1

    nelem = size(Q)[end]
    Xid = (grid.x1id, grid.x2id, grid.x3id)
    X = ntuple(
        j -> reshape((@view vgeo[:, Xid[j], :]), ntuple(j -> Nq, dim)..., nelem),
        dim,
    )
    if fieldnames == nothing
        fields = ntuple(
            i -> ("Q$i", reshape((@view Q[:, i, :]), ntuple(j -> Nq, dim)..., nelem)),
            size(Q, 2),
        )
    else
        fields = ntuple(
            i -> (
                fieldnames[i],
                reshape((@view Q[:, i, :]), ntuple(j -> Nq, dim)..., nelem),
            ),
            size(Q, 2),
        )
    end
    if state_auxiliary !== nothing
        if auxfieldnames === nothing
            auxfields = ntuple(
                i -> (
                    "aux$i",
                    reshape(
                        (@view state_auxiliary[:, i, :]),
                        ntuple(j -> Nq, dim)...,
                        nelem,
                    ),
                ),
                size(state_auxiliary, 2),
            )
        else
            auxfields = ntuple(
                i -> (
                    auxfieldnames[i],
                    reshape(
                        (@view state_auxiliary[:, i, :]),
                        ntuple(j -> Nq, dim)...,
                        nelem,
                    ),
                ),
                size(state_auxiliary, 2),
            )
        end
        fields = (fields..., auxfields...)
    end
    writemesh(
        prefix,
        X...;
        fields = fields,
        realelems = grid.topology.realelems,
    )
end

"""
    writegrid(prefix, grid::DiscontinuousSpectralElementGrid)

Write a vtk file for the grid.  The filename will start with `prefix` which
may also contain a directory path.
"""
function writevtk(prefix, grid::DiscontinuousSpectralElementGrid)
    dim = dimensionality(grid)
    N = polynomialorder(grid)
    Nq = N + 1

    vgeo = grid.vgeo isa Array ? grid.vgeo : Array(grid.vgeo)

    nelem = size(vgeo)[end]
    Xid = (grid.x1id, grid.x2id, grid.x3id)
    X = ntuple(
        j -> reshape((@view vgeo[:, Xid[j], :]), ntuple(j -> Nq, dim)..., nelem),
        dim,
    )
    writemesh(prefix, X...; realelems = grid.topology.realelems)
end

ext: jl

max_stars_repo_name: leios/CLIMA

max_issues_repo_name: leios/CLIMA

max_forks_repo_name: leios/CLIMA


text:
function init_model(model::AlphaModel,components,userlocations,verbose)
    return model
end

function init_model(model::Type{<:AlphaModel},components,userlocations,verbose)
    verbose && @info("""Now creating alpha model:
    $model""")
    return model(components;userlocations,verbose)
end

include("NoAlpha.jl")
include("RKAlpha.jl")
include("PRAlpha.jl")
include("CPAAlpha.jl")
include("sCPAAlpha.jl")
include("PR78Alpha.jl")
include("soave.jl")
include("BM.jl")
include("Twu.jl")
include("MT.jl")


text:
using BinaryBuilder, Pkg

name = "VMEC"
version = v"1.0.3"

sources = [
    ArchiveSource("https://gitlab.com/wistell/VMEC2000/-/archive/v$(version).tar",
                  "cee46dfeb452d2dd79811f8b66fdb6e1a38975d276e71b5531474b03024a5a8f"),
]

script = raw"""
cd ${WORKSPACE}/srcdir/VMEC*
if [[ ${target} == *mingw* ]]; then
  sed "s/LT_INIT/LT_INIT(win32-dll)/" configure.ac | cat > configure.ac.2
  mv configure.ac.2 configure.ac
  ./autogen.sh
  ./configure CC=gcc FC=gfortran F77=gfortran --build=${MACHTYPE} --with-mkl --host=${target} --target=${target} --prefix=${prefix}
  # Deal with the issue that gcc doesn't accept -no-undefined at configure step
  sed "s/AM_LDFLAGS =/AM_LDFLAGS =-no-undefined/" Makefile | cat > Makefile.2
  mv Makefile.2 Makefile
  make && make install && make clean

  ./configure CC=gcc FC=gfortran F77=gfortran --build=${MACHTYPE} --host=${target} --target=${target} --prefix=${prefix}
  # Deal with the issue that gcc doesn't accept -no-undefined at configure step
  sed "s/AM_LDFLAGS =/AM_LDFLAGS =-no-undefined/" Makefile | cat > Makefile.2
  mv Makefile.2 Makefile
  make && make install && make clean

else
  # Configure with MKL provided ScaLAPACK
  ./autogen.sh
  ./configure CC=mpicc FC=mpifort F77=mpifort FFLAGS=-O3 FCFLAGS=-O3 --with-mkl --build=${MACHTYPE} --host=${target} --target=${target} --prefix=${prefix}
  make && make install && make clean

  # Configure with OpenBLAS and ScaLAPACK from SCALAPACK_jll
  ./configure CC=mpicc FC=mpifort F77=mpifort FFLAGS=-O3 FCFLAGS=-O3 --build=${MACHTYPE}  --host=${target} --target=${target} --prefix=${prefix}
  make && make install && make clean
fi
"""

platforms = expand_gfortran_versions(supported_platforms())

# Filter out libgfortran_version = 3.0.0 which is incompatible with VMEC
filter!(p ->libgfortran_version(p) >= v"4", platforms)

# Filter incompatible architectures and operating systems
filter!(p -> arch(p) == "x86_64", platforms)
filter!(!Sys.isfreebsd, platforms)

# Right now VMEC only works with libc=glibc, filter out any musl dependencies
filter!(p -> libc(p) != "musl", platforms)

# The products that we will ensure are always built
# Don't automatically dl_open so that the appropriate
# library can be loaded on intiation of VMEC.jl
products = [
    LibraryProduct("libvmec_mkl", :libvmec_mkl, dont_dlopen = true),
    LibraryProduct("libvmec_openblas", :libvmec_openblas, dont_dlopen = true),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    # MbedTLS is an indirect dependency, fix the version for building
    BuildDependency(PackageSpec(name = "MbedTLS_jll", version = v"2.24.0")),
    Dependency("MPICH_jll"; platforms=filter(!Sys.iswindows, platforms)),
    Dependency("OpenBLAS_jll"),
    Dependency("SCALAPACK_jll"; platforms=filter(!Sys.iswindows, platforms)),
    Dependency("MKL_jll", v"2020.1.216"),
    Dependency("NetCDF_jll"),
    Dependency("NetCDFF_jll"),
    Dependency("CompilerSupportLibraries_jll")
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat = "1.6")

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
# prompt.jl

using MIRTjim: prompt
using Test: @test, @testset, @test_throws

@testset "prompt" begin
    prompt() # test "else c == 'd'"
    @test prompt(:state) === :draw

    _tmp = prompt(:state) # save current state
    prompt(:draw)
    @test prompt(:state) === :draw
    prompt()
    @test prompt(_tmp) isa Symbol # return to original state

    io_out = IOBuffer()

    io_in = IOBuffer("d")
    prompt( ; io_in, io_out)
    @test prompt(:state) == :draw
    prompt(:prompt)

    io_in = IOBuffer("n")
    prompt( ; io_in, io_out)
    @test prompt(:state) == :nodraw
    prompt(:prompt)

    io_in = IOBuffer("q")
    @test_throws String prompt( ; io_in, io_out)
end


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

# run boundscheck tests on separate workers launched with --check-bounds={default,yes,no}

cmd = `$(Base.julia_cmd()) --depwarn=error --startup-file=no boundscheck_exec.jl`
if !success(pipeline(cmd; stdout=stdout, stderr=stderr))
    error("boundscheck test failed, cmd : $cmd")
end

cmd = `$(Base.julia_cmd()) --check-bounds=yes --startup-file=no --depwarn=error boundscheck_exec.jl`
if !success(pipeline(cmd; stdout=stdout, stderr=stderr))
    error("boundscheck test failed, cmd : $cmd")
end

cmd = `$(Base.julia_cmd()) --check-bounds=no --startup-file=no --depwarn=error boundscheck_exec.jl`
if !success(pipeline(cmd; stdout=stdout, stderr=stderr))
    error("boundscheck test failed, cmd : $cmd")
end

max_stars_repo_name: greimel/julia

max_issues_repo_name: greimel/julia

max_forks_repo_name: greimel/julia


text:
# A simple reverse-mode AD.
# Lots of simplifications have been made (in particular, there is no support for
# control flow). But this illustrates most of the principles behind Zygote.
# https://fluxml.ai/Zygote.jl/dev/internals/

using IRTools
using IRTools: @dynamo, IR, Pipe, finish, substitute, return!, block, blocks,
  returnvalue, arguments, isexpr, xcall, self, stmt

struct Pullback{S,T}
  data::T
end

Pullback{S}(data) where S = Pullback{S,typeof(data)}(data)

function primal(ir, T = Any)
  pr = Pipe(ir)
  calls = []
  ret = []
  for (v, st) in pr
    ex = st.expr
    if isexpr(ex, :call)
      t = insert!(pr, v, stmt(xcall(Main, :forward, ex.args...), line = st.line))
      pr[v] = xcall(:getindex, t, 1)
      J = push!(pr, xcall(:getindex, t, 2))
      push!(calls, v)
      push!(ret, J)
    end
  end
  pb = Expr(:call, Pullback{T}, xcall(:tuple, ret...))
  return!(pr, xcall(:tuple, returnvalue(block(ir, 1)), pb))
  return finish(pr), calls
end

_sum() = 0
_sum(x) = x
_sum(x...) = xcall(:+, x...)

function adjoint(pr)
  ir = empty(pr)
  grads = Dict()
  grad(x) = _sum(get(grads, x, [])...)
  grad(x, x̄) = push!(get!(grads, x, []), x̄)
  grad(returnvalue(block(pr, 1)), IRTools.argument!(ir))
  data = push!(ir, xcall(:getfield, self, QuoteNode(:data)))
  _, pbs = primal(pr)
  pbs = Dict(pbs[i] => push!(ir, xcall(:getindex, data, i)) for i = 1:length(pbs))
  for v in reverse(keys(pr))
    ex = pr[v].expr
    isexpr(ex, :call) || continue
    Δs = push!(ir, Expr(:call, pbs[v], grad(v)))
    for (i, x) in enumerate(ex.args)
      grad(x, push!(ir, xcall(:getindex, Δs, i)))
    end
  end
  return!(ir, xcall(:tuple, [grad(x) for x in arguments(pr)]...))
end

@dynamo function forward(m...)
  ir = IR(m...)
  ir == nothing && return :(error("Non-differentiable function ", repr(args[1])))
  length(blocks(ir)) == 1 || error("control flow is not supported")
  return primal(ir, Tuple{m...})[1]
end

@dynamo function (pb::Pullback{S})(Δ) where S
  return adjoint(IR(S.parameters...))
end

forward(::typeof(sin), x) = sin(x), ȳ -> (nothing, ȳ*cos(x))
forward(::typeof(cos), x) = cos(x), ȳ -> (nothing, -ȳ*sin(x))

gradient(f, x...) = Base.tail(forward(f, x...)[2](1))

foo(x) = sin(cos(x))

# ir = @code_ir foo(1.0)
# primal(ir)[1]
# adjoint(ir)

gradient(foo, 1.0)


text:
using ConstrainedDynamics
using ConstrainedDynamicsVis

# Parameters
joint_axis = [1.0;0.0;0.0]

h = 1.
r = .05
box = Cylinder(r, h, h, color = RGBA(1., 0., 0.))

p2 = [0.0;0.0;h / 2] # joint connection point

#Corner vector v
v = [0;0;h/2]

# Initial orientation
ϕ1 = π/2
ϕ2 = 4
ϕ3 = π/2.2
q1 = UnitQuaternion(RotX(ϕ1))
q2 = UnitQuaternion(RotX(ϕ2))
q3 = UnitQuaternion(RotX(ϕ3))

# Links
origin = Origin{Float64}()
link1 = Body(box)
link2 = Body(box)
link3 = Body(box)
link4 = Body(box)

# Constraints
joint0to1 = EqualityConstraint(Floating(origin,link1))
joint1to2 = EqualityConstraint(Fixed(link1,link2;qoffset = q1))
joint2to3 = EqualityConstraint(Fixed(link2,link3;qoffset = q2))
joint3to4 = EqualityConstraint(Fixed(link3,link4;qoffset = q3))

impact11 = InequalityConstraint(Impact(link1,[0;0;1.0]; p = v)) # Comment for friction
impact21 = InequalityConstraint(Impact(link2,[0;0;1.0]; p = v)) # Comment for friction
impact31 = InequalityConstraint(Impact(link3,[0;0;1.0]; p = v)) # Comment for friction
impact41 = InequalityConstraint(Impact(link4,[0;0;1.0]; p = v)) # Comment for friction
impact12 = InequalityConstraint(Impact(link1,[0;0;1.0]; p = -v)) # Comment for friction
impact22 = InequalityConstraint(Impact(link2,[0;0;1.0]; p = -v)) # Comment for friction
impact32 = InequalityConstraint(Impact(link3,[0;0;1.0]; p = -v)) # Comment for friction
impact42 = InequalityConstraint(Impact(link4,[0;0;1.0]; p = -v)) # Comment for friction

# impact11 = InequalityConstraint(Friction(link1,[0;0.2;1.0],0.4; p = v)) # Uncomment for friction
# impact21 = InequalityConstraint(Friction(link2,[0;0.2;1.0],0.4; p = v)) # Uncomment for friction
# impact31 = InequalityConstraint(Friction(link3,[0;0.2;1.0],0.4; p = v)) # Uncomment for friction
# impact41 = InequalityConstraint(Friction(link4,[0;0.2;1.0],0.4; p = v)) # Uncomment for friction
# impact12 = InequalityConstraint(Friction(link1,[0;0.2;1.0],0.4; p = -v)) # Uncomment for friction
# impact22 = InequalityConstraint(Friction(link2,[0;0.2;1.0],0.4; p = -v)) # Uncomment for friction
# impact32 = InequalityConstraint(Friction(link3,[0;0.2;1.0],0.4; p = -v)) # Uncomment for friction
# impact42 = InequalityConstraint(Friction(link4,[0;0.2;1.0],0.4; p = -v)) # Uncomment for friction

links = [link1;link2;link3;link4]
eqcs = [joint0to1;joint1to2;joint2to3;joint3to4]
ineqcs = [impact11;impact21;impact31;impact41;impact12;impact22;impact32;impact42]
shapes = [box]

mech = Mechanism(origin, links, eqcs, ineqcs, shapes = shapes)

setPosition!(link1,x = [0;0;1.0])
setPosition!(link1,link2,Δq = q1)
setPosition!(link2,link3,Δq = q2)
setPosition!(link3,link4,Δq = q3)

setVelocity!(link1,ω=[-10.0;0.0;0],v=[0;5;0]) # Comment for friction
# setVelocity!(link1,ω=[-1.0;0.0;0],v=[0;0;0]) # Uncomment for friction
setVelocity!(link1,link2)
setVelocity!(link2,link3)
setVelocity!(link3,link4)

storage = simulate!(mech, 10., record = true)
visualize(mech, storage, shapes)


text:
# Space-walking recursive functions for random search and tree-parzen estimation.

walkable(x::Delayed.AbstractParam) = true
walkable(x) = false

# Entrypoint (only for TPE, not for random search)
"""
$(TYPEDSIGNATURES)

Resolves a posterior inference space by depth-first iteration, replacing prior random-
variables with new posterior distributions that make use of observations.
"""
function node(
    space::Types.SPACE_TYPE, trials::Vector{Trials.Trial}, config::Config
)::Tuple{Trials.ValsDict, Any}

    params = Dict{Symbol, Types.AbstractDelayed}(
        item.label => item.obj
            for item in Graph.dfs(space)
                if walkable(item)
    )

    vals = Trials.ValsDict()

    hyperparams = node(space, vals, params, trials, config)

    return vals, hyperparams
end

function obs_memo(
    item::Delayed.AbstractDistDelayed, params::Dict{Symbol, Types.AbstractDelayed}
)::Symbol
    for (k, v) in params
        v == item && return k
    end

    throw(DomainError("item was not a value in params"))
end

# Node resolvers. For each node type there is first a random-search resolver and then a TPE
# resolver. They are distinguished by the TPE methods requiring extra items.
"""
$(TYPEDSIGNATURES)

Resolves random search AbstractParam nodes and places parameter results in the vals dictionary.
"""
function node(item::Delayed.AbstractParam, vals::Trials.ValsDict)::Union{IndexObjects.IndexInt, Real}
    if haskey(vals, item.label)
        throw(KeyError("Key $(item) already present in $(vals[item.label])"))
    end

    obj = node(item.obj, vals)
    vals[item.label] = IndexObjects.getval(obj)

    return obj
end
"""
$(TYPEDSIGNATURES)

Resolves random search AbstractParam nodes and places parameter results in the vals dictionary.
"""
function node(
    item::Delayed.AbstractParam, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Union{IndexObjects.IndexInt, Real}
    if haskey(vals, item.label)
        throw(KeyError("Key $(item.label) already present $(vals[item.label])"))
    end

    obj = node(item.obj, vals, params, trials, config)
    vals[item.label] = IndexObjects.getval(obj)

    return obj
end

function node(item::Delayed.BinaryOperator, vals::Trials.ValsDict)::Real

    left = node(item.left, vals)
    right = node(item.right, vals)

    return item.operator(left, right)
end
function node(
    item::Delayed.BinaryOperator, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Float64

    left = node(item.left, vals, params, trials, config)
    right = node(item.right, vals, params, trials, config)

    return item.operator(left, right)
end

function node(item::Delayed.UnaryOperator, vals::Trials.ValsDict)::Real

    operand = node(item.operand, vals)

    return item.operator(operand)
end
function node(
    item::Delayed.UnaryOperator, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Float64

    operand = node(item.operand, vals, params, trials, config)

    return item.operator(operand)
end

function node(item::Delayed.CategoricalIndex, vals::Trials.ValsDict)::IndexObjects.IndexInt
    return IndexObjects.IndexInt(first(Delayed.categoricalindex(item.probabilities, 1).v))
end
function node(
    item::Delayed.CategoricalIndex, vals::Trials.ValsDict,
    params::Dict{Symbol, Types.AbstractDelayed}, trials::Vector{Trials.Trial},
    config::Config
)::IndexObjects.IndexInt

    nid = obs_memo(item, params)

    return Resolve.posterior(item, item.probabilities, nid, trials, config)
end

function node(item::Dict{Symbol, T} where T, vals::Trials.ValsDict)::Dict{Symbol, Any}

    result = Dict{Symbol, Any}()
    # Cannot use a dictionary comprehension because the values will be evaluated twice.
    for (k, v) in item
        result[k] = node(v, vals)
    end

    return result
end
function node(
    item::Dict{Symbol, T} where T, vals::Trials.ValsDict,
    params::Dict{Symbol, Types.AbstractDelayed}, trials::Vector{Trials.Trial},
    config::Config
)::Dict{Symbol, Any}

    result = Dict{Symbol, Any}()
    # Cannot use a dictionary comprehension because the values will be evaluated twice.
    for (k, v) in item
        result[k] = node(v, vals, params, trials, config)
    end

    return result
end

function node(item::Delayed.Float, vals::Trials.ValsDict)::Float64

    return float(node(item.arg, vals))
end
function node(
    item::Delayed.Float, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Float64

    return float(node(item.arg, vals, params, trials, config))
end

function node(item::Delayed.LogNormal, vals::Trials.ValsDict)::Float64
    mu = node(item.mu, vals)
    sigma = node(item.sigma, vals)

    return Delayed.lognormal(mu, sigma)
end
function node(
    item::Delayed.LogNormal, vals::Trials.ValsDict,
    params::Dict{Symbol, Types.AbstractDelayed}, trials::Vector{Trials.Trial},
    config::Config
)::Real

    mu = node(item.mu, vals, params, trials, config)
    sigma = node(item.sigma, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, mu, sigma, nid, trials, config)
end

function node(item::Delayed.LogNormalQuantDist, vals::Trials.ValsDict)::Float64
    mu = node(item.mu, vals)
    sigma = node(item.sigma, vals)
    q = node(item.q, vals)

    return Delayed.lognormalquant(item, mu, sigma, q)
end
function node(
    item::Delayed.LogNormalQuantDist, vals::Trials.ValsDict,
    params::Dict{Symbol, Types.AbstractDelayed}, trials::Vector{Trials.Trial},
    config::Config
)::Real

    mu = node(item.mu, vals, params, trials, config)
    sigma = node(item.sigma, vals, params, trials, config)
    q = node(item.q, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, mu, sigma, q, nid, trials, config)
end

function node(item::Delayed.Normal, vals::Trials.ValsDict)::Float64
    mu = node(item.mu, vals)
    sigma = node(item.sigma, vals)

    return Delayed.normal(mu, sigma)
end
function node(
    item::Delayed.Normal, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Real

    mu = node(item.mu, vals, params, trials, config)
    sigma = node(item.sigma, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, mu, sigma, nid, trials, config)
end

function node(item::Delayed.QuantNormal, vals::Trials.ValsDict)::Float64
    mu = node(item.mu, vals)
    sigma = node(item.sigma, vals)
    q = node(item.q, vals)

    return Delayed.quantnormal(mu, sigma, q)
end
function node(
    item::Delayed.QuantNormal, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Real

    mu = node(item.mu, vals, params, trials, config)
    sigma = node(item.sigma, vals, params, trials, config)
    q = node(item.q, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, mu, sigma, q, nid, trials, config)
end

function node(item::Delayed.RandIndex, vals::Trials.ValsDict)::IndexObjects.IndexInt

    upper = node(item.upper, vals)
    if upper < 1
        throw(ArgumentError("upper will be used as index so must be greater than 0"))
    end

    return IndexObjects.IndexInt(rand(1:upper))
end
function node(
    item::Delayed.RandIndex, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::IndexObjects.IndexInt

    upper = node(item.upper, vals, params, trials, config)
    if upper < 1
        throw(ArgumentError("upper will be used as index so must be greater than 0"))
    end
    nid = obs_memo(item, params)

    return Resolve.posterior(item, upper, nid, trials, config)
end

function node(item::Delayed.AbstractSwitch, vals::Trials.ValsDict)

    # Randomly generate a number to indicate which index of the options will be returned
    choice = node(item.choice, vals)

    return node(item.options[choice.v], vals)
end
function node(
    item::Delayed.AbstractSwitch, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)
    choice = node(item.choice, vals, params, trials, config)

    return node(item.options[choice.v], vals, params, trials, config)
end

function node(item::Delayed.Uniform, vals::Trials.ValsDict)::Float64
    low = node(item.low, vals)
    high = node(item.high, vals)

    return Delayed.uniform(low, high)
end
function node(
    item::Delayed.Uniform, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Real

    low = node(item.low, vals, params, trials, config)
    high = node(item.high, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, low, high, nid, trials, config)
end

function node(item::Delayed.QuantUniform, vals::Trials.ValsDict)::Float64
    low = node(item.low, vals)
    high = node(item.high, vals)
    q = node(item.q, vals)

    return Delayed.quantuniform(low, high, q)
end
function node(
    item::Delayed.QuantUniform, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Real

    low = node(item.low, vals, params, trials, config)
    high = node(item.high, vals, params, trials, config)
    q = node(item.q, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, low, high, q, nid, trials, config)
end

function node(item::Delayed.LogUniform, vals::Trials.ValsDict)::Float64

    low = node(item.low, vals)
    high = node(item.high, vals)

    return Delayed.loguniform(low, high)
end

function node(
    item::Delayed.LogUniform, vals::Trials.ValsDict,
    params::Dict{Symbol, Types.AbstractDelayed}, trials::Vector{Trials.Trial},
    config::Config
)::Real

    low = node(item.low, vals, params, trials, config)
    high = node(item.high, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, low, high, nid, trials, config)
end

function node(item::Delayed.LogUniformQuantDist, vals::Trials.ValsDict)::Float64
    low = node(item.low, vals)
    high = node(item.high, vals)
    q = node(item.q, vals)

    return Delayed.loguniformquant(item, low, high, q)
end
function node(
    item::Delayed.LogUniformQuantDist, vals::Trials.ValsDict,
    params::Dict{Symbol, Types.AbstractDelayed}, trials::Vector{Trials.Trial},
    config::Config
)::Real

    low = node(item.low, vals, params, trials, config)
    high = node(item.high, vals, params, trials, config)
    q = node(item.q, vals, params, trials, config)
    nid = obs_memo(item, params)

    return Resolve.posterior(item, low, high, q, nid, trials, config)
end

function node(items::Vector, vals::Trials.ValsDict)::Vector{<: Any}
    return [
        node(item, vals::Trials.ValsDict)
            for item in items
    ]
end
function node(
    items::Vector, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Vector{<: Any}

    return [
        node(item, vals, params, trials, config)
        for item in items
    ]
end

function node(items::Tuple, vals::Trials.ValsDict)::Tuple
    return tuple((
        node(item, vals::Trials.ValsDict)
            for item in items
    )...)
end
function node(
    items::Tuple, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::Tuple

    return tuple((
        node(item, vals, params, trials, config)
            for item in items
    )...)
end

function node(item::T, vals::Trials.ValsDict)::T where T <: Union{Real, Symbol, String}
    return item
end
function node(
    item::T, vals::Trials.ValsDict, params::Dict{Symbol, Types.AbstractDelayed},
    trials::Vector{Trials.Trial}, config::Config
)::T where T <: Union{Real, Symbol, String}

    return item
end


text:
"""
    module UtilsGJL

A collection of miscellaneous utilities.

EXPORTED FUNCTIONS:

`nonunique`, `nonuniquecount`, `merge1`, `merge1!`, `subst!`, `append`, `arrcountmap`,
`keepkeys`, `arraytodict`, `equalelements`, `fields`,`allkeysequal`, `countmaptypes`, `countmapvalues`, `sortcountmap`,
`foreachdict`, `compactstring`,
`truncfloat`, `rgbtohex`, `hoursfloat`, `daysfloat`, `yearsfloat`, `minutesfloat`,
`loghistogram`, `writeloghist`,
`longdisplay`,`ld`, `alldocs`,
`@withw`
"""
module UtilsGJL

# The following works in some situations, at the cost of loading
# DataFrames.

if isdefined(Main,:DataFrames)
     import DataFrames: nonunique
end

# FIXME: use "import", not "using"
using DataStructures
using StatsBase

export keepkeys, arraytodict, hoursfloat, daysfloat, yearsfloat, minutesfloat
export equalelements, allkeysequal, countmaptypes, countmapvalues, countmapnumvalues, countmaptypenumvalues
export truncfloat, subst!, append, arrcountmap, loghistogram, writeloghist
export foreachdict, fields
export merge1, merge1!, nonunique, nonuniquecount
export rgbtohex
export sortcountmap
export longdisplay,ld
export alldocs
export @withw

include("datastructures.jl")
include("strings.jl")
include("utils.jl")
include("time.jl")
include("io.jl")
include("docs.jl")
include("sparse.jl")

end # module UtilsGJL


text:
# This file was generated, do not modify it. # hide
plt.figure(figsize=(8,6))
plt.hist(df.price[df.isrenovated .== true], color="blue", density=true,
        edgecolor="white", bins=50, label="renovated", alpha=0.5)
plt.hist(df.price[df.isrenovated .== false], color="red", density=true,
        edgecolor="white", bins=50, label="unrenovated", alpha=0.5)
plt.xlabel("Price", fontsize=14)
plt.ylabel("Frequency", fontsize=14)
plt.legend(fontsize=12)
plt.savefig(joinpath(@OUTPUT, "hist_price2.svg")) # hide


text: include("NumFieldOrd/NumFieldOrd.jl")


text:
using Evolution
using Test

@testset "Evolution.jl" begin
    # Tests
end

max_stars_repo_name: TheSquareRoot/Evolution

max_issues_repo_name: TheSquareRoot/Evolution

max_forks_repo_name: TheSquareRoot/Evolution


text:
using GLVisualize, GLWindow, Reactive, GeometryTypes, GLAbstraction

const RS    = GLVisualize.ROOT_SCREEN

function y_partition(area, percent)
	amount = percent / 100.0
	p = lift(area) do r
		(Rectangle{Int}(r.x, r.y, r.w, round(Int, r.h*amount)),
			Rectangle{Int}(r.x, round(Int, r.h*amount), r.w, round(Int, r.h*(1-amount))))
	end
	return lift(first, p), lift(last, p)
end
function x_partition(area, percent)
	amount = percent / 100.0
	p = lift(area) do r
		(Rectangle{Int}(r.x, r.y, round(Int, r.w*amount), r.h ),
			Rectangle{Int}(round(Int, r.w*amount), r.y, round(Int, r.w*(1-amount)), r.h))
	end
	return lift(first, p), lift(last, p)
end

main_area, write_area = y_partition(RS.area, 20.0)

const write_screen 	= Screen(RS, area=main_area)
const main_screen 	= Screen(RS, area=write_area)
function fixedscreen(parent, area)
	inputs = parent.inputs
	area = lift(intersect, parent.area, area)
	children = Screen[]
	#checks if mouse is inside screen
	insidescreen = lift(inputs[:mouseposition]) do mpos
		isinside(area.value, mpos...) && !any(children) do screen
			isinside(screen.area.value, mpos...)
		end
	end
	wsize = lift(x->Vector4(x.x, x.y, x.w, x.h), area)
	ocamera = OrthographicCamera(
		wsize,
		Input(eye(Mat4)),
		Input(-1000f0), # nearclip
		Input(1000f0)	# farclip
	)
	camera_input = merge(inputs, Dict(
		:mouseposition 	=> keepwhen(insidescreen, Vector2(0.0), inputs[:mouseposition]),
		:scroll_x 		=> keepwhen(insidescreen, 0.0, 			inputs[:scroll_x]),
		:scroll_y 		=> keepwhen(insidescreen, 0.0, 			inputs[:scroll_y]),
		:window_size 	=> lift(x->Vector4(x.x, x.y, x.w, x.h), area)
	))
	pcamera = PerspectiveCamera(camera_input, Vec3(2), Vec3(0))
    screen = Screen(area, parent, children, camera_input, RenderObject[], Input(true), parent.hasfocus, pcamera, ocamera, parent.nativewindow)
	push!(parent.children, screen)
	screen
end

text_stream 		= lift(x->"Ima push this so hard\nDude yeah neva now rite?$x\n", fpswhen(RS.inputs[:open], 1.0))
const scroll_window = foldl(+, 0.0, main_screen.inputs[:scroll_y])
visualize(text_stream.value, screen=write_screen)
lift(text_stream) do teeext
	area_handle	= Input(Rectangle{Int}(0,200*length(main_screen.children), main_screen.area.value.w, 180))
	area  		= lift(area_handle, main_screen.area, scroll_window) do h_area, m_area, y
		Rectangle{Int}(h_area.x, h_area.y+(round(Int, y)*50), m_area.w, h_area.h)
	end

	new_screen  = fixedscreen(main_screen, area)
	robj 		= visualize(teeext, screen=new_screen)

	view(visualize(lift(x->Rectangle(0,0,x.w, x.h), area), screen=new_screen), new_screen)
	view(robj, new_screen)
	nothing
end

renderloop()


text:
# Configuration file for test variables
# Not synched to github as each environment can have different configurations
# See baseconfig.jl to see the expected variables
include("config.jl")

# Setup initializes single VM used by the tests
# Will be destroyed in teardown
# Tests only include the JNI package and the jvm will be running
include("setup.jl")

@testset verbose=true "JavaCall" begin
    # Test init options
    @info "Test init opts"
    include("initopts.jl")

    # Test jni api
    @info "Test JNI API"
    include("jni.jl")

    # Test signatures
    @info "Test signatures"
    include("signatures.jl")

    # Test conversions
    @info "Test conversions"
    include("convertions.jl")

    # Test code generation
    @info "Test Code Generation"
    include("codegeneration.jl")

    # Test reflection api
    @info "Test Reflection API"
    include("reflection.jl")

    # Test java code generation
    @info "Test Java Code Generation"
    include("javacodegeneration.jl")

    # Test exceptions
    @info "Test exceptions"
    include("exceptions.jl")

    # Test jimport
    @info "Test Import Statements"
    include("jimport.jl")
end

include("teardown.jl")


text:
# # EQUALITY

# to address #124 and #129:
MLJModelInterface.deep_properties(::Type{<:MLJFluxModel}) =
    (:optimiser, :builder)

# # CLEAN METHOD

function MLJModelInterface.clean!(model::MLJFluxModel)
    warning = ""
    if model.lambda < 0
        warning *= "Need `lambda ≥ 0`. Resetting `lambda = 0`. "
        model.lambda = 0
    end
    if model.alpha < 0 || model.alpha > 1
        warning *= "Need alpha in the interval `[0, 1]`. "*
            "Resetting `alpha = 0`. "
        model.alpha = 0
    end
    if model.epochs < 0
        warning *= "Need `epochs ≥ 0`. Resetting `epochs = 10`. "
        model.epochs = 10
    end
    if model.batch_size < 0
        warning *= "Need `batch_size ≥ 0`. Resetting `batch_size = 1`. "
        model.batch_size = 1
    end
    if model.acceleration isa CUDALibs && gpu_isdead()
        warning *= "`acceleration isa CUDALibs` "*
            "but no CUDA device (GPU) currently live. "
    end
    if ! (model.acceleration isa CUDALibs || model.acceleration isa CPU1)
        warning *= "`Undefined acceleration, falling back to CPU`"
        model.acceleration = CPU1()
    end
    return warning
end

# # FIT AND  UPDATE

true_rng(model) = model.rng isa Integer ? MersenneTwister(model.rng) : model.rng

function MLJModelInterface.fit(model::MLJFluxModel,
                               verbosity,
                               X,
                               y)

    move = Mover(model.acceleration)

    rng = true_rng(model)
    shape = MLJFlux.shape(model, X, y)
    chain = build(model, rng, shape) |> move
    penalty = Penalty(model)
    data = move.(collate(model, X, y))

    optimiser = deepcopy(model.optimiser)

    chain, history = fit!(model.loss,
                          penalty,
                          chain,
                          optimiser,
                          model.epochs,
                          verbosity,
                          data[1],
                          data[2])

    # `optimiser` is now mutated

    cache = (deepcopy(model),
             data,
             history,
             shape,
             optimiser,
             deepcopy(rng),
             move)
    fitresult = MLJFlux.fitresult(model, Flux.cpu(chain), y)

    report = (training_losses=history, )

    return fitresult, cache, report
end

function MLJModelInterface.update(model::MLJFluxModel,
                                  verbosity,
                                  old_fitresult,
                                  old_cache,
                                  X,
                                  y)

    old_model, data, old_history, shape, optimiser, rng, move = old_cache
    old_chain = old_fitresult[1]

    optimiser_flag = model.optimiser_changes_trigger_retraining &&
        model.optimiser != old_model.optimiser

    keep_chain = !optimiser_flag && model.epochs >= old_model.epochs &&
        MLJModelInterface.is_same_except(model, old_model, :optimiser, :epochs)

    if keep_chain
        chain = move(old_chain)
        epochs = model.epochs - old_model.epochs
    else
        move = Mover(model.acceleration)
        rng = true_rng(model)
        chain = build(model, rng, shape) |> move
        data = move.(collate(model, X, y))
        epochs = model.epochs
    end

    penalty = Penalty(model)

    # we only get to keep the optimiser "state" carried over from
    # previous training if we're doing a warm restart and the user has not
    # changed the optimiser hyper-parameter:
    if !keep_chain ||
        !MLJModelInterface._equal_to_depth_one(model.optimiser,
                                              old_model.optimiser)
        optimiser = deepcopy(model.optimiser)
    end

    chain, history = fit!(model.loss,
                          penalty,
                          chain,
                          optimiser,
                          epochs,
                          verbosity,
                          data[1],
                          data[2])
    if keep_chain
        # note: history[1] = old_history[end]
        history = vcat(old_history[1:end-1], history)
    end

    fitresult = MLJFlux.fitresult(model, Flux.cpu(chain), y)
    cache = (deepcopy(model),
             data,
             history,
             shape,
             optimiser,
             deepcopy(rng),
             move)
    report = (training_losses=history, )

    return fitresult, cache, report

end

MLJModelInterface.fitted_params(::MLJFluxModel, fitresult) =
    (chain=fitresult[1],)

# # SUPPORT FOR MLJ ITERATION API

# traits:
MLJModelInterface.supports_training_losses(::Type{<:MLJFluxModel}) =
    true
MLJModelInterface.iteration_parameter(model::Type{<:MLJFluxModel}) = :epochs

# method:
MLJModelInterface.training_losses(::MLJFluxModel, report) =
    report.training_losses[2:end] # exclude pre-training loss


text:
# Structures for reading in data
""" EchelleObservation contains observations for one echelle observation.
Arrays organized into (pixels,orders).
z_bc = Barrycentric correction to convert from observer frame to solar system barrycenter frame.
"""
struct EchelleObservation{T1,T2,T3,T4,T5} <: AbstractEchelleObservation where { T1<:Number, T2<:Number, T3<:Number, T4<:Number, T5<:AbstractInstrument }
   lambda::AbstractArray{T1,2}
   flux::AbstractArray{T2,2}
   var::AbstractArray{T3,2}
   z_bc::T4
   instrument::T5
   metadata::Dict{Symbol,Any}

   function EchelleObservation{T1,T2,T3,T4,T5}(lambda::LambdaT,flux::FluxT,var::VarT,
       z_bc::T4, instrument::T5, metadata::AbstractDict
       )  where { T1<:Number, T2<:Number, T3<:Number, T4<:Number, T5<:AbstractInstrument,
       LambdaT <: AbstractArray{T1,2}, FluxT <: AbstractArray{T2,2},
       VarT <: AbstractArray{T3,2}
       }
      @assert size(lambda)==size(flux)==size(var)
      @assert size(lambda,1) <= max_num_pixels_per_order
      @assert size(lambda,2) <= max_num_orders
      new(lambda,flux,var,z_bc,instrument,metadata)
   end
end
export EchelleObservation

function EchelleObservation(;lambda::LambdaT,flux::FluxT,var::VarT,
    z_bc::T4, instrument::T5, metadata::AbstractDict = Dict{Symbol,Any}()
    )  where { T1<:Number, T2<:Number, T3<:Number, T4<:Number, T5<:AbstractInstrument,
    LambdaT <: AbstractArray{T1,2}, FluxT <: AbstractArray{T2,2},
    VarT <: AbstractArray{T3,2}
    }
    EchelleObservation{eltype(lambda),eltype(flux),eltype(var),typeof(z_bc),typeof(instrument)}(lambda,flux,var,z_bc,instrument,metadata)
end

""" EchelleObservationSet contains observations for multiple echelle observations.
Arrays organized into (pixels,orders,observations).
z_bc = Barrycentric correction to convert from observer frame to solar system barrycenter frame.
"""
struct EchelleObservationSet{T1,T2,T3, #= T4, =# T5} <: AbstractEchelleObservationSet where {T1<:Number, T2<:Number, T3<:Number, #= T4<:Number, =# T5<:AbstractInstrument}
   lambda::Array{T1,3}
   flux::Array{T2,3}
   var::Array{T3,3}
   #= z_bc::Array{T4,1} =#
   instrument::T5
   metadata::Dict{Symbol,Any}
   metadata_list::Array{Dict{Symbol,Any},1}

   function EchelleObservationSet{T1,T2,T3, #= T4, =# T5}(;lambda::AbstractArray{T1,3},
         flux::AbstractArray{T2,3},var::AbstractArray{T3,3}, instrument::T5 = T5(),
         metadata::AbstractDict = Dict{Symbol,Any}(), metadata_list::AbstractArray{Dict{Symbol,Any},1} = Dict{Symbol,Any}[]
          )  where {T1<:Number, T2<:Number, T3<:Number, #= T4<:Number, =# T5<:AbstractInstrument}
      @assert size(lambda)==size(flux)==size(var)
      @assert size(lambda,1) <= max_num_pixels_per_order
      @assert size(lambda,2) <= max_num_orders
      #@assert length(z_bc)==size(lambda,3)
      new(lambda,flux,var,#= z_bc, =# instrument,metadata,metadata_list)
   end

end
export EchelleObservationSet

""" Preallocate arrays for EchelleObservationSet.  Takes obs_size (pixels_per_order,num_orders) and num_obs.  Optionally, instrument and metadata."""
function EchelleObservationSet{T1,T2,T3, #= T4, =# T5}(obs_size::Tuple{Int64,Int64},num_obs::Int = 0;
      instrument::T5 = T5(), metadata::AbstractDict = Dict{Symbol,Any}()
      )  where {T1<:Number, T2<:Number, T3<:Number, #=T4<:Number, =# T5<:AbstractInstrument}
   @assert 0 <= num_obs <= max_num_obs
   lambda = Array{T1,3}(undef,obs_size[1],obs_size[2],num_obs)
   flux   = Array{T2,3}(undef,obs_size[1],obs_size[2],num_obs)
   var    = Array{T3,3}(undef,obs_size[1],obs_size[2],num_obs)
   #=z_bc   = zeros(T4,num_obs) =#
   metadata_list = Array{Dict{Symbol,Any},1}(undef,num_obs)
   EchelleObservationSet{eltype(lambda),eltype(flux),eltype(var),#= eltype(z_bc), =# typeof(instrument) }(lambda=lambda,flux=flux,var=var,#= z_bc=z_bc, =# instrument=instrument,metadata=metadata,metadata_list=metadata_list)
end

function z_bc( eos::EchelleObservationSet{T1,T2,T3, #= T4, =# T5}, obsid::Integer
   ) where {T1<:Number, T2<:Number, T3<:Number, #= T4<:Number, =# T5<:AbstractInstrument}
   @assert 1 <= obsid <= num_obs(eos)
   return eos.metadata_list[obsid][:z_bc]
end

""" Extract one EchelleObservation from an EchelleObservationSet and obs number."""
function EchelleObservation(eos::EchelleObservationSet{T1,T2,T3, #= T4, =# T5}, obs::Integer) where {T1<:Number, T2<:Number, T3<:Number, #= T4<:Number, =# T5<:AbstractInstrument}
   # md = merge(eos.metadata,eos.metadata_list[obs]) # TODO: Should we merge metadata from obs set?
   EchelleObservation(lambda=view(eos.lambda,:,:,obs), flux=view(eos.flux,:,:,obs), var=view(eos.var,:,:,obs), z_bc=z_bc(eos,obs), instrument=eos.instrument, metadata=eos.metadata_list[obs] )
end

function make_average_observation(eos::EchelleObservationSet{T1,T2,T3, #= T4, =# T5}) where {T1<:Number, T2<:Number, T3<:Number, #= T4<:Number, =# T5<:AbstractInstrument}
   nppo = num_pixels_per_order(eos)
   nord = num_orders(eos)
   mean_z_bc = mean(map(i->z_bc(eos,i),1:num_obs(eos)))
   EchelleObservation(lambda=reshape(mean(eos.lambda,dims=3),nppo,nord),
                      flux=reshape(mean(eos.flux,dims=3),nppo,nord),
                      var=reshape(mean(eos.flux,dims=3),nppo,nord),
                      z_bc=mean_z_bc, instrument=eos.instrument, metadata=eos.metadata )
end


text:
module BeamPropagationDev

using StaticArrays, Unitful, LoopVectorization, StatsBase, StructArrays

macro params(fields_tuple)
    fields = fields_tuple.args
    esc(
        quote
            NamedTuple{Tuple($fields)}(($fields_tuple))
        end)
end
export @params

macro with_unit(arg1, arg2)
    arg2 = @eval @u_str $arg2
    return convert(Float64, upreferred(eval(arg1) .* arg2).val)
end
export @with_unit

function dtstep!(rs, vs, as, dt)
    @avx for i in eachindex(rs, vs, as)
        rs[i] += vs[i] * dt + as[i] * (0.5 * dt^2)
        vs[i] += as[i] * dt
    end
    return nothing
end

function dtstep!(particles, dt)
    @avx for i in 1:size(particles, 1)
        r = particles.r[i]
        v = particles.v[i]
        a = particles.a[i]
        particles.r[i] += v * dt + a * (0.5 * dt^2)
        particles.v[i] += a * dt
    end
    return nothing
end

function update_dead!(rs, vs, dead, is_dead)
    @inbounds for i in 1:size(rs,1)
        dead[i] = is_dead(rs[i], vs[i])
    end
    return nothing
end

function save!(save, idxs, rs, vs, as, s)
    @inbounds for i in 1:size(rs,1)
        save(idxs[i], rs[i], vs[i], as[i], s)
    end
    return nothing
end

function setup(idxs, r, v, a, p)
    dead_copy   = zeros(Bool, length(idxs))
    rs_copy     = deepcopy(rs[idxs])
    vs_copy     = deepcopy(vs[idxs])
    as_copy     = deepcopy(as[idxs])
    p_copy      = deepcopy(p)
    return rs_copy, vs_copy, as_copy, dead_copy, p_copy, idxs
end

function initialize_dists(n, r, v, a)
    rx = rand(r[1], n); ry = rand(r[2], n); rz = rand(r[3], n)
    vx = rand(v[1], n); vy = rand(v[2], n); vz = rand(v[3], n)
    ax = rand(a[1], n); ay = rand(a[2], n); az = rand(a[3], n)

    rs = SVector.(rx, ry, rz)
    vs = SVector.(vx, vy, vz)
    as = SVector.(ax, ay, az)

    dead = zeros(Bool, n)
    idxs = collect(1:n)

    return rs, vs, as, dead, idxs
end
export initialize_dists

function copy_save_data(s, chunk_idxs)
    s_copy = NamedTuple()
    for key in keys(s)
        array_to_save = deepcopy(s[key][chunk_idxs])
        s_copy = (; s_copy..., key => array_to_save)
    end
    return s_copy
end

function write_data(s, s_copy, chunk_idxs)
    for key in keys(s)
        s[key][chunk_idxs] .= s_copy[key]
    end
    return nothing
end

function delete_data(rs, vs, as, idxs, dead)
    deleteat!(rs, dead)
    deleteat!(vs, dead)
    deleteat!(as, dead)
    deleteat!(idxs, dead)
    deleteat!(dead, dead)
    return nothing
end

function propagate!(n, dt, r, v, a, f, save, discard, save_every, delete_every, max_steps, p, s_initial, s_final)

    chunk_size = round(Int64, n / Threads.nthreads())
    Threads.@threads for i in 1:Threads.nthreads()

        start_idx   = (i-1)*chunk_size+1
        end_idx     = min(i*chunk_size, n)
        chunk_idxs  = start_idx:end_idx
        actual_chunk_size = length(chunk_idxs)

        rs, vs, as, dead, idxs = initialize_dists(actual_chunk_size, r, v, a)
        #states = s_initial.states # overwrite the initialization of states, which put everything in state "1".

        s_initial_copy = copy_save_data(s_initial, chunk_idxs)
        save!(save, idxs, rs, vs, as, s_initial_copy)
        write_data(s_initial, s_initial_copy, chunk_idxs)

        # Do one round of discards before propagation starts
        update_dead!(rs, vs, dead, discard)
        delete_data(rs, vs, as, idxs, dead)

        # Copy parameters and data arrays to be saved to avoid thread race conditions
        s_copy = copy_save_data(s_final, chunk_idxs)
        p_copy = deepcopy(p)

        #propagate_nosave(dt, rs, vs, as, states, dead, idxs, f, discard, delete_every, max_steps, p_copy, s_copy)
        propagate_withsave(dt, rs, vs, as, dead, idxs, f, discard, save_every, delete_every, max_steps, p_copy, s_copy, save)
        write_data(s_final, s_copy, chunk_idxs)

    end

    return s_initial, s_final
end
export propagate!

function propagate_withsave(dt, rs, vs, as, dead, idxs, f, discard, save_every, delete_every, max_steps, p, s, save)
    step = 0
    while (step <= max_steps)
        if (step % save_every == 0) | (step == max_steps)
            save!(save, idxs, rs, vs, as, s)
        end

        if step % delete_every == 0
            update_dead!(rs, vs, dead, discard)
            delete_data(rs, vs, as, idxs, dead)
        end

        # This should ideally be abstracted out into an `update!` function, defined above. Replacing the code below with `update!(f, idxs, rs, vs, as, states, dt, p, s)` incurs allocations, which can be narrowed down to the arguments `s` and `p`, which are both `NamedTuple`s
        @inbounds for i in 1:size(rs,1)
            v′, a′ = f(idxs[i], rs[i], vs[i], as[i], dt, p, s)
            vs[i] = v′
            as[i] = a′
        end

        dtstep!(rs, vs, as, dt)
        step += 1
    end
    return nothing
end
export propagate_withsave

end


text:
push!(LOAD_PATH, pwd())
using Revise

import Cube
x = Cube.MagicCube(3)
for c in Cube.OneTurnNeighbors(x)
    println(c)
end

y = Cube.shuffle(x, 1)


text:
include("Xpress.jl")
println(version)

m = Model()

println(pwd())
#read_model(m, "testeMod.mps")

#write_model(m, "opt2.mps")

#read_model(m, "testeMod.mps")

#m2 = copy(m)
#write_model(m2, "opt3.mps")

#a = get_int_control(m,XPRS_DEFAULTALG)
#println(a)

add_cvars!(m, [4])
add_vars!(m, XPRS_INTEGER, [33, 43], 0.03, 1.03)
chgcoltype!(m,1,XPRS_INTEGER)
write_model(m, "testeModOut.mps")

add_constr!(m,[1, 2, 3],Cchar('L'),4)

add_constrs!(m, eye(3), XPRS_EQ,ones(3))

A = get_constrmatrix(m)

println(full(A))

#add_rangeconstr!(m,[4,5,6,7],99,100)

#add_rangeconstrs!(m,rand(4,4),20*ones(4),30*ones(4))

add_sos!(m,:SOS1,[1,2],[1.1,1.2])

write_model(m, "teste_withcstr_Out.mps")

show(STDOUT,m)

#out=get_intattr(m,XPRS_COLS)
#out=get_intattr(m,XPRS_MATRIXNAME)
#println(out)


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

using Markdown
using InteractiveUtils

# ╔═╡ 2b3d2532-1bac-491a-aeef-d9c29786341c
begin
	using Pkg
	Pkg.activate(mktempdir())
	Pkg.Registry.update()
	Pkg.add("Yao")
	Pkg.add("YaoPlots")
	Pkg.add("Plots")
	Pkg.add("BitBasis")
	Pkg.add("StatsBase")
end

# ╔═╡ e3cae266-2140-11eb-12f9-31b294a31586
using Yao, YaoPlots

# ╔═╡ 16d09514-2a5d-11eb-23da-b968d2ae5d16
begin
	using StatsBase: Histogram, fit
	using Plots: bar, scatter!, gr; gr()
	using BitBasis
	function plotmeasure(x::Array{BitStr{n,Int},1}, st="#") where n
		hist = fit(Histogram, Int.(x), 0:2^n)
		x = 0
		if(n<=3)
			s=8
		elseif(n>3 && n<=6)
			s=5
		elseif(n>6 && n<=10)
			s=3.2
		elseif(n>10 && n<=15)
			s=2
		elseif(n>15)
			s=1
		end
		bar(hist.edges[1] .- 0.5, hist.weights, title = "Histogram", label="Found in "*string(st)*" tries", size=(600*(2^n)/s,400), ylims=(0:maximum(hist.weights)), xlims=(0:2^n), grid=:false, ticks=false, border=:none, color=:lightblue, lc=:lightblue, foreground_color_legend = nothing, background_color_legend = nothing)
		scatter!(0:2^n-1, ones(2^n,1), markersize=0, label=:none,
         series_annotations="|" .* string.(hist.edges[1]; base=2, pad=n) .* "⟩")
		scatter!(0:2^n-1, zeros(2^n,1) .+ maximum(hist.weights), markersize=0, label=:none, series_annotations=string.(hist.weights))
	end
end

# ╔═╡ ecb98520-212d-11eb-02e4-f3c89c254998
md"# Grover's Algorithm"

# ╔═╡ 0b9fb54a-212e-11eb-1f1d-8912b444cc0c
md"Suppose you've got 10 boxes, each with a paper with a random number on it, and you're searching for a number which may or may not be in one of the boxes. You'll have to search the first box, then the second, then the third... and so on, until you've found what you were looking for. Best case scenario - it just took one search (the number could be in the first box)! Worst case - it took 10 searches(it could've been in the last box, or in no box at all! ).

Even if you get a bit clever, sort all the boxes according to the numbers in them, in ascending or descending order, and apply something like [binary search](https://en.wikipedia.org/wiki/Binary_search_algorithm), it'll almost take log₂(n) searches.

Grover's Algorithm is a search algorithm, which solves the problem in O(`` \sqrt{n} ``) [time complexity](https://en.wikipedia.org/wiki/Time_complexity)(it takes `` 𝜋\sqrt{N}/4 `` searches, for one possible match)."

# ╔═╡ 88c22c5e-2130-11eb-2b73-5fbbbd662df9
md"## Sign flipping"

# ╔═╡ 326c3b46-2140-11eb-333e-27744c831983
md"Consider you've 3 qubits, with the state vector :-

`` \frac{1}{\sqrt{8}} |000〉 + \frac{1}{\sqrt{8}} |001〉 + \frac{1}{\sqrt{8}} |010〉 + \frac{1}{\sqrt{8}} |011〉 + \frac{1}{\sqrt{8}} |100〉 + \frac{1}{\sqrt{8}} |101〉 + \frac{1}{\sqrt{8}} |110〉 + \frac{1}{\sqrt{8}} |111〉 ``"

# ╔═╡ c72bdf32-2140-11eb-1aec-55864296f0d3
begin
	qubits = uniform_state(3)
	state(qubits)
end

# ╔═╡ 746f121a-2141-11eb-2fab-5333ec478316
md"Suppose there was a circuit U, and if you passed the three qubits to U, the resultant state vector would look somewhat like this :-

`` \frac{1}{\sqrt{8}} |000〉 + \frac{1}{\sqrt{8}} |001〉 - \frac{1}{\sqrt{8}} |010〉 + \frac{1}{\sqrt{8}} |011〉 + \frac{1}{\sqrt{8}} |100〉 + \frac{1}{\sqrt{8}} |101〉 + \frac{1}{\sqrt{8}} |110〉 + \frac{1}{\sqrt{8}} |111〉 ``"

# ╔═╡ b8c52404-2141-11eb-0759-6db99f9ffa3a
md"One thing we know about this *magical* circuit is that its matrix representation looks like this,

`` \begin{bmatrix}1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & -1 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\1 & 0 & 0 & 0 & 0 & 0 & 1 & 0\\1 & 0 & 0 & 0 & 0 & 0 & 0 & 1\end{bmatrix} ``

Try multiplying the above state vector to the new matrix."

# ╔═╡ b47f24e2-2143-11eb-2e85-59a9f7762ddd
let
	U = rand(8,8) |> U->round.(round.(U * inv(U)))
	U[3,3] = -1
	U * state(qubits)
end

# ╔═╡ 433f40da-2145-11eb-35c0-6faaad23f32b
md"### Creating the magic circuit"

# ╔═╡ 9971e84e-28df-11eb-25e2-d9c71ae9dc42
md"You'll have to think about each circuit individually, according to the the element you want to flip. We're flipping `` \; |010〉 `` in this case. The circuit will be denoted by `` U_𝑓 ``."

# ╔═╡ 656cf846-444f-11eb-369e-f7919462e228
plot(chain(3, put(1:3 => label(chain(3), "U𝑓"))))

# ╔═╡ 4d81dbde-444f-11eb-1aae-7b666f5af174
md"Below is my implementation of this magic circuit"

# ╔═╡ 1f33e8c2-28e2-11eb-2f62-1fc0b46a05d3
begin
	U𝑓 = chain(3, repeat(X, [1 3]), control(1:2, 3=>Z), repeat(X, [1 3]))
	plot(U𝑓)
end

# ╔═╡ 9f8330b4-28e2-11eb-1a9d-1dce3076770d
md"The circuit for `` |011〉 `` will be"

# ╔═╡ bbc3dac6-28e2-11eb-0907-b72813ebe035
begin
	U𝑓_1 = chain(3, repeat(X, [3]), control(1:2, 3=>Z), repeat(X, [3]))
	plot(U𝑓_1)
end

# ╔═╡ 73b8c0aa-28e4-11eb-2c7c-b3177793ff92
state(uniform_state(3))

# ╔═╡ 72eb8480-28f5-11eb-3315-779a888c1d55
md"After passing the uniform qubits through U𝑓."

# ╔═╡ 089832b4-28f4-11eb-0c43-3de7e3518c9b
state(uniform_state(3) |> U𝑓)

# ╔═╡ d53e1414-28ea-11eb-35ab-81897180dd8b
md"## Amplitude Amplification"

# ╔═╡ cef6748e-28ea-11eb-1956-b9c7e4dd4d2b
md"Lets consider you want to increase one particular probability amplitude and decrease the rest."

# ╔═╡ f10966fe-28f5-11eb-0630-753ba509b76e
md"If your qubits were initially in the state :-

`` \frac{1}{\sqrt{8}} |000〉 + \frac{1}{\sqrt{8}} |001〉 + \frac{1}{\sqrt{8}} |010〉 + \frac{1}{\sqrt{8}} |011〉 + \frac{1}{\sqrt{8}} |100〉 + \frac{1}{\sqrt{8}} |101〉 + \frac{1}{\sqrt{8}} |110〉 + \frac{1}{\sqrt{8}} |111〉 ``"

# ╔═╡ fc46d108-28f5-11eb-0a1c-19b2ba4aa3df
md"Then you want them in the state :-"

# ╔═╡ 2a73a70e-28f6-11eb-1af0-0b5f034c2cf4
md"`` 1 × |010〉 ``"

# ╔═╡ 664e40c2-28f6-11eb-1957-5702b452c054
md"That means, ideally, the probability amplitude of `` |010〉 `` being close to `` 1 ``, while of others being close to `` 0 ``."

# ╔═╡ b5687650-28f6-11eb-12d3-eb2ddd6a7a2b
md"Inversion about the mean is a neat trick which helps you achieve that."

# ╔═╡ c966ad98-28f6-11eb-2f80-5fa5c652e0ea
md"### Inversion about the mean"

# ╔═╡ d0ee0d5e-28f6-11eb-38c5-8b634905b9ff
md"Its simple. I'll give an example."

# ╔═╡ e4be8aca-28f6-11eb-0f6b-35d51dcbce35
testmat = rand(10)

# ╔═╡ 210ef6b8-28f7-11eb-3277-a9fe7833f046
md"Lets plot it as a histogram"

# ╔═╡ 2af2a47c-28f7-11eb-1a3c-77de4ea4f692
bar(testmat)

# ╔═╡ f1fbacd6-28f6-11eb-27bc-e31d6628e6db
md"Say, I want to amplify the 4th element. Here's the procedure"

# ╔═╡ 95570f44-4470-11eb-17d4-83ffdf99888e
mean(x) = sum(x)/length(x)

# ╔═╡ 0fcf3598-28f7-11eb-2716-d7974741c9a8
begin
	matamplified = copy(testmat)
	matamplified[4] = -matamplified[4]
	matamplified = (2 .* mean(matamplified)) .- matamplified
end

# ╔═╡ cecd6894-446f-11eb-3ba2-876a7ff2acef
bar(matamplified)

# ╔═╡ e17009b0-28f9-11eb-0000-5db9eb38b481
md"What just happened:-
- In an array, choose the element you want to amplify.
- Flip the sign of that element.
- Then the new array with the element amplified, will have the elements :-
`` Amplified\; array = (2 × mean) - (the\; original\; array\; with\; the\; flipped\; element). ``
"

# ╔═╡ 98810d58-2a4b-11eb-25c2-9991e8613634
md"What if we do it again? Will it get amplified again?"

# ╔═╡ aa9a9d1a-2a4b-11eb-2433-69c46633f83c
begin
	newmatamplified = copy(matamplified)
	newmatamplified[4] = -newmatamplified[4]
	newmatamplified = (2 .* mean(newmatamplified)) .- newmatamplified
end

# ╔═╡ d6ff51ac-2a4b-11eb-10c8-b715525467d3
bar(newmatamplified)

# ╔═╡ bc7e15c4-2a56-11eb-1645-95457df3f2b6
md"So yes, it does amplified again"

# ╔═╡ dfe846d8-2a56-11eb-31cd-d3d400d0c0b2
md"### The Circuit Implementation"

# ╔═╡ f60823d4-2a56-11eb-2552-e540e863a617
md"The circuit for amplification looks like this, if the sign of the desired state is flipped"

# ╔═╡ 350bf890-4450-11eb-21cc-6db807eeb0e1
YaoPlots.plot(put(3, 1:3 => label(chain(3), "U𝜑")))

# ╔═╡ b2964bf8-4450-11eb-298e-9bf5088ef7ac
md"Again, below is my implementation of it."

# ╔═╡ c5c81956-2a59-11eb-3656-d35c46e52f2a
begin
	U𝜑 = chain(3, repeat(H, 1:3), repeat(X, 1:3), put(3=>H), control(1:2, 3=>X), put(3=>H), repeat(X, 1:3), repeat(H, 1:3))
	plot(U𝜑)
end

# ╔═╡ 923205f4-2a5c-11eb-2075-4bda871c8155
md"Combining this with the circuit for flipping, we get the Grovers Search Circuit, to which we feed qubits with _**uniform state**_."

# ╔═╡ d44b8aba-4450-11eb-39bd-e1e784c7c489
YaoPlots.plot(chain(3, put(1:3 => label(chain(3), "U𝑓")), put(1:3 => label(chain(3), "U𝜑")), Measure(3, locs=1:3)))

# ╔═╡ 4fd7213a-4451-11eb-2c68-81536a97de0a
md"Below is the complete circuit implementation. Remember, the input to the circuit is  quits with uniform state."

# ╔═╡ d8fef778-2a5a-11eb-069c-351c0ff94b59
begin
	GroversSearchCircuit = chain(3, put(1:3=>U𝑓), put(1:3=>U𝜑), Measure(3, locs=1:3))
	plot(GroversSearchCircuit)
end

# ╔═╡ 19662fd2-2a5d-11eb-22fd-771b25ebce68
md"The below function plots the measurement function, just pass the measured values to it. You don't need to know its inner mechanisms to use it."

# ╔═╡ d4234cc0-2a89-11eb-0801-4bdffce7f359
md"Below is the implementation of the **_Grover's Search Algorithm_** to find `` |010〉 ``."

# ╔═╡ d2766870-2a5d-11eb-0484-7dc4c494b160
begin
	n = 3
	output = 0
	j = 0
	for i in 1:(2^3)
		input = uniform_state(n)
		global output = input |> GroversSearchCircuit |> r->measure(r, nshots=1000)
		if(output[1] == bit"010") #Checking for |010〉
			break
		end
		global j = i
	end
	plotmeasure(output, j+1)
end

# ╔═╡ 4f8749de-2a8f-11eb-0687-4b44e155f53c
md"You can keep running the above block of code, and you'll find that it takes a maximum of 4 tries to find the state `` |010〉 ``, which would be the worst case. Most of the times, you can find it in the first try!

Which sounds about right."

# ╔═╡ Cell order:
# ╠═2b3d2532-1bac-491a-aeef-d9c29786341c
# ╟─ecb98520-212d-11eb-02e4-f3c89c254998
# ╟─0b9fb54a-212e-11eb-1f1d-8912b444cc0c
# ╟─88c22c5e-2130-11eb-2b73-5fbbbd662df9
# ╟─326c3b46-2140-11eb-333e-27744c831983
# ╠═e3cae266-2140-11eb-12f9-31b294a31586
# ╠═c72bdf32-2140-11eb-1aec-55864296f0d3
# ╟─746f121a-2141-11eb-2fab-5333ec478316
# ╟─b8c52404-2141-11eb-0759-6db99f9ffa3a
# ╠═b47f24e2-2143-11eb-2e85-59a9f7762ddd
# ╟─433f40da-2145-11eb-35c0-6faaad23f32b
# ╟─9971e84e-28df-11eb-25e2-d9c71ae9dc42
# ╟─656cf846-444f-11eb-369e-f7919462e228
# ╟─4d81dbde-444f-11eb-1aae-7b666f5af174
# ╠═1f33e8c2-28e2-11eb-2f62-1fc0b46a05d3
# ╟─9f8330b4-28e2-11eb-1a9d-1dce3076770d
# ╠═bbc3dac6-28e2-11eb-0907-b72813ebe035
# ╠═73b8c0aa-28e4-11eb-2c7c-b3177793ff92
# ╟─72eb8480-28f5-11eb-3315-779a888c1d55
# ╠═089832b4-28f4-11eb-0c43-3de7e3518c9b
# ╟─d53e1414-28ea-11eb-35ab-81897180dd8b
# ╟─cef6748e-28ea-11eb-1956-b9c7e4dd4d2b
# ╟─f10966fe-28f5-11eb-0630-753ba509b76e
# ╟─fc46d108-28f5-11eb-0a1c-19b2ba4aa3df
# ╟─2a73a70e-28f6-11eb-1af0-0b5f034c2cf4
# ╟─664e40c2-28f6-11eb-1957-5702b452c054
# ╟─b5687650-28f6-11eb-12d3-eb2ddd6a7a2b
# ╟─c966ad98-28f6-11eb-2f80-5fa5c652e0ea
# ╟─d0ee0d5e-28f6-11eb-38c5-8b634905b9ff
# ╠═e4be8aca-28f6-11eb-0f6b-35d51dcbce35
# ╟─210ef6b8-28f7-11eb-3277-a9fe7833f046
# ╠═2af2a47c-28f7-11eb-1a3c-77de4ea4f692
# ╟─f1fbacd6-28f6-11eb-27bc-e31d6628e6db
# ╠═95570f44-4470-11eb-17d4-83ffdf99888e
# ╠═0fcf3598-28f7-11eb-2716-d7974741c9a8
# ╠═cecd6894-446f-11eb-3ba2-876a7ff2acef
# ╟─e17009b0-28f9-11eb-0000-5db9eb38b481
# ╟─98810d58-2a4b-11eb-25c2-9991e8613634
# ╠═aa9a9d1a-2a4b-11eb-2433-69c46633f83c
# ╠═d6ff51ac-2a4b-11eb-10c8-b715525467d3
# ╟─bc7e15c4-2a56-11eb-1645-95457df3f2b6
# ╟─dfe846d8-2a56-11eb-31cd-d3d400d0c0b2
# ╟─f60823d4-2a56-11eb-2552-e540e863a617
# ╟─350bf890-4450-11eb-21cc-6db807eeb0e1
# ╟─b2964bf8-4450-11eb-298e-9bf5088ef7ac
# ╠═c5c81956-2a59-11eb-3656-d35c46e52f2a
# ╟─923205f4-2a5c-11eb-2075-4bda871c8155
# ╟─d44b8aba-4450-11eb-39bd-e1e784c7c489
# ╟─4fd7213a-4451-11eb-2c68-81536a97de0a
# ╠═d8fef778-2a5a-11eb-069c-351c0ff94b59
# ╟─19662fd2-2a5d-11eb-22fd-771b25ebce68
# ╠═16d09514-2a5d-11eb-23da-b968d2ae5d16
# ╟─d4234cc0-2a89-11eb-0801-4bdffce7f359
# ╠═d2766870-2a5d-11eb-0484-7dc4c494b160
# ╟─4f8749de-2a8f-11eb-0687-4b44e155f53c


text:
"""
Provides a consistent interface to retreiving `DocStr` objects from the Julia
docsystem in both `0.4` and `0.5`.
"""
module DocSystem

using DocStringExtensions
import Markdown
import Base.Docs: MultiDoc, parsedoc, formatdoc, DocStr

## Bindings ##

"""
Converts an object to a `Base.Docs.Binding` object.

$(SIGNATURES)

Supported inputs are:

- `Binding`
- `DataType`
- `Function`
- `Module`
- `Symbol`

Note that unsupported objects will throw an `ArgumentError`.
"""
binding(any::Any) = throw(ArgumentError("cannot convert `$(repr(any))` to a `Binding`."))

#
# The simple definitions.
#
binding(b::Docs.Binding) = binding(b.mod, b.var)
binding(d::DataType)     = binding(d.name.module, d.name.name)
binding(m::Module)       = binding(m, nameof(m))
binding(s::Symbol)       = binding(Main, s)
binding(f::Function)     = binding(typeof(f).name.module, typeof(f).name.mt.name)

#
# We need a lookup table for `IntrinsicFunction`s since they do not track their
# own name and defining module.
#
# Note that `IntrinsicFunction` is exported from `Base` in `0.4`, but not in `0.5`.
#
let INTRINSICS = Dict(map(s -> getfield(Core.Intrinsics, s) => s, names(Core.Intrinsics, all=true)))
    global binding(i::Core.IntrinsicFunction) = binding(Core.Intrinsics, INTRINSICS[i]::Symbol)
end

#
# Normalise the parent module.
#
# This is done within the `Binding` constructor on `0.5`, but not on `0.4`.
#
function binding(m::Module, v::Symbol)
    m = nameof(m) === v ? parentmodule(m) : m
    Docs.Binding(m, v)
end

#
# Pseudo-eval of `Expr`s to find their equivalent `Binding`.
#
binding(m::Module, x::Expr) =
    Meta.isexpr(x, :.) ? binding(getmod(m, x.args[1]), x.args[2].value) :
    Meta.isexpr(x, [:call, :macrocall, :curly]) ? binding(m, x.args[1]) :
    Meta.isexpr(x, :where) ? binding(m, x.args[1].args[1]) :
        error("`binding` cannot understand expression `$x`.")

# Helper methods for the above `binding` method.
getmod(m::Module, x::Expr) = getfield(getmod(m, x.args[1]), x.args[2].value)
getmod(m::Module, s::Symbol) = getfield(m, s)

binding(m::Module, q::QuoteNode) = binding(Main, q.value)

binding(m::Module, λ::Any) = binding(λ)

## Signatures. ##

function signature(x, str::AbstractString)
    ts = Base.Docs.signature(x)
    (Meta.isexpr(x, :macrocall, 2) && !endswith(strip(str), "()")) ? :(Union{}) : ts
end

## Docstring containers. ##

"""
Construct a `MultiDoc` object from the provided argument.

Valid inputs are:

- `Markdown.MD`
- `Docs.FuncDoc`
- `Docs.TypeDoc`

"""
function multidoc end

function multidoc(markdown::Markdown.MD)
    md = MultiDoc()
    sig = Union{}
    push!(md.order, sig)
    md.docs[sig] = docstr(markdown)
    md
end

"""
$(SIGNATURES)

Construct a `DocStr` object from a `Markdown.MD` object.

The optional keyword arguments are used to add new data to the `DocStr`'s
`.data` dictionary.
"""
function docstr(md::Markdown.MD; kws...)
    data = Dict{Symbol, Any}(
        :path => md.meta[:path],
        :module => md.meta[:module],
        :linenumber => 0,
    )
    doc = DocStr(Core.svec(), md, data)
    for (key, value) in kws
        doc.data[key] = value
    end
    doc
end
docstr(other) = other

## Formatting `DocStr`s. ##

## Converting docstring caches. ##

"""
$(SIGNATURES)

Converts a `0.4`-style docstring cache into a `0.5` one.

The original docstring cache is not modified.
"""
function convertmeta(meta::IdDict{Any,Any})
    if !haskey(CACHED, meta)
        docs = IdDict{Any,Any}()
        for (k, v) in meta
            if !isa(k, Union{Number, AbstractString, IdDict{Any,Any}})
                docs[binding(k)] = multidoc(v)
            end
        end
        CACHED[meta] = docs
    end
    CACHED[meta]::IdDict{Any,Any}
end
const CACHED = IdDict{Any,Any}()

## Get docs from modules.

"""
$(SIGNATURES)

Find all `DocStr` objects that match the provided arguments:

- `binding`: the name of the object.
- `typesig`: the signature of the object. Default: `Union{}`.
- `compare`: how to compare signatures? Exact (`==`) or subtypes (`<:`). Default: `<:`.
- `modules`: which modules to search through. Default: *all modules*.
- `aliases`: check aliases of `binding` when nothing is found. Default: `true`.

Returns a `Vector{DocStr}` ordered by definition order in `0.5` and by
`type_morespecific` in `0.4`.
"""
function getdocs(
        binding::Docs.Binding,
        typesig::Type = Union{};
        compare = (==),
        modules = Docs.modules,
        aliases = true,
    )
    # Fall back to searching all modules if user provides no modules.
    modules = isempty(modules) ? Docs.modules : modules
    # Keywords are special-cased within the docsystem. Handle those first.
    iskeyword(binding) && return [docstr(Base.Docs.keywords[binding.var])]
    # Handle all the other possible bindings.
    results = DocStr[]
    for mod in modules
        meta = getmeta(mod)
        if haskey(meta, binding)
            multidoc = meta[binding]::MultiDoc
            for signature in multidoc.order
                if compare(typesig, signature)
                    doc = multidoc.docs[signature]
                    doc.data[:binding] = binding
                    doc.data[:typesig] = signature
                    push!(results, doc)
                end
            end
        end
    end
    if compare == (==)
        # Exact matching of signatures:
        #
        # When we get a single match from using `==` as the comparision then we just return
        # that one result.
        #
        # Otherwise we fallback to comparing signatures using `<:` to match, hopefully, a
        # wider range of possible docstrings.
        if length(results) == 1
            results
        else
            getdocs(binding, typesig; compare = (<:), modules = modules, aliases = aliases)
        end
    else
        # When nothing is found we check whether the `binding` is an alias of some other
        # `Binding`. If so then we redo the search using that `Binding` instead.
        if aliases && isempty(results) && (b = aliasof(binding)) != binding
            getdocs(b, typesig; compare = compare, modules = modules)
        else
            results
        end
    end
end

"""
$(SIGNATURES)

Accepts objects of any type and tries to convert them to `Binding`s before
searching for the `Binding` in the docsystem.

Note that when conversion fails this method returns an empty `Vector{DocStr}`.
"""
function getdocs(object::Any, typesig::Type = Union{}; kws...)
    binding = aliasof(object, object)
    binding === object ? DocStr[] : getdocs(binding, typesig; kws...)
end

#
# Helper methods used by the `getdocs` function above.
#

getmeta(m::Module) = Docs.meta(m)

import Base.Docs: aliasof, resolve, defined

aliasof(s::Symbol, b) = binding(s)

iskeyword(b::Docs.Binding) = b.mod === Main && haskey(Base.Docs.keywords, b.var)
ismacro(b::Docs.Binding) = startswith(string(b.var), '@')

function category(b::Docs.Binding)
    if iskeyword(b)
        :keyword
    elseif ismacro(b)
        :macro
    else
        category(resolve(b))
    end
end
category(::Function) = :function
category(::DataType) = :type
category(x::UnionAll) = category(Base.unwrap_unionall(x))
category(::Module) = :module
category(::Any) = :constant

end


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

using Markdown
using InteractiveUtils

# ╔═╡ d473d078-50fd-11ec-2009-8f5f5a7256bc
cd(@__DIR__)

# ╔═╡ 3dba0c21-7b4e-4b9e-b40c-4a7ac8ba006f
readdir(pwd())

# ╔═╡ ddbdb520-3feb-4223-8fa8-c4c771bb89e5
# read the original eventlist file `foo.txt` and
# return a new file named `foo_NEW.txt`.
# The function also print out the converted file.
function refactor_trigger!(
	original_file;
	target_file = split(original_file, ".")[1] * "_NEW" * ".txt"
)
ls = readlines(original_file)
for idx in eachindex(ls)
	if length(ls[idx]) > 0 && !startswith(ls[idx], "#")
		if     lstrip(ls[idx][15:21]) == "211"
   ls[idx  ] = replace(ls[idx  ], ls[idx  ][23:38] => lpad("\"AndNopauseN1\"", 16))
   ls[idx+1] = replace(ls[idx+1], ls[idx+1][23:38] => lpad("\"AndNopauseV\"", 16))
   ls[idx+2] = replace(ls[idx+2], ls[idx+2][23:38] => lpad("\"AndNopauseN2\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][23:38] => lpad("\"AndNopauseC\"", 16))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][23:38] => lpad("\"AndNopauseN3\"", 16))
   ls[idx+5] = replace(ls[idx+5], ls[idx+5][23:38] => lpad("\"AndNopauseEnd\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][15:21]
   		=> lpad(lstrip(ls[idx+3][15:21]) * lstrip(ls[idx][15:21]), 7))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][15:21]
   		=> lpad(lstrip(ls[idx+4][15:21]) * lstrip(ls[idx][15:21]), 7))
		elseif lstrip(ls[idx][15:21]) == "212"
   ls[idx  ] = replace(ls[idx  ], ls[idx  ][23:38] => lpad("\"And200msN1\"", 16))
   ls[idx+1] = replace(ls[idx+1], ls[idx+1][23:38] => lpad("\"And200msV\"", 16))
   ls[idx+2] = replace(ls[idx+2], ls[idx+2][23:38] => lpad("\"And200msN2\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][23:38] => lpad("\"And200msC\"", 16))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][23:38] => lpad("\"And200msN3\"", 16))
   ls[idx+5] = replace(ls[idx+5], ls[idx+5][23:38] => lpad("\"And200msEnd\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][15:21]
   		=> lpad(lstrip(ls[idx+3][15:21]) * lstrip(ls[idx][15:21]), 7))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][15:21]
   		=> lpad(lstrip(ls[idx+4][15:21]) * lstrip(ls[idx][15:21]), 7))
		elseif lstrip(ls[idx][15:21]) == "221"
   ls[idx  ] = replace(ls[idx  ], ls[idx  ][23:38] => lpad("\"OrNopauseN1\"", 16))
   ls[idx+1] = replace(ls[idx+1], ls[idx+1][23:38] => lpad("\"OrNopauseV\"", 16))
   ls[idx+2] = replace(ls[idx+2], ls[idx+2][23:38] => lpad("\"OrNopauseN2\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][23:38] => lpad("\"OrNopauseC\"", 16))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][23:38] => lpad("\"OrNopauseN3\"", 16))
   ls[idx+5] = replace(ls[idx+5], ls[idx+5][23:38] => lpad("\"OrNopauseEnd\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][15:21]
   		=> lpad(lstrip(ls[idx+3][15:21]) * lstrip(ls[idx][15:21]), 7))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][15:21]
   		=> lpad(lstrip(ls[idx+4][15:21]) * lstrip(ls[idx][15:21]), 7))
	   elseif lstrip(ls[idx][15:21]) == "222"
   ls[idx  ] = replace(ls[idx  ], ls[idx  ][23:38] => lpad("\"Or200msN1\"", 16))
   ls[idx+1] = replace(ls[idx+1], ls[idx+1][23:38] => lpad("\"Or200msV\"", 16))
   ls[idx+2] = replace(ls[idx+2], ls[idx+2][23:38] => lpad("\"Or200msN2\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][23:38] => lpad("\"Or200msC\"", 16))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][23:38] => lpad("\"Or200msN3\"", 16))
   ls[idx+5] = replace(ls[idx+5], ls[idx+5][23:38] => lpad("\"Or200msEnd\"", 16))
   ls[idx+3] = replace(ls[idx+3], ls[idx+3][15:21]
   		=> lpad(lstrip(ls[idx+3][15:21]) * lstrip(ls[idx][15:21]), 7))
   ls[idx+4] = replace(ls[idx+4], ls[idx+4][15:21]
   		=> lpad(lstrip(ls[idx+4][15:21]) * lstrip(ls[idx][15:21]), 7))
		end
	end
end
open(target_file, "w") do io
	for line in ls
		println(io, line)
	end
end
return ls
end

# ╔═╡ a45539e9-03c5-4ace-a9a8-eea7236180ca
refactor_trigger!("01/S01_elist.txt")

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
"""

# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised

julia_version = "1.7.2"
manifest_format = "2.0"

[deps]
"""

# ╔═╡ Cell order:
# ╠═d473d078-50fd-11ec-2009-8f5f5a7256bc
# ╠═3dba0c21-7b4e-4b9e-b40c-4a7ac8ba006f
# ╠═a45539e9-03c5-4ace-a9a8-eea7236180ca
# ╠═ddbdb520-3feb-4223-8fa8-c4c771bb89e5
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002


text:
using Statistics

@testset "std" begin
    @test testf(std, rand(10))
    @test testf(std, rand(10,1,2))
    @test testf(std, rand(10,1,2), corrected=true)
    @test testf(std, rand(10,1,2), dims=1)
end
@testset "var" begin
    @test testf(var, rand(10))
    @test testf(var, rand(10,1,2))
    @test testf(var, rand(10,1,2), corrected=true)
    @test testf(var, rand(10,1,2), dims=1)
end


text:
module SVMModels

using Random
using DataFrames
import LIBSVM

using ..AbsTypes
using ..BaseFilters
using ..Utils

import ..AbsTypes: fit, fit!, transform, transform!

export fit, fit!, transform, transform!
export SVMModel, svmlearners

const svm_dict = Dict{String,Any}()

function __init__()
   svm_dict["SVC"]         = LIBSVM.SVC
   svm_dict["NuSVC"]       = LIBSVM.NuSVC
   svm_dict["OneClassSVM"] = LIBSVM.OneClassSVM
   svm_dict["NuSVR"]       = LIBSVM.NuSVR
   svm_dict["EpsilonSVR"]  = LIBSVM.EpsilonSVR
   svm_dict["LinearSVC"]   = LIBSVM.LinearSVC
end

"""
    SVMModel(
      Dict(
        :name => "svm",
        :svmtype => "SVC"
      )
    )

Wrapper for LIBSVM.jl for pipeline integration.

Implements `fit!` and `transform!`.
"""
mutable struct SVMModel <: Transformer
  name::String
  model::Dict{Symbol,Any}

  function SVMModel(args::Dict = Dict())
    default_args = Dict{Symbol,Any}(
	    :name => "libsvm",
       :learner => "SVC",
       :impl_args => Dict{Symbol,Any}(
          :tolerance => 0.001
       )
	 )
	 cargs=nested_dict_merge(default_args,args)
	 cargs[:name] = cargs[:name]*"_"*randstring(3)
    svmlearner = cargs[:learner]
    if !(svmlearner in keys(svm_dict))
       println("$svmlearner is not supported")
       println()
       svmlearners()
       throw(ArgumentError("not in dictionary"))
    end
    new(cargs[:name],cargs)
  end
end

"""
    SVMModel(svmt::String,opt=Dict())

Helper function
"""
function SVMModel(learner::String,opt::Dict)
   SVMModel(Dict(:learner=>learner,:impl_args=>opt))
end

"""
    SVMModel(svmt::String;opt...)

Helper function
"""
function SVMModel(learner::String;opt...)
   SVMModel(Dict(:learner=>learner,:impl_args=>Dict(pairs(opt))))
end

function svmlearners()
   learners = keys(svm_dict) |> collect |> x-> sort(x,lt=(x,y)->lowercase(x)<lowercase(y))
   println("syntax: SVMModel(learner::String; args...)")
   println("where 'learner' can be one of:")
   println()
   [print(learner," ") for learner in learners]
   println()
   println()
   println("and 'args' are the corresponding learner's initial parameters.")
   println("Note: Consult LIBSVM.jl and LIBSVM github for more details about the learner's arguments.")
end

"""
   fit!(svm::SVMModel, features::DataFrame, labels::Vector=[])

Train the model using  SVM fit!

# Arguments
- `svm::SVMModel:` custom type
- `features::DataFrame`: input
- `labels::Vector=[]`:
"""
function fit!(svm::SVMModel, features::DataFrame, labels::Vector=[])::Nothing
   if features == DataFrame()
      throw(ArgumentError("empty dataframe"))
   end
   svmlearner = svm_dict[svm.model[:learner]]
   lv = convert(Vector,labels)
   featarray = convert(Array,features)
   impl_args = svm.model[:impl_args]
   model = LIBSVM.fit!(svmlearner(;impl_args...),featarray,lv)
   svm.model[:svmmodel]=model
   return nothing
end

function fit(svm::SVMModel, features::DataFrame, labels::Vector=[])::SVMModel
   fit!(svm,features,labels)
   return deepcopy(svm)
end

"""
    transform!(svm::SVMModel, features::DataFrame)

Predict using svm model

# Arguments
- `svm::SVMModel`: custom type
- `features::DataFrame`: input
"""
function transform!(svm::SVMModel, features::DataFrame)::Vector
  if features == DataFrame()
      throw(ArgumentError("empty dataframe"))
  end
  featarray = convert(Array,features)
  model = svm.model[:svmmodel]
  pred = LIBSVM.predict(model,featarray)
  return pred
end

function transform(svm::SVMModel, features::DataFrame)::Vector
   return transform!(svm,features)
end

end


text:
using MosekTools, DifferentialEquations, PyPlot, LaTeXStrings, MarkovBounds
DE = DifferentialEquations
@polyvar(x[1:2])
@polyvar(u[1:1])
@polyvar(t)
γ = [1, 2, 1, 2, 0.25*0.1]

f = [γ[1] * x[1] - γ[2] * x[1] * x[2] ;
     γ[4] * x[1] * x[2] - γ[3] * x[2] - x[2]*u[1]]

g = [γ[5]*x[1]; 0]
σ = polynomial.(g*g')

x0 = [1.0; 0.25]

Tf = 10.0
x_target = [0.75, 0.5]
u_target = 0.5

lagrange = (x[1] - x_target[1])^2 + (x[2] - x_target[2])^2/10 + (u[1] - u_target)^2/10

## data
order = 4
nt = 10
trange = range(Tf/nt, stop = Tf, length=nt)

## solve
MP = DiffusionProcess(x, f, σ, @set(x[1] >= 0 && x[2] >= 0))
CP = ControlProcess(MP, Tf, u, t, @set(u[1] >= 0 && u[1] <= 1), nothing, nothing, LagrangeMayer(lagrange, 0), 0)

bnds, V = optimal_control(CP, x0, order, trange, Mosek.Optimizer; value_function = true)

N = 100
urange = 0:0.05:1.0
function control_policy(z,s)
    one_step_MPC = extended_inf_generator(MP, V(z,s)[1], t) + lagrange
    u = urange[findmin([one_step_MPC(z..., u, s) for u in urange])[2]]
    return u
end
drift(x,p,t) = [f[1](x[1],x[2]); f[2](x[1],x[2],control_policy(x[1:2], t)); lagrange(x[1],x[2],control_policy(x[1:2], t))]
drift_uncontrolled(x,p,t) = [f[1](x[1],x[2]); f[2](x[1],x[2], u_target); 0]
diffusion(x,p,t) = [g[1](x[1]); 0; 0]
sde = DE.SDEProblem(drift, diffusion, [x0..., 0], (0.0,Tf))
sde_uncontrolled = DE.SDEProblem(drift_uncontrolled, diffusion, [x0..., 0], (0.0,Tf))
sde_ensemble = DE.EnsembleProblem(sde)
sde_ensemble_uncontrolled = DE.EnsembleProblem(sde_uncontrolled)

trajectories = DE.solve(sde_ensemble, trajectories=N, EM(), dt = 0.01)
trajectories_uncontrolled = DE.solve(sde_ensemble_uncontrolled, trajectories=N, EM(), dt = 0.01)

fig, ax = subplots(3,1,figsize=(10,12))
for sol in trajectories_uncontrolled
    global ln_uc = ax[1].plot(sol.t, [u[1] for u in sol.u], color="blue", linewidth=0.5)
    ax[2].plot(sol.t, [u[2] for u in sol.u], color="blue", linewidth=0.5)
    ax[3].plot([u[1] for u in sol.u], [u[2] for u in sol.u], color = "blue", linewidth=0.5)
end

for sol in trajectories
    global ln_c = ax[1].plot(sol.t, [u[1] for u in sol.u], color="red", linewidth=0.5)
    ax[2].plot(sol.t, [u[2] for u in sol.u], color="red", linewidth=0.5)
    ax[3].plot([u[1] for u in sol.u], [u[2] for u in sol.u], color = "red", linewidth=0.5)
end
ax[1].plot([0,Tf], [x_target[1], x_target[1]], color="k", linewidth=1, linestyle="dashed")
ax[2].plot([0,Tf], [x_target[2], x_target[2]], color="k", linewidth=1, linestyle="dashed")
ax[1].legend([ln_uc[1], ln_c[1]], ["uncontrolled","controlled"])
ax[2].set_xlabel("time [s]")
ax[1].set_ylabel(L"x_1")
ax[2].set_ylabel(L"x_2")
ax[3].set_xlabel(L"x_1")
ax[3].set_ylabel(L"x_2")

empiric_control_cost = sum(sol.u[end][3] for sol in trajectories)/N
display(fig)
println("Empiric control cost = ", empiric_control_cost)
println("Lower bound on control cost = ", bnds.bounds)
println("Degree of suboptimality = ", (empiric_control_cost-bnds.bounds)/bnds.bounds)


text:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Description
#
#   Compute the moon position.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# References
#
#   [1] Vallado, D. A (2013). Fundamentals of Astrodynamics and Applications.
#       Microcosm Press, Hawthorne, CA.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

export moon_position_i

"""
    moon_position_i(JD_TDB::Number)

Compute the Moon position represented in the IAU-76/FK5 (mean-equator,
mean-equinox), also called as J2000, at the Julian Day `JD`. The algorithm was
adapted from [1, p. 288].

"""
function moon_position_i(JD_TDB::Number)
    # Constants.
    deg2rad = π/180

    # Number of Julian centuries from J2000 epoch.
    T_TDB = (JD_TDB-JD_J2000)/36525.0

    # Auxiliary computation to improve performance.
    sin1, cos1 = sincos( (134.9 + 477_198.85T_TDB)*deg2rad )
    sin2, cos2 = sincos( (259.2 - 413_335.38T_TDB)*deg2rad )
    sin3, cos3 = sincos( (235.7 + 890_534.23T_TDB)*deg2rad )
    sin4, cos4 = sincos( (269.9 + 954_397.70T_TDB)*deg2rad )
    sin5       = sind(357.5 +  35_999.05T_TDB)
    sin6       = sind(186.6 + 966_404.05T_TDB)

    # Ecliptic latitude of the Moon [deg].
    λₑ = 218.32 + 481_267.8813T_TDB +
         6.29sin1 - 1.27sin2 + 0.66sin3 + 0.21sin4 - 0.19sin5 - 0.11sin6

    # Ecliptic longitude of the Moon [deg].
    ϕₑ = 5.13sind( 93.3 + 483_202.03T_TDB) + 0.28sind(228.2 + 960_400.87T_TDB) -
         0.28sind(318.3 +   6_003.18T_TDB) - 0.17sind(217.6 - 407_332.20T_TDB)

    # Parallax [deg].
    P = 0.9508 + 0.0518cos1 + 0.0095cos2 + 0.0078cos3 + 0.0028cos4

    # Obliquity of the ecliptic [deg].
    ϵ = @evalpoly(T_TDB, 23.439_291, -0.013_004_2, -1.64e-7, +5.04e-7)

    # Convert to radians and limit to the interval [0,2π].
    λₑ = mod2pi(λₑ*deg2rad)
    ϕₑ = mod2pi(ϕₑ*deg2rad)
    P  = mod2pi( P*deg2rad)
    ϵ  = mod2pi( ϵ*deg2rad)

    # Compute the distance from Earth to the Moon [m].
    r = R0/sin(P)

    # Auxiliary variables.
    sinλ, cosλ = sincos(λₑ)
    sinϕ, cosϕ = sincos(ϕₑ)
    sinϵ, cosϵ = sincos(ϵ)

    # Compute the Moon vector represented in J2000 (IAU-76/KF5 mean-equator,
    # mean-equinox).
    r_J2000 = SVector{3,Float64}(r*(cosϕ*cosλ),
                                 r*(cosϵ*cosϕ*sinλ - sinϵ*sinϕ),
                                 r*(sinϵ*cosϕ*sinλ + cosϵ*sinϕ))

    return r_J2000
end


text:
"""
    function play_doubles_match(
        team1::Team,
        team2::Team,
        tournament::Tournament,
        round::Int64,
        strength_method::String
    )::Team

Simulates a doubles match between two teams.

Arguments
=========
- `team1`:
    a team composed of two players.
- `team2`
    a team composed of two players.
- `tournament`
    the tournament in which this match is taking place.
- `round`
    the current round number of the tournament
- `strength_method`
    the method to use to determine the probability of team 1
    beating team 2.
"""

function play_doubles_match(
    team1::Team,
    team2::Team,
    tournament::Tournament,
    round::Int64,
    strength_method::String
)::Team
    for players in [(team1.player1, team1.player2), (team2.player1, team2.player2)]
        players[1].matches_played += 1
        players[2].matches_played += 1
        if !haskey(players[1].doubles_results, tournament.id)
            players[1].doubles_results[tournament.id] = DoublesTournamentPlayerSummary(
                primary_player_id = players[1].id,
                partner_player_id = players[2].id,
                tournament_name = tournament.name,
                tournament_type = tournament.type,
                result = "",
                matches = Array{DoublesMatchPlayerSummary}([])
            )
        end
        if !haskey(players[2].doubles_results, tournament.id)
            players[2].doubles_results[tournament.id] = DoublesTournamentPlayerSummary(
                primary_player_id = players[2].id,
                partner_player_id = players[1].id,
                tournament_name = tournament.name,
                tournament_type = tournament.type,
                result = "",
                matches = Array{DoublesMatchPlayerSummary}([])
            )
        end
    end

    if rand() <= probabilityOfWinning(team1, team2, strength_method)
        winner = team1
    else
        winner = team2
    end

    for team in [team1, team2]
        if team == winner
            for player in [team.player1, team.player2]
                push!(
                    player.doubles_results[tournament.id].matches,
                    DoublesMatchPlayerSummary(
                        opponent1_player_id = (team1 == winner) ?
                            team2.player1.id : team1.player1.id,
                        opponent2_player_id = (team1 == winner) ?
                            team2.player2.id : team1.player2.id,
                        result = "Won",
                        score = "6-0, 6-0, 6-0"
                    )
                )
            end
        else
            for player in [team.player1, team.player2]
                push!(
                    player.doubles_results[tournament.id].matches,
                    DoublesMatchPlayerSummary(
                        opponent1_player_id = (team1 == winner) ?
                             team1.player1.id : team2.player1.id,
                        opponent2_player_id = (team1 == winner) ?
                             team1.player2.id : team2.player2.id,
                        result = "Lost",
                        score = "0-6, 0-6, 0-6"
                    )
                )
                player.doubles_results[tournament.id].result = round_to_result(round)
            end
        end
    end
    return winner
end

max_stars_repo_name: Danial-Hussain/Tennis-Ranking

max_issues_repo_name: Danial-Hussain/Tennis-Ranking

max_forks_repo_name: Danial-Hussain/Tennis-Ranking