text:
# ---
# title: 803. Bricks Falling When Hit
# id: problem803
# author: Tian Jun
# date: 2020-10-31
# difficulty: Hard
# categories: Union Find
# link: <https://leetcode.com/problems/bricks-falling-when-hit/description/>
# hidden: true
# ---
#
# You are given an `m x n` binary `grid`, where each `1` represents a brick and
# `0` represents an empty space. A brick is **stable** if:
#
#   * It is directly connected to the top of the grid, or
#   * At least one other brick in its four adjacent cells is **stable**.
#
# You are also given an array `hits`, which is a sequence of erasures we want to
# apply. Each time we want to erase the brick at the location `hits[i] = (rowi,
# coli)`. The brick on that location (if it exists) will disappear. Some other
# bricks may no longer be stable because of that erasure and will **fall**. Once
# a brick falls, it is **immediately** erased from the `grid` (i.e., it does not
# land on other stable bricks).
#
# Return _an array_`result` _, where each_`result[i]` _is the number of bricks
# that will **fall** after the _`ith` _erasure is applied._
#
# **Note** that an erasure may refer to a location with no brick, and if it
# does, no bricks drop.
#
#
#
# **Example 1:**
#
#
#
#     Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
#     Output: [2]
#     Explanation: Starting with the grid:
#     [[1,0,0,0],
#      [ _1_ ,1,1,0]]
#     We erase the underlined brick at (1,0), resulting in the grid:
#     [[1,0,0,0],
#      [0, _1_ , _1_ ,0]]
#     The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
#     [[1,0,0,0],
#      [0,0,0,0]]
#     Hence the result is [2].
#
#
# **Example 2:**
#
#
#
#     Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
#     Output: [0,0]
#     Explanation: Starting with the grid:
#     [[1,0,0,0],
#      [1, _1_ ,0,0]]
#     We erase the underlined brick at (1,1), resulting in the grid:
#     [[1,0,0,0],
#      [1,0,0,0]]
#     All remaining bricks are still stable, so no bricks fall. The grid remains the same:
#     [[1,0,0,0],
#      [ _1_ ,0,0,0]]
#     Next, we erase the underlined brick at (1,0), resulting in the grid:
#     [[1,0,0,0],
#      [0,0,0,0]]
#     Once again, all remaining bricks are still stable, so no bricks fall.
#     Hence the result is [0,0].
#
#
#
#
# **Constraints:**
#
#   * `m == grid.length`
#   * `n == grid[i].length`
#   * `1 <= m, n <= 200`
#   * `grid[i][j]` is `0` or `1`.
#   * `1 <= hits.length <= 4 * 104`
#   * `hits[i].length == 2`
#   * `0 <= xi <= m - 1`
#   * `0 <= yi <= n - 1`
#   * All `(xi, yi)` are unique.
#
#
## @lc code=start
using LeetCode

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


text:
cd(@__DIR__); include("setups/grid7x3.jl");
pyplot(dpi = 200)

# DAG pseudo-metric
distDAG = eigDAG_Distance(𝚽, Q, N)

# MDS embedding into R²
D = distDAG
E = transform(fit(MDS, D, maxoutdim=2, distances=true))

# set up all heatmap plots' positions
dx = 0.01; dy = dx;
xej = zeros(Nx, N); yej=zeros(Ny, N);
a = 5.0; b = 9.0;
for k = 1:N
    xej[:,k] = LinRange(E[1,k] - Ny * a * dx, E[1, k] + Ny * a * dx, Nx)
    yej[:,k] = LinRange(E[2,k] - a * dy, E[2, k] + a * dy, Ny)
end

## Build Dual Graph
Gstar_Sig = dualgraph(distDAG)
GP_dual = partition_tree_fiedler(Gstar_Sig; swapRegion = false)
GP_primal = pairclustering(𝚽, GP_dual)

VM_NGWP = vm_ngwp(𝚽, GP_dual)

## level 2 VM-NGWP vectors
j = 3; W_VM = VM_NGWP[:, j, :]'

wav_kl = [[0 0];[0 1];[0 2];[1 0];[1 1];[1 2];[1 3];[2 0];[2 1];[2 2];[3 0];
            [3 1];[3 2];[3 3];[2 3];[2 4];[2 5];[2 6];[3 4];[3 5];[3 6]];
wav_kl = wav_kl[eig2grid_ind,:];

# reorder_ind = [2,3,1,5,7,4,6, 16,17,15,  9,11,8,10, 18,20,21,19, 13,14,12]
reorder_ind = [1,3,2,5,7,4,6, 8,10,9,17,15,18,16, 11,13,14,12,20,21,19]
W_VM = W_VM[:,reorder_ind[eig2grid_ind]];
sgn = ones(N); sgn[grid2eig_ind[[4,6,8,11,12,14]]] .= -1; W_VM = W_VM * Diagonal(sgn);

#################### Fig. 6
plot()
for k=1:N
    heatmap!(xej[:, k], yej[:, k], reshape(W_VM[:,k], (Nx, Ny))', c = :viridis,
        colorbar = false, ratio = 1, annotations = (xej[4, k], yej[3, k] + b * dy,
        text(latexstring("\\psi_{", string(wav_kl[k,1]), ",", string(wav_kl[k,2]), "}"), 10)))
end
plot!(aspect_ratio = 1, xlim = [-1.4, 1.3], ylim = [-1.4, 1.3], grid = false, clims=(-0.34, 0.34))
# first level partition
p1x = [-0.2, 1.0, NaN]; p1y = [1.3, -1.0, NaN]; plot!(p1x, p1y, c = :red, legend = false, width = 3)
# second level partition
p2x = [-1.0, 0.2, NaN, 0.4, 1.2, NaN]; p2y = [-0.8, 0.45, NaN, 0.25, 0.2, NaN];
plot!(p2x, p2y, c = :orange, legend = false, width = 2)
plt = current()
savefig(plt, "../figs/Grid7x3_DAG_VM_NGWP_lvl2_wavelets.png")

ext: jl


text:
using MyGraph

G = buildconnectedgraph(collect(1:6), (a,b) -> first(abs.(rand(Int8, 1))))

T,t = alg1(G; source = 1, start = 1)
H,h = alg1(G; source = 3, start = 3)


text:
@testset "Mutations" begin

    rng = StableRNG(42)

    @testset "ES Strategies" begin
        ss = [IsotropicStrategy{Float64}(1.0,1,0),
              IsotropicStrategy{Float64}(2.0,0,0),
              IsotropicStrategy{Float64}(3.0,0,0)]
        @test average(ss).σ == ss[2].σ
        Random.seed!(rng, 1)
        @test gaussian(ss[1], rng=rng).σ == ss[1].σ
        @test ss[1].σ != 1.0

        ss = [AnisotropicStrategy{Float64}(fill(1.0,3),1,1),
              AnisotropicStrategy{Float64}(fill(2.0,3),0,0),
              AnisotropicStrategy{Float64}(fill(3.0,3),0,0)]
        @test average(ss).σ == ss[2].σ
        Random.seed!(rng, 1)
        @test gaussian(ss[1], rng=rng).σ == ss[1].σ
        @test ss[1].σ != fill(1.0,3)
    end

    @testset "GA" begin

        Random.seed!(rng, 1)
        @testset for i in 1:100
            from, to = Evolutionary.randseg(rng, 5)
            @test from < to
        end

        Random.seed!(rng, 1)
        @test flip(falses(5), rng=rng) == [0,0,0,1,0]
        @test bitinversion(falses(5)) == ones(5)

        Random.seed!(rng, 1)
        @test all(-1 .<= uniform()(zeros(10), rng=rng) .<= 1)
        @test all(-2 .<= gaussian()(zeros(10), rng=rng) .<= 2)
        @test all(-0.5 .<= BGA(ones(10))(zeros(10), rng=rng) .<= 0.5)

        Random.seed!(rng, 1)
        lx = [0.0, 0.0]
        ux = [2.0, 1.0]
        @test PM(lx, ux, Inf)([1.0, 2.0], rng=rng)[1] ∈ [0.0, 2.0]
        @test PM(lx, ux, Inf)([1.0, 2.0], rng=rng)[2] == 1.0
        @test MIPM(lx, ux, Inf, 1.0)(Real[1.0, 2], rng=rng)[1] ∈ [0.0, 2.0]
        @test MIPM(lx, ux, 10.0, Inf)(Real[1.0, 2], rng=rng)[2] == 1.0

        Random.seed!(rng, 1)
        ex = PLM(ones(1000), pm=1.0)(zeros(1000), rng=rng) |> extrema
        @test ex[1] >= -1
        @test ex[2] <= 1

        Random.seed!(rng, 4)
        @test inversion([0:5;], rng=rng) == [0,1,4,3,2,5]
        Random.seed!(rng, 42)
        @test inversion(Bool[1,0,1,0,1], rng=rng) == Bool[0,1,1,0,1]
        Random.seed!(rng, 4)
        @test insertion([0:5;], rng=rng) == [0,1,3,4,2,5]
        Random.seed!(rng, 5)
        @test swap2([0:5;], rng=rng) == [0,1,2,3,5,4]
        Random.seed!(rng, 2)
        @test scramble([0:5;], rng=rng) == [0,4,1,5,3,2]
        Random.seed!(rng, 2)
        @test shifting([0:5;], rng=rng) == [2,3,4,5,0,1]

    end

    @testset "DE" begin
        rec = ones(2)
        mut = [[0.5, 1.0], [1.0, 0.5]]
        @test_throws AssertionError Evolutionary.differentiation(rec, mut[1:1])
        @test Evolutionary.differentiation(rec, mut) == [0.5, 1.5]
    end

    @testset "GP" begin
        Random.seed!(rng, 2)
        H = 2
        tr = TreeGP(maxdepth=H, initialization=:grow);
        ex = rand(rng, tr, H)

        # subtree mutation does not produce offspring expression longer then the parent
        mut = subtree(tr)
        Random.seed!(rng, 1)
        off = [mut(copy(ex), rng=rng) for i in 1:10]
        @testset "Offspring Height" for i in 1:10
            @test all(o->Evolutionary.height(o) <= H, map(o->mut(o,rng=rng), off))
        end

        # subtree mutation does not produce offspring expression longer then the parent
        mut = subtree(tr; growth=0.5)
        Random.seed!(rng, 2)
        off = [mut(copy(ex), rng=rng) for i in 1:10]
        @testset "Offspring Height (Growth)" for i in 1:5
            @test all(o->Evolutionary.height(o) <= 3i, map(o->mut(o,rng=rng), off))
        end

        # hoist
        mut = subtree(tr; growth=0.5)
        Random.seed!(rng, 1)
        off = [mut(copy(ex), rng=rng) for i in 1:10]
        for i in 1:5; map(o->mut(o, rng=rng), off); end
        mut = hoist(tr)
        @testset "Hoist Mutation" for i in 1:10
            n = length(off[i])
            m = length(mut(off[i], rng=rng))
            @test n > m
        end

        # shrink
        mut = subtree(tr; growth=0.6)
        Random.seed!(rng, 1)
        off = [mut(copy(ex), rng=rng) for i in 1:10]
        for i in 1:5; map(o->mut(o, rng=rng), off); end
        mut = shrink(tr)
        @testset "Shrink Mutation" for i in 1:10
            n = length(off[i])
            m = length(mut(off[i], rng=rng))
            @test n >= m
        end

        # point
        mut = point(tr)
        Random.seed!(rng, 1)
        @testset "Point Mutation" for i in 1:10
            mex = mut(copy(ex), rng=rng)
            @test length(ex) == length(mex) == 7
            @test sum(x == y for (x,y) in zip(ex.args, mex.args)) >= 2
        end

    end
end


text:
"""
`module  JAC.HydrogenicIon`
    ... a submodel of JAC that contains methods for computing various one-electron energies, matrix elements, etc..
"""
module HydrogenicIon

    using Printf, ..Basics, ..Defaults, ..Math, ..Nuclear, ..Radial, ..RadialIntegrals,  GSL

    """
    `HydrogenicIon.energy(sh::Shell, Z::Float64)`
        ... to compute the (non-relativistic) energy for the given shell and for a point-like nuclear charge Z; the energy is
            printed in the current energy units to screen but is returned in Hartree. A energy::Float64 is returned.
    """
    function energy(sh::Shell, Z::Float64)
        energy = - Z^2 / sh.n^2 / 2.
        energx = Defaults.convertUnits("energy: from atomic to eV", energy)
        sa     = "  Energie for shell $sh is [in $(Defaults.getDefaults("unit: energy"))]: " * @sprintf("%.8e", energx)
        println(sa)
        return( energy )
    end

    """
    `HydrogenicIon.energy(sh::Subshell, Z::Float64)`
        ... to computes the Dirac energy for the hydrogenic subshell sh and for point-like nucleus with nuclear charge Z;
            a energy::Float64 in atomic units and without the rest energy of the electron is returned. That is the binding
            energy of a 1s_1/2 electron for Z=1 is -0.50000665.
    """
    function energy(sh::Subshell, Z::Float64)
        if  Z <= 0.1    error("Requires nuclear charge Z >= 0.1")    end
        # Compute the energy from the Dirac formula
        jPlusHalf = (Basics.subshell_2j(sh) + 1) / 2;   nr = sh.n - jPlusHalf;    alpha = Defaults.getDefaults("alpha")
        wa = sqrt(jPlusHalf^2 - Z^2 * alpha^2 )
        wa = sqrt(1.0 + Z^2 * alpha^2 / (nr + wa)^2)
        wa = Defaults.getDefaults("speed of light: c")^2 * (1/wa - 1.0)
        wb = Defaults.convertUnits("energy: from atomic to eV", wa)
        sa = "  Energie for subshell $sh is [in $(Defaults.getDefaults("unit: energy"))]: " * @sprintf("%.8e", wb)
        println(sa)
        return( wa )
    end

    """
    `HydrogenicIon.radialOrbital(sh::Shell, Z::Float64, r::Float64)`
        ... to compute the (non-relativistic) orbital function P(r) for the given shell and nuclear charge Z;
            a value::Float64 is returned.
    """
    function radialOrbital(sh::Shell, Z::Float64, r::Float64)
        n = sh.n;    l = sh.l
        value = r^(l+1) / factorial(2l+1) * sqrt( factorial(n+l) / (factorial(n-l-1) *2n)) *
                (2Z / n)^(l+1.5) * exp(-Z*r/n)

        ##x if  abs(value) < 1.e-15  &&  2Z*r/n > 99.   warn(AddWarning, "orbital: value = $value  2Z*r/n = $(2Z*r/n) ");    return(0.)   end
        if  abs(value) < 1.e-15  &&  2Z*r/n > 99.    return(0.)   end

        value = value * GSL.hypergeom(-(n-l-1.), 2l+2., 2Z*r/n)
        return( value )
    end

    """
    `HydrogenicIon.radialOrbital(sh::Shell, Z::Float64, grid::Radial.Grid)`
        ... to compute the same but for all r-values as specified by the given grid; a PList::Array{Float64,1} is returned.
    """
    function radialOrbital(sh::Shell, Z::Float64, grid::Radial.Grid)
        plist = zeros( grid.NoPoints )
        for i = 1:length(plist)    plist[i] = HydrogenicIon.radialOrbital(sh, Z, grid.r[i])    end
        return( plist )
    end

    """
    `HydrogenicIon.radialOrbital(sh::Shell, Z::Float64, rlist::Array{Float64,1})`
        ... to compute the same but for an array of r-values [r_1, r_2, ...]; a PList::Array{Float64,1} is returned.
    """
    function radialOrbital(sh::Shell, Z::Float64, rlist::Array{Float64,1})
        plist = similar(rlist)
        for i = 1:length(plist)    plist[i] = HydrogenicIon.radialOrbital(sh, Z, rlist[i])    end
        return( plist )
    end

    """
    `HydrogenicIon.radialOrbital(sh::Subshell, Z::Float64, grid::Radial.Grid)`
        ... to compute a relativstic hydrogenic Dirac orbital on the given grid by applying the kinetic-balance to a
            corresponding non-relavistic orbital; an orbital::Radial.Orbital is returned.
    """
    function radialOrbital(sh::Subshell, Z::Float64, grid::Radial.Grid)
        en  = HydrogenicIon.energy(sh, Z)
        P   = HydrogenicIon.radialOrbital( Shell(sh.n, Basics.subshell_l(sh)), Z, grid)

        Q   = zeros(size(P, 1));   Pprime   = zeros(size(P, 1));    Qprime   = zeros(size(P, 1))
        if  grid.mesh == MeshGrasp
            dP(i) = Math.derivative(P, i)
            for i = 2:size(Q, 1)
                Q[i] = -1/(2 * Defaults.INVERSE_FINE_STRUCTURE_CONSTANT) * (dP(i) / grid.h / grid.rp[i] + sh.kappa/grid.r[i]) * P[i]
                @warn("radialOrbital():: P' and Q' not yet defined.")
            end
        elseif  grid.mesh == MeshGL
            @warn("radialOrbital():: Q[:] = zero everywhere.")
        else
            error("stop a")
        end

        orb   = Radial.Orbital( sh, true, false, en, P, Q, Pprime, Qprime, grid)
        norma = RadialIntegrals.overlap(orb, orb, grid)
        orb.P = orb.P/sqrt(norma)
        orb.Q = orb.Q/sqrt(norma)
        normb = RadialIntegrals.overlap(orb, orb, grid)
        println("HydrogenicIon.radialOrbital():  for subshell $sh : norm-before = $norma, norm-after = $normb")

        return( orb )
    end

    """
    `HydrogenicIon.radialOrbital(sh::Subshell, nm::Nuclear.Model, grid::Radial.Grid)`
        ... to compute a relativstic hydrogenic Dirac orbital for the given nuclear model by using an explicit diagonalization
            of the Dirac Hamiltonian in a B-spline basis; an orbital::Radial.Orbital is returned.
    """
    function radialOrbital(sh::Subshell, nm::Nuclear.Model, grid::Radial.Grid)
        error("HydrogenicIon.radialOrbital() Not yet implemented.")
        return( orb )
    end

end # module


text:
@enum Scalar begin
    ŝ = Int32(1)
end

show(io::IO, ::MIME"text/plain", a::Scalar) = show(io, a)
show(::IO, ::Scalar) = return

@enum VectorBasis3D begin
    x̂ = Int32(2)
    ŷ
    ẑ
end

@enum PseudoVectorBasis3D begin
    x̂ŷ = Int32(5)
    ŷẑ
    x̂ẑ
end

@enum PseudoScalar3D begin
    x̂ŷẑ = Int32(8)
end

const ı̂ = x̂ŷẑ

const UVecs3D = Union{Scalar, VectorBasis3D, PseudoVectorBasis3D, PseudoScalar3D}

const _uvecs = vcat(instances(Scalar)...,
                    instances(VectorBasis3D)...,
                    instances(PseudoVectorBasis3D)...,
                    instances(PseudoScalar3D)...)

max_stars_repo_name: Samuele-Colombo/Multivectors

max_issues_repo_name: Samuele-Colombo/Multivectors

max_forks_repo_name: Samuele-Colombo/Multivectors


text:
using BetweenFlags
using Test
const src_dir = dirname(dirname(pathof(BetweenFlags)))
const out_dir = joinpath(src_dir, "output")
const fig_dir = joinpath(out_dir, "figs")
const dat_dir = joinpath(src_dir, "data")

export_results = false
if export_results
    include("plot_helper.jl")
end

@testset "BetweenFlags" begin
  @testset "Unit tests" begin
    @testset "Flags" begin
      include(joinpath("unit","flags.jl"))
      include(joinpath("unit","flag_pair.jl"))
    end
    @testset "Tokenize - with boundaries" begin
      include(joinpath("unit","tokenize.jl"))
    end
    @testset "Tokenize - no outer boundaries" begin
      include(joinpath("unit","tokenize_no_outer_boundaries.jl"))
    end
  end
  @testset "Data-driven tests" begin
    include(joinpath("data_driven","tokenize.jl"))
  end
  @testset "Performance tests" begin
    include(joinpath("perf","perf.jl"))
  end
end


text:
#!/usr/bin/env julia

include("../src/MsgPackRpcClient.jl")
include("const.jl")
include("dataset.jl")
using MsgPackRpcClient
using Base.Test

function get_max_arg(data; prefix = "arg")
  i = 1
  while i < 65536
    if haskey(data, "$(prefix)$(i)")
      i += 1
    else
      break
    end
  end
  i - 1
end

function test_data(data, number = 1)
  for d in data
    println("$(number): $d ")
    #try
      max_arg = get_max_arg(d)

      if haskey(d, "arg4")
        result = MsgPackRpcClient.call(session, d["method"], d["arg1"], d["arg2"], d["arg3"], d["arg4"]; sync = true)
      elseif haskey(d, "arg3")
        result = MsgPackRpcClient.call(session, d["method"], d["arg1"], d["arg2"], d["arg3"]; sync = true)
      elseif haskey(d, "arg2")
        result = MsgPackRpcClient.call(session, d["method"], d["arg1"], d["arg2"]; sync = true)
      elseif haskey(d, "arg1")
        result = MsgPackRpcClient.call(session, d["method"], d["arg1"]; sync = true)
      else
        error
      end

      #println("result = ", result)
      #println("first(result) = ", first(result))
      if haskey(d, "expect")
        for i = 1:max_arg
          @test result[i] == d["expect"][i]
        end
      end
      println("  => OK")
    #catch
    #  #println("Error on d[\"arg\"] = ", d["arg"])
    #  println("Error")
    #end
    number += 1
  end
end

session = MsgPackRpcClientSession.create()

test_data(get_dataset_for_arguments())

session.destroy()

max_stars_repo_name: keithseahus/msgpack-rpc-julia

max_issues_repo_name: keithseahus/msgpack-rpc-julia

max_forks_repo_name: keithseahus/msgpack-rpc-julia


text:
#  Message digest constants from mbedtls_md_type_t enum in md.h

@enum(MDKind,
      MD_NONE=0,
      MD_MD2,
      MD_MD4,
      MD_MD5,
      MD_SHA1,
      MD_SHA224,
      MD_SHA256,
      MD_SHA384,
      MD_SHA)

mutable struct MDInfo
  data::Ptr{Cvoid}
end

mutable struct MD{IsHMAC} <: IO
    data::Ptr{Cvoid}
    info::MDInfo

    function MD{IsHMAC}() where IsHMAC
        ctx = new{IsHMAC}()
        ctx.data = Libc.malloc(50)  # 24
        ccall((:mbedtls_md_init, libmbedcrypto), Cvoid, (Ptr{Cvoid},), ctx.data)
        finalizer(ctx->begin
            ccall((:mbedtls_md_free, libmbedcrypto), Cvoid, (Ptr{Cvoid},), ctx.data)
            Libc.free(ctx.data)
        end, ctx)
        ctx
    end
end

function MDInfo(kind::MDKind)
    ret = ccall((:mbedtls_md_info_from_type, libmbedcrypto), Ptr{Cvoid},
        (Cint,), Int(kind))
    if ret == C_NULL
        error("Could not find MD type for kind $kind")
    end
    MDInfo(ret)
end

function MDInfo(kind::AbstractString)
    ret = ccall((:mbedtls_md_info_from_string, libmbedcrypto), Ptr{Cvoid},
        (Cstring,), String(kind))
    MDInfo(ret)
end

function get_name(info::MDInfo)
    ret = ccall((:mbedtls_md_get_name, libmbedcrypto), Ptr{UInt8},
        (Ptr{Cvoid},), info.data)
    unsafe_string(ret)
end

get_name(md::MD) = get_name(md.info)

function Base.show(io::IO, info::MDInfo)
    print(io, "Message digest $(get_name(info))")
end

function Base.show(io::IO, md::MD{true})
    print(io, "HMAC with hash $(get_name(md))")
end

function Base.show(io::IO, md::MD{false})
    print(io, "Digest with hash $(get_name(md))")
end

function MD(kind::MDKind)
    ctx = MD{false}()
    ctx.info = MDInfo(kind)
    @err_check ccall((:mbedtls_md_setup, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Cint),
        ctx.data, ctx.info.data, 0)
    @err_check ccall((:mbedtls_md_starts, libmbedcrypto), Cint,
        (Ptr{Cvoid},), ctx.data)
    ctx
end

function MD(kind::MDKind, key)
    ctx = MD{true}()
    ctx.info = MDInfo(kind)
    @err_check ccall((:mbedtls_md_setup, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Cint),
        ctx.data, ctx.info.data, 1)
    @err_check ccall((:mbedtls_md_hmac_starts, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
        ctx.data, pointer(key), sizeof(key))
    ctx
end

function Base.copy(md::MD)
    new_md = MD()
    @err_check ccall((:mbedtls_md_clone, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}),
        new_md.data, md.data)
    new_md.info = md.info
    new_md
end

"""
`get_size(kind::MDKind) -> Int`

Returns the size of the digest in bytes that the given digest type requires.

For example,

```julia
get_size(MD_SHA256) == 32
```
"""
function get_size(info::MDInfo)
    ret = ccall((:mbedtls_md_get_size, libmbedcrypto), Cuchar,
        (Ptr{Cvoid},), info.data)
    Int(ret)
end

get_size(md::MD) = get_size(md.info)
get_size(kind::MDKind) = get_size(MDInfo(kind))

function _write(ctx::MD{false}, buf, size)
    @err_check ccall((:mbedtls_md_update, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
        ctx.data, buf, size)
end

function _write(ctx::MD{true}, buf, size)
    @err_check ccall((:mbedtls_md_hmac_update, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t),
        ctx.data, buf, size)
end

function Base.write(ctx::MD, buf::Vector)
    isbitstype(eltype(buf)) || error("Expected a vector of bits types got $(typeof(buf))")
    _write(ctx, buf, sizeof(buf))
end
# To avoid ambiguity warnings
Base.write(ctx::MD, buf::Vector{UInt8}) = _write(ctx, buf, sizeof(buf))

function Base.write(ctx::MD, i::Union{Float16,Float32,Float64,Int128,Int16,Int32,Int64,UInt128,UInt16,UInt32,UInt64})
    _write(ctx, Ref(i), sizeof(i))
end
Base.write(ctx::MD, i::UInt8) = _write(ctx, Ref(i), sizeof(i))
Base.write(ctx::MD, i::Int8) = _write(ctx, Ref(i), sizeof(i))

function finish!(ctx::MD{false}, buf)
    @err_check ccall((:mbedtls_md_finish, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}),
        ctx.data, pointer(buf))
end

function finish!(ctx::MD{true}, buf)
    @err_check ccall((:mbedtls_md_hmac_finish, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}),
        ctx.data, pointer(buf))
end

function finish!(ctx::MD)
    buf = Vector{UInt8}(undef, get_size(ctx))
    finish!(ctx, buf)
    buf
end

function reset!(ctx::MD{true})
    @err_check ccall((:mbedtls_md_hmac_reset, libmbedcrypto), Cint,
        (Ptr{Cvoid},),
        ctx.data)
end

function digest!(kind::MDKind, msg, buf)
    @err_check ccall((:mbedtls_md, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}),
        MDInfo(kind).data, pointer(msg), sizeof(msg), pointer(buf))
end

"""
`digest(kind::MDKind, msg::Vector{UInt8}, [key::Vector{UInt8}]) -> Vector{UInt8}`

Perform a digest of the given type on the given message (a byte array),
return a byte array with the digest.

If an optional key is given, perform an HMAC digest.
"""
function digest end

"""
`digest!(kind::MDKind, msg::Vector{UInt8}, [key::Vector{UInt8}, ], buffer::Vector{UInt8})`

In-place version of `digest` that stores the digest to `buffer`.

It is the user's responsibility to ensure that buffer is long enough to contain the digest.
`get_size(kind::MDKind)` returns the appropriate size.
"""
function digest! end

function digest(kind::MDKind, msg)
    buf = Vector{UInt8}(undef, get_size(kind))
    digest!(kind, msg, buf)
    buf
end

function digest!(kind::MDKind, msg, key, buf)
    @err_check ccall((:mbedtls_md_hmac, libmbedcrypto), Cint,
        (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}),
        MDInfo(kind).data, pointer(key), sizeof(key),
        pointer(msg), sizeof(msg), pointer(buf))
end

function digest(kind::MDKind, msg, key)
    buf = Vector{UInt8}(undef, get_size(kind))
    digest!(kind, msg, key, buf)
    buf
end


text:
module MetaDatums

export
    value,
    values,
    kind,
    kinds,
    identifier,
    identifiers

import Base.values

include("types.jl")

end # module


text:
using OpSel
using Test

@testset "OpSel.jl" begin
    # Write your own tests here.
    OpSel.testUnequal(2045);
    OpSel.testEqual(200,50);
end


text:
@testset "helper.jl tests" begin

@testset "multiplicity tests" begin
    @test SparseSymmetricTensors.multiplicity_factor([1,1,1,1,1]) == 1
    @test SparseSymmetricTensors.multiplicity_factor([1,2,1,1,1]) == 5
    @test SparseSymmetricTensors.multiplicity_factor([2,2,1,1,1]) == 10
end

@testset "remap_indices tests" begin
    x = [([2,3,4],1.0)]
    SparseSymmetricTensors.remap_indices!(x)
    @test x == [([1,2,3],1.0)]

    x = [([2,3,4],1.0),([3,4,5],-2.3)]
    SparseSymmetricTensors.remap_indices!(x)
    @test x == [([1,2,3],1.0),([2,3,4],-2.3)]
end

end


text:
export  nodePopPlot,
        nodeEvolutionPlot

function nodePopPlot( mpSim::MPsim, timeGrid::Vector{T},
    nodes::AbstractString...; showPlot::Bool=true, savePlot::Bool=false,
    filename::AbstractString="", timeFactor::Real=12.0 ) where T <: Real

    savePlot |= filename != ""

    # Don't do anything if the plot mustn't be shown or saved.
    if !( showPlot || savePlot )
        return
    end  # if !( showPlot || savePlot )

    # Generate the report.
    popReport = nodePopReport( mpSim, timeGrid, nodes... )

    if isempty( popReport )
        return
    end  # if isempty( popReport )

    generatePopPlot( popReport, timeFactor, showPlot, savePlot, filename )

end  # nodePopPlot( mpSim, timeGrid, nodes, breakdownType, showPlot, savePlot,
     #   filename, timeFactor )

nodePopPlot( mpSim::MPsim, timeRes::Real,
    nodes::AbstractString...; breakdownType::Symbol=:none, showPlot::Bool=true,
    savePlot::Bool=false, filename::AbstractString="", timeFactor::Real=12.0 ) =
    nodePopPlot( mpSim, MP.generateTimeGrid( mpSim, timeRes ), nodes...,
    showPlot=showPlot, savePlot=savePlot, filename=filename,
    timeFactor=timeFactor )

function nodeEvolutionPlot( mpSim::MPsim, timeGrid::Vector{T},
    nodes::AbstractString...; plotType::Symbol=:normal, showPlot::Bool=true,
    savePlot::Bool=false, filename::AbstractString="",
    timeFactor::Real=12.0 ) where T <: Real

    savePlot |= filename != ""
    plotType = haskey( plotTypes, plotType ) ? plotType : :normal
    plotFunction = plotTypes[plotType][1]
    plotFunction2 = plotTypes[plotType][2]

    # Don't do anything if the plot mustn't be shown or saved.
    if !( showPlot || savePlot )
        return
    end  # if !( showPlot || savePlot )

    # Generate the report.
    popReport, fluxReports = nodeEvolutionReport( mpSim, timeGrid, nodes... )

    if isempty( popReport ) || isempty( fluxReports )
        return
    end  # if isempty( popReport ) || ...

    generateEvolutionPlot( popReport, mpSim, fluxReports, nodes, timeFactor,
        showPlot, savePlot, filename, plotFunction, plotFunction2 )

end  # nodeEvolutionPlot( mpSim, timeGrid, nodes, plotType, showPlot, savePlot,
     #   filename, timeFactor )

nodeEvolutionPlot( mpSim::MPsim, timeRes::Real,
    nodes::AbstractString...; plotType::Symbol=:normal, showPlot::Bool=true,
    savePlot::Bool=false, filename::AbstractString="", timeFactor::Real=12.0 ) =
    nodeEvolutionPlot( mpSim, MP.generateTimeGrid( mpSim, timeRes ), nodes...,
    plotType=plotType, showPlot=showPlot, savePlot=savePlot, filename=filename,
    timeFactor=timeFactor )

include( "private/nodepop.jl" )


text:
#types used by kRPC and type conversion utilities

#part of runtime support
#indicate class and enum membership
module kRPCTypes
abstract type Class end
abstract type Enum end
end

#type helper functions

function getWireValue(arg::Union{Int32,Int64,Float32,Float64,UInt32,UInt64})
    opb = PipeBuffer()
    ProtoBuf.write_fixed(opb, arg)
    return readavailable(opb)
end

function getWireValue(arg::Bool)
    opb = PipeBuffer()
    ProtoBuf.write_bool(opb, arg)
    return readavailable(opb)
end

function getWireValue(arg::String)
    opb = PipeBuffer()
    ProtoBuf.write_string(opb, arg)
    return readavailable(opb)
end

function getWireValue(arg::Array{UInt8,1})
    opb = PipeBuffer()
    ProtoBuf.write_bytes(opb, arg)
    return readavailable(opb)
end

function getWireValue(arg::Array{T, 1}) where T
    opb = PipeBuffer()
    ProtoBuf.writeproto(opb, krpc.schema.List(items=map(getWireValue, arg)))
    return readavailable(opb)
end

function getWireValue(arg::Dict{K,V}) where {K, V}
    opb = PipeBuffer()
    op = Array{Array{UInt8,1},1}()
    for kv in arg
        k,v = kv
        push!(op, krpc.schema.DictionaryEntry(key=getWireValue(k), value=getWireValue(v)))
    end
    ProtoBuf.writeproto(opb, krpc.schema.Dictionary(entries=op))
    return readavailable(opb)
end

function getWireValue(arg::Set{T}) where T
    opb = PipeBuffer()
    ProtoBuf.writeproto(opb, krpc.schema.Set(items=map(getWireValue, arg)))
    return readavailable(opb)
end

function getWireValue(arg::Tuple)
    opb = PipeBuffer()
    ProtoBuf.writeproto(opb, krpc.schema.Tuple_(items=convert(Array{Array{UInt8,1},1}, collect(map(getWireValue, arg)))))
    return readavailable(opb)
end

function getWireValue(arg::kRPCTypes.Class)
    res = getWireValue(arg.handle)
    return res
end

function getWireValue(arg::kRPCTypes.Enum)
    return getWireValue(Remote.getEnumVal(arg))
end

function getWireValue(arg::krpc.schema.ProcedureCall)
    opb = PipeBuffer()
    ProtoBuf.writeproto(opb, arg)
    return readavailable(opb)
end

function getWireValue(arg::kStream)
    opb = PipeBuffer()
    ProtoBuf.writeproto(opb, krpc.schema.Stream(id=arg.id))
    return readavailable(opb)
end

function getJuliaValue(value::krpc.schema.Response, rtype::Type)
    return getJuliaValue(value.return_value, rtype)
end
function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{T}) where {T<:kRPCTypes.Class}
    return rtype(ProtoBuf.read_varint(PipeBuffer(value), Int64))
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Nothing)
    return Nothing()
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{AbstractString})
    return ProtoBuf.read_string(PipeBuffer(value))
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{kStream})
    backing = readproto(PipeBuffer(value), krpc.schema.Stream())
    return kStream(backing.id)
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Union{Type{UInt32},Type{Int32},Type{UInt64},Type{Int64},Type{Float32},Type{Float64}})
    return ProtoBuf.read_fixed(PipeBuffer(value), rtype)
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{Bool})
    return ProtoBuf.read_bool(PipeBuffer(value))
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{Array{UInt8,1}})
    return ProtoBuf.read_bytes(PipeBuffer(value))
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{Array{T,1}}) where T
    res = readproto(PipeBuffer(value), krpc.schema.List())
    return T[getJuliaValue(item,T) for item in res.items]
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{T}) where T <: (Tuple{Vararg{T,N} where T where N})
    res = readproto(PipeBuffer(value), krpc.schema.Tuple_())
    return ([getJuliaValue(param[1],param[2]) for param in zip(res.items, rtype.parameters)]...,)
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{Dict{K,V}}) where {K,V}
    res = readproto(PipeBuffer(value), krpc.schema.Dictionary())
    return Dict{K,V}(getJuliaValue(v.key,K) => getJuliaValue(v.value,V) for v in res.entries)
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{Set{T}}) where {T}
    res = readproto(PipeBuffer(value), krpc.schema.Set())
    return Set{T}(getJuliaValue(item,T) for item in res.items)
end

function getJuliaValue(value::Array{UInt8, 1}, rtype::Type{Nullable{T}}) where {T<:kRPCTypes.Class}
    res = ProtoBuf.read_varint(PipeBuffer(value), Int64)
    if res == 0
        return Nullable{T}()
    else
        return Nullable(T(res))
    end
end


text:
using PyCall

#=
you can't omit double quote surrounds `path`
i.e.
good:
pyimport("sys")."path"
bad:
pyimport("sys").path
=#

# import python files located in the current directory
pushfirst!(
    PyVector(pyimport("sys")."path"),
    @__DIR__
)

# import sample module
sample=pyimport("sample")
# we can call module under `mymod`
goma = pyimport("mymod.goma")

sample.main()
goma.say9()

max_stars_repo_name: terasakisatoshi/juliaExer

max_issues_repo_name: terasakisatoshi/juliaExer

max_forks_repo_name: terasakisatoshi/juliaExer


text:
print_timer(; kwargs...) = print_timer(stdout; kwargs...)
print_timer(to::TimerOutput; kwargs...) = print_timer(stdout, to; kwargs...)
print_timer(io::IO; kwargs...) = print_timer(io, DEFAULT_TIMER; kwargs...)
print_timer(io::IO, to::TimerOutput; kwargs...) = (show(io, to; kwargs...); println(io))

Base.show(to::TimerOutput; kwargs...) = show(stdout, to; kwargs...)
function Base.show(io::IO, to::TimerOutput; allocations::Bool = true, sortby::Symbol = :time, linechars::Symbol = :unicode, compact::Bool = false, title::String = "")
    sortby  in (:time, :ncalls, :allocations, :name, :firstexec) || throw(ArgumentError("sortby should be :time, :allocations, :ncalls, :name, or :firstexec, got $sortby"))
    linechars in (:unicode, :ascii)                  || throw(ArgumentError("linechars should be :unicode or :ascii, got $linechars"))

    t₀, b₀ = to.start_data.time, to.start_data.allocs
    t₁, b₁ = time_ns(), gc_bytes()
    Δt, Δb = t₁ - t₀, b₁ - b₀
    ∑t, ∑b = to.flattened ? to.totmeasured : totmeasured(to)

    max_name = longest_name(to)
    available_width = displaysize(io)[2]
    requested_width = max_name
    if compact
        if allocations
            requested_width += 43
        else
            requested_width += 25
        end
    else
        if allocations
            requested_width += 59
        else
            requested_width += 33
        end
    end

    #requested_width = 34 + (allocations ? 27 : 0) + max_name
    name_length = max(9, max_name - max(0, requested_width - available_width))

    print_header(io, Δt, Δb, ∑t, ∑b, name_length, true, allocations, linechars, compact, title)
    for timer in sort!(collect(values(to.inner_timers)); rev = !in(sortby, [:name, :firstexec]), by = x -> sortf(x, sortby))
        _print_timer(io, timer, ∑t, ∑b, 0, name_length, allocations, sortby, compact)
    end
    print_header(io, Δt, Δb, ∑t, ∑b, name_length, false, allocations, linechars, compact, title)
end

function sortf(x, sortby)
    sortby == :time        && return x.accumulated_data.time
    sortby == :ncalls      && return x.accumulated_data.ncalls
    sortby == :allocations && return x.accumulated_data.allocs
    sortby == :name        && return x.name
    sortby == :firstexec   && return x.accumulated_data.firstexec
    error("internal error")
end

# truncate string and add dots
function truncdots(str, n)
    textwidth(str) <= n && return str
    n <= 3 && return ""
    io = IOBuffer()
    for (i, c) in enumerate(str)
        i == n - 2 && (write(io, "..."); break)
        write(io, c)
    end
    return String(take!(io))
end

function print_header(io, Δt, Δb, ∑t, ∑b, name_length, header, allocations, linechars, compact, title)
    global BOX_MODE, ALLOCATIONS_ENABLED

    midrule       = linechars == :unicode ? "─" : "-"
    topbottomrule = linechars == :unicode ? "─" : "-"
    sec_ncalls = string(rpad("Section", name_length, " "), " ncalls  ")
    time_headers = "   time   %tot" * (compact ? "" : "     avg")
    alloc_headers = allocations ? ("  alloc   %tot" * (compact ? "" : "      avg")) : ""
    total_table_width = sum(textwidth.((sec_ncalls, time_headers, alloc_headers))) + 3

    # Just hardcoded shit to make things look nice
    !allocations && (total_table_width -= 3)

    function center(str, len)
        x = (len - textwidth(str)) ÷ 2
        return string(" "^x, str, " "^(len - textwidth(str) - x))
    end

    if header
        time_alloc_pading = " "^(textwidth(sec_ncalls))

        title = center(truncdots(title, textwidth(sec_ncalls)), textwidth(sec_ncalls))

        if compact
            time_header       = "     Time     "
        else
            time_header       = "        Time          "
        end

        time_underline = midrule^textwidth(time_header)

        if compact
            allocation_header       = " Allocations  "
        else
            allocation_header = "      Allocations      "
        end

        alloc_underline = midrule^textwidth(allocation_header)
        #tot_meas_str = string(" ", rpad("Tot / % measured:", textwidth(sec_ncalls) - 1, " "))
        if compact
            tot_meas_str = center("Total measured:", textwidth(sec_ncalls))
        else
            tot_meas_str = center("Tot / % measured:", textwidth(sec_ncalls))
        end

        str_time =  center(string(prettytime(Δt),   compact ? "" : string(" / ", prettypercent(∑t, Δt))), textwidth(time_header))
        str_alloc = center(string(prettymemory(Δb), compact ? "" : string(" / ", prettypercent(∑b, Δb))), textwidth(allocation_header))

        header_str = string("  time  %tot  %timed")
        tot_midstr = string(sec_ncalls, "  ", header_str)
        printstyled(io, " ", topbottomrule^total_table_width, "\n"; bold=true)
        if ! (allocations == false && compact == true)
            printstyled(io, " ", title; bold=true)
            print(io, time_header)
            allocations && print(io, "   ", allocation_header)
            print(io, "\n")
            print(io, " ", time_alloc_pading, time_underline)
            allocations && print(io, "   ", alloc_underline)
            print(io, "\n")
            print(io, " ", tot_meas_str, str_time)
            allocations && print(io, "   ", str_alloc)
            print(io, "\n\n")
        end
        print(io, " ", sec_ncalls, time_headers)
        allocations && print(io, "   ", alloc_headers)
        print(io, "\n")
        print(io, " ", midrule^total_table_width, "\n")
    else
        printstyled(io, " ", topbottomrule^total_table_width; bold=true)
    end
end

function _print_timer(io::IO, to::TimerOutput, ∑t::Integer, ∑b::Integer, indent::Integer, name_length, allocations, sortby, compact)
    accum_data = to.accumulated_data
    t = accum_data.time
    b = accum_data.allocs

    name = truncdots(to.name, name_length - indent)
    print(io, " ")
    nc = accum_data.ncalls
    print(io, " "^indent, rpad(name, name_length + 2 - indent))
    print(io, lpad(prettycount(nc), 5, " "))

    print(io, "   ", lpad(prettytime(t),        6, " "))
    print(io, "  ",  lpad(prettypercent(t, ∑t), 5, " "))
    !compact && print(io, "  ",  rpad(prettytime(t / nc), 6, " "))

    if allocations
    print(io, "   ", rpad(prettymemory(b),      9, " "))
    print(io, rpad(prettypercent(b, ∑b), 5, " "))
    !compact && print(io, "  ",    lpad(prettymemory(b / nc), 5, " "))
    end
    print(io, "\n")

    for timer in sort!(collect(values(to.inner_timers)), rev = sortby != :name, by = x -> sortf(x, sortby))
        _print_timer(io, timer, ∑t, ∑b, indent + 2, name_length, allocations, sortby, compact)
    end
end


text:
module TestQuery

module MyQuerySchema
using Ecto.Schema
schema("my") do
    field(:name, :string)
    field(:age, :integer)
end
end

end # module TestQuery

using Ecto
using Base.Test
mirror = in(TestQuery.MyQuerySchema)
@test isa(mirror.name, Ecto.MirrorTypes.MirrorField)
@test isa(mirror.age, Ecto.MirrorTypes.MirrorField)


text:
# A MinHasher maintains the N smallest hashes by continually removing the top hash
# using a heap. To make sure we don't have the same hashes multiple times, we use a
# HashSet to check for duplicates. A Hash set is like an optimized version of Set.

# F is type parameter because we want the user to choose a hash function with no
# runtime performance. The maximal number of hashes kept is the length of the heap vector.
"""
    MinHasher{F}

A type used to minhash any iterable object with function `F`.

See also: [`update!`](@ref), [`minhash`](@ref)
"""
mutable struct MinHasher{F}
    filled::Int
    heap::Vector{UInt64}
    set::HashSet

    function MinHasher{F}(size::Integer) where F
        heap = Vector{UInt64}(undef, size)
        set = HashSet(4*size)
        new(0, heap, set)
    end
end

MinHasher(size::Integer) = MinHasher{hash}(size)
call(::MinHasher{F}, x) where F = F(x)

function Base.show(io::IO, ::MIME"text/plain", s::MinHasher)
    print(io, typeof(s), ":\n")
    print(io, " hashes:  ", s.filled, " / ", _length(s), '\n')
    heaptop = isinitialized(s) ? repr(first(s.heap)) : "< uninitialized >"
    print(io, " maxhash: ", heaptop, '\n')
    print(io, " hashset: ", s.set)
end

_length(s::MinHasher) = length(s.heap)
Base.show(io::IO, s::MinHasher) = print(io, typeof(s), "()")
isinitialized(s::MinHasher) = _length(s) == s.filled

function Base.empty!(x::MinHasher)
    x.filled = 0
    empty!(x.set)
    return x
end

# The first N hashes will always be the N smallest hashes. So we don't need to use the heap
# to remove largest hash. We only use the HashSet (and we don't even need to repopulate
# that). We build the heap after seeing all N distinct hashes.
function initialize!(s::MinHasher, it)
    len, filled = _length(s), s.filled
    vec, set = s.heap, s.set
    itval = iterate(it)
    @inbounds while (len > filled) && (itval !== nothing)
        i, state = itval
        h = call(s, i)
        if !(h in set)
            filled += 1
            vec[filled] = h
            unsafe_push!(set, h)
        end
        itval = iterate(it, state)
    end
    if !isinitialized(s) && (filled == len)
        heapify!(vec, Base.Order.Reverse)
    end
    s.filled = filled
    return itval
end

# After the first N hashes, we need to use the heap to discard the largest hash when we
# see a smaller one.
function continue!(s::MinHasher, it, itval)
    heap, set = s.heap, s.set
    largest = first(heap)
    while itval !== nothing
        i, state = itval
        h = call(s, i)
        if h < largest && !(h in set)
            push!(set, h, heap)
            setfirst!(heap, h, Base.Order.Reverse)
            largest = first(heap)
        end
        itval = iterate(it, state)
    end
end

"Replace root node in heap, preserving heap property"
function setfirst!(h::Vector, v, order::Base.Order.Ordering)
    val = convert(eltype(h), v)
    @inbounds h[1] = val
    DataStructures.percolate_down!(h, 1, val, order, length(h))
    return h
end

"""
    update!(s::MinHasher, it)

Add hashes of all elements of iterable `it` to MinHasher `s`.

See also: [`minhash`](@ref)
"""
function update!(s::MinHasher, it)
    itval = initialize!(s, it)
    continue!(s, it, itval)
    return s
end

"""
    MinHashSketch

Holds the N smallest hashes of an iterable. Construct from a `MinHasher`.

# Examples

```jldoctest
julia> x = MinHashSketch(update!(MinHasher(10), 1:1000))
MinHashSketch:
 hashes:  10 / 10
 maxhash: 0x0214ce7a1c004d40

julia> length(x)
10
```
"""
struct MinHashSketch
    func::Any # hash function
    requested::Int # maximal number of hashes to keep
    hashes::Vector{UInt64}
end

function MinHashSketch(s::MinHasher{F}) where F
    return MinHashSketch(F, _length(s), sort!(s.heap[1:s.filled]))
end

Base.length(s::MinHashSketch) = length(s.hashes)
Base.isempty(s::MinHashSketch) = iszero(length(s))

function Base.show(io::IO, ::MIME"text/plain", s::MinHashSketch)
    print(io, typeof(s), ":\n")
    print(io, " hashes:  ", length(s.hashes), " / ", s.requested, '\n')
    print(io, " maxhash: ", isempty(s) ? "" : repr(s.hashes[end]))
end

Base.show(io::IO, s::MinHashSketch) = print(io, typeof(s), "()")

"""
minhash([F=hash], it, s::Integer)

Hash every element of iterable `it` using function `F`, and return a `MinHashSketch`
containing at most the `s` smallest hashes.

# Examples:

```jldoctest
julia> minhash("ACGDEFG", 3)
MinHashSketch:
 hashes:  3 / 3
 maxhash: 0x3e1b023d3c92ff8f
```

See also: [`update!`](@ref)
"""
function minhash(F, it, s::Integer)
    sk = MinHasher{F}(s)
    update!(sk, it)
    MinHashSketch(sk)
end

minhash(it, s::Integer) = minhash(hash, it, s)


text:
using Morsel
using Meddle
using JSON
using WebSockets
using REPL
using Docker

f = open("settings.yml")
settings = YAML.load(f)
close(f)
docker_host = settings["docker_host"]
worker_port = settings["worker_port"]

app = Morsel.app()

type BackendSession
    id::Uint64
    name::String
    worker_id::String
    worker_port::Uint16
    isready::Bool
    frontends::Array
end

const backend_sessions = Dict{String,BackendSession}()

immutable FrontendSession
    id::Uint64
    userid::Uint64 # Web facing user id
    username::String
    backend::BackendSession
end

const frontend_sessions = Dict{Uint64,FrontendSession}()

with(app,FileServer(joinpath(pwd(),"www"))) do app
    # Fallback
    get(app, "/<*>") do req, res
        "Hi, looks like you were trying to find file \"$(req.state[:resource])\". We don't have that file, sorry!"
    end
end

get(app, "/") do req, res
    return readall(joinpath(pwd(),"www/index.htm"))
end

get(app, "/repl") do req, res

end

function destroy_backend(b::BackendSession)
    Docker.kill_container(docker_host,b.worker_id)
    Docker.remove_container(docker_host,b.worker_id)
    if haskey(backend_sessions,b.id)
        delete!(backend_sessions,b.id)
    end
end

function destroy_frontend(s::FrontendSession)
    idx = findfirst(s.backend.frontends)
    if idx != 0
        splice!(s.backend.frontends,idx)
        if isempty(s.backend.frontends)
            destroy_backend(s.backend)
        end
    end
    delete!(frontend_sessions,s.id)
end

post(app,"/session/new") do req,res
    data = JSON.parse(req.req.data)
    parameters = {"username" => "julia", "sessionname" => ""}
    println(data)
    for field in data
        if field["name"] == "user_name" && !isempty(field["value"])
            parameters["username"] = field["value"]
        elseif field["name"] == "session_name"
            parameters["sessionname"] = field["value"]
        end
    end
    if haskey(req.state[:cookies],"SessionId")
        id = parseint(Uint64,req.state[:cookies]["SessionId"],16)
        if haskey(frontend_sessions,id)
            destroy_frontend(frontend_sessions[id])
        end
    end
    username = parameters["username"]
    session_name = parameters["sessionname"]
    if !isempty(session_name) && haskey(backend_sessions,session_name)
        backend = backend_sessions[session_name]
    else
        worker_id = Docker.create_container(docker_host,"51d4c6302994",
                `julia -e 'cd(Pkg2.Dir.path("WebREPL","src")); include("worker.jl")'`;
                 attachStdin =  true,
                 openStdin   =  true,
                 ports       =  [worker_port])["Id"]
        Docker.start_container(docker_host,worker_id;binds = ["/home/ubuntu/.julia-container"=>"/.julia"])
        port = uint16(Docker.getNattedPort(docker_host,worker_id,worker_port))
        backend = BackendSession(rand(Uint64),session_name,worker_id,port,false,Array(FrontendSession,0))
        !isempty(session_name) && (backend_sessions[session_name] = backend)
    end
    frontend = FrontendSession(rand(Uint64),rand(Uint64),username,backend)
    push!(backend.frontends,frontend)
    frontend_sessions[frontend.id] = frontend
	set_status(res,201)
	if !haskey(res.state,:cookies)
        res.state[:cookies] = Dict{String,String}()
    end
	res.state[:cookies]["SessionId"] = string(hex(frontend.id),"; path=/")
	hex(frontend.id)
end

include("msg_types.jl")

import Base: repl_show

repl_show(io::WebSocket,result) = write(io,JSON.to_json([MSG_OUTPUT_EVAL_RESULT,"0",sprint(repl_show,result)]))

websocket(app,"/repl/socket") do req,res
	socket = res.res
	session = nothing
	while true
        msg = read(socket)
        julia_msg = JSON.parse(bytestring(msg))
        msg_type = julia_msg[1]
        if msg_type == MSG_INPUT_AUTHENTICATE
        	session = frontend_sessions[parseint(Uint64,julia_msg[2],16)]
            c = Condition()
            @async begin
                stream = Docker.open_logs_stream(docker_host,session.backend.worker_id)
                while isopen(socket) && isopen(stream)
                    if !session.backend.isready && search(readline(stream),"Morsel is listening on $(dec(worker_port))...") != 0:-1
                        notify(c)
                        session.backend.isready = true
                    elseif session.backend.isready
                        data = readavailable(stream)
                        write(socket,JSON.to_json([MSG_OUTPUT_OTHER,data]))
                    end
                end
                close(stream)
            end
            !session.backend.isready && wait(c)
        	#write(socket, JSON.to_json([MSG_OUTPUT_WELCOME]))
        	reply = [MSG_OUTPUT_READY,"ws://128.52.160.116:$(dec(session.backend.worker_port))/"]
        	write(socket, JSON.to_json(reply))
        elseif msg_type == MSG_INPUT_GET_USER
        	reply = [MSG_OUTPUT_GET_USER,session.username,dec(session.userid)]
        	write(socket, JSON.to_json(reply))
        end
    end
end

start(app, parseint(settings["server_port"]))


text:
using CUDAnative
using CuArrays
using StaticArrays
using BenchmarkTools

N = Int(1e6)
pred = rand(SVector{1, Float32}, N)
target = rand(Float32, N)
δ = zeros(SVector{1, Float32}, N)
δ² = zeros(SVector{1, Float32}, N)

pred_g = CuArray(rand(Float32, N))
target_g = CuArray(rand(Float32, N))
δ_g = CuArray(zeros(Float32, N))
δ²_g = CuArray(zeros(Float32, N))

pred = Array(pred_g)
target = Array(target_g)
δ = Array(δ_g)
δ² = Array(δ²_g)

# linear
function update_grads!(pred::Vector{SVector{L,T}}, target::AbstractVector{T}, δ::Vector{SVector{L,T}}, δ²::Vector{SVector{L,T}}) where {T <: AbstractFloat, L}
    @inbounds for i in eachindex(δ)
        δ[i] = SVector(2 * (pred[i][1] - target[i]))
        δ²[i] = SVector(2)
    end
end

# linear
function update_grads_gpu!(pred::AbstractVector{T}, target::AbstractVector{T}, δ::AbstractVector{T}, δ²::AbstractVector{T}, 𝑤::AbstractVector{T}) where {T <: AbstractFloat}
    @. δ = 2f0 * (pred - target) * 𝑤
    @. δ² = 2f0 * 𝑤
    return
end

@time update_grads!(pred, target, δ, δ²)
CuArrays.@time update_grads_gpu!(pred_g, target_g, δ_g, δ²_g)


text:
export ShapeProperties, material, transform
export Shape, normal, getcolor
export Sphere

mutable struct ShapeProperties
    material::Material
    transf::TransfMatrix

    ShapeProperties(mat) = new(mat, TransfMatrix())
    ShapeProperties(mat, transf) = new(mat, transf)
end

abstract type Shape end
material(s::Shape) = s.prop.material
transform(s::Shape) = s.prop.transf

mutable struct Sphere <: Shape
    center::Vec3d
    radius::Float64
    prop::ShapeProperties

    Sphere(c, r, mat) = new(c, r, ShapeProperties(mat))
    Sphere(c, r, mat, transf) = new(c, r, ShapeProperties(mat, transf))
end

"""
    normal(pt::Vec3d, sphere::Sphere)

Given a point `pt` on the surface of the sphere, return a `Vec3d`
object containing the normalize outward vector outwards the surface at
point `pt`.
"""
function normal(pt::Vec3d, sphere::Sphere)
    normalize(pt - sphere.center)
end

function getcolor(sphere::Sphere, point::Vec3d)
    normpoint = normalize(point - sphere.center)
    theta = acos(normpoint[3])
    phi = atan(normpoint[2], normpoint[1])
    getcolor(material(sphere), mod2pi(phi) / 2π, theta / π)
end


text:
function _argnames(fields)
    return [sym for (sym, arg_type, slurp, default) in map(splitarg, fields)]
end

# We generate two initializer functions: one takes all fields, cumulative through superclasses,
# and another initializes only locally-defined fields. This function produces either, depending
# on the fields passed by _constructors().
function _initializer(class, fields, wheres)
    args = _argnames(fields)
    # we use setfield!() to allow classes to override setproperty()
    # assigns = [:(_self.$arg = $arg) for arg in args]
    assigns = [:(setfield!(_self, $(QuoteNode(arg)), $arg)) for arg in args]
    T = gensym(class)

    funcdef = :(
        function $class(_self::$T, $(fields...)) where {$T <: $(abs_symbol(class)), $(wheres...)}
            $(assigns...)
            _self
        end
    )

    return funcdef
end

function super_constructor_inheritance(clsname, super, super_fields, has_params, params)
    guide_constructor = Expr[]
    super_fields_len = length(super_fields)
    # new{T...} is not supported on Julia 1.0.5
    if has_params
        function_return = :(new{(getfield(typeof(super_inctance), :parameters)...)})
    else
        function_return = :(new)
    end
    # paramsless constructor
    if super_fields_len != 0
        argnames = _argnames(super_fields)
        paramsless_guide_constructor = quote
            function $clsname(arguments...)
                super_inctance = $super(arguments...)    # super's extra constructor
                # setting subclass fields
                subcls_fields = getfield.(Ref(super_inctance), $argnames)
                return $function_return(subcls_fields...)
            end
        end
    else
        # call the super constructor that may do some stuff
        paramsless_guide_constructor = quote
            function $clsname(arguments...)
                super_inctance = $super(arguments...) # does something
                return $function_return()
            end
        end
    end
    push!(guide_constructor, paramsless_guide_constructor)
    # paramsful constructor
    if has_params
        if super_fields_len != 0
            argnames = _argnames(super_fields)
            paramsful_guide_constructor = quote
                function $clsname{$(params...)}(arguments...) where {$(params...)}
                    super_inctance = $super{$(params...)}(arguments...)    # super's extra constructor
                    # setting subclass fields
                    subcls_fields = getfield.(Ref(super_inctance), $argnames)
                    return $function_return(subcls_fields...)
                end
            end
        else
            # call the super constructor that may do some stuff
            paramsful_guide_constructor = quote
                function $clsname{$(params...)}(arguments...) where {$(params...)}
                    super_inctance = $super{$(params...)}(arguments...) # does something
                    return $function_return()
                end
            end
        end
        push!(guide_constructor, paramsful_guide_constructor)
    end
    return guide_constructor
end

function _constructors(clsname, super, super_info, local_fields, all_fields, wheres)
    all_wheres = [super_info.wheres; wheres]
    init_all = _initializer(clsname, all_fields, all_wheres)
    inits = [init_all]

    # If clsname is a direct subclasses of Classes.Class, it has no fields
    # other than those defined locally, so the two methods would be identical.
    # In this case, we emit only one of them.
    if all_fields != local_fields
        init_local = _initializer(clsname, local_fields, wheres)
        push!(inits, init_local)
    end

    # extract parameter names from where clauses
    params = [(clause isa Expr ? clause.args[1] : clause) for clause in all_wheres]
    has_params = length(params) != 0

    args = _argnames(all_fields)
    body = has_params ? :(new{$(params...)}($(args...))) : :(new($(args...)))
    dflt = emit_function(clsname, body, args=all_fields, params=params, wparams=all_wheres, rtype=clsname)

    methods = [dflt]

    # Primarily for immutable classes, we emit a constructor that takes an instance
    # of the direct superclass and copies values when creating a new object.
    super_fields = super_info.ivars
    if length(super_fields) != 0
        # super_args = [:(_super.$arg) for arg in _argnames(super_fields)]
        super_args = [:(getfield(_super, $(QuoteNode(arg)))) for arg in _argnames(super_fields)]
        local_args = _argnames(local_fields)
        all_args = [super_args; local_args]

        body = has_params ? :(new{$(params...)}($(all_args...))) : :(new($(all_args...)))
        args = [:(_super::$super); local_fields]
        immut_init = emit_function(clsname, body; args=args, params=params, wparams=all_wheres, rtype=clsname)
        push!(methods, immut_init)
    end

    # super constructor inheritance: when the class and superclass have the same fields,
    # the constructors of the superclass are valid for the subclass,
    # so we make an outter constructor for subclass pointing to those.
    if super !== Class && length(local_fields) === 0
        guide_constructor = super_constructor_inheritance(clsname, super, super_fields, has_params, params)
        push!(methods, guide_constructor...)
    end

    return methods, inits
end

function _defclass(clsname, supercls, mutable, wheres, exprs)
    wheres   = (wheres === nothing ? [] : wheres)
    # @info "clsname:$clsname supercls:$supercls mutable:$mutable wheres:$wheres exprs:$exprs"

    # partition expressions into constructors and field defs
    ctors  = Vector{Expr}()
    fields = Vector{Union{Expr, Symbol}}()
    for ex in exprs
        if ex isa Symbol || (ex isa Expr && ex.head === :(::) && ex.args[1] isa Symbol )  # x or x::Int64
            push!(fields, ex)
        else
            splitdef(ex)        # throws AssertionError if not a func def
            push!(ctors, ex)
        end
    end

    super_info = _class_info(supercls)
    all_fields = [super_info.ivars; fields]
    all_wheres = [super_info.wheres; wheres]

    # add default constructors
    inner, outer = _constructors(clsname, supercls, super_info, fields, all_fields, wheres)
    append!(ctors, inner)

    abs_class = abs_symbol(clsname)
    abs_super = nameof(absclass(supercls))

    struct_def = emit_struct(clsname, abs_class, mutable, all_wheres, all_fields, ctors)

    # set mutability flag
    struct_def.args[1] = mutable

    result = quote
        abstract type $abs_class <: $abs_super end
        Base.@__doc__($struct_def)
        $(outer...)
        Classes.superclass(::Type{$clsname}) = $supercls
        $clsname    # return the struct type
    end

    return result
end

macro class(elements...)
    if (mutable = (elements[1] == :mutable))
        elements = elements[2:end]
    end

    if (len = length(elements)) == 1                       # no fields defined
        name_expr = elements[1]
        definition = quote end
    elseif len == 2
        (name_expr, definition) = elements
    else
        error("Unrecognized form for @class definition: $elements")
    end

    # @info "name_expr: $name_expr, definition: $definition"

    # initialize the "captured" vars to avoid "unknown var" warnings
    cls = clsname = exprs = wheres = nothing

    @capture(definition, begin exprs__ end)

    # allow for optional type params and supertype
    if ! (@capture(name_expr, ((cls_{wheres__} | cls_) <: supername_) | (cls_{wheres__} | cls_)) && cls isa Symbol)
        error("Unrecognized class name expression: `$name_expr`")
    end

    supername = (supername === nothing ? :Class : supername)

    # __module__ is a "hidden" arg passed to macros with the caller's Module
    expr = _defclass(cls, getproperty(__module__, supername), mutable, wheres, exprs)
    return esc(expr)
end


text:
@testset "Evaluation" begin

    gold = DependencyTree(TypedDependency, [
        (1, "The", "DT", 2),
        (2, "cat", "NSUBJ", 3),
        (3, "sleeps", "PRED", 0),
        (4, ".", ".", 3)])

    good = DependencyTree(TypedDependency, [
        (1, "The", "DT", 2),
        (2, "cat", "NSUBJ", 3),
        (3, "sleeps", "PRED", 0),
        (4, ".", ".", 3)])

    ok = DependencyTree(TypedDependency, [
        (1, "The", "DT", 2),
        (2, "cat", "NSUBJ", 3),
        (3, "sleeps", "PRED", 0),
        (4, ".", "WRONG", 3)])

    bad = DependencyTree(TypedDependency, [
        (1, "The", "DT", 2),
        (2, "cat", "NSUBJ", 3),
        (3, "sleeps", "PRED", 0),
        (4, ".", "WRONG", 2)])

    @test unlabeled_accuracy(gold, good) == 1
    @test unlabeled_accuracy(gold, ok)   == 1
    @test unlabeled_accuracy(gold, bad)  == 0.75

    @test labeled_accuracy(gold, good) == 1
    @test labeled_accuracy(gold, ok)   == 0.75
    @test labeled_accuracy(gold, bad)  == 0.75

    @test unlabeled_accuracy([gold], [good]) == 1
    @test unlabeled_accuracy([gold], [ok])   == 1
    @test unlabeled_accuracy([gold], [bad])  == 0.75

    @test labeled_accuracy([gold], [good]) == 1
    @test labeled_accuracy([gold], [ok])   == 0.75
    @test labeled_accuracy([gold], [bad])  == 0.75
end


text:
import NewOnly
import ScientificTypes
import Test

Test.@testset "NewOnly.jl" begin
    Test.@test NewOnly.f(1) == 2
end


text:
# This example demonstrates the use of the high-level Matlab-like interface
#
# First of all we create an array with top-of the atmosphere radiation data

using NetCDF

include("toa.jl")

# Define longitudes and latitudes, day and timesteps
lat = collect(-89:89)
lon = collect(0:359)
day = 1
tim = collect(0:23)

# Create radiation array
rad = Float64[g_pot(x2,x1,day,x3) for x1=lon, x2=lat, x3=tim]

# Define some attributes of the variable (optionlal)
varatts = Dict("longname" => "Radiation at the top of the atmosphere",
               "units"    => "W/m^2")
lonatts = Dict("longname" => "Longitude",
               "units"    => "degrees east")
latatts = Dict("longname" => "Latitude",
               "units"    => "degrees north")
timatts = Dict("longname" => "Time",
               "units"    => "hours since 01-01-2000 00:00:00")

# Now we create the file radiation.nc and call the variable rad, define also the dimensions the variables depends on

isfile("radiation.nc") && rm("radiation.nc")
nccreate("radiation.nc", "rad", "lon", lon, lonatts, "lat", lat, latatts,
    "time", tim, timatts, atts=varatts)

# Now we can write values to the file

ncwrite(rad, "radiation.nc", "rad")

# And close the file

ncclose("radiation.nc")

# Reading the whole dataset is done by:

x = ncread("radiation.nc", "rad")
println("Successfully read an array of size ", size(x))

# Additional
# Reading parts of a file, for example reading only time steps 5 and 6 can be done with:

x = ncread("radiation.nc", "rad", [1,1,5], [-1,-1,2])
println("Successfully read an array of size ", size(x))

# here the first array [1,1,5] gives the starting position for reading while the second array [1,1,2] gives the number of blocks to be read along each dimension.
# If the count is set to -1 the whole dimension is read.

# The same can be done for ncwrite

x = ones(Float64, 1, 360, 1)
# ncwrite(x,"radiation.nc","rad",[60,1,4])
# This would set all values at 60deg longitude at the 4th time step to 1.


text:
module GeoDatasets

using Printf

using RemoteFiles
using CodecZlib
using Shapefile
using GeoInterface
using ZipFile

include("land_sea_mask.jl")
include("gshhg.jl")

end

max_stars_repo_name: JuliaGeo/GeoDatasets

max_issues_repo_name: JuliaGeo/GeoDatasets

max_forks_repo_name: JuliaGeo/GeoDatasets


text:
module Asteroids

import Gloria: onevent!, render!, update!
using Gloria: Gloria, AbstractObject, Audio, Event, Font, Layer, Resources, Scene, Texture, Window,
    add!, kill!, killall!, play!, settimer!,
    isalive, iskey, ispressed, text

using Gloria.Shapes: Vertex, Point, circle, Polygon, intersects
using Gloria.Physics: Physical, timeintersects, position, velocity, angle, angularvelocity,
    setposition!, setangle!, setvelocity!, setangularvelocity!

using StaticArrays
using Colors: @colorant_str

##################################################
# Types
##################################################

mutable struct Controls <: AbstractObject
    level::Int
    lives::Int
    transition::Bool
    t1::Float64
end
Controls() = Controls(0, 3, false, 0.)

struct Banner <: AbstractObject
    text::String
end
Banner(text, t) = (self = Banner(text); settimer!(window, t, ()->kill!(banner_layer, self)); self)

abstract type AsteroidsObject <: AbstractObject end

mutable struct Player <: AsteroidsObject
    a::Float64
    α::Float64
end

struct Shield <: AsteroidsObject end

struct LaserBeam <: AsteroidsObject end

struct Rock <: AsteroidsObject
    scale::Float64
end

function Physical{Player}(a, α)
    shape = Polygon(
        Vertex(-15., 0.),
        Vertex(-25., 15.),
        Vertex(25., 0.),
        Vertex(-25., -15.)
    )
    return Physical(Player(a, α), shape)
end

function Physical{Shield}(t)
    self = Physical(Shield(), circle(Vertex(0., 0.), 50))
    settimer!(window, t, () -> kill!(object_layer, self))
    return self
end

function Physical{LaserBeam}(t, x, y, vx, vy, θ)
    shape = circle(Vertex(0., 0.), 5)
    self = Physical(LaserBeam(), shape; position=SVector(x, y), angle=SVector(θ), velocity=SVector(vx, vy))
    settimer!(window, t, () -> kill!(object_layer, self))
    return self
end

function Physical{Rock}(scale, x, y, vx, vy, θ, ω)
    n = 12
    shape = Polygon([
        Vertex(
            (50cos(2π*i/n))*scale,
            (50sin(2π*i/n)+10randn())*scale
        ) for i in 0:(n-1)
    ]...)
    return Physical(Rock(scale), shape, position=SVector(x, y), angle=SVector(θ), velocity=SVector(vx, vy), angularvelocity=SVector(ω))
end

##################################################
# Events
##################################################

function onevent!(::Controls, e::Event{:key_down})
    iskey(e, "escape") && Gloria.quit!(window, e)
end

function onevent!(self::Controls, e::Event{:key_down}, t, dt)
    self.level == 0 && iskey(e, "space") && nextlevel!(t)
end

function onevent!(self::Physical{Player}, e::Event{:key_down}, t, dt)
    if controls.level > 0 && iskey(e, "space")
        play!(laser_sound, volume=10)
        θ = angle(self)[1]
        add!(object_layer, Physical{LaserBeam}(
            t + 1,
            position(self)...,
            (velocity(self) + SVector(cosd(θ)*500, sind(θ)*500))...,
            θ
        ))
    end
end

function onevent!(self::Physical{Player}, e::Event{:key_up})
    if iskey(e, "right") || iskey(e, "left")
        setangularvelocity!(self, SVector(0.))
    end
end

##################################################
# Update
##################################################

function update!(self::Controls, ::Gloria.AbstractLayer, t, dt)
    if self.level > 0 && count(x->x isa Physical{Rock}, object_layer) == 0
        if !self.transition
            settimer!(window, t + 1, () -> (nextlevel!(t + 1); self.transition = false))
            self.transition = true
        end
    end
    if self.lives < 0 && !self.transition
        gameover!(t)
        self.transition = true
    end
end

function update!(player::Physical{Player}, ::Gloria.AbstractLayer, t, dt)
    if ispressed(keyboard, "up")
        θ = angle(player)[1]
        v = velocity(player)
        new_v = v + player.wrapped.a * dt * SVector(cosd(θ), sind(θ))
        setvelocity!(player, new_v)
    end
    ω = Gloria.Physics.angularvelocity(player)[1]
    if ispressed(keyboard, "left") && abs(ω) < 360
        ω -= player.wrapped.α*dt
        setangularvelocity!(player, SVector(ω))
    end
    if ispressed(keyboard, "right") && abs(ω) < 360
        ω += player.wrapped.α*dt
        setangularvelocity!(player, SVector(ω))
    end

    rocks = filter(
        obj ->  obj isa Physical{Rock} &&
                isalive(object_layer, obj) &&
                intersects(player, obj),
        object_layer
    )

    for rock in rocks
        destroyrock!(rock, player)

        if !any(x->x isa Physical{Shield}, object_layer)
            setposition!(player, SVector(0., 0.))
            setvelocity!(player, SVector(0., 0.))
            controls.lives -= 1
            if controls.lives >= 0
                add!(object_layer, Physical{Shield}(t + 2))
            end
        end
    end
end

function update!(self::Physical{Shield}, ::Gloria.AbstractLayer, t, dt)
    setposition!(self, Gloria.Physics.position(player))

    for obj in object_layer
        if (
            obj isa Physical{Rock} &&
            isalive(object_layer, obj) &&
            intersects(self, obj)
        )
            destroyrock!(obj, self)
        end
    end
end

function update!(self::Physical{LaserBeam}, ::Gloria.AbstractLayer, t, dt)
    for obj in object_layer
        if (
            obj isa Physical{Rock} &&
            isalive(object_layer, obj) &&
            intersects(self, obj)
        )
            kill!(object_layer, self)
            destroyrock!(obj, self)
        end
    end
end

function Gloria.after_update!(self::Physical{<:AsteroidsObject}, ::Gloria.AbstractLayer, t, dt)
    x, y = position(self)
    x > width/2  && (x -= width)
    x < -width/2  && (x += width)
    y > height/2 && (y -= height)
    y < -height/2 && (y += height)
    setposition!(self, SVector(x, y))
end

##################################################
# Render
##################################################

function render!(layer::Layer, self::Banner, frame::Int, fps::Float64)
    render!(layer, text(font_noto, self.text, color=colorant"#FFFFFF", halign=0.5, valign=0.5), 0., 0., 0.)
end

function render!(layer::Layer, self::Controls, frame, fps)
    render!(layer, text(font_noto, "FPS: $(round(fps; digits=1))", color=colorant"#FFFFFF"; halign=1.0), width, 0., 0.)

    if self.level > 0 && self.lives >= 0
        render!(layer, text(font_noto, "Lives: $(self.lives)", color=colorant"#FFFFFF"), 0., 0., 0.)
    elseif self.level == 0
        render!(layer, text(font_noto, "Welcome to Asteroids!", color=colorant"#FFFFFF", halign=0.5, valign=0.5), width/2, height/2 - 50, 0.)
        if (frame % 50) <= 25
            render!(layer, text(font_noto, "Press space to start", color=colorant"#FFFFFF", halign=0.5, valign=0.5), width/2, height/2 + 50, 0.)
        end
    end
end

function render!(layer::Layer, self::Physical{<:Union{LaserBeam,Player,Shield}}, frame::Int, fps::Float64)
    render!(layer, self.shape, position(self)..., angle(self)..., color=colorant"#C0C0C0")
end

function render!(layer::Layer, self::Physical{Rock}, frame::Int, fps::Float64)
    render!(layer, self.shape, position(self)..., angle(self)..., color=colorant"#A0A0A0")
end

##################################################
# Helper functions
##################################################

function startgame!(t)
    killall!(object_layer)
    controls.transition = false
    controls.level = 0
    controls.lives = 3
    setangularvelocity!(player, SVector(0.))
    setangle!(player, SVector(-90.))

    add!(object_layer, player, Physical{Shield}(t + 3))
end

function addrock!(scale, v)
    horv = rand(Bool)
    rock = Physical{Rock}(scale,
                          horv ? rand(-width/2:width/2) : rand([-width/2, width/2]),
                          horv ? rand([-height/2, height/2]) : rand(-height/2:height/2),
                          (0.5-randn())*v, (0.5-randn())*v, 360rand(), 90rand())
    add!(object_layer, rock)
end

function destroyrock!(rock, other)
    if isalive(object_layer, rock)
        kill!(object_layer, rock)
        if rock.scale > 0.25
            for _ in 1:2
                x, y = position(rock)
                scale = rock.wrapped.scale
                vx, vy = 0.1 * velocity(other) ./ scale + velocity(rock)
                ω = angularvelocity(rock)[1] + 50*(rand() - 0.5)
                add!(object_layer, Physical{Rock}(
                    scale/2,
                    x + 25scale*randn(),
                    y + 25scale*randn(),
                    vx, vy, 360rand(), ω))
            end
        end
    end
end

function nextlevel!(t)
    # Reset the current level
    for obj in filter(obj -> obj isa Physical{LaserBeam} || obj isa Physical{Rock}, object_layer)
        kill!(object_layer, obj)
    end

    # Initialize the next level
    controls.level += 1
    level = controls.level
    setposition!(player, SVector(0., 0.))
    setvelocity!(player, SVector(0., 0.))
    setangularvelocity!(player, SVector(0.))

    add!(banner_layer, Banner("Level $level", t + 1))
    add!(object_layer, Physical{Shield}(t + 2))

    # Populate with rocks!
    if level % 5 == 0
        for _ in 1:level
            addrock!(0.7, 30 + 7level)
        end
    elseif level % 3 != 0
        for _ in 1:level
            addrock!(1., 30 + 5level)
        end
    elseif level % 15 == 0
        for _ in 1:5*level
            addrock!(0.10, 30 + 2level)
        end
    elseif level % 6 != 0
        for _ in 1:3*level
            addrock!(0.25, 30 + 10level)
        end
    else
        for _ in 1:level/3
            addrock!(2.0, 30 + 5level)
        end
    end
end

function gameover!(t)
    kill!(object_layer, player)
    add!(banner_layer, Banner("Game over", t + 3))
    settimer!(window, t + 3, ()->startgame!(t + 3))
end

##################################################
# Setup
##################################################

# const width, height = 1920, 1080

function main(; keepalive=true)
    @eval begin
        const width, height = 800, 600
        const wrap_width, wrap_height = width + 100, height + 100

        const controls = Controls()
        const controls_layer = Layer([controls])
        const banner_layer = Layer(Banner[], width/2, height/2)
        const object_layer = Layer(Physical[], width/2, height/2)

        const scene = Scene(object_layer, banner_layer, controls_layer, color=colorant"#202020")
        const window = Window("Asteroids", width, height, scene, fullscreen=false)

        const resources = Resources(window)
        const keyboard = Gloria.KeyboardState()

        const laser_sound = Audio(resources, abspath(@__DIR__, "..", "assets", "laser.wav"))
        const font_noto = Font(resources, abspath(@__DIR__, "..", "assets", "NotoSans-Black.ttf"), fontsize=24)

        const player = Physical{Player}(100., 360.)
    end

    Gloria.run!(window)
    startgame!(0)
    keepalive && wait(window)
end

##################################################
# Precompile
##################################################

# const dir = abspath(@__DIR__, "..", "precompile")
# const blacklist_import = []
# const fnames = collect(filter(x->occursin(r"^precompile_.*\.jl$", x), readdir(dir)))
# const names = (fname->Symbol(match(r"^precompile_(.*)\.jl$", fname)[1])).(fnames)
# for name in names
#     name in blacklist_import && continue
#     try
#         @eval import $name
#     catch e
#         @warn "Failed import of: $name ($e)"
#     end
# end
# for fname in fnames
#     try
#         include(joinpath(dir, fname))
#         _precompile_()
#         catch e
#         @warn "Failed additional precompilation of: $fname ($e)"
#     end
# end

end # module


text:
using Test
using RenderingGeometry

include("component_geometry/pair_test.jl")

run_pair_tests()


text:
# Arc
struct Arc{T} <: AbstractArc{T}
    src::T # source
    tgt::T # target
    key::Union{Nothing,Int}
end

eltype(::Arc{T}) where {T} = T
reverse(a::Arc) = Arc(tgt(a), src(a), key(a))

Arc(u::T, v::T, k::Int) where {T} = Arc{T}(u, v, k)
Arc(u::T, v::T, k::Nothing) where {T} = Arc{T}(u, v, k)
Arc(u::T, v::T) where {T} = Arc{T}(u, v, nothing)

Arc(t::Tuple{T,T,Nothing}) where {T} = Arc(t...)
Arc(t::Tuple{T,T,Int}) where {T} = Arc(t...)
Arc(t::Tuple{T,T}) where {T} = Arc(t...)
Tuple(a::Arc{T}) where {T} = isnothing(a.key) ? (a.src, a.tgt) : (a.src, a.tgt, a.key)

add_arc!(g::AbstractNexus{T}, a::Arc{T}) where T = add_arc!(g, src(a), tgt(a), key(a))
rem_arc!(g::AbstractNexus{T}, a::Arc{T}) where T = rem_arc!(g, src(a), tgt(a), key(a))

has_arc(g::AbstractNexus{T}, a::Arc{T}) where T = has_arc(g, src(a), tgt(a), key(a))


text:
type recdata
  component :: Array{String} # provide information of output data component
  recnumber :: Int64 # Number of Receivers
  location :: Array{Float64} # Receiver coordinates
  nlocation :: Array{Int64}
  BDnlocation :: Array{Int64}
  timesamp :: Int64 # Total time sampling Tn
  data :: Array{Float64}
end

function readrec(DataPath::String)
    fid = open(DataPath,"r")
    CpntDict = Dict(1=>"P",2=>"Vx",3=>"Vz",
                    4=>"Txx",5=>"Tzz",6=>"Txz")

        rn = read(fid,Int64,1)
        nCpnt = read(fid,Int64,1)
        NumCpnt = read(fid,Int64,nCpnt)
        component = []
        for i in NumCpnt
            if i == 23
                push!(component,CpntDict[2])
                push!(component,CpntDict[3])
            elseif i == 45
                push!(component,CpntDict[4])
                push!(component,CpntDict[5])
            else push!(component,CpntDict[i])
            end
        end
        nT = read(fid,Int64,1) # Number of Receivers and Total time sampling Tn
        RowNum = length(component)*rn
        ColNum = nT
        loc = read(fid, Float64, 2*rn)
        loc = reshape(loc, rn,2)
        nloc = read(fid,Int64, 2*rn)
        nloc = reshape(nloc,rn,2)
        BDnloc = read(fid,Int64, 2*rn)
        BDnloc = reshape(BDnloc,rn,2)

        data = read(fid,Float64,RowNum*ColNum)
        data = reshape(data,RowNum,ColNum)

        if eof(fid)
            println("Data reading successful!")
            return recdata(Cpnt,rn,loc,nloc,BDnloc,nT,data)
            close(fid)
        elseif !(eof(fid))
            close(fid)
            error("Check data length, not finished!")
        end

    end


text:
struct Model
    fw
    fc
    fx
    fy
    fout
end

function Model{T}(wordembeds::Matrix{T}, charembeds::Matrix{T}, tagembeds::Matrix{T})
    fw = @graph x begin
        Lookup(wordembeds)(x)
    end

    dc = size(charembeds, 1)
    fc = @graph x begin
        x = Lookup(charembeds)(x)
        x = Conv1D(T,5dc,5dc,2dc,dc)(x)
        max(x, 2)
    end

    dx = size(wordembeds,1) + 5dc
    fx = @graph x begin
        x = Conv1D(T,5dx,2dx,2dx,dx)(x)
        x = relu(x)
        Linear(T,2dx,2dx)(x)
    end

    dy = size(tagembeds, 1)
    fy = @graph x begin
        x = Lookup(tagembeds)(x)
        x = Conv1D(T,5dy,2dy,2dy,dy)(x)
        x = relu(x)
        Linear(T,2dy,2dy)(x)
    end

    dout = 2dx + 2dy
    fout = @graph x begin
        Linear(T,dout,1)(x)
    end
    Model(fw, fc, fx, fy, fout)
end

function (m::Model)(word::Var, char::Var, tag::Var)
    w = m.fw(word)
    c = m.fc(char)
    c.batchdims = w.batchdims
    hx = m.fx(cat(1,w,c))
    hy = m.fy(tag)
    o = m.fout(cat(1,hx,hy))
    o
end

function (m::Model)(word::Var, char::Var, tag::Var, istrain::Bool)
    w = m.fw(word)
    c = m.fc(char)
    c.batchdims = w.batchdims
    hx = m.fx(cat(1,w,c))
    hy = m.fy(tag)
    o = m.fout(cat(1,hx,hy))
    o
end

max_stars_repo_name: hshindo/Merlin-Examples

max_issues_repo_name: hshindo/Merlin-Examples

max_forks_repo_name: hshindo/Merlin-Examples


text:
module DeepRL

greet() = print("Hello Deep Reinforcement Learning!")

import Reexport: @reexport
import MacroTools: @forward

@reexport using MinimalRLCore

export ExperienceReplay,
    WeightedExperienceReplay,
    OnlineReplay,
    getindex,
    add!,
    sample

include("state_buffer.jl")
include("replay.jl")
include("optimizers.jl")

export MountainCar, Atari
include("env.jl")

export ϵGreedy, sample
include("policy.jl")

include("update_utils.jl")

export
    QLearning,
    DoubleQLearning,
    QLearningHuberLoss,
    DoubleQLearningHuberLoss

include("update.jl")

export DQNAgent
include("agent.jl")

include("utils.jl")

end # module


text:
socket = connect("192.168.1.100", 8007)

println(socket, "Dickbutt")

messageBuffer = readline(socket)

fs = open("log.txt", "w")
write(fs, messageBuffer)
close(fs)

max_stars_repo_name: dadarakt/jamon

max_issues_repo_name: dadarakt/jamon

max_forks_repo_name: dadarakt/jamon


text:
module Test
  type Organism
    code::Expr
    codeFn::Function
  end
  type OrganismTask
    task::Task
    organism::Organism
  end

  tasks = OrganismTask[]

  function born(o::Organism)
    return function ()
      while true
        produce()
        o.codeFn(o)
      end
    end
  end

  function run()
    for i=1:5000
      org  = Organism(:(function (o) local i::Int=1; function f() return i end; return f()+1 end), function (o) return 1 end)
      task = Task(born(org))
      push!(tasks, OrganismTask(task, org))
    end

    while true
      for i=1:5000
        consume(tasks[i].task)

        if rand(1:10000) === 1
          #tasks[i].organism.code.args[2].args[2] = :(return $i)
          tasks[i].organism.codeFn = eval(tasks[i].organism.code)
        end
      end

      if rand(1:10000) === 1
        id = rand(1:5000)
        try Base.throwto(tasks[id].task, nothing) end
        splice!(tasks, id)

        org  = Organism(:(function (o) local i::Int=1; function f() return i end; return f()+1 end), function (o) return 1 end)
        task = Task(born(org))
        push!(tasks, OrganismTask(task, org))
      end
    end
  end
end

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
module MacroTests

using Test, LazyArrays, MacroTools
using Base.Broadcast: Broadcasted

A = randn(6, 6)
B = BroadcastArray(+, A, 2)
C = randn(6, 6)

expressions_block = quote
    exp.(A)
    @. exp(A)
    exp(A)
    A .+ 2
    @. A + 2
    A + B
    @. A + B
    A * B + C
    A * B .+ C
    A * (B + C)
    # A * (B .+ C)
    2 .* (A * B) .+ 3 .* C
    exp.(A * C)  # https://github.com/JuliaArrays/LazyArrays.jl/issues/54
    (A * A) .+ (A * C)
end
testparams = [
    ("$(rmlines(ex))", ex) for ex in expressions_block.args if ex isa Expr
]

@testset "@~" begin
    @testset "$label" for (label, ex) in testparams
        desired = @eval $ex
        lazy = @eval @~ $ex
        @test lazy isa Union{Broadcasted, Applied}

        @testset ".= @~ $label" begin
            actual = zero(desired)
            actual .= lazy
            @test actual ≈ desired
        end

        @testset "materialize(@~ $label)" begin
            @test materialize(lazy) ≈ desired
        end

        @testset "LazyArray(@~ $label)" begin
            actual = LazyArray(lazy) :: LazyArray
            @test actual ≈ desired
        end

        @testset "materialize(LazyArray(@~ $label))" begin
            @test_skip materialize(LazyArray(lazy)) == desired  # should work
            @test materialize(LazyArray(lazy)) ≈ desired
        end

        @testset ".= LazyArray(@~ $label)" begin
            actual = zero(desired)
            actual .= LazyArray(lazy)
            @test_skip actual == desired  # should work
            @test actual ≈ desired
        end
    end
end

struct CustomProperty end
Base.getproperty(::CustomProperty, property::Symbol) = property
Base.getproperty(::CustomProperty, property) = property

complex_number = 1 + 2im
custom_property = CustomProperty()

expressions_block = quote
    complex_number.im # https://github.com/JuliaArrays/LazyArrays.jl/pull/69
    custom_property."property"
end
testparams = [
    ("$(rmlines(ex))", ex) for ex in expressions_block.args if ex isa Expr
]

@testset "@~ non-lazy" begin
    @testset "$label" for (label, ex) in testparams
        desired = @eval $ex
        actual = @eval @~ $ex
        @test actual === desired
    end
end

@testset "@~ laziness" begin
    A = ones(1, 1)
    x = [1]

    bc = @~ exp.(A * x)
    @test bc.args isa Tuple{Applied}

    bc = @~ exp.(A * x .+ 1)
    @test bc.args isa Tuple{Broadcasted}
    @test bc.args[1].args isa Tuple{Applied, Int}
end

@testset "@~ and `@views`" begin
    # https://github.com/JuliaArrays/LazyArrays.jl/issues/144
    A = randn(6, 6)
    @test copy(@views @~ exp.(A[1:2, 1:2])) == exp.(A[1:2, 1:2])
end

end  # module


text:
"""
`tooltip!(wdg::AbstractWidget, tooltip; className = "")`

Experimental. Add a tooltip to widget wdg. `tooltip` is the text that will be shown and `className`
can be used to customize the tooltip, for example `is-tooltip-bottom` or `is-tooltip-danger`.
"""
function tooltip!(wdg::AbstractWidget, args...; kwargs...)
    tooltip!(node(wdg)::Node, args...; kwargs...)
    return wdg
end

function tooltip!(n::Node, tooltip; className = "")
    d = props(n)
    get!(d, :attributes, Dict{String, Any})
    get!(d, :className, "")
    d[:attributes]["data-tooltip"] = tooltip
    d[:className] = mergeclasses(d[:className], className, "tooltip")
    n
end


text:
using OrdinaryDiffEq, ParameterizedFunctions, ODE, ODEInterfaceDiffEq, LSODA,
      Sundials, DiffEqDevTools

k(t) = 0.25*sin(t)^2

g = @ode_def RigidBody begin
  dy1  = I₁*y2*y3
  dy2  = I₂*y1*y3
  dy3  = I₃*y1*y2 + k(t)
end I₁ I₂ I₃

p = [-2.0,1.25,-0.5]
prob = ODEProblem(g,[1.0;0.0;0.9],(0.0,10.0),p)

abstols = 1.0 ./ 10.0 .^ (6:13)
reltols = 1.0 ./ 10.0 .^ (3:10);
sol = solve(prob,Vern7(),abstol=1/10^14,reltol=1/10^14)
test_sol = TestSolution(sol)
using Plots; gr()

plot(sol)

setups = [Dict(:alg=>DP5())
          #Dict(:alg=>ode45()) # fails
          Dict(:alg=>dopri5())
          Dict(:alg=>Tsit5())
          Dict(:alg=>Vern6())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=true,numruns=100,maxiters=10000)
plot(wp)

setups = [Dict(:alg=>DP8())
          #Dict(:alg=>ode78()) # fails
          Dict(:alg=>Vern7())
          Dict(:alg=>Vern8())
          Dict(:alg=>dop853())
          Dict(:alg=>Vern6())
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)

setups = [Dict(:alg=>Vern7())
          Dict(:alg=>Vern8())
          Dict(:alg=>odex())
          Dict(:alg=>CVODE_Adams())
          #Dict(:alg=>lsoda())
          Dict(:alg=>ddeabm())
          Dict(:alg=>ARKODE(Sundials.Explicit(),order=6))
]
wp = WorkPrecisionSet(prob,abstols,reltols,setups;appxsol=test_sol,save_everystep=false,numruns=100,maxiters=1000)
plot(wp)

using DiffEqBenchmarks
DiffEqBenchmarks.bench_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])


text:
using EcosystemCore
using StatsBase
#gs = [Grass(id,5) for id in 1:5]
#ss = [Sheep(id,10.0,5.0,0.5,0.5) for id in 6:10]
#ws = [Wolf(id,20.0,10.,0.1,0.1) for id in 11:12]
#
#world = World(vcat(gs, ss, ws))
#simulate!(world, 10, callbacks=[w->@show w])

struct ⚥Sheep <: Animal
    sheep::Sheep
    sex::Symbol
end
⚥Sheep(id,E,ΔE,pr,pf,sex) = ⚥Sheep(Sheep(id,E,ΔE,pr,pf),sex)

EcosystemCore.id(g::⚥Sheep) = EcosystemCore.id(g.sheep)
EcosystemCore.energy(g::⚥Sheep) = energy(g.sheep)
EcosystemCore.energy!(g::⚥Sheep, ΔE) = energy!(g.sheep, ΔE)
EcosystemCore.reproduction_prob(g::⚥Sheep) = reproduction_prob(g.sheep)
EcosystemCore.food_prob(g::⚥Sheep) = food_prob(g.sheep)

EcosystemCore.eats(::⚥Sheep, ::Grass) = true
# eats(::⚥Sheep, ::PoisonedGrass) = true
EcosystemCore.eat!(s::⚥Sheep, g::Plant, w::World) = eat!(s.sheep, g, w)

mates(a::Plant, ::⚥Sheep) = false
mates(a::Animal, ::⚥Sheep) = false
mates(g1::⚥Sheep, g2::⚥Sheep) = g1.sex != g2.sex
function find_mate(g::⚥Sheep, w::World)
    ms = filter(a->mates(a,g), w.agents |> values |> collect)
    isempty(ms) ? nothing : sample(ms)
end

function EcosystemCore.reproduce!(s::⚥Sheep, w::World)
    m = find_mate(s,w)
    if !isnothing(m)
        energy!(s, energy(s)/2)
        vals = [getproperty(s.sheep,n) for n in fieldnames(Sheep) if n!=:id]
        new_id = w.max_id + 1
        ŝ = ⚥Sheep(new_id, vals..., rand(Bool) ? :female : :male)
        w.agents[EcosystemCore.id(ŝ)] = ŝ
        w.max_id = new_id
    end
end

f = ⚥Sheep(1,3.0,1.0,1.0,1.0,:female)
m = ⚥Sheep(2,4.0,1.0,1.0,1.0,:male)
w = World([f,m])
@show w
simulate!(w, 3, callbacks=[w->@show w])


text:
macro def(name, definition)
    return quote
        macro $(esc(name))()
            esc($(Expr(:quote, definition)))
        end
    end
end

# http://www.stochasticlifestyle.com/type-dispatch-design-post-object-oriented-programming-julia/


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApiAppsV1beta2Scale <: SwaggerModel
    apiVersion::Any # spec type: Union{ Nothing, String } # spec name: apiVersion
    kind::Any # spec type: Union{ Nothing, String } # spec name: kind
    metadata::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1ObjectMeta } # spec name: metadata
    spec::Any # spec type: Union{ Nothing, IoK8sApiAppsV1beta2ScaleSpec } # spec name: spec
    status::Any # spec type: Union{ Nothing, IoK8sApiAppsV1beta2ScaleStatus } # spec name: status

    function IoK8sApiAppsV1beta2Scale(;apiVersion=nothing, kind=nothing, metadata=nothing, spec=nothing, status=nothing)
        o = new()
        validate_property(IoK8sApiAppsV1beta2Scale, Symbol("apiVersion"), apiVersion)
        setfield!(o, Symbol("apiVersion"), apiVersion)
        validate_property(IoK8sApiAppsV1beta2Scale, Symbol("kind"), kind)
        setfield!(o, Symbol("kind"), kind)
        validate_property(IoK8sApiAppsV1beta2Scale, Symbol("metadata"), metadata)
        setfield!(o, Symbol("metadata"), metadata)
        validate_property(IoK8sApiAppsV1beta2Scale, Symbol("spec"), spec)
        setfield!(o, Symbol("spec"), spec)
        validate_property(IoK8sApiAppsV1beta2Scale, Symbol("status"), status)
        setfield!(o, Symbol("status"), status)
        o
    end
end # type IoK8sApiAppsV1beta2Scale

const _property_map_IoK8sApiAppsV1beta2Scale = Dict{Symbol,Symbol}(Symbol("apiVersion")=>Symbol("apiVersion"), Symbol("kind")=>Symbol("kind"), Symbol("metadata")=>Symbol("metadata"), Symbol("spec")=>Symbol("spec"), Symbol("status")=>Symbol("status"))
const _property_types_IoK8sApiAppsV1beta2Scale = Dict{Symbol,String}(Symbol("apiVersion")=>"String", Symbol("kind")=>"String", Symbol("metadata")=>"IoK8sApimachineryPkgApisMetaV1ObjectMeta", Symbol("spec")=>"IoK8sApiAppsV1beta2ScaleSpec", Symbol("status")=>"IoK8sApiAppsV1beta2ScaleStatus")
Base.propertynames(::Type{ IoK8sApiAppsV1beta2Scale }) = collect(keys(_property_map_IoK8sApiAppsV1beta2Scale))
Swagger.property_type(::Type{ IoK8sApiAppsV1beta2Scale }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiAppsV1beta2Scale[name]))}
Swagger.field_name(::Type{ IoK8sApiAppsV1beta2Scale }, property_name::Symbol) =  _property_map_IoK8sApiAppsV1beta2Scale[property_name]

function check_required(o::IoK8sApiAppsV1beta2Scale)
    true
end

function validate_property(::Type{ IoK8sApiAppsV1beta2Scale }, name::Symbol, val)
end


text:
#######################################################################################################################################################################################################
#
# Changes to the function
# General:
#     2022-Jan-28: add general function create_nc! for multiple dispatch
#     2022-Jan-28: add documentation
#
#######################################################################################################################################################################################################
"""
This function creates a netcdf file, and the supported methods are

$(METHODLIST)

"""
function create_nc! end

#######################################################################################################################################################################################################
#
# Changes to this method
# General
#     2022-Jan-28: add the basic function to create an empty netcdf file
#     2022-Jan-28: add documentation
#     2022-Jan-28: add global attributes to the generated file
#
#######################################################################################################################################################################################################
"""

    create_nc!(file::String)

Create an empty netcdf file, given
- `file` Path to save the netcdf dataset

---
# Examples
```julia
create_nc!("test.nc");
```
"""
create_nc!(file::String) = (
    # create a dataset using "c" mode
    _dset = Dataset(file, "c");

    # global title attribute
    for (_title,_notes) in ATTR_ABOUT
        _dset.attrib[_title] = _notes;
    end;

    close(_dset);

    return nothing
);

#######################################################################################################################################################################################################
#
# Changes to the method
# General
#     2022-Jan-27: define the function to create an empty growable netcdf file
#     2022-Jan-27: add documentation and examples
#     2022-Jan-28: add input sizes to signal which dimensions are growable
#     2022-Jan-28: add global attributes to the generated file
#
#######################################################################################################################################################################################################
"""

    create_nc!(file::String, dim_names::Vector{String}, dim_sizes::Vector)

Create an empty netcdf file with dimensions, given
- `file` Path to save the netcdf dataset
- `dim_names` Dimension names in the netcdf file
- `dim_sizes` Sizes of the dimensions (must be Integer or Inf), the dimension is growable if size is Integer 0

---
# Examples
```julia
create_nc!("test1.nc", String["lon", "lat", "ind"], [36, 18, 0]);
create_nc!("test2.nc", String["lon", "lat", "ind"], [36, 18, Inf]);
```
"""
create_nc!(file::String, dim_names::Vector{String}, dim_sizes::Vector) = (
    # create a dataset using "c" mode
    _dset = Dataset(file, "c");

    # global title attribute
    for (_title,_notes) in ATTR_ABOUT
        _dset.attrib[_title] = _notes;
    end;

    add_nc_dim!.([_dset], dim_names, dim_sizes);

    close(_dset);

    return nothing
);

#######################################################################################################################################################################################################
#
# Changes to the function
# General:
#     2022-Jan-28: add general function add_nc_dim! for multiple dispatch
#     2022-Jan-28: add documentation
#
#######################################################################################################################################################################################################
"""
This function adds dim name and size information to netcdf file, and the supported methods are

$(METHODLIST)

"""
function add_nc_dim! end

#######################################################################################################################################################################################################
#
# Changes to the method
# General:
#     2022-Jan-28: add method to add dim information to Dataset using Int
#     2022-Jan-28: add documentation
#     2022-Jan-28: remove nested if else statement
#
#######################################################################################################################################################################################################
"""

    add_nc_dim!(ds::Dataset, dim_name::String, dim_size::Int)

Add dimension information to netcdf dataset, given
- `ds` A `NCDatasets.Dataset` type dataset
- `dim_name` Dimension name
- `dim_size` Integer dimension size (0 for Inf, growable)

---
# Examples
```julia
ds = Dataset("test.nc", "a");
add_nc_dim!(ds, "lat", 180);
add_nc_dim!(ds, "ind", 0);
close(ds);
```
"""
add_nc_dim!(ds::Dataset, dim_name::String, dim_size::Int) = (
    # if dim exists already, do nothing
    if dim_name in keys(ds.dim)
        @warn "Dimension $(dim_name) exists already, do nothing...";

        return nothing
    end;

    # if dim does not exist, define the dimension (0 for unlimited)
    ds.dim[dim_name] = (dim_size == 0 ? Inf : dim_size);

    return nothing
);

#######################################################################################################################################################################################################
#
# Changes to the method
# General:
#     2022-Jan-28: add method to add dim information to Dataset using Inf
#     2022-Jan-28: add documentation
#     2022-Jan-28: call the method for Int rather rather than duplicating the code
#
#######################################################################################################################################################################################################
"""

    add_nc_dim!(ds::Dataset, dim_name::String, dim_size::AbstractFloat)

Add dimension information to netcdf dataset, given
- `ds` A `NCDatasets.Dataset` type dataset
- `dim_name` Dimension name
- `dim_size` Float dimension size, can be Inf

---
# Examples
```julia
ds = Dataset("test.nc", "a");
add_nc_dim!("test.nc", "ind", Inf);
close(ds);
```
"""
add_nc_dim!(ds::Dataset, dim_name::String, dim_size::AbstractFloat) = (
    _size = (dim_size == Inf ? 0 : Int(dim_size));
    add_nc_dim!(ds, dim_name, _size);

    return nothing
);

#######################################################################################################################################################################################################
#
# Changes to the method
# General:
#     2022-Jan-28: add method to add dim information to file directly
#     2022-Jan-28: add documentation
#
#######################################################################################################################################################################################################
"""

    add_nc_dim!(file::String, dim_name::String, dim_size::Union{Int, AbstractFloat})

Add dimension information to netcdf file, given
- `file` Path of the netcdf dataset
- `dim_name` Dimension name
- `dim_size` Dimension size, must be Inf or Integer

---
# Examples
```julia
add_nc_dim!("test.nc", "lat", 180);
add_nc_dim!("test.nc", "ind", Inf);
```
"""
add_nc_dim!(file::String, dim_name::String, dim_size::Union{Int, AbstractFloat}) = (
    _dset = Dataset(file, "a");
    add_nc_dim!(_dset, dim_name, dim_size);
    close(_dset);

    return nothing
);