text:
### Data structures ###
abstract type OptData <: InputData end

"""
     OptModelCEP
The essential elements of a CapacityExpansionProblem are organized as a `OptModelCEP` struct:
- `model`::JuMP.Model - contains the actual JuMP-Model
- `info`::Array{String} - contains the information about the model setup in form of multiple lines of equations
- `set`::Dict{String,Array} - contains the sets used by the model
"""
struct OptModelCEP
  model::JuMP.Model
  info::Array{String}
  set::Dict{String,Dict{String,Array}}
end

"""
    OptVariable{T,N,Ax,L<:NTuple{N,Dict}} <: AbstractArray{T,N}{
    data::Array{T,N},
    axes::Ax,
    lookup::L,
    axes_names::Array{String,1}}
    type::String
OptVariable is a structure that allows to have a multi-dimensional `data`-Array that can be indexed using keys. An examplary lookup can be done the following way: `optvar['key1','key2']=value`.
The value can be of any type like e.g. `Float64`.
The OptVariable is used both for data input and output.
- `data::Array` - includes the optimization variable output in  form of an array
- `axes_names::Array{String,1}`` - includes the names of the different axes and is equivalent to the sets in the optimization formulation
- `axes::Tuple` - includes the values of the different axes of the optimization variables
- `type::String` - defines the type of the variable being cv - cost variable - dv -design variable - ov - operating variable - sv - slack variable
"""
struct OptVariable{T,N,Ax,L<:NTuple{N,Dict}} <: AbstractArray{T,N}
    data::Array{T,N}
    axes::Ax
    lookup::L
    axes_names::Array{String,1}
    type::String
end

"""
      OptResult{status::Symbol,
                objective::Float64,
                variables::Dict{String,Any},
                sets::Dict{String,Dict{String,Array}},
                opt_config::Dict{String,Any},
                opt_info::Dict{String,Any}}
The result of an optimized model is organized as an `OptResult` struct:
- `status`: Symbol about the solution status of the model in normal cases `:OPTIMAL`
- `objective`: Value of the objective function
- `variables`: Dictionary with each variables in form of `OptVariable` structs as entries. For details on indexing the `OptVariables` see the `OptVariable` documentation
- `sets`: Dictionary with each set as an entry
- `config`: The configuration of the model setup - for more detail see tye `run_opt` documentation that sets the `config` up
- `info`: Holds information about the model. E.g. `info["model"]` contains the exact equations used in the model.

## Sets
The sets are setup as a dictionary and organized as `set[tech_name][tech_group]=[elements...]`, where:
- `tech_name` is the name of the dimension like e.g. `tech`, or `node`
- `tech_group` is the name of a group of elements within each dimension like e.g. `["all", "generation"]`. The group `'all'` always contains all elements of the dimension
- `[elements...]` is the Array with the different elements like `["pv", "wind", "gas"]`

| name             | description                                                           |
|------------------|-----------------------------------------------------------------------|
| lines            | transmission lines connecting the nodes                               |
| nodes            | spacial energy system nodes                                           |
| tech             | generation, conversion, storage, and transmission technologies        |
| carrier          | carrier that an energy balance is calculated for `electricity`, `hydrogen`...|
| impact           | impact categories like EUR or USD, CO 2 − eq., ...                    |
| account          | fixed costs for installation and yearly expenses, variable costs      |
| infrastruct      | infrastructure status being either new or existing                    |
| time K           | numeration of the representative periods                              |
| time T period    | numeration of the time intervals within a period                      |
| time T point     | numeration of the time points within a period                          |
| time I period    | numeration of the time invervals of the full input data periods       |
| time I point     | numeration of the time points of the full input data periods           |
| dir transmission | direction of the flow uniform with or opposite to the lines direction |

## Variables
| name      | type | dimensions                 | unit                    | description |
|-----------|------|----------------------------|-------------------------|------------|
| COST      | `cv` | [account,impact,tech]      | EUR/USD, LCA-categories | Costs      |
| CAP       | `dv` | [tech,infrastruct,node]    | MW                      | Capacity   |
| GEN       | `ov` | [tech,carrier,t,k,node]    | MW                      | Generation |
| SLACK     | `sv` | [carrier,t,k,node]         | MW                      | Power gap, not provided by installed CAP |
| LL        | `sv` | [carrier]                  | MWh                     | LoastLoad Generation gap, not provided by installed CAP |
| LE        | `sv` | [impact]                   | LCA-categories          | LoastEmission Amount of emissions that installed CAP crosses the Emission constraint |
| INTRASTOR | `ov` | [tech,carrier,t,k,node]    | MWh                     | Storage level within a period |
| INTERSTOR | `ov` | [tech,carrier,i,node]      | MWh                     | Storage level between periods of the full time series |
| FLOW      | `ov` | [tech,carrier,dir,t,k,line]| MW                      | Flow over transmission line |
| TRANS     | `ov` | [tech,infrastruct,lines]   | MW                      | maximum capacity of transmission lines |
"""
struct OptResult
 status::Symbol
 objective::Float64
 variables::Dict{String,Any}
 sets::Dict{String,Dict{String,Array}}
 config::Dict{String,Any}
 info::Dict{String,Any}
end

"""
     OptDataCEP{region::String,
                costs::OptVariable,
                techs::OptVariable,
                nodes::OptVariable,
                lines::OptVariabl} <: OptData
All not timeseries depending data for the CapacityExpansionProblem is stored in an `OptDataCEP` struct. `OptVariable` structs are used to index an element of e.g. `.costs['pv','germany',2016,'var','EUR']=value`. Depending on the field the value has another type like `Number`, `OptDataCEPLine`,...
- `region::String`:          name of state or region data belongs to
- `costs::OptVariable`:    costs[tech,node,year,account,impact] - `Number`
- `techs::OptVariable`:    techs[tech] - `OptDataCEPTech`
- `nodes::OptVariable`:    nodes[tech, node] - `OptDataCEPNode`
- `lines::OptVariable`:     lines[tech, line] - `OptDataCEPLine`
"""
struct OptDataCEP <: OptData
   region::String
   costs::OptVariable
   techs::OptVariable
   nodes::OptVariable
   lines::OptVariable
end

#struct LatLon() adapted from Package Geodesy.jl: Copyright (c) 2014-2016: Ted Steiner, Sean Garborg, Yeesian Ng, Andy Ferris, Andrew Smith

#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
"""
    LatLon(lat, lon)
    LatLon(lat = ϕ, lon = Θ)
Latitude and longitude co-ordinates. *Note:* assumes degrees not radians
"""
struct LatLon{T <: Number}
    lat::T
    lon::T
end
LatLon(lat::Number, lon::Number) = LatLon(promote(lat, lon)...)
LatLon(;lat=NaN,lon=NaN) = LatLon(lat,lon) # Constructor that is independent of storage order
Base.show(io::IO, ll::LatLon) = print(io, "LatLon(lat=$(ll.lat)°, lon=$(ll.lon)°)")
Base.isapprox(ll1::LatLon, ll2::LatLon; atol = 1e-6, kwargs...) = isapprox(ll1.lat, ll2.lat; atol = 180*atol/6.371e6, kwargs...) & isapprox(ll1.lon, ll2.lon; atol = 180*atol/6.371e6, kwargs...) # atol in metres (1μm)

"""
     OptDataCEPNode{name::String,
                    value::Number,
                    lat::Number,
                    lon::Number} <: OptData
The information about the nodes in stored in an `OptDataCEPNode` struct:
- `name`
- `power_ex` existing capacity [MW or MWh (tech_e)]
- `power_lim` capacity limit [MW or MWh (tech_e)]
- `region`
- `latlon` hold geolocation information [°,°]
"""
struct OptDataCEPNode <: OptData
  name::String
  power_ex::Number
  power_lim::Number
  region::String
  latlon::LatLon
end

"""
     OptDataCEPLine{name::String,
                    node_start::String,
                    node_end::String,
                    reactance::Number,
                    resistance::Number,
                    power::Number,
                    circuits::Int,
                    voltage::Number,
                    length::Number} <: OptData
The information of the single lines is stored in an `OptDataCEPLine` struct:
- `name`: Name of the line
- `node_start` Node where line starts
- `node_end` Node where line ends
- `reactance`
- `resistance` [Ω]
- `power_ex`: existing power limit [MW]
- `power_lim`: limit power limit [MW]
- `circuits` [-]
- `voltage` [V]
- `length` [km]
- `eff` [-]
"""
struct OptDataCEPLine <: OptData
  name::String
  node_start::String
  node_end::String
  reactance::Number
  resistance::Number
  power_ex::Number
  power_lim::Number
  circuits::Int
  voltage::Number
  length::Number
  eff::Number
end

"""
     OptDataCEPTech{name::String
                   tech_group::Array{String,1}
                   unit::String
                   structure::String
                   plant_lifetime::Number
                   financial_lifetime::Number
                   discount_rate::Number
                   annuityfactor::Number
                   input::Dict
                   output::Dict
                   constraints::Dict} <: OptData
The information of the single tech is stored in an `OptDataCEPTech` struct:
- `name`: A detailed name of the technology
- `tech_group`: technology-groups that the technology belongs to. Groups can be: `all`, `demand`, `generation`, `dispatchable_generation`, `non_dispatchable_generation`, `storage`, `conversion`, `transmission`
- `plant_lifetime`: the lifetime of this technologies plant [a]
- `financial_lifetime`: financial time to break even [a]
- `annuityfactor`: the annuityfactor is calculated based on the discount_rate and the plant_lifetime
- `discount_rate`: discount rate for technology [a]
- `structure`: `node` or `line` depending on the structure of the technology
- `unit`: the unit that the capacity of the technology scales with. It can be `power`[MW] or `energy`[MWh]
- `input`: the input can be a `carrier` like e.g. electricity `"carrier" => electricity, a `timeseries` like e.g. `"timeseries"=> demand_electricity`, or a `fuel` like e.g. `fuel: gas`
- `constraints`: a dictionary with information like an `efficiency` like e.g. `"efficiency"=> 0.53` or `cap_eq` (e.g. discharge capacity is same as charge capacity) `"cap_eq" => "bat_in"`
returns `techs::OptVariable`    techs[tech] - OptDataCEPTech
"""
struct OptDataCEPTech <: OptData
  name::String
  tech_group::Array{String,1}
  unit::String
  structure::String
  plant_lifetime::Number
  financial_lifetime::Number
  discount_rate::Number
  annuityfactor::Number
  input::Dict
  output::Dict
  constraints::Dict
end

"""
     Scenario{descriptor::String,
     clust_res::AbstractClustResult,
     opt_res::OptResult}
A scenario is organized in a `Scenario` struct:
-`descriptor::String`
-`clust_res::AbstractClustResult`
-`opt_res::OptResult`
"""
struct Scenario
 descriptor::String
 clust_res::AbstractClustResult
 opt_res::OptResult
end


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

using Markdown
using InteractiveUtils

# ╔═╡ 0b19c578-762b-11eb-34b6-01e80cef1406
using Pkg, DrWatson

# ╔═╡ 3f814e9e-762b-11eb-1340-91617ca7b58a
begin
    using Distributions
    using StatsPlots
    using StatsBase
    using LaTeXStrings
    using CSV
    using DataFrames
    using LinearAlgebra
    using Random
    using StanSample
    using StatisticalRethinking
end

# ╔═╡ af1efcf4-779a-11eb-0d62-e3c63876a09b
md" ## Clip-09-25-27s.jl"

# ╔═╡ cb88768a-779b-11eb-1a4e-99f92ded29ca
begin
	y = rand(Normal(), 100)
	data = (N = length(y), y=y)
end;

# ╔═╡ e37331ea-779b-11eb-1b02-1fdb61aae124
stan9_4 = "
data {
	int N;
	vector[N] y;
}
parameters{
    real a1;
    real a2;
    real<lower=0> sigma;
}
model{
    real mu;
    sigma ~ exponential( 1 );
    a2 ~ normal( 0 , 1000 );
    a1 ~ normal( 0 , 1000 );
    mu = a1 + a2;
    y ~ normal( mu , sigma );
}
";

# ╔═╡ 3fafc7fe-762b-11eb-37da-254b6d75f5ca
begin
	m9_4s = SampleModel("m9.4s", stan9_4)
	rc9_4s = stan_sample(m9_4s; data)

	if success(rc9_4s)
		m9_4s_df = read_samples(m9_4s, :dataframe)
		PRECIS(m9_4s_df)
	end
end

# ╔═╡ 140d4962-7ebd-11eb-20f6-efc652cf9335
read_summary(m9_4s)

# ╔═╡ b4d020b8-762d-11eb-167a-9fd79d948647
trankplot(m9_4s, :a1)[1]

# ╔═╡ 7b4bc93e-7ebb-11eb-1912-f152a5e76df6
trankplot(m9_4s, :a2)[1]

# ╔═╡ 728ad3aa-7eb7-11eb-2fea-634a82832501
trankplot(m9_4s, :sigma)[1]

# ╔═╡ 059b3ada-7eb8-11eb-10aa-459e3ec2bc55
begin
	chns9_4s = read_samples(m9_4s, :mcmcchains)
	Text(sprint(show, "text/plain", summarize(chns9_4s)))
end

# ╔═╡ 453b6b34-8356-11eb-0049-51a7363b24d4
CHNS(chns9_4s)

# ╔═╡ 6fbfa790-7eb9-11eb-0360-ed6fc7fa11a3
plot(chns9_4s)

# ╔═╡ a93a71e4-7eb9-11eb-2a36-d33e7b88e2d6
stan9_5 = "
data {
	int N;
	vector[N] y;
}
parameters{
    real a1;
    real a2;
    real<lower=0> sigma;
}
model{
    real mu;
    sigma ~ exponential( 1 );
    a2 ~ normal( 0 , 10 );
    a1 ~ normal( 0 , 10 );
    mu = a1 + a2;
    y ~ normal( mu , sigma );
}
";

# ╔═╡ b4ea8d58-7eb9-11eb-172f-3941a1b8fe98
begin
	m9_5s = SampleModel("m9.5s", stan9_5)
	rc9_5s = stan_sample(m9_5s; data)

	if success(rc9_5s)
		m9_5s_df = read_samples(m9_5s, :dataframe)
		PRECIS(m9_5s_df)
	end
end

# ╔═╡ ef7953e8-7eb9-11eb-3344-8d762d7e3584
trankplot(m9_5s, :a1)[1]

# ╔═╡ f042277e-7ebb-11eb-33d4-b7edd9539943
trankplot(m9_5s, :a2)[1]

# ╔═╡ 29b1d698-7eba-11eb-00aa-e95796579cc6
trankplot(m9_5s, :sigma)[1]

# ╔═╡ 39bb0f76-7eba-11eb-1bc2-293259d12dfc
begin
	chns9_5s = read_samples(m9_5s, :mcmcchains)
	Text(sprint(show, "text/plain", summarize(chns9_5s)))
end

# ╔═╡ 6748f438-8380-11eb-312d-cbfe0500b586
CHNS(chns9_5s)

# ╔═╡ 43b362c6-7eba-11eb-389e-fb53b3783e8d
plot(chns9_5s)

# ╔═╡ ca61c622-779a-11eb-1292-3f272953867f
md" ## End of clip-09-25-27s.jl"

# ╔═╡ Cell order:
# ╟─af1efcf4-779a-11eb-0d62-e3c63876a09b
# ╠═0b19c578-762b-11eb-34b6-01e80cef1406
# ╠═3f814e9e-762b-11eb-1340-91617ca7b58a
# ╠═cb88768a-779b-11eb-1a4e-99f92ded29ca
# ╠═e37331ea-779b-11eb-1b02-1fdb61aae124
# ╠═3fafc7fe-762b-11eb-37da-254b6d75f5ca
# ╠═140d4962-7ebd-11eb-20f6-efc652cf9335
# ╠═b4d020b8-762d-11eb-167a-9fd79d948647
# ╠═7b4bc93e-7ebb-11eb-1912-f152a5e76df6
# ╠═728ad3aa-7eb7-11eb-2fea-634a82832501
# ╠═059b3ada-7eb8-11eb-10aa-459e3ec2bc55
# ╠═453b6b34-8356-11eb-0049-51a7363b24d4
# ╠═6fbfa790-7eb9-11eb-0360-ed6fc7fa11a3
# ╠═a93a71e4-7eb9-11eb-2a36-d33e7b88e2d6
# ╠═b4ea8d58-7eb9-11eb-172f-3941a1b8fe98
# ╠═ef7953e8-7eb9-11eb-3344-8d762d7e3584
# ╠═f042277e-7ebb-11eb-33d4-b7edd9539943
# ╠═29b1d698-7eba-11eb-00aa-e95796579cc6
# ╠═39bb0f76-7eba-11eb-1bc2-293259d12dfc
# ╠═6748f438-8380-11eb-312d-cbfe0500b586
# ╠═43b362c6-7eba-11eb-389e-fb53b3783e8d
# ╟─ca61c622-779a-11eb-1292-3f272953867f

ext: jl


text:
using LCPSim
using Base.Test
using RigidBodyDynamics
using RigidBodyDynamics: Bounds
using StaticArrays: SVector
using Gurobi

@testset "joint limits" begin
    @testset "1D mechanism" begin
        world = RigidBody{Float64}("world")
        mech = Mechanism(world; gravity=SVector(0, 0, -9.81))
        frame = CartesianFrame3D("link")
        inertia = SpatialInertia(frame, eye(3), SVector(0., 0, 0), 1.0)
        link = RigidBody(inertia)
        slider = Joint("slider", Prismatic(SVector(0., 0, 1)),
                       position_bounds=[Bounds(0.0, 1.0)],
                       velocity_bounds=[Bounds(-10., 10.)],
                       effort_bounds=[Bounds(0., 0.)])
        attach!(mech, world, link, slider)
        env = Environment{Float64}([])
        x0 = MechanismState{Float64}(mech)
        set_configuration!(x0, [0.5])

        Δt = 0.05
        N = 100
        controller = LCPSim.passive_controller()
        results = LCPSim.simulate(x0, controller,
                                  env, Δt, N, GurobiSolver(Gurobi.Env(), OutputFlag=0))
        @test length(results) == N
        for r in results
            @test -1e-3 <= configuration(r.state)[1] <= 1 + 1e-3
        end
        @test configuration(results[end].state)[1] <= 1e-3
        @test norm(velocity(results[end].state)) <= 1e-3
    end

    @testset "planar mechanism" begin
        world = RigidBody{Float64}("world")
        mech = Mechanism(world; gravity=SVector(0, 0, -9.81))
        frame = CartesianFrame3D("link")
        inertia = SpatialInertia(frame, eye(3), SVector(0., 0, 0), 1.0)
        link = RigidBody(inertia)

        planar = Joint("planar", Planar([1., 0, 0], [0., 0, 1.]),
                       position_bounds=[Bounds(-5., 5), Bounds(0., 3), Bounds(-2π, 2π)],
                       velocity_bounds=[Bounds(-10., 10), Bounds(-10., 10), Bounds(-2π, 2π)],
                       effort_bounds=[Bounds(0., 0) for i in 1:3])
        attach!(mech, world, link, planar)
        env = Environment{Float64}([])
        x0 = MechanismState{Float64}(mech)
        set_configuration!(x0, [0.5, 1.0, 0.3])

        Δt = 0.05
        N = 100
        controller = LCPSim.passive_controller()
        results = LCPSim.simulate(x0, controller,
                                  env, Δt, N, GurobiSolver(Gurobi.Env(), OutputFlag=0))
        @test length(results) == N
        for r in results
            @test -5.0 - 1e-3 <= configuration(r.state)[1] <= 5.0 + 1e-3
            @test 0.0 - 1e-3 <= configuration(r.state)[2] <= 3.0 + 1e-3
            @test -2π - 1e-3 <= configuration(r.state)[3] <= 2π + 1e-3
        end
        @test configuration(results[end].state) ≈ [0.5, 0.0, 0.3]
        @test norm(velocity(results[end].state)) ≈ 0 atol=1e-8
    end
end


text:
using OffsetArrays

using Compiler3
import Compiler3: entrypoint, mi_at_cursor, FunctionGraph

struct ADCursor
    level::Int
    mi::MethodInstance
end
mi_at_cursor(c::ADCursor) = c.mi

#=
Cthulhu.get_cursor(c::ADCursor, callinfo::Cthulhu.PullbackCallInfo) = ADCursor(c.level+1, Cthulhu.get_mi(callinfo.mi))
Cthulhu.get_cursor(c::ADCursor, cs::Cthulhu.Callsite) = Cthulhu.get_cursor(c, cs.info)
Cthulhu.get_cursor(c::ADCursor, callinfo) = ADCursor(c.level, Cthulhu.get_mi(callinfo))
=#

struct ADGraph <: FunctionGraph
    code::OffsetVector{Dict{MethodInstance, Any}}
    msgs::Vector{Tuple{Int, MethodInstance, Int, String}}
    entry_mi::MethodInstance
end
entrypoint(graph::ADGraph) = ADCursor(0, graph.entry_mi)
Compiler3.has_codeinfo(graph::ADGraph, cursor::ADCursor) =
    lastindex(graph.code) >= cursor.level && haskey(graph.code[cursor.level], cursor.mi)
function Compiler3.get_codeinstance(graph::ADGraph, cursor::ADCursor)
    return graph.code[cursor.level][cursor.mi]
end

struct ADInterpreter <: AbstractInterpreter
    # This cache is stratified by AD nesting level. Depending on the
    # nesting level of the derivative, The AD primitives may behave
    # differently.
    # Level 0 == Straightline Code, no AD
    # Level 1 == Gradients
    # Level 2 == Seconds Derivatives
    # and so on
    code::OffsetVector{Dict{MethodInstance, Any}}
    native_interpreter::NativeInterpreter
    current_level::Int
    msgs::Vector{Tuple{Int, MethodInstance, Int, String}}
end
change_level(interp::ADInterpreter, new_level::Int) = ADInterpreter(interp.code, interp.native_interpreter, new_level, interp.msgs)
raise_level(interp::ADInterpreter) = change_level(interp, interp.current_level + 1)
lower_level(interp::ADInterpreter) = change_level(interp, interp.current_level - 1)

function Core.Compiler.is_same_frame(interp::ADInterpreter, linfo::MethodInstance, frame::InferenceState)
    linfo === frame.linfo || return false
    return interp.current_level === frame.interp.current_level
end

ADInterpreter() = ADInterpreter(
    OffsetVector([Dict{MethodInstance, Any}(), Dict{MethodInstance, Any}()], 0:1),
    NativeInterpreter(),
    0,
    Vector{Tuple{Int, MethodInstance, Int, String}}()
)

ADInterpreter(fg::ADGraph, level) =
    ADInterpreter(fg.code, NativeInterpreter(), level, fg.msgs)

InferenceParams(ei::ADInterpreter) = InferenceParams(ei.native_interpreter)
OptimizationParams(ei::ADInterpreter) = OptimizationParams(ei.native_interpreter)
get_world_counter(ei::ADInterpreter) = get_world_counter(ei.native_interpreter)
get_inference_cache(ei::ADInterpreter) = get_inference_cache(ei.native_interpreter)

# No need to do any locking since we're not putting our results into the runtime cache
lock_mi_inference(ei::ADInterpreter, mi::MethodInstance) = nothing
unlock_mi_inference(ei::ADInterpreter, mi::MethodInstance) = nothing

struct CodeInfoView
    d::Dict{MethodInstance, Any}
end

function code_cache(ei::ADInterpreter)
    while ei.current_level > lastindex(ei.code)
        push!(ei.code, Dict{MethodInstance, Any}())
    end
    ei.code[ei.current_level]
end
Core.Compiler.may_optimize(ei::ADInterpreter) = false
Core.Compiler.may_compress(ei::ADInterpreter) = false
Core.Compiler.may_discard_trees(ei::ADInterpreter) = false
function Core.Compiler.get(view::CodeInfoView, mi::MethodInstance, default)
    r = get(view.d, mi, nothing)
    if r === nothing
        return default
    end
    if isa(r, OptimizationState)
        r = r.src
    end
    return r::CodeInfo
end

function Core.Compiler.add_remark!(ei::ADInterpreter, sv::InferenceState, msg)
    push!(ei.msgs, (ei.current_level, sv.linfo, sv.currpc, msg))
end

function Core.Compiler.const_prop_heuristic(interp::AbstractInterpreter, method::Method, mi::MethodInstance)
    return true
end

function Core.Compiler.transform_result_for_cache(ei::ADInterpreter, linfo::MethodInstance, @nospecialize(result::Any))
    if isa(result, OptimizationState)
        ci = result.src
        nargs = result.nargs - 1
        ir = Core.Compiler.convert_to_ircode(ci, Core.Compiler.copy_exprargs(ci.code), false, nargs, result)
        ir = Core.Compiler.slot2reg(ir, ci, nargs, result)
        ir = compact!(ir)
        resize!(ir.argtypes, result.nargs)
        result = ir
    end
    return result
end


text:
abstract type FranklinException <: Exception end

#
# Parsing related
#

"""An OCBlock was not parsed properly (e.g. the closing token was not found)."""
struct OCBlockError <: FranklinException
    m::String
    c::String
end

"""An Env Block was not parsed properly (e.g. the closing delim not found)."""
struct EnvBlockError <: FranklinException
    m::String
    c::String
end

function Base.showerror(io::IO, be::OCBlockError)
    println(io, be.m)
    print(io, be.c)
end

"""A `\\newcommand` was not parsed properly."""
struct LxDefError <: FranklinException
    m::String
end

"""A latex command or environment was found but could not be processed properly."""
struct LxObjError <: FranklinException
    m::String
end

"""A math block name failed to parse."""
struct MathBlockError <: FranklinException
    m::String
end

"""A Page Variable wasn't set properly."""
struct PageVariableError <: FranklinException
    m::String
end

#
# HTML related
#

"""An HTML block (e.g. [`HCond`](@see)) was erroneous."""
struct HTMLBlockError <: FranklinException
    m::String
end

"""An HTML function (e.g. `{{fill ...}}`) failed."""
struct HTMLFunctionError <: FranklinException
    m::String
end

#
# ASSET PATH error
#

"""A relative path was erroneous."""
struct RelativePathError <: FranklinException
    m::String
end

"""A file was not found."""
struct FileNotFoundError <: FranklinException
    m::String
end

#
# CODE
#

"""A relative path was erroneous for Literate."""
struct LiterateRelativePathError <: FranklinException
    m::String
end


text:
# Autogenerated wrapper script for Clingo_jll for i686-w64-mingw32-cxx11
export clasp, clingo, gringo, libclingo, lpconvert, reify

JLLWrappers.@generate_wrapper_header("Clingo")
JLLWrappers.@declare_executable_product(clasp)
JLLWrappers.@declare_executable_product(clingo)
JLLWrappers.@declare_executable_product(gringo)
JLLWrappers.@declare_library_product(libclingo, "libclingo.dll")
JLLWrappers.@declare_executable_product(lpconvert)
JLLWrappers.@declare_executable_product(reify)
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_executable_product(
        clasp,
        "bin\\clasp.exe",
    )

    JLLWrappers.@init_executable_product(
        clingo,
        "bin\\clingo.exe",
    )

    JLLWrappers.@init_executable_product(
        gringo,
        "bin\\gringo.exe",
    )

    JLLWrappers.@init_library_product(
        libclingo,
        "bin\\libclingo.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_executable_product(
        lpconvert,
        "bin\\lpconvert.exe",
    )

    JLLWrappers.@init_executable_product(
        reify,
        "bin\\reify.exe",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
export Disk,𝔻

# T is Real or Complex
# TT is (Real,Real) or Complex
"""
    Disk(c,r)

represents the disk centred at `c` with radius `r`.
"""
struct Disk{T} <: Domain{T}
    center::T
    radius::Float64
end

Disk(c,r) = Disk{typeof(c)}(c,r)
Disk(c::Real,r) = Disk(complex(c),r)
Disk(c::Integer,r) = Disk(float(c),r)
Disk(c::Complex{<:Integer},r) = Disk(float(c),r)

Disk() = Disk(Vec(0.,0.),1.)
Disk(::AnyDomain) = Disk(NaN,(NaN,NaN))

const 𝔻 = Disk()

isambiguous(d::Disk) = isnan(d.radius) && all(isnan,d.center)

#canonical is rectangle [r,0]x[-π,π]
# we assume radius and centre are zero for now
fromcanonical(D::Disk{T},x,t) where {T<:Real} =
    Vec(D.radius*x*cos(t)+D.center[1],D.radius*x*sin(t)+D.center[2])
tocanonical(D::Disk{T},x,y) where {T<:Real} =
    Vec(sqrt((x-D.center[1])^2+(y-D.center[2])^2)/D.radius,
        atan(y-D.center[2],x-D.center[1]))
checkpoints(d::Disk) = [fromcanonical(d,(.1,.2243));fromcanonical(d,(-.212423,-.3))]

# function points(d::Disk,n,m,k)
#     ptsx=0.5*(1-gaussjacobi(n,1.,0.)[1])
#     ptst=points(PeriodicSegment(),m)
#
#     Float64[fromcanonical(d,x,t)[k] for x in ptsx, t in ptst]
# end

boundary(d::Disk) = Circle(d.center,d.radius)


text:
"""
    swapHomes!(S::Array{Int, 2}, i::Int, j::Int)

swaps home/away roles of two teams `i` and `j` in the schedule.
"""
function swap_homes!(S::Array{Int, 2}, i::Int, j::Int)
    slot1 = 0
    slot2 = 0
    @inbounds for col = 1:size(S, 2)
        if S[i, col] == j
            slot1 = col
        end
        if S[j, col] == i
            slot2 = col
        end
        if slot1 !== 0 && slot2 !== 0
            break
        end
    end
    @assert slot1 != 0 && slot2 != 0
    S[i, slot1], S[i, slot2] = S[i, slot2], S[i, slot1]
    S[j, slot1], S[j, slot2] = S[j, slot2], S[j, slot1]
end

"""
    swapRounds!(S::Array{Int, 2}, k::Int, l::Int)

Swaps the two rounds `k` and `l` in the schedule.
"""
function swap_rounds!(S::Array{Int, 2}, k, l)
    @inbounds for row = 1:size(S, 1)
        S[row, k], S[row, l] = S[row, l], S[row, k]
    end
end

"""
    slot_swap_teams!(S::Array{Int, 2}, i::Int, j::Int, k::Int)

Swaps games of the two teams `i` and `j` in a single slot `k`. Does `not`
produce a RR2-tournament schedule.
"""
@inline function slot_swap_teams!(S::Array{Int, 2}, i::Int, j::Int, k::Int)
    oppi, oppj = S[i, k], S[j, k]
    if sign(oppi) == sign(oppj)
        S[abs(oppi), k], S[abs(oppj), k] = S[abs(oppj), k], S[abs(oppi), k]
    else
        S[abs(oppi), k], S[abs(oppj), k] = -S[abs(oppj), k], -S[abs(oppi), k]
    end
    S[i, k], S[j, k] = S[j, k], S[i, k]
end

"""
    swapTeams!(S::Array{Int, 2}, i::Int, j::Int)

Swaps games of two teams `i` and `j` in all slots except the two slots in which
they meet.
"""
function swap_teams!(S::Array{Int, 2}, i::Int, j::Int)
    for col = 1:size(S, 2)
        if S[i, col] == j || S[j, col] == i
            continue
        end
        slot_swap_teams!(S, i, j, col)
    end
end

"""
    partialSwapRounds!(S::Array{Int, 2}, i::Int, k::Int, l::Int)

Swaps games in two slots `k` and `l` for a team `i` and updates the schedule in
a deterministic way to produce a double round-robin tournament.
"""
function partial_swap_rounds!(S::Array{Int, 2}, i::Int, k::Int, l::Int)
    swapped = 2^i
    team1, team2 = abs(S[i, k]), abs(S[i, l])
    idx1, idx2 = k, l
    S[i, k], S[i, l] = S[i, l], S[i, k]
    while true
        cont = false
        if swapped & (1 << team1) === 0
            S[team1, k], S[team1, l] = S[team1, l], S[team1, k]
            swapped += 2^team1
            team1 = abs(S[team1, idx1])
            idx1 = idx1 == k ? l : k
            cont = true
        end
        if swapped & (1 << team2) === 0
            S[team2, k], S[team2, l] = S[team2, l], S[team2, k]
            swapped += 2^team2
            team2 = abs(S[team2, idx2])
            idx2 = idx2 == k ? l : k
            cont = true
        end
        cont || break
    end
end

"""
    partial_swap_teams!(S::Array{Int, Int}, i::Int, j::Int, k::Int)

Swaps games of two teams `i` and `j` in a single slot `k` and updates the
schedule in a deterministic way to produce a double round-robin tournament.
"""
function partial_swap_teams!(S::Array{Int,2}, i::Int, j::Int, k::Int)
    swapped = 2^k
    slot_swap_teams!(S, i, j, k)
    match1, match2 = S[i, k], S[j, k]
    offset = 0
    fixedi, fixedj = false, false
    for col in Iterators.cycle(vcat(k+1:size(S, 2), 1:k))
        if !fixedi && S[i, col] == match1
            if swapped & (1 << col) !== 0
                fixedi = true
            else
                slot_swap_teams!(S, i, j, col)
                swapped += 2^col
                match1 = S[i, col]
            end
        end
        if !fixedj && S[j, col] == match2
            if swapped & (1 << col) !== 0
                fixedj = true
            else
                slot_swap_teams!(S, i, j, col)
                swapped += 2^col
                match2 = S[j, col]
            end
        end

        fixedi && fixedj && break
    end
end

"""
    getmoves(rr2::RR2)

Compute all possible neighbor moves for a given tournament. If the touramenent
is phased the neighborhood is restricted, only alowing moves that retain the
phased structure.

# Parameters
-`rr2::RR2`- Tournament structure data

# Returns
-`Vector{Move}` - Vector of
    moves. A move tuple contains the neighborhood move function to
    be called (given as a `Symbol`), followed by the call arguments.
"""
function getmoves(rr2::RR2)
    sh = [(:swap_homes!, i, j) for (i, j) in combinations(1:rr2.nteams, 2)]
    st = [(:swap_teams!, i, j) for (i, j) in combinations(1:rr2.nteams, 2)]

    if rr2.isphased
        pst = Vector{Move}()
        sr = vcat(
            [
                (:swap_rounds!, k, l) for
                (k, l) in combinations(1:rr2.nslots÷2, 2)
            ],
            [
                (:swap_rounds!, k, l) for
                (k, l) in combinations(rr2.nslots÷2+1:rr2.nslots, 2)
            ],
        )
        psr = vcat(
            vec([
                (:partial_swap_rounds!, i, k, l) for i = 1:rr2.nteams,
                (k, l) in combinations(1:rr2.nslots÷2, 2)
            ]),
            vec([
                (:partial_swap_rounds!, i, k, l) for i = 1:rr2.nteams,
                (k, l) in combinations(rr2.nslots÷2+1:rr2.nslots, 2)
            ]),
        )
    else
        pst = vec([
            (:partial_swap_teams!, i, j, k) for
            (i, j) in combinations(1:rr2.nteams, 2), k = 1:rr2.nslots
        ])
        sr = [
            (:swap_rounds!, k, l) for (k, l) in combinations(1:rr2.nslots÷2, 2)
        ]
        psr = vec([
            (:partial_swap_rounds!, i, k, l) for i = 1:rr2.nteams,
            (k, l) in combinations(1:rr2.nslots, 2)
        ])
    end
    vcat(sh, sr, st, psr, pst)
end

"""
    move!(sched::Matrix{Int}, mv::Move)

Apply a move `mv` to a schedule `sched`.
"""
move!(sched::Matrix{Int}, mv::Move) = eval(mv[1])(sched, mv[2:end]...)


text:
@testset "1074.number-of-submatrices-that-sum-to-target.jl" begin
    @test num_submatrix_sum_target(hcat([[0, 1, 0], [1, 1, 1], [0, 1, 0]]...), 0) == 4
    @test num_submatrix_sum_target(hcat([[1, -1], [-1, 1]]...), 0) == 5
    @test num_submatrix_sum_target(hcat([[904]]...), 0) == 0
    @test num_submatrix_sum_target(hcat([[17, 6, -41, -45, -23, 38, -41, 49, 2, 26, -9, -17,
                                          -47, 18, -43, -28, 4, 1, 15, 19, -32, -45, 36,
                                          -30, -35, 37, -21, -6, 25, 8],
                                         [-12, 9, -44, -21, -30, -35, -31, -1, -32, 5, 25,
                                          44, 30, -25, 15, 25, -35, -29, 36, 17, -47, -33,
                                          -49, -48, -33, -44, 3, 29, 5, 8],
                                         [12, -21, -4, -48, -34, 30, 27, 20, 38, 9, -34, 47,
                                          45, 9, -33, -46, 38, -4, 47, -17, 39, -43, -30,
                                          32, 8, 37, -15, 40, 15, 21],
                                         [-9, -44, 4, 47, 24, -35, -20, -47, -25, -33, -33,
                                          -37, -9, 25, -7, -41, -31, -16, 23, -15, -7, 50,
                                          -19, -49, 3, 37, 11, -42, -34, -30],
                                         [12, 45, -28, -30, 40, 2, -22, 4, 39, 11, 46, -28,
                                          -39, 17, -42, -23, -40, 1, 9, 29, 7, -47, -2, 5,
                                          5, 11, -41, -39, -18, 10],
                                         [-44, -46, 48, 23, 49, 38, 10, 22, 29, 43, 5, 32,
                                          0, -46, 39, -30, -33, -42, -15, -11, 16, 46, -29,
                                          16, 25, 46, 35, 3, 2, -41],
                                         [-8, 30, -42, 37, 45, -28, -35, -2, 48, -47, -26,
                                          -45, 12, 20, 35, -39, -36, 9, -31, -3, 49, -24,
                                          -8, 14, 22, -39, 33, -31, -5, 11],
                                         [-30, 16, -23, -17, 15, 24, 18, 6, 31, 19, 30, -36,
                                          25, -6, 44, 1, -10, -12, -6, 31, 35, -32, 13, 34,
                                          -45, 29, -33, -8, 24, -38],
                                         [-34, -2, 24, 30, 21, -22, -5, 5, -1, 32, -37, 36,
                                          19, 42, 5, -24, 3, 49, 0, 16, -22, -30, -8, -4,
                                          18, 13, 38, -3, -39, -21],
                                         [40, -41, -33, 39, -14, -48, 49, -22, 9, 21, -9,
                                          46, 24, 32, 28, 37, 12, -15, 13, 0, -11, 42, 41,
                                          27, -42, 14, 18, -4, 46, 33],
                                         [20, -3, -41, -28, 5, 10, 19, 48, 24, 29, 47, -21,
                                          -1, -11, -41, 37, -33, 13, -5, 36, -39, 22, -32,
                                          44, -29, 17, 5, 36, -40, 48],
                                         [-32, -44, 43, 28, 26, -41, 4, 21, 1, 11, 3, -15,
                                          -36, -10, -13, -17, -11, -7, 32, -40, -13, -30, 7,
                                          21, -28, 29, 24, -17, -9, -33],
                                         [-19, 6, -24, -45, -9, -21, -45, -29, -11, 46, -15,
                                          8, 5, 14, 40, 10, 0, -12, -18, -10, 17, -45, 18,
                                          37, 7, 19, -6, 21, -11, -1],
                                         [40, -42, 0, 13, -12, -49, -42, 46, -13, -21, -16,
                                          -34, -15, 26, 48, -22, -32, 10, -3, 16, 40, 18,
                                          -35, 44, 26, -34, 30, -19, -44, -5],
                                         [24, 3, -41, 29, -46, -3, -30, 41, -33, -3, -41,
                                          -38, 34, -43, 41, -37, 6, 39, -3, 47, -50, -12,
                                          -20, 44, -26, -30, 36, 19, 42, -40],
                                         [49, 33, 26, -35, 43, 50, 15, -19, -27, -37, -2,
                                          16, 35, -16, 11, -30, -7, 34, -32, -42, -14, 0,
                                          -3, -29, 35, 19, 32, 14, 44, 8],
                                         [2, -22, -39, 19, 19, 22, -45, -19, 1, -22, -6, 33,
                                          -16, -34, 33, 14, 30, -11, 22, -50, -24, 24, 22,
                                          -23, 24, 2, 17, 46, 31, 45],
                                         [48, -49, 15, 3, 49, 11, 11, 6, -18, 24, -5, 10,
                                          37, 42, 41, 2, -5, 39, -6, 10, 42, -13, -11, -19,
                                          26, -47, -30, -26, 33, 3],
                                         [-20, -42, 37, 12, 10, 11, 26, 34, -15, -20, -9,
                                          -32, -11, -39, -8, -19, -36, -39, -5, 19, 47, 43,
                                          19, 39, -6, -2, -31, 13, 34, -4],
                                         [26, -36, 28, 3, 35, -47, 5, -38, -10, 25, -8, -47,
                                          -29, 43, 1, -16, 20, 12, 19, 35, 39, 24, 47, 47,
                                          -8, 3, -2, -1, -39, -4],
                                         [-15, 4, 29, 12, -23, 11, -4, 48, -7, -3, -29, -10,
                                          -45, 42, -26, -21, -25, -46, 10, 6, 20, 40, -8, 7,
                                          5, -38, -23, -33, 11, 16],
                                         [6, -10, -40, -35, -38, 39, -20, 43, -17, -43, 15,
                                          19, 4, -23, 42, 15, 10, -47, -5, -1, -30, 14, 47,
                                          -46, 11, -10, -9, 28, -46, -23],
                                         [2, -17, -26, 38, -50, 43, 25, -4, 5, 30, 21, 34,
                                          -50, -31, -20, -41, -25, 22, 23, 34, 15, -43, 20,
                                          -6, -14, -21, -47, -12, -27, -27],
                                         [-44, 27, -46, -45, -14, -19, 2, -34, -36, 11, 23,
                                          39, 9, -49, 47, 0, 11, -1, 27, 44, -28, 29, -46,
                                          -36, 24, 1, 45, -25, 11, 27],
                                         [-41, -39, 19, 3, 39, -9, -50, 31, 31, 33, 21, -30,
                                          12, -39, 45, -40, 13, 21, 41, 20, 31, -2, -21, 50,
                                          43, 21, 36, 0, -7, -28],
                                         [37, 46, -14, -34, -46, 35, 3, 48, 37, -38, -10,
                                          -24, -5, 42, 11, -47, 2, 9, 49, -26, -41, -33,
                                          -42, 32, 33, 36, -32, 47, 13, -49],
                                         [45, -45, -38, 27, -45, -19, -17, 35, 6, -33, 47,
                                          0, 18, -6, 16, 19, -17, -43, 6, 41, -31, -32, 11,
                                          -11, -50, 29, -33, 2, -46, 44],
                                         [32, -42, -7, -20, 9, 42, -37, 10, -41, 1, -37,
                                          -10, -24, 19, 2, -39, -18, 41, -18, 7, 44, 30, 7,
                                          -40, 23, -19, 21, -45, -6, 26],
                                         [28, 22, 1, -21, 46, 28, -43, 16, -13, -47, 33, 40,
                                          24, -8, -27, -42, -17, -34, 44, -5, 14, 28, -4,
                                          36, 47, -43, 1, 7, -14, -18],
                                         [-14, 46, 5, -40, 10, -13, 20, 39, -9, -32, -46,
                                          -7, -7, 24, 3, 36, -8, 10, 11, 35, -37, -46, 46,
                                          35, 49, -43, -25, -36, -28, -13]]...), 5) == 476
end


text:
function search11444(r::Robot)
    i = 2
    while (i > 0)
        if !ismarker(r)
            stepgoodvery(r,Nord)
            stepgoodvery(r,West)
            i += rrrruond444(r,i)
            i += 2

        end
    end
end

function rrrruond444(r::Robot,i::Int64)
    j=0
    for side in (Ost,Sud,West,Nord)
        a = i
        while (a > 0)
            stepgoodvery(r,side)
            if ismarker(r)
                a = -1
                break
            end
            a -= 1
        end

        if (a == -1)
            j = -i-2
            break
        end
    end
    return(j)
end
function stepgoodvery(r::Robot,side::HorizonSide)
    i = 0
    j = Int(side) + 1
    while isborder(r,side)
        backgrow(r,HorizonSide(mod(j, 4)),i )
        j = mod(j+2,4)
        i += 1
    end
    p = mod(i,2)
    i = ((i+1)//2) - 1
    move!(r,side)
    while (i > 0)
        if (p == 1)
            move!(r,HorizonSide(mod(Int(side)+3, 4)))
        else
            move!(r,HorizonSide(mod(Int(side)+1, 4)))
        end
        i -=1
    end

end
function backgrow(r::Robot,side::HorizonSide,i::Int64)
     o = i
     while (i > 0)
        move!(r,side)
        i -= 1
     end
    end

max_stars_repo_name: bubasooo/proggggggggg

max_issues_repo_name: bubasooo/proggggggggg

max_forks_repo_name: bubasooo/proggggggggg


text:
# issue related tests

using Graphs
using Test

g = graph([1, 3], [])  ## Create a graph with 2 vertices and no edges
e = Edge(1, 4, 2)
try
add_edge!(g, 2, 4)
catch
end
try
add_edge!(g, e)
catch
end
@test length(edges(g))==0


text:
@testset "processOverflow.jl" begin

    data = CSO.dataset("cso_raw")
    dropmissing!(data, :Duration)

    @testset "addColOverflow!(df, ColDuration, NewCol, ColNum)" begin
        data = CSO.dataset("cso_raw")
        dropmissing!(data, :Duration)
        transformedDF = addColOverflow!(data, "Duration", "Surverse", 3)

        #New column contains only 0's and 1'
        @test unique(transformedDF.Surverse) in [0, 1, [0,1]]

        #The number of 1 equals the number of positive durations
        @test count(transformedDF[:, :Duration] .> 0.0) == sum(transformedDF.Surverse)

        #Ancient DF has been changed
        @test nrow(data) == nrow(transformedDF)
    end

    @testset "countOverflow(df, ColOverflow, Print=true)" begin
        data = CSO.dataset("cso_raw")
        dropmissing!(data, :Duration)
        DF = addColOverflow!(data, "Duration", "Surverse", 3)
        result = countOverflow(DF, "Surverse", false)
        NO = result[1]
        O = result[2]
        perc = result[3]

        #Numbers are well derived
        @test NO == (nrow(DF) - sum(DF.Surverse))
        @test O == sum(DF.Surverse)
        @test perc == (O/(NO + O))

    end

end

max_stars_repo_name: AlexLsn/CSO

max_issues_repo_name: AlexLsn/CSO

max_forks_repo_name: AlexLsn/CSO


text:
__precompile__()
module mj
using Libdl
using StaticArrays

const depsfile = joinpath(dirname(@__FILE__), "..", "deps", "deps.jl")
if isfile(depsfile)
   include(depsfile)
else
   error("MuJoCo was not installed correctly.")
end

const VERSION_HEADER = 200

const mjtNum = Cdouble
const mjtByte = Cuchar

# mujoco header files in julia form
include("./mjmodel.jl")
include("./mjdata.jl")
include("./mjvisualize.jl")
include("./mjrender.jl")
include("./mjui.jl")

# additional structs and functionality
include("./mj_common.jl")
include("./mjextra.jl")

# mujoco functions
include("./mujoco_c.jl")
#include("./mjderiv.jl")

include("./export_all.jl") # a list of all function and struct names
export mjtNum, mjtByte
export jlData, jlModel
end


text:
#   This file is part of Maxima.jl. It is licensed under the MIT license
#   Copyright (c) 2016 Nathan Smith

export rhs,
       lhs

function rhs(m::MExpr)
    return mcall(MExpr("rhs($m)"))
end

"""
    rhs(expr::T) where T

Right hand side of an equation.

If `expr` is not an equation than `rhs` will return `0`
"""
function rhs(m::T) where T
    return convert(T, rhs(MExpr(m)))
end

function lhs(m::MExpr)
    return mcall(MExpr("lhs($m)"))
end

"""
    lhs(expr::T) where T

Left hand side of an equation.

If `expr` is not an equation then `lhs` will return `expr`
"""
function lhs(m::T) where T
    return convert(T, lhs(MExpr(m)))
end

allroots(m::MExpr) = mcall(MExpr("rhs($m)"))
allroots(m::T) where T = convert(T, allroots(MExpr(m)))


text:
using Weave

jmd_files=filter(endswith("jmd"),readdir(@__DIR__))

jmd_path=joinpath.(@__DIR__,jmd_files)
html_path=joinpath(@__DIR__,"html")
markdown_path=joinpath(@__DIR__,"markdown")

weave.(jmd_path,doctype = "github", out_path = markdown_path)

weave.(jmd_path, out_path = html_path)


text:
ms = map(measures()) do m
    m.name
end
@test "LogLoss" in ms
@test "RootMeanSquaredError"  in ms

# test `M()` makes sense for all measure types `M` extracted from `name`,
@test all(Symbol.(ms)) do ex
    try
        eval(:($ex()))
        true
    catch
        false
    end
end

task(m) = AbstractVector{<:Finite} <: m.target_scitype

ms = map(measures(task)) do m
    m.name
end

@test "LogLoss" in ms
@test !("RootMeanSquaredError"  in ms)

task(m) = AbstractVector{Continuous} <: m.target_scitype

ms = map(measures(task)) do m
    m.name
end

@test !("LogLoss" in ms)
@test "RootMeanSquaredError"  in ms

ms = map(measures("Brier")) do  m
    m.name
end

@test Set(ms) == Set(["BrierLoss", "BrierScore"])
true


text:
@inline posnegzeros(x::Float64, y::Float64) =
    (reinterpret(UInt64, x) | reinterpret(UInt64, y))  === 0x8000_0000_0000_0000
@inline posnegzeros(x::Float32, y::Float32) =
    (reinterpret(UInt32, x) | reinterpret(UInt32, y))  === 0x8000_0000
@inline posnegzeros(x::Float16, y::Float16) =
    (reinterpret(UInt16, x) | reinterpret(UInt16, y))  === 0x8000

@inline function (==)(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (LO(x) === LO(y)) && (HI(x) === HI(y) || posnegzeros(HI(x),HI(y)))
end
@inline function (!=)(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (LO(x) !== LO(y)) || (HI(x) !== HI(y) || posnegzeros(HI(x),HI(y)))
end
@inline function (<)(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) < HI(y)) || (HI(x) === HI(y) && LO(x) < LO(y))
end
@inline function (>)(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) > HI(y)) || (HI(x) === HI(y) && LO(x) > LO(y))
end
@inline function (<=)(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) < HI(y)) || (HI(x) === HI(y) && LO(x) <= LO(y))
end
@inline function (>=)(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) > HI(y)) || (HI(x) === HI(y) && LO(x) >= LO(y))
end

@inline function isequal(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return x == y || (isnan(x) && isnan(y))
end
@inline function isless(x::DoubleFloat{T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return x < y
end

@inline function (==)(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
    return (==)(x, DoubleFloat{T}(y))
end
@inline function (==)(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return (==)(DoubleFloat{T}(x), y)
end
@inline function (!=)(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
    return (!=)(x, DoubleFloat{T}(y))
end
@inline function (!=)(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return (!=)(DoubleFloat{T}(x), y)
end

@inline function (<)(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
    return (<)(x, DoubleFloat{T}(y))
end
@inline function (<)(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return (<)(DoubleFloat{T}(x), y)
end
@inline function (>)(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
    return (>)(x, DoubleFloat{T}(y))
end
@inline function (>)(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return (>)(DoubleFloat{T}(x), y)
end
@inline function (<=)(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
        return (<=)(x, DoubleFloat{T}(y))
end
@inline function (<=)(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return (<=)(DoubleFloat{T}(x), y)
end
@inline function (>=)(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
        return (>=)(x, DoubleFloat{T}(y))
end
@inline function (>=)(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return (>=)(DoubleFloat{T}(x), y)
end

@inline function isequal(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
    return isequal(x, DoubleFloat{T}(y))
end
@inline function isequal(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return isequal(DoubleFloat{T}(x), y)
end

@inline function isless(x::DoubleFloat{T}, y::F) where {T<:IEEEFloat, F<:AbstractFloat}
    return isless(x, DoubleFloat{T}(y))
end
@inline function isless(x::F, y::DoubleFloat{T}) where {T<:IEEEFloat, F<:AbstractFloat}
    return isless(DoubleFloat{T}(x), y)
end

@inline function (==)(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
    return (==)(x, DoubleFloat{T}(y))
end
@inline function (==)(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (==)(DoubleFloat{T}(x), y)
end
@inline function (!=)(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
    return (!=)(x, DoubleFloat{T}(y))
end
@inline function (!=)(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (!=)(DoubleFloat{T}(x), y)
end

@inline function (<)(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
    return (<)(x, DoubleFloat{T}(y))
end
@inline function (<)(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (<)(DoubleFloat{T}(x), y)
end
@inline function (>)(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
    return (>)(x, DoubleFloat{T}(y))
end
@inline function (>)(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (>)(DoubleFloat{T}(x), y)
end
@inline function (<=)(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
        return (<=)(x, DoubleFloat{T}(y))
end
@inline function (<=)(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (<=)(DoubleFloat{T}(x), y)
end
@inline function (>=)(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
        return (>=)(x, DoubleFloat{T}(y))
end
@inline function (>=)(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (>=)(DoubleFloat{T}(x), y)
end

@inline function isequal(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
    return isequal(x, DoubleFloat{T}(y))
end

@inline function isequal(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return isequal(DoubleFloat{T}(x), y)
end

@inline function isless(x::DoubleFloat{T}, y::Integer) where {T<:IEEEFloat}
    return isless(x, DoubleFloat{T}(y))
end

@inline function isless(x::Integer, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return isless(DoubleFloat{T}(x), y)
end

# mixing numbers and tuples

@inline function (==)(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return (LO(x) === LO(y)) && (HI(x) === HI(y))
end
@inline function (!=)(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return (LO(x) !== LO(y)) || (HI(x) !== HI(y))
end
@inline function (<)(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return (HI(x) < HI(y)) || (HI(x) === HI(y) && LO(x) < LO(y))
end
@inline function (>)(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return (HI(x) > HI(y)) || (HI(x) === HI(y) && LO(x) > LO(y))
end
@inline function (<=)(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return (HI(x) < HI(y)) || (HI(x) === HI(y) && LO(x) <= LO(y))
end
@inline function (>=)(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return (HI(x) > HI(y)) || (HI(x) === HI(y) && LO(x) >= LO(y))
end

@inline function isequal(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return x == y
end
@inline function isless(x::DoubleFloat{T}, y::Tuple{T,T}) where {T<:IEEEFloat}
    return x < y
end

@inline function (==)(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (LO(x) === LO(y)) && (HI(x) === HI(y))
end
@inline function (!=)(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (LO(x) !== LO(y)) || (HI(x) !== HI(y))
end
@inline function (<)(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) < HI(y)) || (HI(x) === HI(y) && LO(x) < LO(y))
end
@inline function (>)(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) > HI(y)) || (HI(x) === HI(y) && LO(x) > LO(y))
end
@inline function (<=)(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) < HI(y)) || (HI(x) === HI(y) && LO(x) <= LO(y))
end
@inline function (>=)(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return (HI(x) > HI(y)) || (HI(x) === HI(y) && LO(x) >= LO(y))
end

@inline function isequal(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return x == y
end
@inline function isless(x::Tuple{T,T}, y::DoubleFloat{T}) where {T<:IEEEFloat}
    return x < y
end

@inline function (==)(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return x == yy
end
@inline function (!=)(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return x != yy
end
@inline function (<)(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return x < yy
end
@inline function (>)(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return x > yy
end
@inline function (<=)(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return x <= yy
end
@inline function (>=)(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return x >= yy
end

@inline function isequal(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return isequal(x, yy)
end
@inline function isless(x::DoubleFloat{T}, y::Rational) where {T<:IEEEFloat}
    yy = DoubleFloat{T}(numerator(y)) / denominator(y)
    return isless(x, yy)
end

@inline function (==)(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return xx == y
end
@inline function (!=)(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return xx != y
end
@inline function (<)(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return xx < y
end
@inline function (>)(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return xx > y
end
@inline function (<=)(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return xx <= y
end
@inline function (>=)(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return xx >= y
end

@inline function isequal(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return isequal(xx, y)
end
@inline function isless(x::Rational, y::DoubleFloat{T}) where {T<:IEEEFloat}
    xx = DoubleFloat{T}(numerator(x)) / denominator(x)
    return isless(xx, y)
end


text:
using ControlSystems
using LinearAlgebra

"""
    v, xn, xmax, y = simulateDSM(u, ABCD, nlev=2, x0=0)
    v, xn, xmax, y = simulateDSM(u, ntf, nlev=2, x0=0)

Compute the output of a general delta-sigma modulator with input `u`, a
structure described by `ABCD`, an initial state `x0` (default zero) and a
quantizer with a number of levels specified by `nlev`.

Alternatively, the modulator may be described by an `ntf`. The `ntf` is a
TransferFunction object. (The stf is assumed to be 1).

The structure that is simulated is the controllable canonical form
generated by ss().
"""
function simulateDSM(u, arg2, nlev=2, x0=0)
    if arg2 isa TransferFunction
        ntf = arg2
        order = length(ntf.matrix[1].z)

        ABCD = ss(-1/ntf)
        C = ABCD.C
        Sinv = orth([C' Matrix(I,order,order)]) / norm(C)
        S = inv(Sinv)
        C = C * Sinv
        if C[1] < 0
            S = -S
            Sinv = -Sinv
        end

        A = S * ABCD.A * Sinv
        B = S * ABCD.B
        B = [-B B]
        C = [1; zeros(order-1)]
        D = 1
    elseif arg2 isa Array
        if size(arg2,2) > 2 && size(arg2,2) == size(arg2,1)+1 # ABCD dimensions OK
            ABCD = arg2
            order = size(ABCD, 1) - 1
            A = ABCD[1:order, 1:order]
            B = ABCD[1:order, (order+1):(order+2)]
            C = ABCD[order+1, 1:order][:]
            D = ABCD[order+1, order+1]
        else
            error("ABCD argument does not have proper dimensions")
        end
    else
        error("arg2 is neither an ABCD matrix nor an NTF")
    end

    N = length(u)
    v = zeros(Int, N)
    y = zeros(N)
    xn = zeros(order, N)
    xmax = abs(x0)
    if x0 == 0
        x0 = zeros(order)
    end

    for i = 1:N
        y[i] = dot(C, x0) + D*u[i]
        v[i] = ds_quantize(y[i], nlev)
        x0 = A*x0 + B*[u[i]; v[i]]
        xn[:,i] = x0
        xmax = max.(abs.(x0), xmax)
    end

    return v, xn, xmax, y
end

# return an orthormal basis for the columns of A
function orth(A)
    return svd(A).U[:,1:rank(A)]
end

function ds_quantize(y, n)
    if iseven(n)
        v = 2 * floor(Int, 0.5 * y) + 1
    else
        v = 2 * floor(Int, 0.5 * (y + 1))
    end
    L = n - 1
    if v >= L
        v = L
    elseif v <= -L
        v = -L
    end
    return v
end

max_stars_repo_name: Mahmoud-Kharsa/DeltaSigma

max_issues_repo_name: Mahmoud-Kharsa/DeltaSigma

max_forks_repo_name: Mahmoud-Kharsa/DeltaSigma


text:
using Tables

"""
    some_elm(::Type{T})

Some arbitrary element of type `T`
"""
function some_elm(::Type{T}) where {T}
    try
        return zero(T)
    catch
        try
            return T(0)
        catch
            try
                rand(T)
            catch
                try
                    Vector{T}(undef, 1)[1]
                catch
                    throw("the type $T is not supported by JDF.jl yet. Try to update JDF.jl. If it still doesn't work after update, please submit an issue at https://github.com/xiaodaigh/JDF.jl/issues")
                end
            end
        end
    end
end

some_elm(::Type{Date}) = Date(0)

"""
    JDF.save(outdir, table)

    JDF.save(table, outdir)

Save a `Tables.jl` compatitable table to the `outdir`. On Julia > v1.3, a multi-threaded version is
used.

The columns of the table can be of the following vector types columns are
supported

    * `isbits` types e.g. `Int*`, `UInt*`, `Float*`
    * `Bool`
    * `Strings`
    * `WeakRefStrings.StringVector`
    * `CategoricalArrays`
    * `Union{Missing, T}`` for `T` support above

"""
save(df, outdir::AbstractString; kwargs...) = save(outdir, df; kwargs...)

function save(outdir::AbstractString, df; verbose = false)
    @assert Tables.istable(df)

    pmetadatas = Any[missing for i = 1:length(Tables.columnnames(df))]

    if !isdir(outdir)
        mkpath(outdir)
    end

    # use a bounded channel to limit the number simultaneous writes
    c1 = Channel{Bool}(Threads.nthreads())
    atexit(() -> close(c1))

    for (i, n) in enumerate(Tables.columnnames(df))
        if verbose
            println(n)
        end
        put!(c1, true)
        pmetadatas[i] = @spawn begin
            io = BufferedOutputStream(open(joinpath(outdir, string(n)), "w"))
            res = compress_then_write(Tables.getcolumn(df, n), io)
            close(io)
            res
        end
        take!(c1)
    end

    metadatas = fetch.(pmetadatas)

    fnl_metadata = (
        names = Tables.columnnames(df),
        rows = length(Tables.columns(df)[1]),
        metadatas = metadatas,
        version = v"0.2",
    )

    open(joinpath(outdir, "metadata.jls"), "w") do io
        serialize(io, fnl_metadata)
    end
    #fnl_metadata
    JDFFile(outdir)
end

# figure out from metadata how much space is allocated
""" Get tthe number of bytes used by the file"""
get_bytes(metadata) = begin
    if metadata.type == String
        return max(metadata.string_compressed_bytes, metadata.string_len_bytes)
    elseif metadata.type == Missing
        return 0
    elseif metadata.type >: Missing
        return max(get_bytes(metadata.Tmeta), get_bytes(metadata.missingmeta))
    else
        return metadata.len
    end
end

hasfieldnames(::Type{T}) where {T} = fieldnames(T) >= 1

savejdf(args...; kwargs...) = save(args...; kwargs...)

max_stars_repo_name: xiaodaigh/JDF

max_issues_repo_name: xiaodaigh/JDF

max_forks_repo_name: xiaodaigh/JDF


text:
"""
    reise_data_mods(case)

Given a dictionary of input data, modify accordingly and return a Case object.
"""
function reise_data_mods(case::Dict; num_segments::Int=1)::Case
    # Take in a dict from source data, tweak values and return a Case struct.

    # Modify PMINs
    case["gen_pmin"][case["genfuel"] .!= "coal"] .= 0
    nuclear_idx = case["genfuel"] .== "nuclear"
    case["gen_pmin"][nuclear_idx] = 0.95 * (case["gen_pmax"][nuclear_idx])
    geo_idx = case["genfuel"] .== "geothermal"
    case["gen_pmin"][geo_idx] = 0.95 * (case["gen_pmax"][geo_idx])
    offstatus_idx = case["gen_status"] .== 0
    case["gen_pmin"][offstatus_idx] .= 0

    # Save original gencost to gencost_orig
    case["gencost_orig"] = copy(case["gencost"])
    # Modify gencost based on desired linearization structure
    case["gencost"] = _linearize_gencost(case; num_segments=num_segments)

    # Relax ramp constraints
    case["gen_ramp30"] .= Inf
    # Then set them based on capacity
    ramp30_points = Dict(
        "coal" => Dict("xs" => (200, 1400), "ys" => (0.4, 0.15)),
        "dfo" => Dict("xs" => (200, 1200), "ys" => (0.5, 0.2)),
        "ng" => Dict("xs" => (200, 600), "ys" => (0.5, 0.2)),
    )
    for (fuel, points) in ramp30_points
        fuel_idx = findall(case["genfuel"] .== fuel)
        slope = ((points["ys"][2] - points["ys"][1]) / (points["xs"][2] - points["xs"][1]))
        intercept = points["ys"][1] - slope * points["xs"][1]
        for idx in fuel_idx
            norm_ramp = case["gen_pmax"][idx] * slope + intercept
            if case["gen_pmax"][idx] < points["xs"][1]
                norm_ramp = points["ys"][1]
            end
            if case["gen_pmax"][idx] > points["xs"][2]
                norm_ramp = points["ys"][2]
            end
            case["gen_ramp30"][idx] = norm_ramp * case["gen_pmax"][idx]
        end
    end

    # Convert Dict to NamedTuple
    case = (; (Symbol(k) => v for (k, v) in case)...)
    # Convert NamedTuple to Case
    case = Case(; case...)

    return case
end

"""
    _linearize_gencost(case)
    _linearize_gencost(case; num_segments=2)

Using case dict data, linearize cost curves with a give number of segments.
"""
function _linearize_gencost(case::Dict; num_segments::Int=1)::Array{Float64,2}
    # Positional indices from mpc.gencost
    MODEL = 1
    STARTUP = 2
    SHUTDOWN = 3
    NCOST = 4
    COST = 5

    println("linearizing")
    num_gens = size(case["gencost"], 1)
    non_polynomial = (case["gencost"][:, MODEL] .!= 2)::BitArray{1}
    if sum(non_polynomial) > 0
        throw(ArgumentError("gencost currently limited to polynomial"))
    end
    non_quadratic = (case["gencost"][:, NCOST] .!= 3)::BitArray{1}
    if sum(non_quadratic) > 0
        throw(ArgumentError("gencost currently limited to quadratic"))
    end
    old_a = case["gencost"][:, COST]
    old_b = case["gencost"][:, COST + 1]
    old_c = case["gencost"][:, COST + 2]
    diffP_mask = (case["gen_pmin"] .!= case["gen_pmax"])::BitArray{1}
    # Convert non-fixed generators to piecewise segments
    if sum(diffP_mask) > 0
        # If we are linearizing at least one generator, need to expand gencost
        gencost_width = 6 + 2 * num_segments
        new_gencost = zeros(num_gens, gencost_width)
        new_gencost[diffP_mask, MODEL] .= 1
        new_gencost[:, STARTUP:SHUTDOWN] = case["gencost"][:, STARTUP:SHUTDOWN]
        new_gencost[diffP_mask, NCOST] .= num_segments + 1
        power_step = (case["gen_pmax"] - case["gen_pmin"]) / num_segments
        for i in 0:num_segments
            x_index = COST + 2 * i
            y_index = COST + 1 + (2 * i)
            x_data = (case["gen_pmin"] + power_step * i)
            y_data = old_a .* x_data .^ 2 + old_b .* x_data + old_c
            new_gencost[diffP_mask, x_index] = x_data[diffP_mask]
            new_gencost[diffP_mask, y_index] = y_data[diffP_mask]
        end
    else
        # If we are not linearizing any segments, gencost can stay as is
        new_gencost = copy(case["gencost"])
    end
    # Convert fixed gens to fixed values
    sameP_mask = .!diffP_mask
    if sum(sameP_mask) > 0
        new_gencost[sameP_mask, MODEL] = case["gencost"][sameP_mask, MODEL]
        new_gencost[sameP_mask, NCOST] = case["gencost"][sameP_mask, NCOST]
        power = case["gen_pmax"]
        y_data = old_a .* power .^ 2 + old_b .* power + old_c
        new_gencost[sameP_mask, COST:(COST + 1)] .= 0
        new_gencost[sameP_mask, COST + 2] = y_data[sameP_mask]
    end

    return new_gencost
end


text:
"""
This function creates the model for a full themal dispatch formulation depending on combination of devices, device_formulation and system_formulation
"""
function construct_device!(ps_m::CanonicalModel,
                           device::Type{T},
                           device_formulation::Type{D},
                           system_formulation::Type{S},
                           sys::PSY.System,
                           time_range::UnitRange{Int64};
                           kwargs...) where {T <: PSY.ThermalGen,
                                             D <: AbstractThermalFormulation,
                                             S <: PM.AbstractPowerFormulation}

    parameters = get(kwargs, :parameters, true)

    if isempty(keys(ps_m.initial_conditions))
        @warn("Initial Conditions not provided, this can lead to infeasible problem formulations")
    end

    #Variables
    activepower_variables(ps_m, sys.generators.thermal, time_range);

    reactivepower_variables(ps_m, sys.generators.thermal, time_range);

    commitment_variables(ps_m, sys.generators.thermal, time_range)

    #Constraints
    activepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    reactivepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    commitment_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    ramp_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    time_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    #Cost Function
    cost_function(ps_m, sys.generators.thermal, device_formulation, system_formulation)

    return

end

"""
This function creates the model for a full themal dispatch formulation depending on combination of devices, device_formulation and system_formulation
"""
function construct_device!(ps_m::CanonicalModel,
                           device::Type{T},
                           device_formulation::Type{D},
                           system_formulation::Type{S},
                           sys::PSY.System,
                           time_range::UnitRange{Int64};
                           kwargs...) where {T <: PSY.ThermalGen,
                                             D <: AbstractThermalFormulation,
                                             S <: PM.AbstractActivePowerFormulation}

    parameters = get(kwargs, :parameters, true)

    if isempty(keys(ps_m.initial_conditions))
        @warn("Initial Conditions not provided, this can lead to infeasible problem formulations")
    end

    #Variables
    activepower_variables(ps_m, sys.generators.thermal, time_range);

    commitment_variables(ps_m, sys.generators.thermal, time_range)

    #Constraints
    activepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    commitment_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    ramp_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    time_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    #Cost Function
    cost_function(ps_m, sys.generators.thermal, device_formulation, system_formulation)

    return

end

"""
This function creates the model for a full themal dispatch formulation depending on combination of devices, device_formulation and system_formulation
"""
function construct_device!(ps_m::CanonicalModel,
                           device::Type{T},
                           device_formulation::Type{PSI.ThermalRampLimited},
                           system_formulation::Type{S},
                           sys::PSY.System,
                           time_range::UnitRange{Int64};
                           kwargs...) where {T <: PSY.ThermalGen,
                                             S <: PM.AbstractPowerFormulation}

    if isempty(keys(ps_m.initial_conditions))
        @warn("Initial Conditions not provided, this can lead to infeasible problem formulations")
    end

    parameters = get(kwargs, :parameters, true)

    #Variables
    activepower_variables(ps_m, sys.generators.thermal, time_range);

    reactivepower_variables(ps_m, sys.generators.thermal, time_range);

    #Constraints
    activepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    reactivepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    ramp_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    #Cost Function
    cost_function(ps_m, sys.generators.thermal, device_formulation, system_formulation)

    return

end

"""
This function creates the model for a full themal dispatch formulation depending on combination of devices, device_formulation and system_formulation
"""
function construct_device!(ps_m::CanonicalModel,
                           device::Type{T},
                           device_formulation::Type{ThermalRampLimited},
                           system_formulation::Type{S},
                           sys::PSY.System,
                           time_range::UnitRange{Int64};
                           kwargs...) where {T <: PSY.ThermalGen,
                                             S <: PM.AbstractActivePowerFormulation}

    if isempty(keys(ps_m.initial_conditions))
        @warn("Initial Conditions not provided, this can lead to infeasible problem formulations")
    end

    parameters = get(kwargs, :parameters, true)

    #Variables
    activepower_variables(ps_m, sys.generators.thermal, time_range);

    #Constraints
    activepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    ramp_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range, parameters)

    #Cost Function
    cost_function(ps_m, sys.generators.thermal, device_formulation, system_formulation)

    return

end

function construct_device!(ps_m::CanonicalModel,
                           device::Type{T},
                           device_formulation::Type{D},
                           system_formulation::Type{S},
                           sys::PSY.System,
                           time_range::UnitRange{Int64};
                           kwargs...) where {T<: PSY.ThermalGen,
                                             D <: AbstractThermalDispatchForm,
                                             S <: PM.AbstractPowerFormulation}

    #Variables
    activepower_variables(ps_m, sys.generators.thermal, time_range);

    reactivepower_variables(ps_m, sys.generators.thermal, time_range);

    #Constraints
    activepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    reactivepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    #Cost Function
    cost_function(ps_m, sys.generators.thermal, device_formulation, system_formulation)

    return

end

function construct_device!(ps_m::CanonicalModel,
                           device::Type{T},
                           device_formulation::Type{D},
                           system_formulation::Type{S},
                           sys::PSY.System,
                           time_range::UnitRange{Int64};
                           kwargs...) where {T<: PSY.ThermalGen,
                                             D <: AbstractThermalDispatchForm,
                                             S <: PM.AbstractActivePowerFormulation}

    #Variables
    activepower_variables(ps_m, sys.generators.thermal, time_range);

    #Constraints
    activepower_constraints(ps_m, sys.generators.thermal, device_formulation, system_formulation, time_range)

    #Cost Function
    cost_function(ps_m, sys.generators.thermal, device_formulation, system_formulation)

    return

end


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

#
# The Computer Language Benchmarks Game
# nbody benchmark
# http://shootout.alioth.debian.org/u32/performance.php?test=nbody
#
# A vectorized version of the Java port from nbody.jl
#

module NBodyVec

# Constants
const solar_mass = 4 * pi * pi
const days_per_year = 365.24

# A heavenly body in the system
mutable struct Body
    pos::Array{Float64, 1}
    v::Array{Float64, 1}
    mass::Float64
end

function offset_momentum(b::Body, p)
    b.v -= p / solar_mass
end

function init_sun(bodies)
    local p::Array{Float64,1} = [0.0, 0.0, 0.0]
    for b in bodies
        p += b.v * b.mass
    end
    offset_momentum(bodies[1], p)
end

function advance(bodies, dt)
    for i = 1:length(bodies)
        for j = i+1:length(bodies)
            delta = bodies[i].pos - bodies[j].pos
            dsq = sum(delta .^ 2)
            distance = sqrt(dsq)
            mag = dt / (dsq * distance)

            bodies[i].v -= delta * (bodies[j].mass * mag)
            bodies[j].v += delta * (bodies[i].mass * mag)
        end
    end

    for b in bodies
        b.pos += dt * b.v
    end
end

function energy(bodies)
    local e::Float64 = 0.0
    for i = 1:length(bodies)
        e += 0.5 * bodies[i].mass *
             sum(bodies[i].v .^ 2)
        for j = i+1:length(bodies)
            delta = bodies[i].pos - bodies[j].pos
            distance = sqrt(sum(delta .^ 2))
            e -= (bodies[i].mass * bodies[j].mass) / distance
        end
    end
    e
end

function nbody_vec(N::Int=1000)
    jupiter = Body( [4.84143144246472090e+00,                   # pos[1] = x
                     -1.16032004402742839e+00,                  # pos[2] = y
                     -1.03622044471123109e-01],                 # pos[3] = z
                   [1.66007664274403694e-03 * days_per_year,   # v[1] = vx
                    7.69901118419740425e-03 * days_per_year,   # v[2] = vy
                    -6.90460016972063023e-05 * days_per_year], # v[3] = vz
                   9.54791938424326609e-04 * solar_mass)       # mass

    saturn = Body( [8.34336671824457987e+00,
                    4.12479856412430479e+00,
                    -4.03523417114321381e-01],
                  [-2.76742510726862411e-03 * days_per_year,
                   4.99852801234917238e-03 * days_per_year,
                   2.30417297573763929e-05 * days_per_year],
                  2.85885980666130812e-04 * solar_mass)

    uranus = Body( [1.28943695621391310e+01,
                    -1.51111514016986312e+01,
                    -2.23307578892655734e-01],
                  [2.96460137564761618e-03 * days_per_year,
                   2.37847173959480950e-03 * days_per_year,
                   -2.96589568540237556e-05 * days_per_year],
                  4.36624404335156298e-05 * solar_mass)

    neptune = Body( [1.53796971148509165e+01,
                     -2.59193146099879641e+01,
                     1.79258772950371181e-01],
                   [2.68067772490389322e-03 * days_per_year,
                    1.62824170038242295e-03 * days_per_year,
                    -9.51592254519715870e-05 * days_per_year],
                   5.15138902046611451e-05 * solar_mass)

    sun = Body([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], solar_mass)

    bodies = [sun, jupiter, saturn, uranus, neptune]

    init_sun(bodies)
#    @printf("%.9f\n", energy(bodies))
    for i = 1:N
        advance(bodies, 0.01)
    end
#    @printf("%.9f\n", energy(bodies))
end

end # module

max_stars_repo_name: JuliaTagBot/Benchmarks

max_issues_repo_name: JuliaArchive/Benchmarks

max_forks_repo_name: JuliaArchive/Benchmarks


text:
# This file was generated, do not modify it. # hide
SimplePipe = Pipeline(
    OneHotEncoder(),
    MultinomialClassifier(),
    prediction_type=:probabilistic
)
mach = machine(SimplePipe, Xtrain, ytrain)
res = evaluate!(
    mach;
    resampling=Holdout(fraction_train=0.9),
    measure=cross_entropy
)
round(res.measurement[1], sigdigits=3)

max_issues_repo_name: alan-turing-institute/MLJTutorials

max_forks_repo_name: alan-turing-institute/MLJTutorials


text:
# Define linear evolution
Φ = [0.8 0.5; -0.1 0.8]
b = zeros(2)
Q = [0.2 0.0; 0.0 1.0]

E = LinearEvolution(Φ, Gaussian(b, Q))

# Define observation scheme
H = [1.0 0.0]
R = Matrix(1.0I, 1, 1)

O = LinearObservation(E, H, R)

# Prior
x0 = [1., 0.]
P0 = Matrix(1.0I, 2, 2)
prior = 0 => Gaussian(x0, P0)

# Observations (mock)
Y = [1 => [1.14326], 2 => [-0.271804], 3 => [-0.00512675]]

# Filter
Xf, ll = kalmanfilter(O, prior, Y)
@show Xf

# Online
@testset "Online" begin
    ϕ = iterate(Y)
    ϕ === nothing && error("no observations")
    y, ystate = ϕ

    ϕ = dyniterate(O, Start(Kalman.Filter(prior, 0.0)), y)
    ϕ === nothing && error("no observations")
    (t, u), state = ϕ

    X = trajectory((t => u[1],))
    while true
        ϕ = iterate(Y, ystate)
        ϕ === nothing && break
        y, ystate = ϕ

        ϕ = dyniterate(O, state, y)
        ϕ === nothing && break
        (t, u), state = ϕ
        push!(X, t => u[1]) # filtered state as Gaussian
    end
    ll = u[3] # likelihood
    @show  X, ll
end