text:
#!/usr/bin/env julia

#Import Statements for MPC
# import Pkg; Pkg.activate(@__DIR__);
# Pkg.instantiate()
# include("Arthur.jl")
# include("MPCUtil.jl")
# using RigidBodyDynamics
# using StaticArrays
# using RobotDynamics
# using Altro
# using TrajectoryOptimization
include("MPC.jl")

# Black magic to make Julia and Python happy
using Distributed

using Pkg
Distributed.@everywhere using Pkg

Distributed.@everywhere begin
  ENV["PYTHON"] = "/usr/bin/python3"
  Pkg.build("PyCall")
end

using PyCall
Distributed.@everywhere using PyCall

#Import Statements for RobotOS
using RobotOS

@rosimport trajectory_msgs.msg: JointTrajectory, JointTrajectoryPoint
@rosimport arthur_planning.msg: arthur_traj
rostypegen()
using .trajectory_msgs.msg
using .arthur_planning.msg

function get_trajectory(params)
    qref = typeof(zeros(7))[]
    push!(qref,  [4.9268856741946365e-05, 0.26016423071338934, 3.140069344584098, -2.27008100955155, -2.40769461674617e-05, 0.9598460188468598, 1.569995694393751])
    push!(qref,  [-0.003768053224579125, 0.26079787208394173, 3.1395327288847428, -2.269096150780195, -0.004224076946167462, 0.9616197667116058, 1.5721591274301712])
    push!(qref,  [-0.01522001946854234, 0.2626987961955988, 3.137922881786677, -2.2661415744661304, -0.016824076946167464, 0.9669410103058437, 1.578649426539432])
    push!(qref,  [-0.03430662987514771, 0.26586700304836064, 3.135239803289901, -2.2612172806093556, -0.03782407694616747, 0.9758097496295736, 1.5894665917215332])
    push!(qref,  [-0.0610278844443952, 0.2703024926422273, 3.131483493394414, -2.254323269209871, -0.06722407694616747, 0.9882259846827953, 1.6046106229764747])
    push!(qref,  [-0.0953296828066516, 0.2759962847990445, 3.126661557197997, -2.2454734980167035, -0.10496455313664366, 1.0041645773154986, 1.6240508594052145])
    push!(qref,  [-0.13259401741002397, 0.2821818315115795, 3.121423165847148, -2.23585940048681, -0.14596455313664364, 1.0214797350427807, 1.6451700866655072])
    push!(qref,  [-0.1698583520133963, 0.2883673782241145, 3.116184774496299, -2.226245302956917, -0.18696455313664362, 1.0387948927700625, 1.6662893139258002])
    push!(qref,  [-0.20712268661676866, 0.2945529249366496, 3.1109463831454507, -2.2166312054270234, -0.2279645531366436, 1.0561100504973449, 1.6874085411860928])
    push!(qref,  [-0.24438702122014103, 0.3007384716491846, 3.1057079917946018, -2.20701710789713, -0.2689645531366436, 1.0734252082246267, 1.7085277684463855])
    push!(qref,  [-0.2816513558235134, 0.3069240183617196, 3.100469600443753, -2.1974030103672364, -0.3099645531366436, 1.090740365951909, 1.7296469957066785])
    push!(qref,  [-0.3189156904268857, 0.31310956507425464, 3.095231209092904, -2.1877889128373433, -0.3509645531366436, 1.108055523679191, 1.7507662229669712])
    push!(qref,  [-0.3561800250302581, 0.3192951117867897, 3.089992817742055, -2.17817481530745, -0.39196455313664363, 1.1253706814064732, 1.7718854502272638])
    push!(qref,  [-0.3934443596336305, 0.3254806584993247, 3.0847544263912066, -2.1685607177775563, -0.43296455313664367, 1.1426858391337553, 1.7930046774875568])
    push!(qref,  [-0.43070869423700286, 0.33166620521185974, 3.0795160350403576, -2.158946620247663, -0.47396455313664365, 1.1600009968610374, 1.8141239047478495])
    push!(qref,  [-0.4679730288403753, 0.3378517519243948, 3.0742776436895087, -2.1493325227177693, -0.5149645531366437, 1.1773161545883195, 1.8352431320081424])
    push!(qref,  [-0.5052373634437477, 0.34403729863692983, 3.06903925233866, -2.1397184251878762, -0.5559645531366437, 1.1946313123156016, 1.856362359268435])
    push!(qref,  [-0.54250169804712, 0.3502228453494649, 3.063800860987811, -2.1301043276579827, -0.5969645531366438, 1.2119464700428837, 1.8774815865287278])
    push!(qref,  [-0.5797660326504925, 0.3564083920619999, 3.0585624696369624, -2.1204902301280892, -0.6379645531366438, 1.2292616277701658, 1.8986008137890207])
    push!(qref,  [-0.6170303672538648, 0.36259393877453494, 3.0533240782861135, -2.1108761325981957, -0.6789645531366438, 1.2465767854974479, 1.9197200410493134])
    push!(qref,  [-0.6542947018572371, 0.36877948548706996, 3.0480856869352646, -2.1012620350683022, -0.7199645531366438, 1.26389194322473, 1.940839268309606])
    push!(qref,  [-0.6915590364606096, 0.37496503219960503, 3.0428472955844157, -2.091647937538409, -0.7609645531366438, 1.281207100952012, 1.961958495569899])
    push!(qref,  [-0.728823371063982, 0.38115057891214005, 3.0376089042335668, -2.0820338400085157, -0.8019645531366438, 1.2985222586792942, 1.983077722830192])
    push!(qref,  [-0.7660877056673544, 0.3873361256246751, 3.0323705128827183, -2.072419742478622, -0.8429645531366439, 1.3158374164065763, 2.0041969500904844])
    push!(qref,  [-0.8033520402707267, 0.39352167233721014, 3.0271321215318694, -2.0628056449487286, -0.8839645531366439, 1.3331525741338583, 2.0253161773507773])
    push!(qref,  [-0.8406163748740991, 0.39970721904974515, 3.0218937301810205, -2.053191547418835, -0.9249645531366439, 1.3504677318611407, 2.04643540461107])
    push!(qref,  [-0.8778807094774715, 0.4058927657622802, 3.0166553388301716, -2.043577449888942, -0.965964553136644, 1.3677828895884225, 2.067554631871363])
    push!(qref,  [-0.915145044080844, 0.41207831247481524, 3.0114169474793226, -2.0339633523590486, -1.006964553136644, 1.3850980473157049, 2.0886738591316556])
    push!(qref,  [-0.9524093786842164, 0.4182638591873503, 3.006178556128474, -2.024349254829155, -1.0479645531366442, 1.402413205042987, 2.1097930863919485])
    push!(qref,  [-0.9896737132875887, 0.42444940589988533, 3.0009401647776253, -2.0147351572992616, -1.088964553136644, 1.419728362770269, 2.1309123136522414])
    push!(qref,  [-1.026938047890961, 0.43063495261242035, 2.9957017734267763, -2.005121059769368, -1.1299645531366442, 1.4370435204975511, 2.1520315409125343])
    push!(qref,  [-1.0642023824943334, 0.43682049932495537, 2.9904633820759274, -1.9955069622394748, -1.1709645531366442, 1.4543586782248332, 2.173150768172827])
    push!(qref,  [-1.101466717097706, 0.44300604603749044, 2.9852249907250785, -1.9858928647095815, -1.2119645531366443, 1.4716738359521153, 2.1942699954331197])
    push!(qref,  [-1.1387310517010785, 0.4491915927500255, 2.97998659937423, -1.976278767179688, -1.2529645531366442, 1.4889889936793974, 2.215389222693412])
    push!(qref,  [-1.1759953863044506, 0.45537713946256053, 2.974748208023381, -1.9666646696497945, -1.2939645531366444, 1.5063041514066795, 2.236508449953705])
    push!(qref,  [-1.213259720907823, 0.46156268617509555, 2.969509816672532, -1.9570505721199012, -1.3349645531366443, 1.5236193091339616, 2.257627677213998])
    push!(qref,  [-1.2478021278200226, 0.46729641720217435, 2.9646540572035307, -1.9481387245716801, -1.3729697583408722, 1.5396697023673502, 2.277204276379416])
    push!(qref,  [-1.2748022884966306, 0.4717782027187738, 2.9608585403999896, -1.9411727561509207, -1.402676624155692, 1.5522155332738579, 2.292506375168055])
    push!(qref,  [-1.2941678050105965, 0.47499270549426853, 2.9581362549951593, -1.9361765052728712, -1.423983489970512, 1.5612138684508734, 2.3034816078838536])
    push!(qref,  [-1.3058986773619201, 0.4769399255286585, 2.9564872009890393, -1.9331499719375316, -1.4368903557853316, 1.566664707898397, 2.310129974526812])
    push!(qref,  [-1.3099949055506017, 0.47761986282194374, 2.95591137838163, -1.932093156144902, -1.4413972216001514, 1.5685680516164289, 2.3124514750969296])
    push!(qref,  [-1.3100000000000003, 0.47762070845504206, 2.955910662235214, -1.9320918417907373, -1.4414028267565981, 1.568570418791257, 2.312454362330413])

    q̇ref = typeof(zeros(7))[]
    push!(q̇ref,  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
    push!(q̇ref,  [-0.07634644162642143, 0.012672827411047383, -0.010732313987104905, 0.019697175427098694, -0.084, 0.03547495729491942, 0.04326866072840471])
    push!(q̇ref,  [-0.15269288325284286, 0.025345654822094766, -0.02146462797420981, 0.03939435085419739, -0.168, 0.07094991458983883, 0.08653732145680942])
    push!(q̇ref,  [-0.22903932487926432, 0.03801848223314215, -0.032196941961314715, 0.05909152628129609, -0.252, 0.10642487188475827, 0.12980598218521414])
    push!(q̇ref,  [-0.3053857665056857, 0.05069130964418953, -0.04292925594841962, 0.07878870170839478, -0.336, 0.14189982917967767, 0.17307464291361885])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3726433460337236, 0.061855467125350325, -0.05238391350848822, 0.09614097529893409, -0.41, 0.17315157727282096, 0.21119227260292772])
    push!(q̇ref,  [-0.3081748275792907, 0.05115426887151827, -0.04332132502896183, 0.07950827192114293, -0.3390686581481977, 0.14319578771253505, 0.17465531825059288])
    push!(q̇ref,  [-0.2318283859528692, 0.038481441460470875, -0.03258901104185691, 0.05981109649404422, -0.2550686581481976, 0.1077208304176156, 0.13138665752218814])
    push!(q̇ref,  [-0.1554819443264477, 0.02580861404942348, -0.021856697054752, 0.04011392106694551, -0.17106865814819755, 0.07224587312269615, 0.08811799679378339])
    push!(q̇ref,  [-0.07913550270002623, 0.013135786638376092, -0.011124383067647084, 0.0204167456398468, -0.08706865814819748, 0.036770915827776696, 0.04484933606537864])
    push!(q̇ref,  [-0.002789061073605048, 0.00046295922732875194, -0.00039206908054222056, 0.0007195702127481829, -0.0030686581481977893, 0.0012959585328574108, 0.0015806753369740911])
    push!(q̇ref,  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])

    Xref = typeof(zeros(14))[]
    for k = 1:length(qref)
        push!(Xref, [qref[k]; q̇ref[k]])
    end
    for k = 1:params.H
        push!(Xref, [qref[end]; q̇ref[end]])
    end
    return Xref
end

function callback(msg::JointTrajectory, X, U, initialized, N)
    N .= length(msg.points)
    for k = 1:N[1]
        X[k][1:7] .= msg.points[k].positions
        X[k][8:14] .= msg.points[k].velocities
        U[k][1:end] .= msg.points[k].effort
    end
    if !initialized[1]
        initialized .= true
    end
end

function traj_callback(msg::arthur_traj, Xref, x0)
    Xref[1] = typeof(zeros(14))[]
    for k=1:length(msg.traj.points)
        q = msg.traj.points[k].positions
        q̇ = msg.traj.points[k].velocities
        push!(Xref[1], [q; q̇])
    end
    if norm(x0 - zeros(14)) == 0
        copy!(x0, Xref[1][1])
    end
    # RobotOS.loginfo("In Callback")
    # println(Xref[1][1])
end

function loop(sub_obj, pub_obj, x0, X, U, params, initialized, N, Xref, mpc_controller)
    loop_rate = Rate(10)
    while ! is_shutdown()
        RobotOS._run_callbacks(sub_obj)
        if initialized[1] && mpc_controller[1]
            i = argmin(norm.([(X[k] - x0) for k=1:N[1]]))
            x0 = rk4(params.model, x0, U[i], params.dt)
            if norm(x0[1:7] - Xref[1][end][1:7]) < 0.05
                mpc_controller .= false
            end
            if !isnan(x0[1])
                RobotOS.loginfo("MPC Control")
                println(U[i])
                println(x0)
                println(norm(x0 - Xref[1][end]))
            end
            JointTrajectoryOutput = JointTrajectoryPoint()
            JointTrajectoryOutput.positions = x0[1:7]
            JointTrajectoryOutput.velocities = x0[8:14]
            publish(pub_obj, JointTrajectoryOutput)
        else
            set_configuration!(params.state, x0[1:7])
            set_velocity!(params.state, x0[8:14])
            i = argmin(norm.([(Xref[1][k][1:7] - x0[1:7]) for k=1:length(Xref[1])]))
            ∆x = Xref[1][i][1:7] - x0[1:7]
            Kp = [10, 10, 10, 10, 10, 10, 10]
            Kd = [20, 20, 20, 20, 20, 20, 20]
            params.v̇ .= (Kp .* ∆x) .- (Kd .* x0[8:14])
            U_PD = inverse_dynamics(params.state, params.v̇)
            x0 .= rk4(params.model, x0, U_PD, params.dt)
            if !isnan(x0[1])
                RobotOS.loginfo("PD Control")
                println(params.v̇[1:7])
                println(U_PD[1:7])
                println(x0[1:7])
                # println(norm(x0 - Xref[end]))
            end
        end
        rossleep(loop_rate)
    end
end

function main()
    init_node("Simulation_Node")
    params = MPC_Params()

    # Xref = get_trajectory(params)
    # x0 = copy(Xref[1])
    Xref = [typeof(zeros(14))[]]
    x0 = zeros(14)
    N = [params.H-1]
    X = [zeros(14) for k = 1:params.H-1]
    U = [zeros(7) for k = 1:params.H-1]
    initialized = [false]
    mpc_controller = [true]

    sub = Subscriber{JointTrajectory}("joint_torques",callback,(X, U, initialized, N),queue_size=1)
    sub_traj = Subscriber{arthur_traj}("/my_gen3/arthur_traj",traj_callback,(Xref,x0),queue_size=1)
    pub = Publisher{JointTrajectoryPoint}("state",queue_size=1)

    while norm(x0 - zeros(14)) == 0
        RobotOS._run_callbacks(sub_traj)
    end

    loop(sub, pub, x0, X, U, params, initialized, N, Xref, mpc_controller)
end

if !isinteractive()
    main()
end


text:
"""
MPC controller

    #Parameters

    -A differential equation x' = f(x,u)
    -States and inputs linearization points
    -States and inputs constraints
    -A sample time for discretization
    -A method, 'l'
    -Weithing matrices with appropriate dimension Q and R and P
    _Horizon length N

    #Example

    regulator = mpc_problem(f, x_cons, u_cons, Ts, method, Q, R, P, N)

"""

function mpc_problem(f, xl::AbstractArray, ul::AbstractArray, x_cons::AbstractArray, u_cons::AbstractArray, Ts::Float64, method::String, Q::AbstractArray, R::Array, N::Integer)
    if method == "l"
        # the dynamical system is linearised
        JacobM = ForwardDiff.jacobian(f, vcat(xl, ul))
        A = JacobM[begin:size(xl,1), begin:size(xl,1)]
        B = JacobM[begin:size(xl,1), size(xl,1)+1:end]

        # the linear system is dicretized
        sysc = ControlSystems.ss(A, B,  Matrix(LinearAlgebra.I, size(A,1), size(A,1)), zeros(size(B,1),size(B,2)))
        sysd = ControlSystems.c2d(sysc, Ts)

        # The tmerinal weighting matrix is computed
        P = ModelPredictiveControl.terminal_weight(sysd.A, sysd.B, Q, R)
        controller = ModelPredictiveControl.linear_mpc(sysd.A, sysd.B, x_cons, u_cons, Q, R, P, N)
    end

    return controller

end

"""
Terminal matrix computation of the terminal cost x'Px. P is the solution to the discrete-time algebraic Riccati equation.

    #Parameters
    -State and input discrete matrices A and B
    _Weighting matrices Q and R

    #Example

    P = terminal_weight(Ad, Bd, Q, R)

"""

function terminal_weight(Ad::AbstractMatrix, Bd::AbstractMatrix, Q::AbstractMatrix, R::AbstractMatrix)
    return ControlSystems.dare(Ad, Bd, Q, R)
end

ext: jl


text:
module PkgServerClient

using Downloads
include("registry.jl")

# This get updated once during module initialization: `__init__`.
# To avoid unnecessary delay due to network check, only explicit `registry_response_time` call
# updates it.
const _registry_response_time = Dict(k => Inf for k in keys(registry))
"""
    registry_response_time(; timeout=1)::Dict{String, Float64}

Query and return the registry response time. If any of the HEAD request exceeds the timeout,
the response time is set to `Inf`.
"""
function registry_response_time(; timeout=1)
    timeout = max(0.001, timeout) # The minimal is 1ms, otherwise it is likely to be ignored.

    function response_time(url, timeout)
        try
            return @elapsed Downloads.request(url*"/registries",
                method="HEAD", timeout=timeout, throw=true)
        catch err
            return Inf
        end
    end

    # TODO:
    # Because some mirror server might fail to response, so it's almost certainly that calling this function
    # takes `timeout` seconds to execute. An improvement is to early exit when there're enough response counts
    # from the registry.
    @sync for (k, v) in registry
        @async _registry_response_time[k] = response_time(v.url, timeout)
    end

    # When all fails to response in a very limited `timeout` time, set the default to "JuliaLang"
    # with a convenient lie.
    if all(isinf, values(_registry_response_time))
        _registry_response_time["JuliaLang"] = 0
    end
    return _registry_response_time
end

"""
    get_fasted_mirror()

Directly return the codename for the mirror with lowest response time.

!!! note
    This function only query a cached mirror response time, that is, it doesn't send actual HEAD
    request to the mirror server. If you want to update the cached value, you can explicitly call
    `registry_response_time()`
"""
get_fasted_mirror() = first(sort(collect(_registry_response_time), by=item->item[2]))[1]

"""
    set_mirror([server])

Set current Pkg server to `server`. The available upstreams are:

$(registry_str)

By default, it will use the one with lowest response time.
"""
function set_mirror(server::String = get_fasted_mirror())
    haskey(registry, server) || throw(ArgumentError("Server $server not found. Please check `PkgServerClient.registry`."))
    ENV["JULIA_PKG_SERVER"] = registry[server].url
    return nothing
end

const regex_PKG_SERVER = r"^\s*[^#]*\s*(ENV\[\"JULIA_PKG_SERVER\"\]\s*=\s*)\"([\w\.:\/]*)\""

"""
    generate_startup(server)

Hardcode the following line into `startup.jl` file:

```julia
ENV["JULIA_PKG_SERVER"] = <mirror-url>
```

where `mirror-url` is the url to upstream `server`. By default, it will use
the one with lowest response time.
"""
function generate_startup(server::String = get_fasted_mirror())
    haskey(registry, server) || throw(ArgumentError("Server $server not found. Please check `PkgServerClient.registry`."))
    # Manually update the response time before doing this.
    registry_response_time()

    default_dot_julia = first(DEPOT_PATH)
    config_path = joinpath(default_dot_julia, "config")
    if !ispath(config_path)
        mkpath(config_path)
    end

    startup_path = joinpath(config_path, "startup.jl")
    if ispath(startup_path)
        startup_lines = readlines(startup_path)
    else
        startup_lines = String[]
    end

    new_upstream = registry[server].url
    new_line = "ENV[\"JULIA_PKG_SERVER\"] = \"$(new_upstream)\""

    pkg_matches = map(x->match(regex_PKG_SERVER, x), startup_lines)
    pkg_indices = findall(x->!isnothing(x), pkg_matches)
    if isempty(pkg_indices)
        @info "New PkgServer" Server=new_upstream ConfigFile=startup_path
        append!(startup_lines, ["", "# Generated by PkgServerClient", new_line, ""])
    else
        # only modify the last match
        idx = last(pkg_indices)
        old_upstream = pkg_matches[idx].captures[2]

        is_upstream_unchanged = occursin(new_upstream, old_upstream) || occursin(old_upstream, new_upstream)
        if !is_upstream_unchanged
            @info "Update PkgServer" NewServer=new_upstream OldServer=old_upstream ConfigFile=startup_path
            startup_lines[idx] = new_line
        end
    end

    write(startup_path, join(startup_lines, "\n"))
    return
end

function _auto_switch()
    # only do smart pkg server redirection when users haven't set the environment
    # `JULIA_PKG_SERVER` manually.
    if isempty(get(ENV, "JULIA_PKG_SERVER", ""))
        registry_response_time()
        mirror_node = get_fasted_mirror()
        set_mirror(mirror_node)
    end
end

function __init__()
    # In REPL mode a little bit delay is allowed
    if isinteractive()
        @async _auto_switch()
    else
        _auto_switch()
    end
end

end


text:
# ------------------------------------------------------------------------------------------
# # Character based RNN language model trained on 'The Complete Works of William
# Shakespeare'
# Based on http://karpathy.github.io/2015/05/21/rnn-effectiveness
# ------------------------------------------------------------------------------------------

RNNTYPE = :lstm
BATCHSIZE = 64
SEQLENGTH = 64
INPUTSIZE = 512
VOCABSIZE = 128
HIDDENSIZE = 512
NUMLAYERS = 2
DROPOUT = 0.0
LR=0.001
BETA_1=0.9
BETA_2=0.999
EPS=1e-08
EPOCHS = 30;

base = joinpath(Base.JULIA_HOME, Base.DATAROOTDIR, "julia", "base")
text = ""
for (root,dirs,files) in walkdir(base)
    for f in files
        f[end-2:end] == ".jl" || continue
        text *= readstring(joinpath(root,f))
    end
    # println((root,length(files),all(f->contains(f,".jl"),files)))
end
length(text)

charcnt = Dict{Char,Int}()
for c in text; charcnt[c]=1+get(charcnt,c,0); end
chars = sort(collect(keys(charcnt)), by=(x->charcnt[x]), rev=true)
charid = Dict{Char,Int}()
for i=1:length(chars); charid[chars[i]]=i; end
hcat(chars, map(c->charcnt[c],chars))

data = map(c->charid[c], collect(text))
data[data .> VOCABSIZE] = VOCABSIZE
ntst = 1<<19
tst = data[1:ntst]
trn = data[1+ntst:end]
length.((data,trn,tst))

# Load 'The Complete Works of William Shakespeare'
using Knet
#include(Knet.dir("data","gutenberg.jl"))
#trn,tst,chars = shakespeare()
#map(summary,(trn,tst,chars))

# Print a sample
r = rand(1:(length(trn)-1000))
println(string(chars[trn[r:r+1000]]...))

# Minibatch data
function mb(a)
    N = div(length(a),BATCHSIZE)
    x = reshape(a[1:N*BATCHSIZE],N,BATCHSIZE)' # reshape full data to (B,N) with contiguous rows
    minibatch(x[:,1:N-1], x[:,2:N], SEQLENGTH) # split into (B,T) blocks
end
dtrn,dtst = mb(trn),mb(tst)
map(length, (dtrn,dtst))

# Define model
function initmodel()
    w(d...)=KnetArray(xavier(Float32,d...))
    b(d...)=KnetArray(zeros(Float32,d...))
    r,wr = rnninit(INPUTSIZE,HIDDENSIZE,rnnType=RNNTYPE,numLayers=NUMLAYERS,dropout=DROPOUT)
    wx = w(INPUTSIZE,VOCABSIZE)
    wy = w(VOCABSIZE,HIDDENSIZE)
    by = b(VOCABSIZE,1)
    return r,wr,wx,wy,by
end;

# Given the current character, predict the next character
function predict(ws,xs,hx,cx;pdrop=0)
    r,wr,wx,wy,by = ws
    x = wx[:,xs]                                    # xs=(B,T) x=(X,B,T)
    x = dropout(x,pdrop)
    y,hy,cy = rnnforw(r,wr,x,hx,cx,hy=true,cy=true) # y=(H,B,T) hy=cy=(H,B,L)
    y = dropout(y,pdrop)
    y2 = reshape(y,size(y,1),size(y,2)*size(y,3))   # y2=(H,B*T)
    return wy*y2.+by, hy, cy
end

# Define loss and its gradient
function loss(w,x,y,h;o...)
    py,hy,cy = predict(w,x,h...;o...)
    h[1],h[2] = getval(hy),getval(cy)
    return nll(py,y)
end

lossgradient = gradloss(loss);

function train(model,data,optim)
    hiddens = Any[nothing,nothing]
    Σ,N=0,0
    for (x,y) in data
        grads,loss1 = lossgradient(model,x,y,hiddens;pdrop=DROPOUT)
        update!(model, grads, optim)
        Σ,N=Σ+loss1,N+1
    end
    return Σ/N
end;

function test(model,data)
    hiddens = Any[nothing,nothing]
    Σ,N=0,0
    for (x,y) in data
        Σ,N = Σ+loss(model,x,y,hiddens), N+1
    end
    return Σ/N
end;

# Sample from trained model
function generate(model,n)
    function sample(y)
        p,r=Array(exp.(y-logsumexp(y))),rand()
        for j=1:length(p); (r -= p[j]) < 0 && return j; end
    end
    h,c = nothing,nothing
    chars = model[end]
    x = findfirst(chars,'\n')
    for i=1:n
        y,h,c = predict(model,[x],h,c)
        x = sample(y)
        print(chars[x])
    end
    println()
end;

#=
# Train model or load from file if exists
using JLD
model=optim=nothing; knetgc()
if true # !isfile("juliacharlm.jld")
    model = initmodel()
    optim = optimizers(model, Adam; lr=LR, beta1=BETA_1, beta2=BETA_2, eps=EPS);    info("Training...")
    @time for epoch in 1:EPOCHS
        @time trnloss = train(model,dtrn,optim) # ~18 seconds
        @time tstloss = test(model,dtst)        # ~0.5 seconds
        println((:epoch, epoch, :trnppl, exp(trnloss), :tstppl, exp(tstloss)))
    end
    save("juliacharlm.jld","model",model)
else
    model = load("juliacharlm.jld","model")
end
summary(model)
=#

# generate(model,1000)

function hyperloss(v)
    global HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, EPOCHS, model
    HIDDENSIZE = floor(Int, 128 * 2^v[1])
    INPUTSIZE = floor(Int, 128 * 2^v[2])
    NUMLAYERS = max(1,floor(Int,v[3]))
    DROPOUT = isa(v[4],Number) ? sigm(v[4]) : 0
    @show (HIDDENSIZE,INPUTSIZE,NUMLAYERS,DROPOUT)
    knetgc()
    model = initmodel()
    optim = optimizers(model, Adam; lr=LR, beta1=BETA_1, beta2=BETA_2, eps=EPS)
    for epoch in 1:10
        trnloss = train(model,dtrn,optim) # ~18 seconds
        tstloss = test(model,dtst)        # ~0.5 seconds
        println((:epoch, epoch, :trnppl, exp(trnloss), :tstppl, exp(tstloss)))
    end
    trnloss = test(model,dtrn)
    trnppl = exp(trnloss)
    @show (HIDDENSIZE,INPUTSIZE,NUMLAYERS,DROPOUT,trnppl)
    return trnppl
end

model=nothing; knetgc(); hyperloss([3,0,3,0])

#=

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (1024, 128, 2, 0.5)
(:epoch, 1, :trnppl, 9.589466f0, :tstppl, 4.9871907f0)
(:epoch, 2, :trnppl, 3.741831f0, :tstppl, 3.9569008f0)
(:epoch, 3, :trnppl, 3.111019f0, :tstppl, 3.6438942f0)
(:epoch, 4, :trnppl, 2.842651f0, :tstppl, 3.490925f0)
(:epoch, 5, :trnppl, 2.6792212f0, :tstppl, 3.406119f0)
(:epoch, 6, :trnppl, 2.567202f0, :tstppl, 3.337223f0)
(:epoch, 7, :trnppl, 2.484569f0, :tstppl, 3.2894032f0)
(:epoch, 8, :trnppl, 2.4184995f0, :tstppl, 3.2509122f0)
(:epoch, 9, :trnppl, 2.3658345f0, :tstppl, 3.2483802f0)
(:epoch, 10, :trnppl, 2.3232405f0, :tstppl, 3.2095058f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) = (1024, 128, 2, 0.5, 2.0069642f0)

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (4096, 128, 1, 0.5)
(:epoch, 1, :trnppl, 7.630349f0, :tstppl, 8.994627f0)
(:epoch, 2, :trnppl, 3.1094067f0, :tstppl, 3.7359138f0)
(:epoch, 3, :trnppl, 2.5211895f0, :tstppl, 3.406949f0)
(:epoch, 4, :trnppl, 2.24173f0, :tstppl, 3.3002508f0)
(:epoch, 5, :trnppl, 2.0695934f0, :tstppl, 3.2824345f0)
(:epoch, 6, :trnppl, 1.9510676f0, :tstppl, 3.2519991f0)
(:epoch, 7, :trnppl, 1.8637797f0, :tstppl, 3.2833624f0)
(:epoch, 8, :trnppl, 1.7990172f0, :tstppl, 3.2755644f0)
(:epoch, 9, :trnppl, 1.7516453f0, :tstppl, 3.3127692f0)
(:epoch, 10, :trnppl, 1.7112837f0, :tstppl, 3.3849468f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) = (4096, 128, 1, 0.5, 1.5795085f0)
1.5795085f0

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (2048, 128, 1, 0.5)
(:epoch, 1, :trnppl, 6.897045f0, :tstppl, 4.5084825f0)
(:epoch, 2, :trnppl, 3.1653059f0, :tstppl, 3.7902246f0)
(:epoch, 3, :trnppl, 2.6861045f0, :tstppl, 3.5171616f0)
(:epoch, 4, :trnppl, 2.4583292f0, :tstppl, 3.4100456f0)
(:epoch, 5, :trnppl, 2.3147066f0, :tstppl, 3.3488684f0)
(:epoch, 6, :trnppl, 2.2171206f0, :tstppl, 3.3439498f0)
(:epoch, 7, :trnppl, 2.1446044f0, :tstppl, 3.3066962f0)
(:epoch, 8, :trnppl, 2.0894327f0, :tstppl, 3.3102229f0)
(:epoch, 9, :trnppl, 2.0460289f0, :tstppl, 3.287103f0)
(:epoch, 10, :trnppl, 2.0100765f0, :tstppl, 3.3185039f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) = (2048, 128, 1, 0.5, 1.7895192f0)
1.7895192f0

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (2896, 128, 1, 0.5)
(:epoch, 1, :trnppl, 7.1333003f0, :tstppl, 4.4698453f0)
(:epoch, 2, :trnppl, 3.04668f0, :tstppl, 3.719867f0)
(:epoch, 3, :trnppl, 2.5365477f0, :tstppl, 3.439777f0)
(:epoch, 4, :trnppl, 2.295574f0, :tstppl, 3.3415797f0)
(:epoch, 5, :trnppl, 2.1462688f0, :tstppl, 3.27515f0)
(:epoch, 6, :trnppl, 2.044871f0, :tstppl, 3.2823677f0)
(:epoch, 7, :trnppl, 1.9718276f0, :tstppl, 3.2806444f0)
(:epoch, 8, :trnppl, 1.9180799f0, :tstppl, 3.2798069f0)
(:epoch, 9, :trnppl, 1.8782355f0, :tstppl, 3.2703993f0)
(:epoch, 10, :trnppl, 1.8446114f0, :tstppl, 3.3073356f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) =
1.6504527f0
(2896, 128, 1, 0.5, 1.6504527f0)

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (2048, 128, 1, 0)
(:epoch, 1, :trnppl, 17.54582f0, :tstppl, 9.120878f0)
(:epoch, 2, :trnppl, 5.3387966f0, :tstppl, 5.298701f0)
(:epoch, 3, :trnppl, 3.4404564f0, :tstppl, 4.2200007f0)
(:epoch, 4, :trnppl, 2.7447715f0, :tstppl, 3.8503358f0)
(:epoch, 5, :trnppl, 2.3742914f0, :tstppl, 3.695858f0)
(:epoch, 6, :trnppl, 2.1303215f0, :tstppl, 3.6608467f0)
(:epoch, 7, :trnppl, 1.9553958f0, :tstppl, 3.687474f0)
(:epoch, 8, :trnppl, 1.8226186f0, :tstppl, 3.7828565f0)
(:epoch, 9, :trnppl, 1.7212292f0, :tstppl, 3.8975382f0)
(:epoch, 10, :trnppl, 1.6417012f0, :tstppl, 4.0848227f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) =
1.7484467f0
(2048, 128, 1, 0, 1.7484467f0)

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (1024, 128, 2, 0.5)
(:epoch, 1, :trnppl, 22.390598f0, :tstppl, 13.189085f0)
(:epoch, 2, :trnppl, 7.4823937f0, :tstppl, 5.720241f0)
(:epoch, 3, :trnppl, 4.6992884f0, :tstppl, 4.448046f0)
(:epoch, 4, :trnppl, 3.7799704f0, :tstppl, 3.972568f0)
(:epoch, 5, :trnppl, 3.3514497f0, :tstppl, 3.7654393f0)
(:epoch, 6, :trnppl, 3.0903006f0, :tstppl, 3.5971427f0)
(:epoch, 7, :trnppl, 2.9079294f0, :tstppl, 3.484381f0)
(:epoch, 8, :trnppl, 2.7710462f0, :tstppl, 3.443712f0)
(:epoch, 9, :trnppl, 2.663027f0, :tstppl, 3.3361208f0)
(:epoch, 10, :trnppl, 2.5764978f0, :tstppl, 3.3100765f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) =
2.175947f0
(1024, 128, 2, 0.5, 2.175947f0)

(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT) = (1024, 128, 2, 0)
(:epoch, 1, :trnppl, 22.009565f0, :tstppl, 11.428911f0)
(:epoch, 2, :trnppl, 6.030965f0, :tstppl, 5.366185f0)
(:epoch, 3, :trnppl, 3.614693f0, :tstppl, 4.288177f0)
(:epoch, 4, :trnppl, 2.906743f0, :tstppl, 3.948376f0)
(:epoch, 5, :trnppl, 2.572164f0, :tstppl, 3.8014898f0)
(:epoch, 6, :trnppl, 2.3514614f0, :tstppl, 3.7232788f0)
(:epoch, 7, :trnppl, 2.1846726f0, :tstppl, 3.7083063f0)
(:epoch, 8, :trnppl, 2.056641f0, :tstppl, 3.7179863f0)
(:epoch, 9, :trnppl, 1.9550104f0, :tstppl, 3.768648f0)
(:epoch, 10, :trnppl, 1.8722341f0, :tstppl, 3.8625576f0)
(HIDDENSIZE, INPUTSIZE, NUMLAYERS, DROPOUT, trnppl) =
1.9898754f0

=#

#foo = download("http://ai.ku.edu.tr/models/nlp-demos/juliacharlm.jld")
using JLD
model = nothing; knetgc()
model = load(foo,"model")
summary.(model)

cpumodel = (model[1],map(Array,model[2:end])...)

generate(cpumodel,1000)

dump(cpumodel[1])

cpumodel[1].rnnDesc = cpumodel[1].dropoutDesc = nothing

dump(cpumodel[1])

save("juliacharlm.jld","model",cpumodel)

pwd()

foo

shake = load("shakespeare.jld","model")

generate(shake,1000)

cpumodel = (cpumodel..., chars)

include(Knet.dir("data","gutenberg.jl"))
_,_,chars2 = shakespeare()

shake = (shake..., chars2)

generate(shake,1000)

summary.(shake)

cpushake = (shake[1],map(Array,shake[2:end])...)

dump(cpushake[1])

cpushake[1].rnnDesc = cpushake[1].dropoutDesc = nothing

save("shakespeare.jld","model",cpushake)

foo1 = download("http://people.csail.mit.edu/deniz/models/nlp-demos/shakespeare.jld")

m1 = load(foo1,"model")

generate(m1,100)

generate(m2,100)

cpumodel

save("juliacharlm.jld","model",cpumodel)

foo2 = download("http://people.csail.mit.edu/deniz/models/nlp-demos/juliacharlm.jld")
m2 = load(foo2,"model")

generate(m2,100)

dump(m2[1])

max_stars_repo_name: grenkoca/JuliaTutorials

max_issues_repo_name: grenkoca/JuliaTutorials

max_forks_repo_name: grenkoca/JuliaTutorials


text:
# AUTO GENERATED FILE - DO NOT EDIT

export dcc_input

"""
    dcc_input(;kwargs...)

An Input component.
A basic HTML input control for entering text, numbers, or passwords.

Note that checkbox and radio types are supported through
the Checklist and RadioItems component. Dates, times, and file uploads
are also supported through separate components.
Keyword arguments:
- `id` (String; optional): The ID of this component, used to identify dash components
in callbacks. The ID needs to be unique across all of the
components in an app.
- `value` (String | Real; optional): The value of the input
- `style` (Dict; optional): The input's inline styles
- `className` (String; optional): The class of the input element
- `debounce` (Bool; optional): If true, changes to input will be sent back to the Dash server only on enter or when losing focus.
If it's false, it will sent the value back on every change.
- `type` (a value equal to: "text", 'number', 'password', 'email', 'range', 'search', 'tel', 'url', 'hidden'; optional): The type of control to render.
- `autoComplete` (String; optional): This attribute indicates whether the value of the control can be automatically completed by the browser.
- `autoFocus` (a value equal to: 'autoFocus', 'autofocus', 'AUTOFOCUS' | Bool; optional): The element should be automatically focused after the page loaded.
autoFocus is an HTML boolean attribute - it is enabled by a boolean or
'autoFocus'. Alternative capitalizations `autofocus` & `AUTOFOCUS`
are also acccepted.
- `disabled` (a value equal to: 'disabled', 'DISABLED' | Bool; optional): If true, the input is disabled and can't be clicked on.
disabled is an HTML boolean attribute - it is enabled by a boolean or
'disabled'. Alternative capitalizations `DISABLED`
- `inputMode` (a value equal to: "verbatim", "latin", "latin-name", "latin-prose", "full-width-latin", "kana", "katakana", "numeric", "tel", "email", "url"; optional): Provides a hint to the browser as to the type of data that might be
entered by the user while editing the element or its contents.
- `list` (String; optional): Identifies a list of pre-defined options to suggest to the user.
The value must be the id of a <datalist> element in the same document.
The browser displays only options that are valid values for this
input element.
This attribute is ignored when the type attribute's value is
hidden, checkbox, radio, file, or a button type.
- `max` (String | Real; optional): The maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
- `maxLength` (String | Real; optional): If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in UTF-16 code units) that the user can enter. For other control types, it is ignored. It can exceed the value of the size attribute. If it is not specified, the user can enter an unlimited number of characters. Specifying a negative number results in the default behavior (i.e. the user can enter an unlimited number of characters). The constraint is evaluated only when the value of the attribute has been changed.
- `min` (String | Real; optional): The minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value.
- `minLength` (String | Real; optional): If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the minimum number of characters (in Unicode code points) that the user can enter. For other control types, it is ignored.
- `multiple` (Bool; optional): This Boolean attribute indicates whether the user can enter more than one value. This attribute applies when the type attribute is set to email or file, otherwise it is ignored.
- `name` (String; optional): The name of the control, which is submitted with the form data.
- `pattern` (String; optional): A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url, email, or password, otherwise it is ignored. The regular expression language is the same as JavaScript RegExp algorithm, with the 'u' parameter that makes it treat the pattern as a sequence of unicode code points. The pattern is not surrounded by forward slashes.
- `placeholder` (String | Real; optional): A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. Note: Do not use the placeholder attribute instead of a <label> element, their purposes are different. The <label> attribute describes the role of the form element (i.e. it indicates what kind of information is expected), and the placeholder attribute is a hint about the format that the content should take. There are cases in which the placeholder attribute is never displayed to the user, so the form must be understandable without it.
- `readOnly` (Bool | a value equal to: 'readOnly', 'readonly', 'READONLY'; optional): This attribute indicates that the user cannot modify the value of the control. The value of the attribute is irrelevant. If you need read-write access to the input value, do not add the "readonly" attribute. It is ignored if the value of the type attribute is hidden, range, color, checkbox, radio, file, or a button type (such as button or submit).
readOnly is an HTML boolean attribute - it is enabled by a boolean or
'readOnly'. Alternative capitalizations `readonly` & `READONLY`
are also acccepted.
- `required` (a value equal to: 'required', 'REQUIRED' | Bool; optional): This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate.
required is an HTML boolean attribute - it is enabled by a boolean or
'required'. Alternative capitalizations `REQUIRED`
are also acccepted.
- `selectionDirection` (String; optional): The direction in which selection occurred. This is "forward" if the selection was made from left-to-right in an LTR locale or right-to-left in an RTL locale, or "backward" if the selection was made in the opposite direction. On platforms on which it's possible this value isn't known, the value can be "none"; for example, on macOS, the default direction is "none", then as the user begins to modify the selection using the keyboard, this will change to reflect the direction in which the selection is expanding.
- `selectionEnd` (String; optional): The offset into the element's text content of the last selected character. If there's no selection, this value indicates the offset to the character following the current text input cursor position (that is, the position the next character typed would occupy).
- `selectionStart` (String; optional): The offset into the element's text content of the first selected character. If there's no selection, this value indicates the offset to the character following the current text input cursor position (that is, the position the next character typed would occupy).
- `size` (String; optional): The initial size of the control. This value is in pixels unless the value of the type attribute is text or password, in which case it is an integer number of characters. Starting in, this attribute applies only when the type attribute is set to text, search, tel, url, email, or password, otherwise it is ignored. In addition, the size must be greater than zero. If you do not specify a size, a default value of 20 is used.' simply states "the user agent should ensure that at least that many characters are visible", but different characters can have different widths in certain fonts. In some browsers, a certain string with x characters will not be entirely visible even if size is defined to at least x.
- `spellCheck` (a value equal to: 'true', 'false' | Bool; optional): Setting the value of this attribute to true indicates that the element needs to have its spelling and grammar checked. The value default indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck value. The value false indicates that the element should not be checked.
- `step` (String | Real; optional): Works with the min and max attributes to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this attribute is not set to any, the control accepts only values at multiples of the step value greater than the minimum.
- `n_submit` (Real; optional): Number of times the `Enter` key was pressed while the input had focus.
- `n_submit_timestamp` (Real; optional): Last time that `Enter` was pressed.
- `n_blur` (Real; optional): Number of times the input lost focus.
- `n_blur_timestamp` (Real; optional): Last time the input lost focus.
- `loading_state` (optional): Object that holds the loading state object coming from dash-renderer. loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
  - `is_loading` (Bool; optional): Determines if the component is loading or not
  - `prop_name` (String; optional): Holds which property is loading
  - `component_name` (String; optional): Holds the name of the component that is loading
- `persistence` (Bool | String | Real; optional): Used to allow user interactions in this component to be persisted when
the component - or the page - is refreshed. If `persisted` is truthy and
hasn't changed from its previous value, a `value` that the user has
changed while using the app will keep that change, as long as
the new `value` also matches what was given originally.
Used in conjunction with `persistence_type`.
- `persisted_props` (Array of a value equal to: 'value's; optional): Properties whose user interactions will persist after refreshing the
component or the page. Since only `value` is allowed this prop can
normally be ignored.
- `persistence_type` (a value equal to: 'local', 'session', 'memory'; optional): Where persisted user changes will be stored:
memory: only kept in memory, reset on page refresh.
local: window.localStorage, data is kept after the browser quit.
session: window.sessionStorage, data is cleared once the browser quit.
"""
function dcc_input(; kwargs...)
        available_props = Symbol[:id, :value, :style, :className, :debounce, :type, :autoComplete, :autoFocus, :disabled, :inputMode, :list, :max, :maxLength, :min, :minLength, :multiple, :name, :pattern, :placeholder, :readOnly, :required, :selectionDirection, :selectionEnd, :selectionStart, :size, :spellCheck, :step, :n_submit, :n_submit_timestamp, :n_blur, :n_blur_timestamp, :loading_state, :persistence, :persisted_props, :persistence_type]
        wild_props = Symbol[]
        return Component("dcc_input", "Input", "dash_core_components", available_props, wild_props; kwargs...)
end

max_stars_repo_name: asc-csa/dash-core-components

max_issues_repo_name: asc-csa/dash-core-components

max_forks_repo_name: asc-csa/dash-core-components


text:
function vote2{V,W}(g::Graph{V,W}, m::Dict{V,Int}, u::V)
	c = Dict{V,Int}()
	max_cnt = 0
    if !isempty(keys(g[u]))
    	for neigh in keys(g[u])
    		neigh_comm = m[neigh]
    		c[neigh_comm] = get(c, neigh_comm, 0) + 1
    		if c[neigh_comm] > max_cnt
    			max_cnt = c[neigh_comm]
    		end
    	end
    	random_order = collect(keys(c))
    	shuffle!(random_order)
    	for lbl in random_order
    		if c[lbl] == max_cnt
    			return lbl
    		end
    	end
    else
        return m[u]
    end
end

function vote{V,W}(g::Graph{V,W}, m::Dict{V,Int}, u::V)
	c = Dict{V,Int}()
	max_cnt = 0
    if !isempty(keys(g[u]))
    	for neigh in keys(g[u])
    		neigh_comm = m[neigh]
    		c[neigh_comm] = get(c, neigh_comm, 0) + 1
    		if c[neigh_comm] > max_cnt
    			max_cnt = c[neigh_comm]
    		end
    	end
    	#random_order = collect(keys(c))
    	#shuffle!(random_order)
    	for (lbl, cnt) in c
    		if cnt == max_cnt
    			return lbl
    		end
    	end
    else
        return m[u]
    end
end

function vote1{V,W}(g::Graph{V,W}, m::Dict{V,Int}, u::V, all_active_nodes)
	c = Dict{V,Int}()
	max_cnt = 0
    if !isempty(keys(g[u]))
    	for neigh in keys(g[u])
			if in(neigh, all_active_nodes)
	    		neigh_comm = m[neigh]
	    		c[neigh_comm] = get(c, neigh_comm, 0) + 1
	    		if c[neigh_comm] > max_cnt
	    			max_cnt = c[neigh_comm]
	    		end
			end
    	end
		if isempty(c)
			return m[u]
		end
    	random_order = collect(keys(c))
    	shuffle!(random_order)
    	for lbl in random_order
    		if c[lbl] == max_cnt
    			return lbl
    		end
    	end
    else
        return m[u]
    end
end

function update!(g, m, active_nodes)
  num_active_nodes = 0
  while !isempty(active_nodes)
    if length(active_nodes) > num_active_nodes
        num_active_nodes = length(active_nodes)
    end
    random_order = collect(active_nodes)
    shuffle!(random_order)
    for u in random_order
      old_comm = m[u]
      new_comm = vote(g, m, u)
      if new_comm != old_comm
        for v in keys(g[u])
          push!(active_nodes, v)
          m[u] = new_comm
        end
      else
        delete!(active_nodes, u)
      end
    end
  end
  num_active_nodes
end

function update1!(g, m, active_nodes)
  all_active_nodes = copy(active_nodes)
  while !isempty(active_nodes)
    random_order = collect(active_nodes)
    shuffle!(random_order)
    for u in random_order
      old_comm = m[u]
      new_comm = vote1(g, m, u, all_active_nodes)
      if new_comm != old_comm
        for v in keys(g[u])
		  if in(v, all_active_nodes)
	          push!(active_nodes, v)
	          m[u] = new_comm
		  end
        end
      else
        delete!(active_nodes, u)
      end
    end
  end
end

function lpa_addnode!(g, m, u)
  if !haskey(g, u)
    addnode!(g, u)
    m[u] = u
  end
end

function lpa_deletenode1!(g, m, u)
  active_nodes = Set{keytype(g)}()
  for v in keys(g[u])
    push!(active_nodes, v)
    m[v] = v
  end
  deletenode!(g, u)
  delete!(m, u)
  update!(g, m, active_nodes)
end

function lpa_deletenode!(g, m, u)
  active_nodes = Set{keytype(g)}()
  active_lbls = IntSet()
  for v in keys(g[u])
    push!(active_lbls, m[v])
  end
  deletenode!(g, u)
  delete!(m, u)
  for v in keys(g)
    if in(m[v], active_lbls)
      push!(active_nodes, v)
      m[v] = v
    end
  end
  all_active_nodes = copy(active_nodes)
  update1!(g, m, active_nodes)
  update!(g, m, all_active_nodes)
end

function lpa_addedge1!(g, m, u, v)
  lpa_addnode!(g, m, u)
  lpa_addnode!(g, m, v)
  active_nodes = Set{keytype(g)}()
  if m[u] != m[v]
    for i in keys(g[u])
      push!(active_nodes, i)
      m[i] = i
    end
    for i in keys(g[v])
      push!(active_nodes, i)
      m[i] = i
    end
    push!(active_nodes, u)
    m[u] = u
    push!(active_nodes, v)
    m[v] = v
    addedge!(g, u, v)
	all_active_nodes = copy(active_nodes)
	update1!(g, m, active_nodes)
    return update!(g, m, all_active_nodes)
  else
  	addedge!(g, u, v)
    return 0
  end
end

function lpa_addedge!(g, m, u, v)
  lpa_addnode!(g, m, u)
  lpa_addnode!(g, m, v)
  active_nodes = Set{keytype(g)}()
  if m[u] != m[v]
    for i in keys(g)
      if m[i] == m[u] || m[i] == m[v]
        push!(active_nodes, i)
        m[i] = i
      end
    end
    addedge!(g, u, v)
	all_active_nodes = copy(active_nodes)
	update1!(g, m, active_nodes)
    return update!(g, m, all_active_nodes)
  else
  	addedge!(g, u, v)
    return 0
  end
end

function lpa_deleteedge1!(g, m, u, v)
  active_nodes = Set{keytype(g)}()
  if m[u] == m[v]
    for i in keys(g[u])
      push!(active_nodes, i)
      m[i] = i
    end
    for i in keys(g[v])
      push!(active_nodes, i)
      m[i] = i
    end
    push!(active_nodes, u)
    m[u] = u
    push!(active_nodes, v)
    m[v] = v
    deleteedge!(g, u, v)
    update!(g, m, active_nodes)
  else
  	deleteedge!(g, u, v)
  end
end

function lpa_deleteedge!(g, m, u, v)
  active_nodes = Set{keytype(g)}()
  if m[u] == m[v]
    for i in keys(g)
      if m[i] == m[u]
        push!(active_nodes, i)
        m[i] = i
      end
    end
    deleteedge!(g, u, v)
	all_active_nodes = copy(active_nodes)
	update1!(g, m, active_nodes)
    return update!(g, m, all_active_nodes)
  else
  	deleteedge!(g, u, v)
    return 0
  end
end


text:
# ---
# title: 132. Palindrome Partitioning II
# id: problem132
# author: Indigo
# date: 2021-03-08
# difficulty: Hard
# categories: Dynamic Programming
# link: <https://leetcode.com/problems/palindrome-partitioning-ii/description/>
# hidden: true
# ---
#
# Given a string `s`, partition `s` such that every substring of the partition
# is a palindrome.
#
# Return _the minimum cuts needed_ for a palindrome partitioning of `s`.
#
#
#
# **Example 1:**
#
#
#
#     Input: s = "aab"
#     Output: 1
#     Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
#
#
# **Example 2:**
#
#
#
#     Input: s = "a"
#     Output: 0
#
#
# **Example 3:**
#
#
#
#     Input: s = "ab"
#     Output: 1
#
#
#
#
# **Constraints:**
#
#   * `1 <= s.length <= 2000`
#   * `s` consists of lower-case English letters only.
#
#
## @lc code=start
using LeetCode

function partition_ps132(s::String)
    len = length(s)
    is_ps = fill(true, len, len)
    dp = fill(typemax(Int) >> 4, len)
    dp[1] = 0
    for i in len:-1:1, j in (i + 1):len
        is_ps[i, j] = (s[i] == s[j]) && is_ps[i + 1, j - 1]
    end
    for i in 2:len
        if is_ps[1, i]
            dp[i] = 0
        else
            for j in 2:i
                (is_ps[j, i]) && (dp[i] = min(dp[i], dp[j - 1] + 1))
            end
        end
    end
    return dp[end]
end
## @lc code=end


text:
using Documenter, RLEVectors

makedocs()

deploydocs(
           repo = "github.com/phaverty/RLEVectors.jl.git",
           julia = "0.6"
           )


text:
using LinearAlgebra: cross, norm, dot, normalize

@testset "V" begin
    @testset "Vector operations" begin
        v1 = randn(3)
        v2 = randn(3)
        @test SPICE._vadd(v1, v2) == v1 .+ v2
        @test SPICE._vaddg(v1, v2) == v1 .+ v2
        @test SPICE._vcrss(v1, v2) ≈ cross(v1, v2)
        @test SPICE._vdist(v1, v2) ≈ norm(v1 .- v2)
        @test SPICE._vdistg(v1, v2) ≈ norm(v1 .- v2)
        @test SPICE._vdot(v1, v2) ≈ dot(v1, v2)
        @test SPICE._vdotg(v1, v2) ≈ dot(v1, v2)
        w1 = fill(0.0, 3)
        SPICE._vequ(v1, w1)
        w2 = fill(0.0, 3)
        w2 .= v2
        @test w1 == v1
        @test w2 == v2
        @test SPICE._vhat(v1) ≈ normalize(v1)
        v3 = randn(3)
        a, b, c = randn(3)
        @test SPICE._vlcom3(a, v1, b, v2, c, v3) ≈ a .* v1 .+ b .* v2 .+ c .* v3
        @test SPICE._vlcom(a, v1, b, v2) ≈ a .* v1 .+ b .* v2
        @test SPICE._vminus(v1) == -v1
        @test SPICE._vnorm(v1) ≈ norm(v1)
        @test SPICE._vpack(a, b, c) == [a, b, c]
        @test SPICE._vscl(a, v1) ≈ a .* v1
        @test SPICE._vsub(v1, v2) ≈ v1 .- v2
        A = randn(3, 3)
        @test SPICE._vtmv(v1, A, v2) ≈ v1' * A * v2
        x1, y1, z1 = SPICE._vupack(v1)
        x2, y2, z2 = v1
        @test x1 == x2
        @test y1 == y2
        @test z1 == z2
        @test SPICE._vzero([0.0, 0.0, 0.0]) == iszero([0.0, 0.0, 0.0])
    end
    @testset "Vector operations 2" begin
        v1 = randn(6)
        v2 = randn(6)
        @test SPICE._vdistg(v1, v2) ≈ norm(v1 .- v2)
        @test SPICE._vdotg(v1, v2) ≈ dot(v1, v2)
        w1 = fill(0.0, 6)
        SPICE._vequg(v1, w1)
        w2 = fill(0.0, 6)
        w2 .= v2
        @test w1 == v1
        @test w2 == v2
        @test SPICE._vhatg(v1) ≈ normalize(v1)
        a, b = randn(2)
        @test SPICE._vlcomg(a, v1, b, v2) ≈ a .* v1 .+ b .* v2
        @test SPICE._vminug(v1) == -v1
        @test SPICE._vnormg(v1) ≈ norm(v1)
        @test SPICE._vsclg(a, v1) ≈ a .* v1
        @test SPICE._vsubg(v1, v2) ≈ v1 .- v2
        A = randn(6, 6)
        @test SPICE._vtmvg(v1, A, v2) ≈ v1' * A * v2
        @test SPICE._vzerog([0.0, 0.0, 0.0]) == iszero([0.0, 0.0, 0.0])
    end
    @testset "valid" begin
        c = SpiceIntCell(3)
        push!(c, 2, 1, 2)
        valid!(c)
        @test c[1:end] == [1, 2]
    end
    @testset "vperp" begin
        a = [6.0, 6.0, 6.0]
        b = [2.0, 0.0, 0.0]
        @test vperp(a, b) == [0.0, 6.0, 6.0]
    end
    @testset "vprjp" begin
        vec1 = [-5.0, 7.0, 2.2]
        norm = [0.0, 0.0, 1.0]
        orig = [0.0, 0.0, 0.0]
        plane = nvp2pl(norm, orig)
        proj = vprjp(vec1, plane)
        expected = [-5.0, 7.0, 0.0]
        @test proj ≈ expected
    end
    @testset "vprjpi" begin
        norm1 = [0.0, 0.0, 1.0]
        norm2 = [1.0, 0.0, 1.0]
        con1 = 1.2
        con2 = 0.65
        plane1 = nvc2pl(norm1, con1)
        plane2 = nvc2pl(norm2, con2)
        vec = [1.0, 1.0, 0.0]
        result = vprjpi(vec, plane1, plane2)
        expected = [1.0, 1.0, -0.35]
        @test result ≈ expected
    end
    @testset "vproj" begin
        v1 = [6.0, 6.0, 6.0]
        v2 = [2.0, 0.0, 0.0]
        expected = [6.0, 0.0, 0.0]
        vout = vproj(v1, v2)
        @test expected ≈ vout
    end
    @testset "vrel" begin
        vec1 = [12.3, -4.32, 76.0]
        vec2 = [23.0423, -11.99, -0.10]
        @test vrel(vec1, vec2) ≈ 1.0016370 rtol=1e-6
    end
    @testset "vrel" begin
        vec1 = [12.3, -4.32, 76.0, 1.87]
        vec2 = [23.0423, -11.99, -0.10, -99.1]
        @test vrelg(vec1, vec2) ≈ 1.2408623 rtol=1e-6
    end
    @testset "vrotv" begin
        v = [1.0, 2.0, 3.0]
        axis = [0.0, 0.0, 1.0]
        theta = π/2
        vout = vrotv(v, axis, theta)
        expected = [-2.0, 1.0, 3.0]
        @test vout ≈ expected rtol=1e-7
    end
    @testset "vsep" begin
        v1 = [1.0, 0.0, 0.0]
        v2 = [0.0, 1.0, 0.0]
        @test vsep(v1, v2) ≈ π/2
    end
    @testset "vsepg" begin
        v1 = [3.0, 0.0]
        v2 = [-5.0, 0.0]
        @test vsepg(v1, v2) ≈ π
    end
end


text:
using KernelOps
using Test

@inline function op_mean(A,r,c)
    m=zero(eltype(A))
    @simd for i in r
        @inbounds m+=A[i]
    end
    m/length(r)
end

@inline function op_max(A,r,c)
    m=A[r[1]]
    @simd for i in r
        @inbounds m=max(m,A[i])
    end
    m
end

@inline function kop(M)
    f1=KernelOp(op_mean,M,(1,1))
    f2=KernelOp(op_max,f1,(1,1))
    return KernelOp(M,(0,0)) do A,Is,I
        @inbounds f1[I]==f2[I]
    end
end

@noinline function compare_kop(M,R)
    kop(M)==R
end

@testset "Basic Test" begin
    M=[exp(-(x-3)^2-(y-3)^2) for x in 1:5, y in 1:5]
    result=Bool[0 0 0 0 0; 0 0 0 0 0; 0 0 1 0 0; 0 0 0 0 0; 0 0 0 0 0]
    @test compare_kop(M,result)
end

@testset "Type Inference" begin
    M=rand(Bool,2,2)
    ko=KernelOp(M,(0,0)) do A,Is,I
        A[I] && return 0.5
        return true
    end
    @test eltype(ko)==Union{Bool, Float64}
end


text:
## ------------------------------------------------------------------
function _new_tagmeta!(callinfo::LineNumberNode, label)

    # book
    book = _check_currbook()

    # TODO: Update book but just if necessary

    # checks
    _check_call_inbook(callinfo, book)

    # new doc
    tmeta = RBTagMeta(label)
    set_book!(tmeta, book)
    srcfile!(tmeta, srcfile(callinfo))
    srcline!(tmeta, srcline(callinfo))

    # add to book
    add_tagmeta!(book, tmeta)

    currobj!(tmeta)
end

## ------------------------------------------------------------------
macro new_tagmeta!(label::String)
    _new_tagmeta!(__source__, label)
end


text:
# A general way to do mutation testing is to rewrite the AST of a function
# so that we can then dynamically select what, if anything, to mutate.
# This is a manual test of this.

# Target function we want to mutate
function tf(x::Integer)
    a = 2*x
    res = 0
    for i in 1:a
        res += x * i
    end
    if a > 9
        res = -res
    end
    return res
end

# Abstract class for any dynamic code instrumentation scheme and the
abstract DynamicInstrumenter

# The default instrumenter has inlined no-ops as its instrumentation implementation =>
# as little overhead as possible
@inline start_execution(d::DynamicInstrumenter, funcname::Symbol, types, maxlines::Int) = nothing
@inline exec_line(d::DynamicInstrumenter, linenum::Int) = true
@inline binop_mult(d::DynamicInstrumenter, lhs, rhs) = lhs * rhs
@inline binop_plus(d::DynamicInstrumenter, lhs, rhs) = lhs + rhs
@inline binop_geq(d::DynamicInstrumenter, lhs, rhs) = lhs >= rhs
@inline binop_gt(d::DynamicInstrumenter, lhs, rhs) = lhs > rhs
@inline unop_neg(d::DynamicInstrumenter, val) = -val
@inline const_val(d::DynamicInstrumenter, val) = val
@inline const_var(d::DynamicInstrumenter, varname::Symbol, val) = val
@inline forloop_iterator(d::DynamicInstrumenter, it) = it
@inline stop_execution(d::DynamicInstrumenter, funcname::Symbol, types, retval) = retval

# The target function tf is rewritten dynamically to (this is the default instrumentation,
# to speed things up individual instrumenters might need to make leaner versions, this includes a lot
# to allow dynamic instrumentation/mutation etc):
function tf(d::DynamicInstrumenter, x::Integer)
    start_execution(d, :tf, (Int), 7)
    if exec_line(d, 1)
        a = binop_mult(d, 2, x)
    end
    if exec_line(d, 2)
        res = const_val(d, 0)
    end
    if exec_line(d, 3)
        for i in forloop_iterator(d, 1:a)
            if exec_line(d, 4)
                res = binop_plus(d, res, binop_mult(d, x, i))
            end
        end
    end
    if exec_line(d, 5)
        if binop_gt(d, a, 9)
            if exec_line(d, 6)
                res = unop_neg(d, res)
            end
        end
    end
    if exec_line(d, 7)
        retval = const_var(d, :res, res)
        return stop_execution(d, :tf, (Int), retval)
    end
    stop_execution(d, :tf, (Int), nothing)
end

# Instrumenter 1.
# Toy instrumenter that just measures the execution time. Not very well though since
# it is hard to separate the instrumented code from the original code...
type ExecTimingInstrumenter <: DynamicInstrumenter
    start::Float64
    elapsed::Float64
    ExecTimingInstrumenter() = new(0.0, 0.0)
end
@inline start_execution(i::ExecTimingInstrumenter, funcname::Symbol, types, maxlines::Int) = (i.start = time())
@inline function stop_execution(i::ExecTimingInstrumenter, funcname::Symbol, types, retval)
    i.elapsed = time() - i.start
    retval
end

arg1 = 5
@time r1 = tf(arg1)
eti = ExecTimingInstrumenter()
@time r2 = tf(eti, arg1)
@show (r1 == r2, eti) # Not getting the performance I expected here yet, but solvable in principle with better type info?

# Instrumenter 2.
# A more interesting instrumenter is one that counts which statements has been executed.
type StmtCoverageInstrumenter <: DynamicInstrumenter
    totallines::Int
    executions::Vector{Set{Int}}
    StmtCoverageInstrumenter() = new(-1, Set{Int}[])
end
function start_execution(s::StmtCoverageInstrumenter, funcname::Symbol, types, maxlines::Int)
    s.totallines = maxlines
    push!(s.executions, Set{Int}())
end
function exec_line(s::StmtCoverageInstrumenter, linenum::Int)
    push!(s.executions[end], linenum)
    true
end
stmt_coverages(s::StmtCoverageInstrumenter) = Float64[stmt_coverage(s, executedlines) for executedlines in s.executions]
function stmt_coverage(s::StmtCoverageInstrumenter, execlines::Set{Int})
    length(unique(execlines)) / s.totallines
end
all_covered_lines(s::StmtCoverageInstrumenter) = foldl(union, Set{Int}(), s.executions)
function stmt_coverage(s::StmtCoverageInstrumenter)
    stmt_coverage(s, all_covered_lines(s))
end

scov = StmtCoverageInstrumenter()
@time r3 = tf(scov, arg1)
@show (r1 == r3)
stmt_coverage(scov) # Should be 1.0

# But when argument is below 5 we don't cover all lines
scov2 = StmtCoverageInstrumenter()
arg2 = 4
@time r4 = tf(scov2, arg2)
@show (tf(arg2) == r4)
stmt_coverage(scov2) # should be 6/7 since only the unary negation is not executed

# Instrumenter 3.
# Mutates binary operator + to * and vice versa.
type BinopMutatingInstrumenter <: DynamicInstrumenter
end
@inline binop_mult(b::BinopMutatingInstrumenter, lhs, rhs) = lhs + rhs
@inline binop_plus(d::BinopMutatingInstrumenter, lhs, rhs) = lhs * rhs

mut = BinopMutatingInstrumenter()
@time r5 = tf(mut, arg1)
@show (r1 != r5)


text:
# ---
# title: 823. Binary Trees With Factors
# id: problem823
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories:
# link: <https://leetcode.com/problems/binary-trees-with-factors/description/>
# hidden: true
# ---
#
# Given an array of unique integers, each integer is strictly greater than 1.
#
# We make a binary tree using these integers and each number may be used for any
# number of times.
#
# Each non-leaf node's value should be equal to the product of the values of
# it's children.
#
# How many binary trees can we make?  Return the answer **modulo 10 ** 9 + 7**.
#
# **Example 1:**
#
#
#
#     Input: A = [2, 4]
#     Output: 3
#     Explanation: We can make these trees: [2], [4], [4, 2, 2]
#
# **Example 2:**
#
#
#
#     Input: A = [2, 4, 5, 10]
#     Output: 7
#     Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
#
#
#
# **Note:**
#
#   1. `1 <= A.length <= 1000`.
#   2. `2 <= A[i] <= 10 ^ 9`.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
supportedAxes(::PlottingPackage) = [:left]
supportedTypes(::PlottingPackage) = []
supportedStyles(::PlottingPackage) = [:solid]
supportedMarkers(::PlottingPackage) = [:none]
supportedScales(::PlottingPackage) = [:identity]
subplotSupported(::PlottingPackage) = false
stringsSupported(::PlottingPackage) = false

supportedAxes() = supportedAxes(backend())
supportedTypes() = supportedTypes(backend())
supportedStyles() = supportedStyles(backend())
supportedMarkers() = supportedMarkers(backend())
supportedScales() = supportedScales(backend())
subplotSupported() = subplotSupported(backend())
stringsSupported() = stringsSupported(backend())

# --------------------------------------------------------------------------------------

supportedArgs(::GadflyPackage) = [
    :annotation,
    # :axis,
    :background_color,
    :linecolor,
    :color_palette,
    :fillrange,
    :fillcolor,
    :fillalpha,
    :foreground_color,
    :group,
    :label,
    :layout,
    :legend,
    :linestyle,
    :linetype,
    :linewidth,
    :linealpha,
    :markershape,
    :markercolor,
    :markersize,
    :markeralpha,
    :markerstrokewidth,
    :markerstrokecolor,
    # :markerstrokestyle,
    :n,
    :nbins,
    :nc,
    :nr,
    # :pos,
    :smooth,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    :xticks,
    :y,
    :ylabel,
    :ylims,
    # :yrightlabel,
    :yticks,
    :xscale,
    :yscale,
    :xflip,
    :yflip,
    :z,
    :zcolor,
    :tickfont,
    :guidefont,
    :legendfont,
    :grid,
    # :surface,
    :levels,
  ]
supportedAxes(::GadflyPackage) = [:auto, :left]
supportedTypes(::GadflyPackage) = [:none, :line, :path, :steppre, :steppost, :sticks,
                                   :scatter, :heatmap, :hexbin, :hist, :bar,
                                   :hline, :vline, :contour]
supportedStyles(::GadflyPackage) = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot]
supportedMarkers(::GadflyPackage) = vcat(_allMarkers, Shape)
supportedScales(::GadflyPackage) = [:identity, :ln, :log2, :log10, :asinh, :sqrt]
subplotSupported(::GadflyPackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::ImmersePackage) = supportedArgs(GadflyPackage())
supportedAxes(::ImmersePackage) = supportedAxes(GadflyPackage())
supportedTypes(::ImmersePackage) = supportedTypes(GadflyPackage())
supportedStyles(::ImmersePackage) = supportedStyles(GadflyPackage())
supportedMarkers(::ImmersePackage) = supportedMarkers(GadflyPackage())
supportedScales(::ImmersePackage) = supportedScales(GadflyPackage())
subplotSupported(::ImmersePackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::PyPlotPackage) = [
    :annotation,
    :axis,
    :background_color,
    :linecolor,
    :color_palette,
    :fillrange,
    :fillcolor,
    :foreground_color,
    :group,
    :label,
    :layout,
    :legend,
    :linestyle,
    :linetype,
    :linewidth,
    :markershape,
    :markercolor,
    :markersize,
    :markerstrokewidth,
    :markerstrokecolor,
    # :markerstrokestyle,
    :n,
    :nbins,
    :nc,
    :nr,
    # :pos,
    :smooth,
    # :ribbon,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    :xticks,
    :y,
    :ylabel,
    :ylims,
    :yrightlabel,
    :yticks,
    :xscale,
    :yscale,
    :xflip,
    :yflip,
    :z,
    :zcolor,  # only supported for scatter/scatter3d
    :tickfont,
    :guidefont,
    :legendfont,
    :grid,
    # :surface,
    :levels,
    :fillalpha,
    :linealpha,
    :markeralpha,
  ]
supportedAxes(::PyPlotPackage) = _allAxes
supportedTypes(::PyPlotPackage) = [:none, :line, :path, :steppre, :steppost, #:sticks,
                                   :scatter, :heatmap, :hexbin, :hist, :density, :bar,
                                   :hline, :vline, :contour, :path3d, :scatter3d, :surface, :wireframe]
supportedStyles(::PyPlotPackage) = [:auto, :solid, :dash, :dot, :dashdot]
# supportedMarkers(::PyPlotPackage) = [:none, :auto, :rect, :ellipse, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5, :hexagon]
supportedMarkers(::PyPlotPackage) = vcat(_allMarkers, Shape)
supportedScales(::PyPlotPackage) = [:identity, :ln, :log2, :log10]
subplotSupported(::PyPlotPackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::GRPackage) = [
    :annotation,
    :axis,
    :background_color,
    :linecolor,
    :color_palette,
    :fillrange,
    :fillcolor,
    :foreground_color,
    :group,
    :label,
    :layout,
    :legend,
    :linestyle,
    :linetype,
    :linewidth,
    :markershape,
    :markercolor,
    :markersize,
    :markerstrokewidth,
    :markerstrokecolor,
    # :markerstrokestyle,
    :n,
    :nbins,
    :nc,
    :nr,
    # :pos,
    :smooth,
    # :ribbon,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    :xticks,
    :y,
    :ylabel,
    :ylims,
    :yrightlabel,
    :yticks,
    :xscale,
    :yscale,
    :xflip,
    :yflip,
    :z,
    :zcolor,  # only supported for scatter/scatter3d
    :tickfont,
    :guidefont,
    :legendfont,
    :grid,
    # :surface,
    :nlevels,
    :fillalpha,
    :linealpha,
    :markeralpha,
  ]
supportedAxes(::GRPackage) = _allAxes
supportedTypes(::GRPackage) = [:none, :line, :path, :steppre, :steppost, :sticks,
                               :scatter, :heatmap, :hexbin, :hist, :density, :bar,
                               :hline, :vline, :contour, :path3d, :scatter3d, :surface,
                               :wireframe, :ohlc, :pie]
supportedStyles(::GRPackage) = [:auto, :solid, :dash, :dot, :dashdot]
supportedMarkers(::GRPackage) = vcat([:none, :ellipse, :rect, :diamond, :utriangle, :dtriangle, :pentagon, :hexagon, :cross, :xcross, :star5], Shape)
supportedScales(::GRPackage) = [:identity, :log10]
subplotSupported(::GRPackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::QwtPackage) = [
    :annotation,
    # :args,
    :axis,
    :background_color,
    :linecolor,
    :color_palette,
    :fillrange,
    :fillcolor,
    :foreground_color,
    :group,
    # :heatmap_c,
    # :kwargs,
    :label,
    :layout,
    :legend,
    :linestyle,
    :linetype,
    :linewidth,
    :markershape,
    :markercolor,
    :markersize,
    # :markerstrokewidth,
    # :markerstrokecolor,
    # :markerstrokestyle,
    :n,
    :nbins,
    :nc,
    :nr,
    :pos,
    :smooth,
    # :ribbon,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    :xticks,
    :y,
    :ylabel,
    :ylims,
    :yrightlabel,
    :yticks,
    :xscale,
    :yscale,
    # :xflip,
    # :yflip,
    # :z,
  ]
supportedTypes(::QwtPackage) = [:none, :line, :path, :steppre, :steppost, :sticks, :scatter, :heatmap, :hexbin, :hist, :bar, :hline, :vline]
supportedMarkers(::QwtPackage) = [:none, :auto, :rect, :ellipse, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5, :star8, :hexagon]
supportedScales(::QwtPackage) = [:identity, :log10]
subplotSupported(::QwtPackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::UnicodePlotsPackage) = [
    # :annotation,
    # :args,
    # :axis,
    # :background_color,
    # :linecolor,
    # :fill,
    # :foreground_color,
    :group,
    # :heatmap_c,
    # :kwargs,
    :label,
    # :layout,
    :legend,
    :linestyle,
    :linetype,
    # :linewidth,
    :markershape,
    # :markercolor,
    # :markersize,
    # :markerstrokewidth,
    # :markerstrokecolor,
    # :markerstrokestyle,
    # :n,
    :nbins,
    # :nc,
    # :nr,
    # :pos,
    # :reg,
    # :ribbon,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    # :xticks,
    :y,
    :ylabel,
    :ylims,
    # :yrightlabel,
    # :yticks,
    # :xscale,
    # :yscale,
    # :xflip,
    # :yflip,
    # :z,
  ]
supportedAxes(::UnicodePlotsPackage) = [:auto, :left]
supportedTypes(::UnicodePlotsPackage) = [:none, :line, :path, :steppost, :sticks, :scatter, :heatmap, :hexbin, :hist, :bar, :hline, :vline]
supportedStyles(::UnicodePlotsPackage) = [:auto, :solid]
supportedMarkers(::UnicodePlotsPackage) = [:none, :auto, :ellipse]
supportedScales(::UnicodePlotsPackage) = [:identity]
subplotSupported(::UnicodePlotsPackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::WinstonPackage) = [
    :annotation,
    # :args,
    # :axis,
    # :background_color,
    :linecolor,
    :color_palette,
    :fillrange,
    :fillcolor,
    # :foreground_color,
    :group,
    # :heatmap_c,
    # :kwargs,
    :label,
    # :layout,
    :legend,
    :linestyle,
    :linetype,
    :linewidth,
    :markershape,
    :markercolor,
    :markersize,
    # :markerstrokewidth,
    # :markerstrokecolor,
    # :markerstrokestyle,
    # :n,
    :nbins,
    # :nc,
    # :nr,
    # :pos,
    :smooth,
    # :ribbon,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    # :xticks,
    :y,
    :ylabel,
    :ylims,
    # :yrightlabel,
    # :yticks,
    :xscale,
    :yscale,
    # :xflip,
    # :yflip,
    # :z,
  ]
supportedAxes(::WinstonPackage) = [:auto, :left]
supportedTypes(::WinstonPackage) = [:none, :line, :path, :sticks, :scatter, :hist, :bar]
supportedStyles(::WinstonPackage) = [:auto, :solid, :dash, :dot, :dashdot]
supportedMarkers(::WinstonPackage) = [:none, :auto, :rect, :ellipse, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5]
supportedScales(::WinstonPackage) = [:identity, :log10]
subplotSupported(::WinstonPackage) = false

# --------------------------------------------------------------------------------------

supportedArgs(::BokehPackage) = [
    # :annotation,
    # :axis,
    # :background_color,
    :linecolor,
    # :color_palette,
    # :fillrange,
    # :fillcolor,
    # :fillalpha,
    # :foreground_color,
    :group,
    # :label,
    # :layout,
    # :legend,
    :linestyle,
    :linetype,
    :linewidth,
    # :linealpha,
    :markershape,
    :markercolor,
    :markersize,
    # :markeralpha,
    # :markerstrokewidth,
    # :markerstrokecolor,
    # :markerstrokestyle,
    # :n,
    # :nbins,
    # :nc,
    # :nr,
    # :pos,
    # :smooth,
    # :show,
    :size,
    :title,
    # :windowtitle,
    :x,
    # :xlabel,
    # :xlims,
    # :xticks,
    :y,
    # :ylabel,
    # :ylims,
    # :yrightlabel,
    # :yticks,
    # :xscale,
    # :yscale,
    # :xflip,
    # :yflip,
    # :z,
    # :tickfont,
    # :guidefont,
    # :legendfont,
    # :grid,
    # :surface,
    # :levels,
  ]
supportedAxes(::BokehPackage) = [:auto, :left]
supportedTypes(::BokehPackage) = [:none, :path, :scatter] #,:steppre, :steppost, :sticks, :heatmap, :hexbin, :hist, :bar, :hline, :vline, :contour]
supportedStyles(::BokehPackage) = [:auto, :solid, :dash, :dot, :dashdot, :dashdotdot]
supportedMarkers(::BokehPackage) = [:none, :auto, :ellipse, :rect, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5] #vcat(_allMarkers, Shape)
supportedScales(::BokehPackage) = [:identity, :ln] #, :ln, :log2, :log10, :asinh, :sqrt]
subplotSupported(::BokehPackage) = false

# --------------------------------------------------------------------------------------

supportedArgs(::PlotlyPackage) = [
    :annotation,
    # :axis,
    :background_color,
    :color_palette,
    :fillrange,
    :fillcolor,
    :fillalpha,
    :foreground_color,
    :group,
    :label,
    :layout,
    :legend,
    :linecolor,
    :linestyle,
    :linetype,
    :linewidth,
    :linealpha,
    :markershape,
    :markercolor,
    :markersize,
    :markeralpha,
    :markerstrokewidth,
    :markerstrokecolor,
    :markerstrokestyle,
    :n,
    :nbins,
    :nc,
    :nr,
    # :pos,
    # :smooth,
    :show,
    :size,
    :title,
    :windowtitle,
    :x,
    :xlabel,
    :xlims,
    :xticks,
    :y,
    :ylabel,
    :ylims,
    # :yrightlabel,
    :yticks,
    :xscale,
    :yscale,
    :xflip,
    :yflip,
    :z,
    :zcolor,
    :tickfont,
    :guidefont,
    :legendfont,
    :grid,
    :levels,
  ]
supportedAxes(::PlotlyPackage) = [:auto, :left]
supportedTypes(::PlotlyPackage) = [:none, :line, :path, :scatter, :steppre, :steppost,
                                   :heatmap, :hist, :density, :bar, :contour, :surface, :path3d, :scatter3d,
                                   :pie] #,, :sticks, :hexbin, :hline, :vline]
supportedStyles(::PlotlyPackage) = [:auto, :solid, :dash, :dot, :dashdot]
supportedMarkers(::PlotlyPackage) = [:none, :auto, :ellipse, :rect, :diamond, :utriangle, :dtriangle, :cross, :xcross,
                                     :pentagon, :hexagon, :octagon, :vline, :hline] #vcat(_allMarkers, Shape)
supportedScales(::PlotlyPackage) = [:identity, :log10] #, :ln, :log2, :log10, :asinh, :sqrt]
subplotSupported(::PlotlyPackage) = true
stringsSupported(::PlotlyPackage) = true

# --------------------------------------------------------------------------------------

supportedArgs(::GLVisualizePackage) = [
    # :annotation,
    # :axis,
    # :background_color,
    # :color_palette,
    # :fillrange,
    # :fillcolor,
    # :fillalpha,
    # :foreground_color,
    # :group,
    # :label,
    # :layout,
    # :legend,
    # :linecolor,
    # :linestyle,
    # :linetype,
    # :linewidth,
    # :linealpha,
    # :markershape,
    # :markercolor,
    # :markersize,
    # :markeralpha,
    # :markerstrokewidth,
    # :markerstrokecolor,
    # :markerstrokestyle,
    # :n,
    # :nbins,
    # :nc,
    # :nr,
    # :pos,
    # :smooth,
    # :show,
    # :size,
    # :title,
    # :windowtitle,
    # :x,
    # :xlabel,
    # :xlims,
    # :xticks,
    # :y,
    # :ylabel,
    # :ylims,
    # :yrightlabel,
    # :yticks,
    # :xscale,
    # :yscale,
    # :xflip,
    # :yflip,
    # :z,
    # :tickfont,
    # :guidefont,
    # :legendfont,
    # :grid,
    # :surface
    # :levels,
  ]
supportedAxes(::GLVisualizePackage) = [:auto, :left]
supportedTypes(::GLVisualizePackage) = [:contour] #, :path, :scatter ,:steppre, :steppost, :sticks, :heatmap, :hexbin, :hist, :bar, :hline, :vline, :contour]
supportedStyles(::GLVisualizePackage) = [:auto, :solid] #, :dash, :dot, :dashdot, :dashdotdot]
supportedMarkers(::GLVisualizePackage) = [:none, :auto, :ellipse] #, :rect, :diamond, :utriangle, :dtriangle, :cross, :xcross, :star5] #vcat(_allMarkers, Shape)
supportedScales(::GLVisualizePackage) = [:identity] #, :log, :log2, :log10, :asinh, :sqrt]
subplotSupported(::GLVisualizePackage) = false


text:
"""
	$(SIGNATURES)

Retrieve a property from an object or its child objects.
If the property is not unique, returns the first match and then stops.
Returns `nothing` if not found.
"""
function retrieve_property(o, pName :: Symbol)
    if hasproperty(o, pName)
        outVal = getproperty(o, pName);
    else
        outVal = nothing;
        pn = propertynames(o);
        for propName in pn
            outVal = retrieve_property(getproperty(o, propName), pName);
            if !isnothing(outVal)
                break;
            end
        end
    end
    return outVal
end

"""
	$(SIGNATURES)

Retrieve a property in a child object of a given name.
Does not retrieve property from object itself.
This helps when properties are not unique.
"""
function retrieve_child_property(o, childName :: Symbol, pName :: Symbol)
    # First retrieve the child
    child = retrieve_property(o, childName);
    @assert !isnothing(child)  "Cannot find $childName"
    return retrieve_property(child, pName)
end

"""
	$(SIGNATURES)

Does object or a child object have a property?
"""
function has_property(o, pName :: Symbol)
    return !isnothing(retrieve_property(o, pName))
end

# -------------


text:
"""
Collection of plotting functions, used mostly in Thesis.
"""

using Plots
using KernelDensity
using StatsBase
using Colors

"""
Makes a palette interpolating between two colors returning
an array of length=length(x)
"""
function make_palette(x::AbstractVector)
    return range(HSL(217, .64, .55), stop=HSL(320, .73, .78), length=length(x))
end

function make_palette(n::Int64)
    return range(HSL(217, .64, .55), stop=HSL(320, .73, .78), length=n)
end

"""
Plot the 95th confidence interval of X as a vertical bar at the x axis value xpos
"""
function plot_CI!(X, xpos, color; kwargs...)
    low, med, high = percentile(X, [2.5, 50, 97.5])

    plot!(
        [xpos, xpos], [low, high],
        color=color,
        lw=12;
        kwargs...
    )
    Δ = max(0.02 * med, .2)
    plot!(
        [xpos, xpos], [med - Δ, med + Δ],
        color="white",
        lw=10, label=nothing
    )
end

"""
Plot the KDE of X as a density plot with the 95th CI underneath a a bar
"""
function plot_kde_and_CI(X; bandwidth=1.0, xlabel="", color="black", ylabel="", label=nothing, kwargs...)
    B = kde(Vector{Float64}(X); bandwidth=bandwidth)
    low, med, high = percentile(X, [2.5, 50, 97.5])

    plt = plot(
        B.x,
        B.density;
        lw=2,
        color=color,
        fillalpha=.2,
        fillcolor=color,
        fillrange=zeros(length(B.density)),
        xlabel="", ylabel="", label=label, kwargs...
    )

    y = -maximum(B.density) / 20
    plot!(
        [low, high], [y, y], lw=8, color=color, alpha=1, label=nothing
    )
    # plot!([med - med * 0.15, med + med * 0.15], [y, y], lw=4, color="white", alpha=1, label=nothing)
    scatter!([med], [y], color="white", label=nothing, alpha=1, ms=6, shape=:rect)
    return plt
end

function plot_kde_and_CI!(X; bandwidth=1.0, xlabel="", color="black", ylabel="", label=nothing)
    B = kde(Vector{Float64}(X); bandwidth=bandwidth)
    low, med, high = percentile(X, [2.5, 50, 97.5])

    plot!(
        B.x,
        B.density;
        lw=2,
        color=color,
        fillalpha=.2,
        fillcolor=color,
        fillrange=zeros(length(B.density)),
        xlabel="", ylabel="", label=label
    )

    y = -maximum(B.density) / 20
    plot!(
        [low, high], [y, y], lw=8, color=color, alpha=1, label=nothing
    )
    # plot!([med - med * 0.15, med + med * 0.15], [y, y], lw=4, color="white", alpha=1, label=nothing)
    scatter!([med], [y], color="white", label=nothing, alpha=1, ms=6, shape=:rect)
end

"""
More complex 1D KDE plot with options to move and scale the KDE.
"""
function kdeplot!(X;
        scaling=1.0,
        shift=0.0,
        v0=0,
        v1=1.0,
        bw=1.0,
        xshift=0.0,
         color="red",
        nbins=nothing,
        horizontal=false,
        normalize=false,
        fillalpha=.3,
         kwargs...
)
    kde = KDEUniv(ContinuousDim(), bw, X, MultiKDE.gaussian)

    nbins = isnothing(nbins) ? (Int64 ∘ round)(v1-v0) * 2 : 100
    x = Vector(LinRange(v0, v1, nbins))

    density = [MultiKDE.pdf(kde, _x, keep_all=false) for _x in x]
    density = normalize ? density ./ maximum(density) : density
    y = density .* scaling .+ shift

    if horizontal
        x, y = y, x
    end

    plot!(
        x .- xshift,
        y;
        colorbar=false,
        color = color,
        lw=2,
        fillcolor=color, fillalpha=fillalpha, fillrange=zeros(length(density)) .+ shift .+  minimum(density),
        kwargs...
    )
end

max_stars_repo_name: FedeClaudi/LocomotionControl

max_issues_repo_name: FedeClaudi/LocomotionControl

max_forks_repo_name: FedeClaudi/LocomotionControl


text:
isempty(line::String) = !ismatch(r"[^\s\t\n\r]+", line)

iscomment(line::String) = ismatch(r"^#", line)

istitle(line::String) = ismatch(r"^\*\*\*(.*)MODEL (STATES|PARAMETERS|ODES)", line)

is_ode_name(name::String) = ismatch(r"^d/dt\((.*)\)$", name)

function get_title_type(line::String)
  if ismatch(r"^\*\*\*(.*)MODEL STATES(.*)", line)
    return "state"
  elseif ismatch(r"^\*\*\*(.*)MODEL PARAMETERS(.*)", line)
    return "parameter"
  elseif ismatch(r"^\*\*\*(.*)MODEL ODES(.*)", line)
    return "ode"
  else
    throw(ParseError("Unknown title \""*line*"\" type in model specification"))
  end
end

function parse_line(line::String, linetype::String, model::OdeModel)
  if linetype == "state"
    nTokens = parse_state_line(line, model.states)
  elseif linetype == "parameter"
    nTokens = parse_parameter_line(line, model.parameters)
  elseif linetype == "ode"
    nTokens = parse_ode_line(line, model.odes)
  else
    throw(ParseError("Unknown title \""*line*"\" type in model specification"))
  end

  return nTokens
end

function parse_state_line(line::String, dict::Dict{String, Float64})
  tokens = split(line, '=')
  nTokens = length(tokens)

  if nTokens != 2
    throw(ParseError("Line \""*line*"\" has wrong format"))
  end

  name, value = [strip(i) for i in tokens]

  haskey(dict, name) ? throw(KeyError("\""*name*"\" specified more than once")) : (dict[name] = float64(value))

  return nTokens
end

function parse_parameter_line(line::String, dict::Dict{String, Float64})
  tokens = split(line, '=')
  nTokens = length(tokens)

  if nTokens == 1
    dict[strip(tokens)] = NaN
  elseif nTokens == 2
    name, value = [strip(i) for i in tokens]

    haskey(dict, name) ? throw(KeyError("\""*name*"\" specified more than once")) : (dict[name] = float64(value))
  else
    throw(ParseError("Line \""*line*"\" has wrong format"))
  end

  return nTokens
end

function parse_ode_line(line::String, dict::Dict{String, NSE})
  tokens = split(line, '=')
  nTokens = length(tokens)

  if nTokens != 2
    throw(ParseError("Line \""*line*"\" has wrong format"))
  end

  name, value = [strip(i) for i in tokens]

  is_ode_name(name) ? (name = name[6:end-1]) : throw(KeyError("Time derivative \""*name*"\" has wrong format"))

  haskey(dict, name) ? throw(KeyError("\""*name*"\" specified more than once")) : (dict[name] = parse(value))

  return nTokens
end

function parse_model(file::String)
  odeModel = OdeModel(file, Dict{String, Float64}(), Dict{String, Float64}(), Dict{String, NSE}())

  s = open(file)

  while !eof(s)
    line = readline(s)
    if isempty(line) || iscomment(line)
      continue
    elseif istitle(line)
      title = get_title_type(line)
    else
      parse_line(line, title, odeModel)
    end
  end

  close(s)

  if sort(collect(keys(odeModel.states))) != sort(collect(keys(odeModel.odes)))
    throw(KeyError("States and their time derivatives in the ODE model are inconsistent"))
  end

  return odeModel
end


text:
export iauLteceq
"""
Transformation from ecliptic coordinates (mean equinox and ecliptic
of date) to ICRS RA,Dec, using a long-term precession model.

This function is part of the International Astronomical Union's
SOFA (Standards of Fundamental Astronomy) software collection.

Status:  support function.

Given:
   epj     double     Julian epoch (TT)
   dl,db   double     ecliptic longitude and latitude (radians)

Returned:
   dr,dd   double     ICRS right ascension and declination (radians)

   1. No assumptions are made about whether the coordinates represent
   starlight and embody astrometric effects such as parallax or
   aberration.

   2. The transformation is approximately that from ecliptic longitude
   and latitude (mean equinox and ecliptic of date) to mean J2000.0
   right ascension and declination, with only frame bias (always
   less than 25 mas) to disturb this classical picture.

   3. The Vondrak et al. (2011, 2012) 400 millennia precession model
   agrees with the IAU 2006 precession at J2000.0 and stays within
   100 microarcseconds during the 20th and 21st centuries.  It is
   accurate to a few arcseconds throughout the historical period,
   worsening to a few tenths of a degree at the end of the
   +/- 200,000 year time span.

Called:
   iauS2c       spherical coordinates to unit vector
   iauLtecm     J2000.0 to ecliptic rotation matrix, long term
   iauTrxp      product of transpose of r-matrix and p-vector
   iauC2s       unit vector to spherical coordinates
   iauAnp       normalize angle into range 0 to 2pi
   iauAnpm      normalize angle into range +/- pi

References:

   Vondrak, J., Capitaine, N. and Wallace, P., 2011, New precession
   expressions, valid for long time intervals, Astron.Astrophys. 534,
   A22

   Vondrak, J., Capitaine, N. and Wallace, P., 2012, New precession
   expressions, valid for long time intervals (Corrigendum),
   Astron.Astrophys. 541, C1

This revision:  2016 February 9

SOFA release 2018-01-30

Copyright (C) 2018 IAU SOFA Board.  See notes at end.
"""

# void iauLteceq(double epj, double dl, double db, double *dr, double *dd)
function iauLteceq(epj::Real, dl::Real, db::Real)
   ref_dr = Ref{Float64}(0.0)
   ref_dd = Ref{Float64}(0.0)
   ccall((:iauLteceq, libsofa_c), Cvoid,
         (Cdouble, Cdouble, Cdouble,
         Ref{Cdouble}, Ref{Cdouble}),
          convert(Float64, epj),
          convert(Float64, dl),
          convert(Float64, db),
          ref_dr, ref_dd)

   return ref_dr[], ref_dd[]
end


text:
"""
    exponents = get_exponents(variables, dmax::Int)

Compute the set of all exponents in `variables` variables, of degree up to
`dmax`.
"""
function compute_exponents(variables, dmax::Int)
    cur_order = Set{Exponent}([Exponent()])
    result = copy(cur_order)
    prev_order = Set{Exponent}()
    for i=1:d
        prev_order = copy(cur_order)
        cur_order = Set{Exponent}()
        for var in input_vars
            union!(cur_order, Set([product(Exponent(var), elt) for elt in prev_order]))
        end
        union!(result, cur_order)
    end
    return result
end

max_stars_repo_name: Gimaju/GOC

max_issues_repo_name: Gimaju/GOC

max_forks_repo_name: Gimaju/GOC


text:
@testset "Corpus" begin

    sample_text1 = "This is a string"
    sample_text2 = "This is also a string"
    sample_file = joinpath(dirname(@__FILE__), "data", "poem.txt")

    sd = StringDocument(sample_text1)
    fd = FileDocument(sample_file)
    td = TokenDocument(sample_text1)
    ngd = NGramDocument(sample_text1)

    crps = Corpus(Any[sd, fd, td, ngd])
    crps2 = Corpus([ngd, ngd])

    documents(crps)

    for doc in crps
    	@test isa(doc, AbstractDocument)
    end

    lexicon(crps)
    update_lexicon!(crps)
    lexicon(crps)

    inverse_index(crps)
    update_inverse_index!(crps)
    inverse_index(crps)

    hash_function(crps)
    hash_function!(crps, TextHashFunction())

    crps[1]
    crps["string"]

    crps = Corpus([StringDocument("1 2 1 4")])
    standardize!(crps, StringDocument)
    remove_words!(crps, [""])
    update_lexicon!(crps)
    answer = Dict("1"=> 2, "2"=> 1, "4"=> 1)

     @test answer == lexicon(crps)
end

using DataFrames

@testset "Convert Corpus to DataFrames" begin
    crps = Corpus([StringDocument("hello world"), StringDocument("goodbye world")])
    df = convert(DataFrame, crps)
    @test typeof(df) == DataFrames.DataFrame
    @test df[1, :Text] == "hello world"
    @test df[1, :Length] == 11
    @test df[2, :Text] == "goodbye world"
    @test df[2, :Length] == 13
end


text: const Rₑ_m = 6371008.7714


text:
# Find _a_ unitary transform U that maps U†X(g)U = Y(g) where X(g) and Y(g) are irreps that
# are related by a constant unitary transform, following https://doi.org/10.1088/1751-8113/47/50/505203
function find_unitary_irrep_transform(Xs, Ys, gs)
    N = size(first(Xs), 1)
    G = length(gs)

    all(((X,Y),) -> tr(X) ≈ tr(Y), zip(Xs,Ys)) || error("Xs and Ys are not unitarily equivalent")

    rᵃᵇ²s = zeros(ComplexF64, N, N)
    for (X, g) in zip(Xs, gs)
        g⁻¹ = inv(g)
        idx_g⁻¹ = something(findfirst(≈(g⁻¹), gs))
        Y = Ys[idx_g⁻¹]
        for a in 1:N
            for b in 1:N
                rᵃᵇ²s[a,b] += X[a,a]*Y[b,b]
            end
        end
    end

    ab = findfirst(rᵃᵇ² -> real(rᵃᵇ²) > 0.0 && abs(imag(rᵃᵇ²)) < ATOL_DEFAULT, rᵃᵇ²s)
    a, b = Tuple(something(ab))
    rᵃᵇ = sqrt(N/G * real(rᵃᵇ²s[a,b]))
    U = zeros(ComplexF64, N, N)
    for (X,Y) in zip(Xs, Ys)
        for i in 1:N
            for j in 1:N
                U[i,j] += X'[i,a]*Y[b,j]
            end
        end
    end
    U .*= N/(G*rᵃᵇ)

    return mapto_canonical_unitary!(U)
end

# find the unitary transformation that connects Xᵢ and Yᵢ by UXᵢU⁻¹ = Yᵢ for some set {i},
# following https://mathoverflow.net/a/391741
function find_unitary_transform(Xs, Ys)
    N = LinearAlgebra.checksquare(first(Xs))
    M = length(Xs)

    M == length(Ys) || error("the lengths of Xs and Ys must match")
    all(X->LinearAlgebra.checksquare(X)==N, Xs) || error("`Xs` matrices are not square or not of identical size")
    all(Y->LinearAlgebra.checksquare(Y)==N, Ys) || error("`Ys` matrices are not square or not of identical size")

    N² = N^2
    T = promote_type(eltype(first(Xs)), eltype(first(Ys)))
    Q = Matrix{T}(undef, M*N², N²)
    for i in 1:M
        Q[(i-1)*N² .+ (1:N²), 1:N²] .= kron(I(N), transpose(Xs[i]))  .-  kron(Ys[i], I(N))
    end

    # find a matrix U which is not necessarily unitary, but which obeys UXU⁻¹ = Y ∀i
    Uv = nullspace(Q, atol=ATOL_DEFAULT)
    U = if size(Uv,2) ≠ 1 # multiple solution vectors found; need some combination of them...
        # let's do a hail-mary attempt and just add them up; works sometimes... FIXME!?
        permutedims(reshape(sum(Uv, dims=2), N, N))
    else
        permutedims(reshape(Uv, N, N))
    end

    check_transform = all(zip(Xs, Ys)) do (X,Y)
        U*X/U ≈ Y
    end
    check_transform || error("initial transform is invalid :(")

    U = mapto_canonical_unitary(U)
    check_transform = all(zip(Xs, Ys)) do (X,Y)
        U*X*U' ≈ Y
    end
    check_transform || error("'unitarized' transform is invalid :(")
    U'*U ≈ I || error("computed transformation is not unitary :(")

    return U
end

# Eq. (4.5.51) of Bradley & Cracknell's book. Find a unitary operator U such that
#           Y(g) = UX(g)U⁻¹   ∀g∈G
# Construct P as:
#           U = |G|⁻¹ ∑ Y(g)MX⁻¹(g)
# with M an arbitrary (?) matrix. This approach is derived by Wigner in his book on p. 80
# and the "unitarization" is discussed on p. 78-79. It's not completely clear what
# conditions should be imposed on M; for now, we choose it as some arbitrary unitary matrix,
# generated from the Gell-Mann matrices. The initial construction doesn't guarantee that
# Not clear what conditions should be imposed on X, if any -
# if it is chosen completely arbitrary, it does not ensure that P is unitary (but it can
# then be rescaled to become unitary; i.e., it is a "scalar away" from being unitary).
function find_unitary_transform_bc(Xs, Ys, M=nothing)
    if Xs ≈ Ys # fast-path
        return Matrix{ComplexF64}(I(size(first(Xs), 1)))
    end

    N = size(first(Xs), 1)
    hs = gellmann(N, skip_identity=true)
    Ms = isnothing(M) ? [sum(hs), cis.(hs)...] : [M]
    for M in Ms
        U = sum(zip(Xs, Ys)) do (X,Y)
            X*M*inv(Y)
        end ./ length(Xs)
        rank(U) == N || continue

        check_transform = all(zip(Xs, Ys)) do (X,Y)
            U*X/U ≈ Y
        end
        check_transform || continue # initial transform guess is invalid :(

        U = mapto_canonical_unitary(U)
        check_transform = all(zip(Xs, Ys)) do (X,Y)
            U*X*U' ≈ Y
        end
        check_transform || continue # 'unitarized' transform is invalid :(
        U'*U ≈ I || continue # computed transformation is not unitary :(

        return U
    end
    error("failed to find a unitary transform")
end

# find unitary part of 𝒯g₀ operation, using Eq. (S58) of Bradlyn, Science (2016)
#   D(𝒯g₀) D(gᵢ) D(𝒯g₀ )⁻¹  =  D*(g₀gᵢg₀⁻¹)
function find_antiunitary_irrep(lgir, g₀)
    Xs = lgir(nothing)                               # D(gᵢ)
    Ys = trs_transformed_irreps(Xs, group(lgir), g₀) # D*(g₀gᵢg₀⁻¹)

    if all(((X,Y),) -> tr(X) ≈ tr(Y), zip(Xs, Ys))
        D_𝒯g₀ = try
            find_unitary_transform_bc(Xs, Ys)
        catch
            find_unitary_transform(Xs, Ys)
        end
        return D_𝒯g₀
    else
        # TODO: The irrep is complex; this should probably not be possible if fed by a
        #       corep, but would be nice to generalize our scope here
        error("Xs and Ys are not equivalent: don't know how to proceed")
    end
end

function find_antiunitary_irrep(lgir::LGIrrep)
    g₀ = find_kv_to_negative_kv_operation(lgir) # find g₀ s.t. g₀k = -k + G
    if !isnothing(g₀)
        return find_antiunitary_irrep(lgir, g₀)
    else
        return nothing
    end
end

# find an operation in the space group of `lgir` that maps `kv` to `-kv`
function kv_to_negative_kv_operation(lgir::LGIrrep{D}) where D
    sg = spacegroup(num(lgir), Val(D))
    cntr = centering(sg)
    kv = position(lgir)
    g₀_idx = findfirst(g -> isapprox(g*kv, -kv, cntr), sg)
    return isnothing(g₀_idx) ? nothing : sg[g₀_idx]
end

function trs_transformed_irreps(Xs, lg, g₀)
    Ys = similar(Xs)  # D*(g₀gᵢg₀⁻¹)
    cntr = centering(lg)
    kv = position(lg)() # TODO: αβγ?
    g₀⁻¹ = inv(g₀)
    for (i, gᵢ) in enumerate(lg)
        g₀gᵢg₀⁻¹ = compose(g₀, compose(gᵢ, g₀⁻¹, #=modτ=#false), #=modτ=#false)
        j, Δw = something(Crystalline.findequiv(g₀gᵢg₀⁻¹, lg, cntr))
        ϕ_g₀gᵢg₀⁻¹ = cispi(2*dot(kv, Δw)) # translation phase factor
        D_g₀gᵢg₀⁻¹ = Xs[j] * ϕ_g₀gᵢg₀⁻¹   # D(g₀gᵢg₀⁻¹)
        Ys[i] = conj.(D_g₀gᵢg₀⁻¹)         # D*(g₀gᵢg₀⁻¹)
    end
    return Ys
end

function mapto_canonical_unitary(U)
    # we assume that `U` is at most "a scalar away" from being unitary, and we want to
    # mutate `U` to become this related unitary matrix; additionally, we want to map it to
    # a canonical form. We have two steps:

    # 1. "unitarize" `U` (a unitary operator must have UU† = I; let's ensure this - assuming
    # that `U` is indeed a "scalar away" from being unitary). Trick is from Wigner p. 78-79:
    K = sqrt(U*U') # a multiple of the identity matrix
    U = K*U

    # 2. "canonicalize" `U` (currently has an arbitrary complex phase of norm 1) by
    # requiring that it is a special unitary matrix (i.e., in SU(N)), so that `det(U) = 1`.
    # Already, `U` is in U(N), i.e. `norm(det(U)) = 1`; below, we find the phase needed to
    # "rotate" it into SU(N), using that det(cA) = cᴺdet(A)
    N = LinearAlgebra.checksquare(U)
    c = det(U)^(1/N)
    U ./= c

    return U
end