text:
using WAV
using DSP
using ArgParse

push!(LOAD_PATH, pwd())

using Plotting

function main(wav_file)

	s, fs = wavread(wav_file)

	# Tukey Windows

	plot_spectrogram(s, fs, win=tukey(300, 0.5),
			 plot_title="Spectrogram, window: Tukey(300)",
			 image_name="spec-tuk-300")

	plot_spectrogram(s, fs, win=tukey(200, 0.5),
			 plot_title="Spectrogram, window: Tukey(200)",
			 image_name="spec-tuk-200")

	plot_spectrogram(s, fs, win=tukey(100, 0.5),
			 plot_title="Spectrogram, window: Tukey(100)",
			 image_name="spec-tuk-100")

	# Hanning Windows

	plot_spectrogram(s, fs, win=tukey(300, 1),
			 plot_title="Spectrogram, window: Hanning(300)",
			 image_name="spec-hann-300")

	plot_spectrogram(s, fs, win=tukey(200, 1),
			 plot_title="Spectrogram, window: Hanning(200)",
			 image_name="spec-hann-200")

	plot_spectrogram(s, fs, win=tukey(100, 1),
			 plot_title="Spectrogram, window: Hanning(100)",
			 image_name="spec-hann-100")

	# Rectangular Window

	plot_spectrogram(s, fs, win=tukey(300, 0),
			 plot_title="Spectrogram, window: Rect(300)",
			 image_name="spec-rect-300")

	plot_spectrogram(s, fs, win=tukey(200, 0),
			 plot_title="Spectrogram, window: Rect(200)",
			 image_name="spec-rect-200")

	plot_spectrogram(s, fs, win=tukey(100, 0),
			 plot_title="Spectrogram, window: Rect(100)",
			 image_name="spec-rect-100")

	# Bartlett Windows

	plot_spectrogram(s, fs, win=bartlett(300),
			 plot_title="Spectrogram, window: Bartlett(300)",
			 image_name="spec-bart-300")

	plot_spectrogram(s, fs, win=bartlett(200),
			 plot_title="Spectrogram, window: Bartlett(200)",
			 image_name="spec-bart-200")

	plot_spectrogram(s, fs, win=bartlett(100),
			 plot_title="Spectrogram, window: Bartlett(100)",
			 image_name="spec-bart-100")

end

if PROGRAM_FILE == "SpectrogramAnalysis.jl"

	# Set backend renderer
	set_plot()

	# Parse the argument
	s = ArgParseSettings("Audio dialing analisys")

	@add_arg_table s begin
		"--audio"
		help = "The audio file (WAV)"
		required = true
	end

	parsed_args = parse_args(ARGS, s)

	main(parsed_args["audio"])
end

max_stars_repo_name: PatricioIribarneCatella/TP-Telefono

max_issues_repo_name: PatricioIribarneCatella/TP-Telefono

max_forks_repo_name: PatricioIribarneCatella/TP-Telefono


text:
# A generalized generated function implementation, but not that generalized.

struct RuntimeFn{Args, Kwargs, Body, Name} end
struct Unset end

@implement Typeable{RuntimeFn{Args, Kwargs, Body, Name}} where {Args, Kwargs, Body, Name}

Base.show(io::IO, rtfn::RuntimeFn{Args, Kwargs, Body, Name}) where {Args, Kwargs, Body, Name} = begin
        args = interpret(Args)
        kwargs = interpret(Kwargs)
        args = join(map(string, args), ", ")
        kwargs = join(map(string, kwargs), ", ")
        body = interpret(Body) |> rmlines
        repr = "$Name = ($args;$kwargs) -> $body"
        print(io, repr)
end

struct Argument
    name    :: Symbol
    type    :: Union{Nothing, Any}
    default :: Union{Unset,  Any}
end

Base.show(io::IO, arg::Argument) = begin
    print(io, arg.name)
    if arg.type !== nothing
        print(io, "::", arg.type)
    end
    if arg.default !== Unset()
        print(io, "=", arg.default)
    end
end

@implement Typeable{Unset}

@implement Typeable{Argument} begin
    to_type(@nospecialize(arg)) =
        let f = Argument
            args = [arg.name, arg.type, arg.default] |> to_typelist
            TApp{Argument, f, args}
        end
end

function _ass_positional_args!(assign_block::Vector{Expr}, args :: List{Argument}, ninput::Int, pargs :: Symbol)
    i = 1
    for arg in args
        ass = arg.name
        if arg.type !== nothing
            ass = :($ass :: $(arg.type))
        end
        if i > ninput
            arg.default === Unset() && error("Input arguments too few.")
            ass = :($ass = $(arg.default))
        else
            ass = :($ass = $pargs[$i])
        end
        push!(assign_block, ass)
        i += 1
    end
end

@generated function (::RuntimeFn{Args, TNil{Argument}, Body})(pargs...) where {Args, Body}
    args   = interpret(Args)
    ninput = length(pargs)
    assign_block = Expr[]
    body = interpret(Body)
    _ass_positional_args!(assign_block, args, ninput, :pargs)
    quote
        let $(assign_block...)
            $body
        end
    end
end

@generated function (::RuntimeFn{Args, Kwargs, Body})(pargs...; pkwargs...) where {Args, Kwargs, Body}
    args   = interpret(Args)
    kwargs = interpret(Kwargs)
    ninput = length(pargs)
    assign_block = Expr[]
    body = interpret(Body)
    if isempty(kwargs)
        _ass_positional_args!(assign_block, args, ninput, :pargs)
    else
        function get_kwds(::Type{Base.Iterators.Pairs{A, B, C, NamedTuple{Kwds,D}}}) where {Kwds, A, B, C, D}
            Kwds
        end
        kwds = gensym("kwds")
        feed_in_kwds = get_kwds(pkwargs)
        push!(assign_block, :($kwds = pkwargs))
        _ass_positional_args!(assign_block, args, ninput, :pargs)
        for kwarg in kwargs
            ass = k = kwarg.name
            if kwarg.type !== nothing
                ass = :($ass :: $(kwarg.type))
            end
            if k in feed_in_kwds
                ass = :($ass = $kwds[$(QuoteNode(k))])
            else
                default = kwarg.default
                default === Unset() && error("no default value for keyword argument $(k)")
                ass = :($ass = $default)
            end
            push!(assign_block, ass)
        end
    end
    quote
        let $(assign_block...)
            $body
        end
    end
end

ext: jl


text:
module test_julia_parse

using Test

@test parse(Bool, "1") === true
@test parse(Bool, "0") === false
@test parse(Bool, "true")  === true
@test parse(Bool, "false") === false

@test tryparse(Bool, "1") === true
@test tryparse(Bool, "0") === false
@test tryparse(Bool, "true")  === true
@test tryparse(Bool, "false") === false

@test_throws ArgumentError parse(Bool, "ON")
@test                      tryparse(Bool, "ON") === nothing

end # module test_julia_parse


text:
module Whitespaces
export Whitespace, compile!, execute!

include("lexer.jl")
include("vm.jl")

mutable struct Whitespace
    src::AbstractString
    insns::Vector
    stack::Vector
    heap::Dict
    labels::Dict

    function Whitespace(src)
        insns = Vector{Tuple{Symbol, String}}()
        stack = Vector{Int}()
        heap = Dict{Int, Int}()
        labels = Dict{AbstractString, Int}()
        new(src, insns, stack, heap, labels)
    end
end

function compile!(ws::Whitespace)
    ws.insns = tokenize(ws.src)
    nothing
end

function execute!(io, ws::Whitespace)
    ws.labels = find_labels(ws.insns)
    vm_execute!(io, ws)
end

execute!(ws::Whitespace) = execute!(stdout, ws)

end # module


text:
# abstract type for binning

import Base.push!

# K = key type, V = value type
"""
  Implements a binning algorithm.  The algorithm takes key-value pairs and
  sorts them into bins according to the values.

  **Static Parameters**

   * K: the type of the keys
   * V: the type of the values
"""
abstract type AbstractBinning{K, V} end

"""
  Compute the bin a given value falls in

  **Inputs**

   * obj: `AbstractBinning`
   * val: the value
"""
function calcBin(obj::AbstractBinning, val)

  error("abstract fallback for calcBin() reached")
end

"""
  Add a new key-value pair to the binning

  **Inputs**

   * obj: `AbstractBinning`
   * key: the key
   * val: the value
"""
function push!(obj::AbstractBinning, key, val)

  error("abstract fallback for calcBin() reached")
end

"""
  Computes the total number of keys and the sum of the values in each bin.
  This is a global collective operation.

  **Inputs**

   * obj: `AbstractBinning`

  **Outputs**

   * nkeys: vector of length `nBins`, containing the total number of keys in
            each bin
   * valsum: vector of length `nBins` the sum of the values in each bin
"""
function sumBins(obj::AbstractBinning)

  error("abstract fallback for sumBins() reached")
end


text:
function mdl_shaft_ode!(
    device_states,
    output_ode,
    f0::Float64,
    ω_sys,
    dynamic_device::PSY.DynamicGenerator{M, PSY.SingleMass, A, TG, P},
) where {M <: PSY.Machine, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}

    #Obtain indices for component w/r to device
    local_ix = get_local_state_ix(dynamic_device, PSY.SingleMass)

    #Define internal states for component
    internal_states = @view device_states[local_ix]
    δ = internal_states[1]
    ω = internal_states[2]

    #Obtain inner variables for component
    τe = get_inner_vars(dynamic_device)[τe_var]
    τm = get_inner_vars(dynamic_device)[τm_var]

    #Get parameters
    shaft = PSY.get_shaft(dynamic_device)
    H = PSY.get_H(shaft)
    D = PSY.get_D(shaft)

    #Compute 2 states ODEs
    output_ode[local_ix[1]] = 2 * π * f0 * (ω - ω_sys)                    #15.5
    output_ode[local_ix[2]] = (1 / (2 * H)) * (τm - τe - D * (ω - ω_sys))   #15.5

    return
end

function mdl_shaft_ode!(
    device_states,
    output_ode,
    f0::Float64,
    ω_sys,
    dynamic_device::PSY.DynamicGenerator{M, PSY.FiveMassShaft, A, TG, P},
) where {M <: PSY.Machine, A <: PSY.AVR, TG <: PSY.TurbineGov, P <: PSY.PSS}

    #Obtain indices for component w/r to device
    local_ix = get_local_state_ix(dynamic_device, PSY.FiveMassShaft)

    #Define internal states for component
    internal_states = @view device_states[local_ix]
    δ = internal_states[1]
    ω = internal_states[2]
    δ_hp = internal_states[3]
    ω_hp = internal_states[4]
    δ_ip = internal_states[5]
    ω_ip = internal_states[6]
    δ_lp = internal_states[7]
    ω_lp = internal_states[8]
    δ_ex = internal_states[9]
    ω_ex = internal_states[10]

    #Obtain inner variables for component
    τe = get_inner_vars(dynamic_device)[τe_var]
    τm = get_inner_vars(dynamic_device)[τm_var]

    #Get parameters
    shaft = PSY.get_shaft(dynamic_device)
    H = PSY.get_H(shaft)
    H_hp = PSY.get_H_hp(shaft)
    H_ip = PSY.get_H_ip(shaft)
    H_lp = PSY.get_H_lp(shaft)
    H_ex = PSY.get_H_ex(shaft)
    D = PSY.get_D(shaft)
    D_hp = PSY.get_D_hp(shaft)
    D_ip = PSY.get_D_ip(shaft)
    D_lp = PSY.get_D_lp(shaft)
    D_ex = PSY.get_D_ex(shaft)
    D_12 = PSY.get_D_12(shaft)
    D_23 = PSY.get_D_23(shaft)
    D_34 = PSY.get_D_34(shaft)
    D_45 = PSY.get_D_45(shaft)
    K_hp = PSY.get_K_hp(shaft)
    K_ip = PSY.get_K_ip(shaft)
    K_lp = PSY.get_K_lp(shaft)
    K_ex = PSY.get_K_ex(shaft)

    #Compute 10 states ODEs #15.51
    output_ode[local_ix[1]] = 2.0 * π * f0 * (ω - ω_sys)

    output_ode[local_ix[2]] =
        (1.0 / (2.0 * H)) * (
            -τe - D * (ω - ω_sys) - D_34 * (ω - ω_lp) - D_45 * (ω - ω_ex) +
            K_lp * (δ_lp - δ) +
            K_ex * (δ_ex - δ)
        )

    output_ode[local_ix[3]] = 2.0 * π * f0 * (ω_hp - ω_sys)

    output_ode[local_ix[4]] =
        (1.0 / (2.0 * H_hp)) *
        (τm - D_hp * (ω_hp - ω_sys) - D_12 * (ω_hp - ω_ip) + K_hp * (δ_ip - δ_hp))

    output_ode[local_ix[5]] = 2 * π * f0 * (ω_ip - ω_sys)

    output_ode[local_ix[6]] =
        (1.0 / (2 * H_ip)) * (
            -D_ip * (ω_ip - ω_sys) - D_12 * (ω_ip - ω_hp) - D_23 * (ω_ip - ω_lp) +
            K_hp * (δ_hp - δ_ip) +
            K_ip * (δ_lp - δ_ip)
        )

    output_ode[local_ix[7]] = 2.0 * π * f0 * (ω_lp - ω_sys)

    output_ode[local_ix[8]] =
        (1.0 / (2.0 * H_lp)) * (
            -D_lp * (ω_lp - ω_sys) - D_23 * (ω_lp - ω_ip) - D_34 * (ω_lp - ω) +
            K_ip * (δ_ip - δ_lp) +
            K_lp * (δ - δ_lp)
        )

    output_ode[local_ix[9]] = 2 * π * f0 * (ω_ex - ω_sys)

    output_ode[local_ix[10]] =
        (1.0 / (2.0 * H_ex)) *
        (-D_ex * (ω_ex - ω_sys) - D_45 * (ω_ex - ω) + K_ex * (δ - δ_ex))

    return
end


text:
abstract InterpType
type InterpNearest <: InterpType; end
type InterpLinear <: InterpType; end
type InterpQuadratic <: InterpType; end
type InterpCubic <: InterpType; end


text:
const Rmath = :libRmath

# TODO: Replace the three _jl_dist_*p macros with one by defining
# the argument tuples for the ccall dynamically from pn

macro _jl_dist_1p(T, b)
    dd = Expr(:quote, string("d", b))     # C name for pdf
    pp = Expr(:quote, string("p", b))     # C name for cdf
    qq = Expr(:quote, string("q", b))     # C name for quantile
    rr = Expr(:quote, string("r", b))     # C name for random sampler
    Ty = eval(T)
    dc = Ty <: DiscreteDistribution
    pn = Ty.names                       # parameter names
    p  = Expr(:quote, pn[1])
    quote
        global pdf, logpdf, cdf, logcdf, ccdf, logccdf
        global quantile, cquantile, invlogcdf, invlogccdf, rand
        function pdf(d::($T), x::Real)
            ccall(($dd, Rmath), Float64,
                  (Float64, Float64, Int32),
                  x, d.($p), 0)
        end
        function logpdf(d::($T), x::Real)
            ccall(($dd, Rmath), Float64,
                  (Float64, Float64, Int32),
                  x, d.($p), 1)
        end
        function cdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64,
                  (Float64, Float64, Int32, Int32),
                  q, d.($p), 1, 0)
        end
        function logcdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64,
                  (Float64, Float64, Int32, Int32),
                  q, d.($p), 1, 1)
        end
        function ccdf(d::($T), q::Real)
            ccall(($pp, Rmath),
                  Float64, (Float64, Float64, Int32, Int32),
                  q, d.($p), 0, 0)
        end
        function logccdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64, (Float64, Float64, Int32, Int32),
                  q, d.($p), 0, 1)
        end
        function quantile(d::($T), p::Real)
            ccall(($qq, Rmath), Float64, (Float64, Float64, Int32, Int32),
                  p, d.($p), 1, 0)
        end
        function cquantile(d::($T), p::Real)
            ccall(($qq, Rmath), Float64, (Float64, Float64, Int32, Int32),
                  p, d.($p), 0, 0)
        end
        function invlogcdf(d::($T), lp::Real)
            ccall(($qq, Rmath), Float64, (Float64, Float64, Int32, Int32),
                  lp, d.($p), 1, 1)
        end
        function invlogccdf(d::($T), lp::Real)
            ccall(($qq, Rmath), Float64, (Float64, Float64, Int32, Int32),
                  lp, d.($p), 0, 1)
        end
        if $dc
            function rand(d::($T))
                int(ccall(($rr, Rmath), Float64, (Float64,), d.($p)))
            end
        else
            function rand(d::($T))
                ccall(($rr, Rmath), Float64, (Float64,), d.($p))
            end
        end
    end
end

macro _jl_dist_2p(T, b)
    dd = Expr(:quote, string("d",b))     # C name for pdf
    pp = Expr(:quote, string("p",b))     # C name for cdf
    qq = Expr(:quote, string("q",b))     # C name for quantile
    rr = Expr(:quote, string("r",b))     # C name for random sampler
    Ty = eval(T)
    dc = Ty <: DiscreteDistribution
    pn = Ty.names                       # parameter names
    p1 = Expr(:quote, pn[1])
    p2 = Expr(:quote, pn[2])
    if string(b) == "norm"              # normal dist has unusual names
        dd = Expr(:quote, :dnorm4)
        pp = Expr(:quote, :pnorm5)
        qq = Expr(:quote, :qnorm5)
    end
    quote
        global pdf, logpdf, cdf, logcdf, ccdf, logccdf
        global quantile, cquantile, invlogcdf, invlogccdf, rand
        function pdf(d::($T), x::Real)
            ccall(($dd, Rmath),
                  Float64, (Float64, Float64, Float64, Int32),
                  x, d.($p1), d.($p2), 0)
        end
        function logpdf(d::($T), x::Real)
            ccall(($dd, Rmath),
                  Float64, (Float64, Float64, Float64, Int32),
                  x, d.($p1), d.($p2), 1)
        end
        function cdf(d::($T), q::Real)
            ccall(($pp, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), 1, 0)
        end
        function logcdf(d::($T), q::Real)
            ccall(($pp, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), 1, 1)
        end
        function ccdf(d::($T), q::Real)
            ccall(($pp, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), 0, 0)
        end
        function logccdf(d::($T), q::Real)
            ccall(($pp, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), 0, 1)
        end
        function quantile(d::($T), p::Real)
            ccall(($qq, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  p, d.($p1), d.($p2), 1, 0)
        end
        function cquantile(d::($T), p::Real)
            ccall(($qq, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  p, d.($p1), d.($p2), 0, 0)
        end
        function invlogcdf(d::($T), lp::Real)
            ccall(($qq, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  lp, d.($p1), d.($p2), 1, 1)
        end
        function invlogccdf(d::($T), lp::Real)
            ccall(($qq, Rmath),
                  Float64, (Float64, Float64, Float64, Int32, Int32),
                  lp, d.($p1), d.($p2), 0, 1)
        end
        if $dc
            function rand(d::($T))
                int(ccall(($rr, Rmath), Float64,
                          (Float64,Float64), d.($p1), d.($p2)))
            end
        else
            function rand(d::($T))
                ccall(($rr, Rmath), Float64,
                      (Float64,Float64), d.($p1), d.($p2))
            end
        end
    end
end

macro _jl_dist_3p(T, b)
    dd = Expr(:quote, string("d", b))     # C name for pdf
    pp = Expr(:quote, string("p", b))     # C name for cdf
    qq = Expr(:quote, string("q", b))     # C name for quantile
    rr = Expr(:quote, string("r", b))     # C name for random sampler
    Ty = eval(T)
    dc = Ty <: DiscreteDistribution
    pn = Ty.names                       # parameter names
    p1 = Expr(:quote, pn[1])
    p2 = Expr(:quote, pn[2])
    p3 = Expr(:quote, pn[3])
    quote
        global pdf, logpdf, cdf, logcdf, ccdf, logccdf
        global quantile, cquantile, invlogcdf, invlogccdf, rand
        function pdf(d::($T), x::Real)
            ccall(($dd, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32),
                  x, d.($p1), d.($p2), d.($p3), 0)
        end
        function logpdf(d::($T), x::Real)
            ccall(($dd, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32),
                  x, d.($p1), d.($p2), d.($p3), 1)
        end
        function cdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), d.($p3), 1, 0)
        end
        function logcdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), d.($p3), 1, 1)
        end
        function ccdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), d.($p3), 0, 0)
        end
        function logccdf(d::($T), q::Real)
            ccall(($pp, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  q, d.($p1), d.($p2), d.($p3), 0, 1)
        end
        function quantile(d::($T), p::Real)
            ccall(($qq, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  p, d.($p1), d.($p2), d.($p3), 1, 0)
        end
        function cquantile(d::($T), p::Real)
            ccall(($qq, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  p, d.($p1), d.($p2), d.($p3), 0, 0)
        end
        function invlogcdf(d::($T), lp::Real)
            ccall(($qq, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  lp, d.($p1), d.($p2), d.($p3), 1, 1)
        end
        function invlogccdf(d::($T), lp::Real)
            ccall(($qq, Rmath), Float64,
                  (Float64, Float64, Float64, Float64, Int32, Int32),
                  lp, d.($p1), d.($p2), d.($p3), 0, 1)
        end
        if $dc
            function rand(d::($T))
                int(ccall(($rr, Rmath), Float64,
                          (Float64,Float64,Float64), d.($p1), d.($p2), d.($p3)))
            end
        else
            function rand(d::($T))
                ccall(($rr, Rmath), Float64,
                      (Float64,Float64,Float64), d.($p1), d.($p2), d.($p3))
            end
        end
    end
end


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

mutable struct Restriction <: SwaggerModel
    type::Any # spec type: Union{ Nothing, String } # spec name: type
    values::Any # spec type: Union{ Nothing, Vector{String} } # spec name: values
    reasonCode::Any # spec type: Union{ Nothing, String } # spec name: reasonCode

    function Restriction(;type=nothing, values=nothing, reasonCode=nothing)
        o = new()
        validate_property(Restriction, Symbol("type"), type)
        setfield!(o, Symbol("type"), type)
        validate_property(Restriction, Symbol("values"), values)
        setfield!(o, Symbol("values"), values)
        validate_property(Restriction, Symbol("reasonCode"), reasonCode)
        setfield!(o, Symbol("reasonCode"), reasonCode)
        o
    end
end # type Restriction

const _property_map_Restriction = Dict{Symbol,Symbol}(Symbol("type")=>Symbol("type"), Symbol("values")=>Symbol("values"), Symbol("reasonCode")=>Symbol("reasonCode"))
const _property_types_Restriction = Dict{Symbol,String}(Symbol("type")=>"String", Symbol("values")=>"Vector{String}", Symbol("reasonCode")=>"String")
Base.propertynames(::Type{ Restriction }) = collect(keys(_property_map_Restriction))
Swagger.property_type(::Type{ Restriction }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_Restriction[name]))}
Swagger.field_name(::Type{ Restriction }, property_name::Symbol) =  _property_map_Restriction[property_name]

const _allowed_Restriction_reasonCode = ["QuotaId", "NotAvailableForSubscription"]

function check_required(o::Restriction)
    true
end

function validate_property(::Type{ Restriction }, name::Symbol, val)
    if name === Symbol("reasonCode")
        Swagger.validate_param(name, "Restriction", :enum, val, _allowed_Restriction_reasonCode)
    end
end


text:
import baobzi

function testfunc(xp::Ptr{Float64})::Cdouble
    x = unsafe_load(xp, 1)
    y = unsafe_load(xp, 2)
    return x * y
end

center = [0.0, 0.0]
hl = [0.5, 1.0]
test_point = [0.25, 0.25]
dim = 2
order = 6
tol = 1E-8
output_file = "simple2d.baobzi"

func_approx = baobzi.init(testfunc, dim, order, center, hl, tol)
println(baobzi.eval(func_approx, test_point) - testfunc(pointer(test_point)))

baobzi.save(func_approx, output_file)
baobzi.free(func_approx)

func_approx = baobzi.restore(output_file)
println(baobzi.eval(func_approx, test_point) - testfunc(pointer(test_point)))

max_stars_repo_name: ahbarnett/baobzi

max_issues_repo_name: ahbarnett/baobzi

max_forks_repo_name: ahbarnett/baobzi


text:
"""
# Method p63_skyline

Plane strain bearing capacity analysis of an elastic-plastic (Mohr-Coulomb) material
using 8-node rectangular quadrilaterals. Rigid smooth footing. Displacement control.
Viscoplastic strain method.

### Constructors
```julia
p63_skyline(data)
```
### Arguments
```julia
* `data::Dict{Symbol, Any}` : Dictionary containing all input data
```

### Required data dictionary keys
```julia
* struc_el::StructuralElement                          : Structural element
* properties::Vector{Float64}                          : Material properties
* x_coords::FloatRange{Floalt64}                       : x-coordinate vector
* y_coords::FloatRange{Floalt64}                       : y-coordinate vector
```

### Optional additional data dictionary keys
```julia
* tol::Float64                 : Convergence tolerance
* limit = 250                  : Iteration limit
* incs::Int                    : Incremental load steps
* presc::Float64               : Wall displacement increment
* penalty = 1e20               : Penalty used for fixed degrees of freedoms
* etype::Vector{Int}           : Element material vector if np_types > 1
```

### Return values
```julia
* (g_coord, g_num, disp)        : where:
                                    g_coord  : Coordinates
                                    g_num    : Node numbering
                                    disp     : Matrix of displacements
```

### Related help
```julia
?StructuralElement             : List of available structural element types
?Plane                         : Help on a Plane structural element
?FiniteElement                 : List finite element types
?Quadrilateral                 : Help on Quadrilateral finite element
```
"""
function p63_skyline(data::Dict)

  # Setup basic dimensions of arrays

  # Parse & check FEdict data

  if :struc_el in keys(data)
    struc_el = data[:struc_el]
    @assert typeof(struc_el) <: StructuralElement
  else
    println("No fin_el type specified.")
    return
  end

  ndim = struc_el.ndim
  nst = struc_el.nst

  if struc_el.axisymmetric
    nst = 4
  end

  fin_el = struc_el.fin_el
  @assert typeof(fin_el) <: FiniteElement

  if typeof(fin_el) == Line
    (nels, nn) = PtFEM.mesh_size(fin_el, struc_el.nxe)
  elseif typeof(fin_el) == Triangle || typeof(fin_el) == Quadrilateral
    (nels, nn) = PtFEM.mesh_size(fin_el, struc_el.nxe, struc_el.nye)
  elseif typeof(fin_el) == Hexahedron
    (nels, nn) = PtFEM.mesh_size(fin_el, struc_el.nxe, struc_el.nye, struc_el.nze)
  else
    println("$(typeof(fin_el)) is not a known finite element.")
    return
  end

  nodof = fin_el.nodof           # Degrees of freedom per node
  ndof = fin_el.nod * nodof      # Degrees of freedom per fin_el

  # Update penalty if specified in FEdict

  penalty = 1e20
  if :penalty in keys(data)
    penalty = data[:penalty]
  end

  # Allocate all arrays

  # Start with arrays to be initialized from FEdict

  if :properties in keys(data)
    prop = zeros(size(data[:properties], 1), size(data[:properties], 2))
    for i in 1:size(data[:properties], 1)
      prop[i, :] = data[:properties][i, :]
    end
  else
    println("No :properties key found in FEdict")
  end

  nf = ones(Int, nodof, nn)
  if :support in keys(data)
    for i in 1:size(data[:support], 1)
      nf[:, data[:support][i][1]] = data[:support][i][2]
    end
  end

  x_coords = zeros(nn)
  if :x_coords in keys(data)
    x_coords = data[:x_coords]
  end

  y_coords = zeros(nn)
  if :y_coords in keys(data)
    y_coords = data[:y_coords]
  end

  z_coords = zeros(nn)
  if :z_coords in keys(data)
    z_coords = data[:z_coords]
  end

  g_coord = zeros(ndim,nn)
  if :g_coord in keys(data)
    g_coord = data[:g_coord]'
  end

  g_num = zeros(Int, fin_el.nod, nels)
  if :g_num in keys(data)
    g_num = reshape(data[:g_num]', fin_el.nod, nels)
  end

  etype = ones(Int, nels)
  if :etype in keys(data)
    etype = data[:etype]
  end

  # All other arrays

  points = zeros(struc_el.nip, ndim)
  g = zeros(Int, ndof)
  fun = zeros(fin_el.nod)
  coord = zeros(fin_el.nod, ndim)
  gamma = zeros(nels)
  jac = zeros(ndim, ndim)
  der = zeros(ndim, fin_el.nod)
  deriv = zeros(ndim, fin_el.nod)
  bee = zeros(nst,ndof)
  km = zeros(ndof, ndof)
  mm = zeros(ndof, ndof)
  gm = zeros(ndof, ndof)
  kg = zeros(ndof, ndof)
  eld = zeros(ndof)
  weights = zeros(struc_el.nip)
  g_g = zeros(Int, ndof, nels)
  num = zeros(Int, fin_el.nod)
  actions = zeros(ndof, nels)
  displacements = zeros(size(nf, 1), ndim)
  gc = ones(ndim)
  dee = zeros(nst,nst)
  sigma = zeros(nst)
  axial = zeros(nels)

  eps = zeros(nst)
  stress = zeros(nst)
  bload =zeros(ndof)
  eload =zeros(ndof)
  erate = zeros(nst)
  evp = zeros(nst)
  devp = zeros(nst)
  m1 = zeros(nst, nst)
  m2 = zeros(nst, nst)
  m3 = zeros(nst, nst)
  flow = zeros(nst, nst)

  PtFEM.bc_rect!(struc_el.nxe, struc_el.nye, nf, struc_el.direction)
  neq = maximum(nf)
  kdiag = zeros(Int, neq)

  #
  # Program 6.3 specific variables
  #

  tol = 1.0e-10
  if :tol in keys(data)
    tol = copy(data[:tol])
  end

  limit = 100
  if :limit in keys(data)
    limit = copy(data[:limit])
  end

  @assert :incs in keys(data)
  incs = copy(data[:incs])

  @assert :nbo2 in keys(data)
  nbo2 = copy(data[:nbo2])

  @assert :qs in keys(data)
  qs = copy(data[:qs])

  @assert :presc in keys(data)
  presc = copy(data[:presc])

  # Find global array sizes
  for iel in 1:nels
    PtFEM.geom_rect!(fin_el, iel, collect(x_coords), collect(y_coords), coord, num,
      struc_el.direction)
    PtFEM.num_to_g!(num, nf, g)
    g_num[:, iel] = num
    g_coord[:, num] = coord'
    g_g[:, iel] = g
    PtFEM.fkdiag!(kdiag, g)
  end

  for i in 2:neq
    kdiag[i] = kdiag[i] + kdiag[i-1]
  end

  kv = zeros(kdiag[neq])
  gv = zeros(kdiag[neq])

  println("There are $(neq) equations and the skyline storage is $(kdiag[neq]).")

  start_df = 1.0e15
  dt = copy(start_df)

  for i in 1:size(data[:properties], 1)
    ϕ, c, ψ, γ, E, ν  = prop[i, :]
    snph = sind(ϕ)
    ddt = 4.0 * (1.0 + ν) * ( 1.0 - 2.0ν) / (E * (1.0 - 2.0ν + snph^2))
    ddt < dt && (dt = ddt)
    #println([i ddt dt])
  end

  gravlo = zeros(Float64, neq+1)

  PtFEM.sample!(fin_el, points, weights)

  for iel in 1:nels
    PtFEM.deemat!(dee, prop[etype[iel], 5], prop[etype[iel], 6])
    num = g_num[:, iel]
    coord = g_coord[:, num]'              # Transpose
    g = g_g[:, iel]
    km = zeros(ndof, ndof)
    eld = zeros(ndof)
    for i in 1:struc_el.nip
      PtFEM.shape_fun!(fun, points, i)
      PtFEM.shape_der!(der, points, i)
      jac = der*coord
      detm = det(jac)
      jac = inv(jac)
      deriv = jac*der
      PtFEM.beemat!(bee, deriv)
      km += (bee')*dee*bee*detm*weights[i]
      eld[2:2:ndof] += fun .* detm * weights[i]
    end
    PtFEM.fsparv!(kv, km, g, kdiag)
    gravlo[g+1] -= eld .* prop[etype[iel], 4]
  end

  kvc = deepcopy(kv)

  # Surcharge loads

  nf1 = deepcopy(nf) + 1
  for i in 1:struc_el.nxe
    i3 = g_num[3, (i-1)*struc_el.nye+1]
    i4 = g_num[4, (i-1)*struc_el.nye+1]
    i5 = g_num[5, (i-1)*struc_el.nye+1]
    qq = (x_coords[i+1] - x_coords[i]) * qs
    gravlo[nf1[2, i3]] -= qq/6.0
    gravlo[nf1[2, i4]] -= 2.0qq/3.0
    gravlo[nf1[2, i5]] -= qq/6.0
  end

  PtFEM.sparin!(kv, kdiag)
  gravlo[2:end] = PtFEM.spabac!(kv, gravlo[2:end], kdiag)
  gravlo[1] = 0.0

  tensor = zeros(nst, struc_el.nip, nels)

  for iel in 1:nels
    PtFEM.deemat!(dee, prop[etype[iel], 5], prop[etype[iel], 6])
    g = g_g[:, iel]
    eld = gravlo[g+1]
    num = g_num[:, iel]
    coord = g_coord[:, num]'              # Transpose
    for i in 1:struc_el.nip
      PtFEM.shape_der!(der, points, i)
      jac = der*coord
      jac = inv(jac)
      deriv = jac*der
      PtFEM.beemat!(bee, deriv)
      sigma = dee*(bee*eld)
      for j in 1:4
        tensor[j, i, iel] = sigma[j]
      end
    end
  end

  fixed_freedoms = 2nbo2 + 1
  node = zeros(Int, fixed_freedoms)
  no = zeros(Int, fixed_freedoms)
  storkv = zeros(Float64, fixed_freedoms)
  node[1] = 1
  k = 1

  for i in 1:nbo2
    k += 2*struc_el.nye + 1
    node[2*i] = k
    k += struc_el.nye + 1
    node[2*i + 1] = k
  end

  kv = deepcopy(kvc)
  for i in 1:fixed_freedoms
    no[i] = nf[2, node[i]]
  end
  kv = kvc
  kv[kdiag[no]] += penalty
  storkv = kv[kdiag[no]]

  sparin!(kv, kdiag)

  local iters, loads, bdylds, converged
  oldis = zeros(Float64, neq+1)
  totd = zeros(Float64, neq+1)

  println("\nstep   disp    load1    load2     iters\n")

  disps = Array{Float64, 1}()
  loads1 = Array{Float64, 1}()
  loads2 = Array{Float64, 1}()
  iterations = Array{Int, 1}()

  for iy in 1:incs
    iters = 0
    bdylds = zeros(Float64, neq+1)
    react = zeros(Float64, neq+1)
    evpt = zeros(nst, struc_el.nip, nels)

    while true
      iters += 1

      loads = zeros(Float64, neq+1)
      loads += bdylds

      for i in 1:fixed_freedoms
        loads[no[i]+1] = storkv[i] * presc
      end

      loads[2:end] = spabac!(kv, loads[2:end], kdiag)

      converged = checon(loads, oldis, tol)
      iters == 1 && (converged = false)

      if converged || iters == limit
        bdylds = zeros(Float64, neq+1)
      end

      sigm = 0.0
      dsbar = 0.0
      lode_theta = 0.0
      f = 0.0
      dq1 = 0.0
      dq2 = 0.0
      dq3 = 0.0
      for iel in 1:nels
        ϕ, c, ψ, γ, E, ν  = prop[etype[iel], :]
        deemat!(dee, E, ν)
        bload = zeros(ndof)
        rload = zeros(ndof)
        num = g_num[:, iel]
        coord = g_coord[:, num]'
        g = g_g[:, iel]
        eld = loads[g+1]
        for i in 1:struc_el.nip
          shape_der!(der, points, i)
          jac = der*coord
          detm = det(jac)
          jac = inv(jac)
          deriv = jac*der
          beemat!(bee, deriv)
          eps = bee*eld
          eps -= evpt[:, i, iel]
          sigma = dee*eps
          stress = sigma + tensor[:, i, iel]
          (sigm, dsbar, lode_theta) = invar(stress, sigm, dsbar, lode_theta)
          f = mocouf(ϕ, c, sigm, dsbar, lode_theta)
          if converged || iters == limit
            devp = deepcopy(stress)
          else
            if f >= 0.0
              dq1, dq2, dq3 = mocouq(ϕ, dsbar, lode_theta)
              (m1, m2, m3) = formm!(stress, m1, m2, m3)
              flow = f*(m1*dq1 + m2*dq2 + m3*dq3)
              erate = flow*stress
              evp = erate*dt
              evpt[:,i,iel] += evp
              devp = dee*evp
            end
          end
          if f >= 0.0 || converged || iters == limit
            eload = devp' * bee
            bload += eload' * detm * weights[i]
          end
          if converged || iters == limit
            tensor[:,i,iel] = stress
            rload += (stress' * bee)' * detm * weights[i]
          end
        end
        bdylds[g+1] += bload
        react[g+1] += rload
        bdylds[1] = 0.0
      end
      (converged || iters == limit) && break
    end
    totd += loads
    pr = 0.0
    for i in 1:fixed_freedoms
      pr += react[no[i]+1]
    end
    pr /= x_coords[nbo2+1]
    pav = 0.0
    for i in 1:nbo2
      pav += tensor[2, 1, (i-1)*struc_el.nye+1] + tensor[2, 2, (i-1)*struc_el.nye+1]
    end
    pav /= 2nbo2
    append!(disps, -totd[2])
    append!(loads1, -pr)
    append!(loads2, -pav)
    append!(iterations, iters)
    println("$(iy)     $(-round.(totd[2], 5))   $(-round.(pr, 5)) $(-round.(pav, 5))    $(iters)")
    iters == limit && continue
  end

  println()
  displacements = zeros(size(nf))
  for i in 1:size(displacements, 1)
    for j in 1:size(displacements, 2)
      if nf[i, j] > 0
        displacements[i,j] = totd[nf[i, j]+1]
      end
    end
  end

  res_df = DataFrame(
    displacement = disps,
    load1 = loads1,
    load2 = loads2,
    iters = iterations
  )

  (res_df, g_coord, g_num, displacements')
end


text:
# Imports and prepares specific conductance data for Bayesian inference algorithm
# Modify to grab data from MySQL database once it's set up
function prepData(filePath)
    df = CSV.read(filePath, DataFrame)
    mat = zeros(2, nrow(df))
    mat[1,:] = df.modelTime
    mat[2,:] = df.SpecificConductance
    return(mat)
end

max_stars_repo_name: elizabethjmohr/hyporheicBGC

max_issues_repo_name: elizabethjmohr/hyporheicBGC

max_forks_repo_name: elizabethjmohr/hyporheicBGC


text: angle(n::Int)::Int = 180(n-2)

max_stars_repo_name: UlrichBerntien/Codewars-Katas

max_issues_repo_name: UlrichBerntien/Codewars-Katas

max_forks_repo_name: UlrichBerntien/Codewars-Katas


text:
using SpatialGrids
using StaticArrays
using Base.Test

include("spatial_grid_test.jl")


text:
"""
    residreg(pred, Y)
Compute regression prediction errors.
* `pred` : Predictions.
* `Y` : Observed data.
"""
residreg(pred, Y) = Y - pred

"""
    residcla(pred, y)
Compute classification prediction error (0 = no error, 1 = error).
* `pred` : Predictions.
* `Y` : Observed data.
"""
residcla(pred, Y) = pred .!= Y

"""
    ssr(pred, Y)
Compute the sum of squared prediction errors (SSR).
* `pred` : Predictions.
* `Y` : Observed data.
"""
function ssr(pred, Y)
    r = residreg(pred, Y)
    reshape(sum(r.^2, dims = 1), 1, :)
end

"""
    msep(pred, Y)
Compute the mean of the squared prediction errors (MSEP).
* `pred` : Predictions.
* `Y` : Observed data.
"""
function msep(pred, Y)
    r = residreg(pred, Y)
    reshape(colmeans(r.^2), 1, :)
end

"""
    rmsep(pred, Y)
Compute the square root of the mean of the squared prediction errors (RMSEP).
* `pred` : Predictions.
* `Y` : Observed data.
"""
rmsep(pred, Y) = sqrt.(msep(pred, Y))

"""
    bias(pred, Y)
Compute the prediction bias, i.e. the opposite of the mean prediction error.
* `pred` : Predictions.
* `Y` : Observed data.
"""
function bias(pred, Y)
    r = residreg(pred, Y)
    reshape(-colmeans(r), 1, :)
end

"""
    sep(pred, Y)
Compute the corrected SEP ("SEP_c"), i.e. the standard deviation of the prediction errors.
* `pred` : Predictions.
* `Y` : Observed data.

## References

Bellon-Maurel, V., Fernandez-Ahumada, E., Palagos, B., Roger, J.-M., McBratney, A., 2010.
Critical review of chemometric indicators commonly used for assessing the quality of
the prediction of soil attributes by NIR spectroscopy.
TrAC Trends in Analytical Chemistry 29, 1073–1081. https://doi.org/10.1016/j.trac.2010.05.006
"""
sep(pred, Y) = sqrt.(msep(pred, Y) .- bias(pred, Y).^2)

"""
    r2(pred, Y)
Compute the R2 coefficient.
* `pred` : Predictions.
* `Y` : Observed data.

The rate R2 is calculated by R2 = 1 - MSEP(current model) / MSEP(null model),
where the "null model" is the overall mean.
For predictions over CV or test sets, and/or for non linear models,
it can be different from the square of the correlation coefficient (`cor2`)
between the true data and the predictions.
"""
function r2(pred, Y)
    m = size(Y, 1)
    mu = colmeans(Y)
    zmu = reduce(hcat, fill(mu, m, 1))'
    1 .- msep(pred, Y) ./ msep(zmu, Y)
end

"""
    cor2(pred, Y)
Compute the squared linear correlation between data and predictions.
* `pred` : Predictions.
* `Y` : Observed data.
"""
function cor2(pred, Y)
    q = size(Y, 2)
    res = cor(pred, Y).^2
    q == 1 ? res = [res; ] : res = diag(res)
    reshape(res, 1, :)
end

"""
    rpd(pred, Y)
Compute the ratio "deviation to model performance" (RPD).
* `pred` : Predictions.
* `Y` : Observed data.

This is the ratio of the deviation to the model performance to the deviation,
defined by RPD = Std(Y) / RMSEP, where Std(Y) is the standard deviation.

Since Std(Y) = RMSEP(null model) where the null model is the simple average,
this also gives RPD = RMSEP(null model) / RMSEP.
"""
rpd(pred, Y) = std(Y, dims = 1, corrected = false) ./ rmsep(pred, Y)

"""
    rpdr(pred, Y)
Compute a robustified RPD.
* `pred` : Predictions.
* `Y` : Observed data.
"""
function rpdr(pred, Y)
    #Y = ensure_mat(Y)
    u = mapslices(Jchemo.mad, Y; dims = 1) / 1.4826
    r = residreg(pred, Y)
    v = mapslices(median, abs.(r); dims = 1)
    res = u ./ v
    reshape(res, 1, :)
end

# Robust RPD = MAD(Y) / Median(Abs(prediction errors))
# MAD = Median(Abs(prediction errors)) where the median is the null model
#rpdr <- function(pred, Y) {
#    u <- apply(.mat(Y), FUN = mad, MARGIN = 2) / 1.4826
#    r <- residreg(pred, Y)
#    v <- apply(.mat(abs(r)), FUN = median, MARGIN = 2)
#    u / v
#}

"""
    mse(pred, Y)
Summary of model performance for regression.
* `pred` : Predictions.
* `Y` : Observed data.
"""
# Summary for regression
function mse(pred, Y)
    q = size(Y, 2)
    zmsep = msep(pred, Y)
    zrmsep = sqrt.(zmsep)
    zsep = sep(pred, Y)
    zbias = bias(pred, Y)
    zcor2 = cor2(pred, Y)
    zr2 = r2(pred, Y)
    zrpd = rpd(pred, Y)
    zrpdr = rpdr(pred, Y)
    zmean = reshape(colmeans(Y), 1, :)
    nam = map(string, repeat(["y"], q), 1:q)
    nam = reshape(nam, 1, :)
    res = (nam = nam, msep = zmsep, rmsep = zrmsep, sep = zsep, bias = zbias,
        cor2 = zcor2, r2 = zr2, rpd = zrpd, rpdr = zrpdr, mean = zmean)
    DataFrame(res)
end

"""
    err(pred, y)
Compute the classification error rate (ERR).
* `pred` : Predictions.
* `y` : Observed data.
"""
function err(pred, y)
    r = residcla(pred, y)
    res = [sum(r)] / size(y, 1)
    reshape(res, 1, :)
end

# scores:
# - Must return a matrix
# - In particular for err, create multiple dispatches Y::AbstractVector, Y::AbstractMatrix


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

# some test strings
astr = "Hello, world.\n"
u8str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"

# I think these should give error on 4 also, and "" is not treated
# consistently with SubString("",1,1), nor with Char[]
for ind in (0, 5)
    @test_throws BoundsError findnext(SubString("",1,1), "foo", ind)
    @test_throws BoundsError findprev(SubString("",1,1), "foo", ind)
end

# Note: the commented out test will be enabled after fixes to make
# sure that findnext/findprev are consistent
# no matter what type of AbstractString the second argument is
@test_throws BoundsError findnext(isequal('a'), "foo", 0)
@test_throws BoundsError findnext(in(Char[]), "foo", 5)
# @test_throws BoundsError findprev(in(Char[]), "foo", 0)
@test_throws BoundsError findprev(in(Char[]), "foo", 5)

# @test_throws ErrorException in("foobar","bar")
@test_throws BoundsError findnext(isequal(0x1),b"\x1\x2",0)

# ascii forward search
for str in [astr, GenericString(astr)]
    @test_throws BoundsError findnext(isequal('z'), str, 0)
    @test_throws BoundsError findnext(isequal('∀'), str, 0)
    @test findfirst(isequal('x'), str) == nothing
    @test findfirst(isequal('\0'), str) == nothing
    @test findfirst(isequal('\u80'), str) == nothing
    @test findfirst(isequal('∀'), str) == nothing
    @test findfirst(isequal('H'), str) == 1
    @test findfirst(isequal('l'), str) == 3
    @test findnext(isequal('l'), str, 4) == 4
    @test findnext(isequal('l'), str, 5) == 11
    @test findnext(isequal('l'), str, 12) == nothing
    @test findfirst(isequal(','), str) == 6
    @test findnext(isequal(','), str, 7) == nothing
    @test findfirst(isequal('\n'), str) == 14
    @test findnext(isequal('\n'), str, 15) == nothing
    @test_throws BoundsError findnext(isequal('ε'), str, nextind(str,lastindex(str))+1)
    @test_throws BoundsError findnext(isequal('a'), str, nextind(str,lastindex(str))+1)
end

for str in [astr, GenericString(astr)]
    @test_throws BoundsError findnext('z', str, 0)
    @test_throws BoundsError findnext('∀', str, 0)
    @test findfirst('x', str) == nothing
    @test findfirst('\0', str) == nothing
    @test findfirst('\u80', str) == nothing
    @test findfirst('∀', str) == nothing
    @test findfirst('H', str) == 1
    @test findfirst('l', str) == 3
    @test findfirst('e', str) == 2
    @test findfirst('u', str) == nothing
    @test findnext('l', str, 4) == 4
    @test findnext('l', str, 5) == 11
    @test findnext('l', str, 12) == nothing
    @test findfirst(',', str) == 6
    @test findnext(',', str, 7) == nothing
    @test findfirst('\n', str) == 14
    @test findnext('\n', str, 15) == nothing
    @test_throws BoundsError findnext('ε', str, nextind(str,lastindex(str))+1)
    @test_throws BoundsError findnext('a', str, nextind(str,lastindex(str))+1)
end

# ascii backward search
for str in [astr]
    @test findlast(isequal('x'), str) == nothing
    @test findlast(isequal('\0'), str) == nothing
    @test findlast(isequal('\u80'), str) == nothing
    @test findlast(isequal('∀'), str) == nothing
    @test findlast(isequal('H'), str) == 1
    @test findprev(isequal('H'), str, 0) == nothing
    @test findlast(isequal('l'), str) == 11
    @test findprev(isequal('l'), str, 5) == 4
    @test findprev(isequal('l'), str, 4) == 4
    @test findprev(isequal('l'), str, 3) == 3
    @test findprev(isequal('l'), str, 2) == nothing
    @test findlast(isequal(','), str) == 6
    @test findprev(isequal(','), str, 5) == nothing
    @test findlast(isequal('\n'), str) == 14
end

for str in [astr]
    @test findlast('x', str) == nothing
    @test findlast('\0', str) == nothing
    @test findlast('\u80', str) == nothing
    @test findlast('∀', str) == nothing
    @test findlast('H', str) == 1
    @test findprev('H', str, 0) == nothing
    @test findlast('l', str) == 11
    @test findprev('l', str, 5) == 4
    @test findprev('l', str, 4) == 4
    @test findprev('l', str, 3) == 3
    @test findprev('l', str, 2) == nothing
    @test findlast(',', str) == 6
    @test findprev(',', str, 5) == nothing
    @test findlast('\n', str) == 14
end

# utf-8 forward search
for str in (u8str, GenericString(u8str))
    @test_throws BoundsError findnext(isequal('z'), str, 0)
    @test_throws BoundsError findnext(isequal('∀'), str, 0)
    @test findfirst(isequal('z'), str) == nothing
    @test findfirst(isequal('\0'), str) == nothing
    @test findfirst(isequal('\u80'), str) == nothing
    @test findfirst(isequal('∄'), str) == nothing
    @test findfirst(isequal('∀'), str) == 1
    @test_throws StringIndexError findnext(isequal('∀'), str, 2)
    @test findnext(isequal('∀'), str, 4) == nothing
    @test findfirst(isequal('∃'), str) == 13
    @test_throws StringIndexError findnext(isequal('∃'), str, 15)
    @test findnext(isequal('∃'), str, 16) == nothing
    @test findfirst(isequal('x'), str) == 26
    @test findnext(isequal('x'), str, 27) == 43
    @test findnext(isequal('x'), str, 44) == nothing
    @test findfirst(isequal('δ'), str) == 17
    @test_throws StringIndexError findnext(isequal('δ'), str, 18)
    @test findnext(isequal('δ'), str, nextind(str,17)) == 33
    @test findnext(isequal('δ'), str, nextind(str,33)) == nothing
    @test findfirst(isequal('ε'), str) == 5
    @test findnext(isequal('ε'), str, nextind(str,5)) == 54
    @test findnext(isequal('ε'), str, nextind(str,54)) == nothing
    @test findnext(isequal('ε'), str, nextind(str,lastindex(str))) == nothing
    @test findnext(isequal('a'), str, nextind(str,lastindex(str))) == nothing
    @test_throws BoundsError findnext(isequal('ε'), str, nextind(str,lastindex(str))+1)
    @test_throws BoundsError findnext(isequal('a'), str, nextind(str,lastindex(str))+1)
end

# utf-8 backward search
for str in [u8str]
    @test findlast(isequal('z'), str) == nothing
    @test findlast(isequal('\0'), str) == nothing
    @test findlast(isequal('\u80'), str) == nothing
    @test findlast(isequal('∄'), str) == nothing
    @test findlast(isequal('∀'), str) == 1
    @test findprev(isequal('∀'), str, 0) == nothing
    @test findlast(isequal('∃'), str) == 13
    @test findprev(isequal('∃'), str, 14) == 13
    @test findprev(isequal('∃'), str, 13) == 13
    @test findprev(isequal('∃'), str, 12) == nothing
    @test findlast(isequal('x'), str) == 43
    @test findprev(isequal('x'), str, 42) == 26
    @test findprev(isequal('x'), str, 25) == nothing
    @test findlast(isequal('δ'), str) == 33
    @test findprev(isequal('δ'), str, 32) == 17
    @test findprev(isequal('δ'), str, 16) == nothing
    @test findlast(isequal('ε'), str) == 54
    @test findprev(isequal('ε'), str, 53) == 5
    @test findprev(isequal('ε'), str, 4) == nothing
end

# string forward search with a single-char string
@test findfirst("x", astr) == nothing
@test findfirst("H", astr) == 1:1
@test findnext("H", astr, 2) == nothing
@test findfirst("l", astr) == 3:3
@test findnext("l", astr, 4) == 4:4
@test findnext("l", astr, 5) == 11:11
@test findnext("l", astr, 12) == nothing
@test findfirst("\n", astr) == 14:14
@test findnext("\n", astr, 15) == nothing

@test findfirst("z", u8str) == nothing
@test findfirst("∄", u8str) == nothing
@test findfirst("∀", u8str) == 1:1
@test findnext("∀", u8str, 4) == nothing
@test findfirst("∃", u8str) == 13:13
@test findnext("∃", u8str, 16) == nothing
@test findfirst("x", u8str) == 26:26
@test findnext("x", u8str, 27) == 43:43
@test findnext("x", u8str, 44) == nothing
@test findfirst("ε", u8str) == 5:5
@test findnext("ε", u8str, 7) == 54:54
@test findnext("ε", u8str, 56) == nothing

# strifindprev  backward search with a single-char string
@test findlast("x", astr) == nothing
@test findlast("H", astr) == 1:1
@test findprev("H", astr, 2) == 1:1
@test findprev("H", astr, 0) == nothing
@test findlast("l", astr) == 11:11
@test findprev("l", astr, 10) == 4:4
@test findprev("l", astr, 4) == 4:4
@test findprev("l", astr, 3) == 3:3
@test findprev("l", astr, 2) == nothing
@test findlast("\n", astr) == 14:14
@test findprev("\n", astr, 13) == nothing

@test findlast("z", u8str) == nothing
@test findlast("∄", u8str) == nothing
@test findlast("∀", u8str) == 1:1
@test findprev("∀", u8str, 0) == nothing
#TODO: setting the limit in the middle of a wide char
#      makes findnext fail but findprev succeed.
#      Should findprev fail as well?
#@test findprev("∀", u8str, 2) == nothing # gives 1:3
@test findlast("∃", u8str) == 13:13
@test findprev("∃", u8str, 12) == nothing
@test findlast("x", u8str) == 43:43
@test findprev("x", u8str, 42) == 26:26
@test findprev("x", u8str, 25) == nothing
@test findlast("ε", u8str) == 54:54
@test findprev("ε", u8str, 53) == 5:5
@test findprev("ε", u8str, 4) == nothing

# string forward search with a single-char regex
@test findfirst(r"x", astr) == nothing
@test findfirst(r"H", astr) == 1:1
@test findnext(r"H", astr, 2) == nothing
@test findfirst(r"l", astr) == 3:3
@test findnext(r"l", astr, 4) == 4:4
@test findnext(r"l", astr, 5) == 11:11
@test findnext(r"l", astr, 12) == nothing
@test findfirst(r"\n", astr) == 14:14
@test findnext(r"\n", astr, 15) == nothing
@test findfirst(r"z", u8str) == nothing
@test findfirst(r"∄", u8str) == nothing
@test findfirst(r"∀", u8str) == 1:1
@test findnext(r"∀", u8str, 4) == nothing
@test findfirst(r"∀", u8str) == findfirst(r"\u2200", u8str)
@test findnext(r"∀", u8str, 4) == findnext(r"\u2200", u8str, 4)
@test findfirst(r"∃", u8str) == 13:13
@test findnext(r"∃", u8str, 16) == nothing
@test findfirst(r"x", u8str) == 26:26
@test findnext(r"x", u8str, 27) == 43:43
@test findnext(r"x", u8str, 44) == nothing
@test findfirst(r"ε", u8str) == 5:5
@test findnext(r"ε", u8str, 7) == 54:54
@test findnext(r"ε", u8str, 56) == nothing
for i = 1:lastindex(astr)
    @test findnext(r"."s, astr, i) == i:i
end
for i = 1:lastindex(u8str)
    if isvalid(u8str,i)
        @test findnext(r"."s, u8str, i) == i:i
    end
end

# string forward search with a zero-char string
for i = 1:lastindex(astr)
    @test findnext("", astr, i) == i:i-1
end
for i = 1:lastindex(u8str)
    @test findnext("", u8str, i) == i:i-1
end
@test findfirst("", "") === 1:0

# string backward search with a zero-char string
for i = 1:lastindex(astr)
    @test findprev("", astr, i) == i:i-1
end
for i = 1:lastindex(u8str)
    @test findprev("", u8str, i) == i:i-1
end
@test findlast("", "") === 1:0

# string forward search with a zero-char regex
for i = 1:lastindex(astr)
    @test findnext(r"", astr, i) == i:i-1
end
for i = 1:lastindex(u8str)
    # TODO: should regex search fast-forward invalid indices?
    if isvalid(u8str,i)
        @test findnext(r"", u8str, i) == i:i-1
    end
end

# string forward search with a two-char string literal
@test findfirst("xx", "foo,bar,baz") == nothing
@test findfirst("fo", "foo,bar,baz") == 1:2
@test findnext("fo", "foo,bar,baz", 3) == nothing
@test findfirst("oo", "foo,bar,baz") == 2:3
@test findnext("oo", "foo,bar,baz", 4) == nothing
@test findfirst("o,", "foo,bar,baz") == 3:4
@test findnext("o,", "foo,bar,baz", 5) == nothing
@test findfirst(",b", "foo,bar,baz") == 4:5
@test findnext(",b", "foo,bar,baz", 6) == 8:9
@test findnext(",b", "foo,bar,baz", 10) == nothing
@test findfirst("az", "foo,bar,baz") == 10:11
@test findnext("az", "foo,bar,baz", 12) == nothing

# issue #9365
# string forward search with a two-char UTF-8 (2 byte) string literal
@test findfirst("éé", "ééé") == 1:3
@test findnext("éé", "ééé", 1) == 1:3
# string forward search with a two-char UTF-8 (3 byte) string literal
@test findfirst("€€", "€€€") == 1:4
@test findnext("€€", "€€€", 1) == 1:4
# string forward search with a two-char UTF-8 (4 byte) string literal
@test findfirst("\U1f596\U1f596", "\U1f596\U1f596\U1f596") == 1:5
@test findnext("\U1f596\U1f596", "\U1f596\U1f596\U1f596", 1) == 1:5

# string forward search with a two-char UTF-8 (2 byte) string literal
@test findfirst("éé", "éé") == 1:3
@test findnext("éé", "éé", 1) == 1:3
# string forward search with a two-char UTF-8 (3 byte) string literal
@test findfirst("€€", "€€") == 1:4
@test findnext("€€", "€€", 1) == 1:4
# string forward search with a two-char UTF-8 (4 byte) string literal
@test findfirst("\U1f596\U1f596", "\U1f596\U1f596") == 1:5
@test findnext("\U1f596\U1f596", "\U1f596\U1f596", 1) == 1:5

# string backward search with a two-char UTF-8 (2 byte) string literal
@test findlast("éé", "ééé") == 3:5
@test findprev("éé", "ééé", lastindex("ééé")) == 3:5
# string backward search with a two-char UTF-8 (3 byte) string literal
@test findlast("€€", "€€€") == 4:7
@test findprev("€€", "€€€", lastindex("€€€")) == 4:7
# string backward search with a two-char UTF-8 (4 byte) string literal
@test findlast("\U1f596\U1f596", "\U1f596\U1f596\U1f596") == 5:9
@test findprev("\U1f596\U1f596", "\U1f596\U1f596\U1f596", lastindex("\U1f596\U1f596\U1f596")) == 5:9

# string backward search with a two-char UTF-8 (2 byte) string literal
@test findlast("éé", "éé") == 1:3        # should really be 1:4!
@test findprev("éé", "éé", lastindex("ééé")) == 1:3
# string backward search with a two-char UTF-8 (3 byte) string literal
@test findlast("€€", "€€") == 1:4        # should really be 1:6!
@test findprev("€€", "€€", lastindex("€€€")) == 1:4
# string backward search with a two-char UTF-8 (4 byte) string literal
@test findlast("\U1f596\U1f596", "\U1f596\U1f596") == 1:5        # should really be 1:8!
@test findprev("\U1f596\U1f596", "\U1f596\U1f596", lastindex("\U1f596\U1f596\U1f596")) == 1:5

# string backward search with a two-char string literal
@test findlast("xx", "foo,bar,baz") == nothing
@test findlast("fo", "foo,bar,baz") == 1:2
@test findprev("fo", "foo,bar,baz", 1) == nothing
@test findlast("oo", "foo,bar,baz") == 2:3
@test findprev("oo", "foo,bar,baz", 2) == nothing
@test findlast("o,", "foo,bar,baz") == 3:4
@test findprev("o,", "foo,bar,baz", 1) == nothing
@test findlast(",b", "foo,bar,baz") == 8:9
@test findprev(",b", "foo,bar,baz", 6) == 4:5
@test findprev(",b", "foo,bar,baz", 3) == nothing
@test findlast("az", "foo,bar,baz") == 10:11
@test findprev("az", "foo,bar,baz", 10) == nothing

# string search with a two-char regex
@test findfirst(r"xx", "foo,bar,baz") == nothing
@test findfirst(r"fo", "foo,bar,baz") == 1:2
@test findnext(r"fo", "foo,bar,baz", 3) == nothing
@test findfirst(r"oo", "foo,bar,baz") == 2:3
@test findnext(r"oo", "foo,bar,baz", 4) == nothing
@test findfirst(r"o,", "foo,bar,baz") == 3:4
@test findnext(r"o,", "foo,bar,baz", 5) == nothing
@test findfirst(r",b", "foo,bar,baz") == 4:5
@test findnext(r",b", "foo,bar,baz", 6) == 8:9
@test findnext(r",b", "foo,bar,baz", 10) == nothing
@test findfirst(r"az", "foo,bar,baz") == 10:11
@test findnext(r"az", "foo,bar,baz", 12) == nothing

# occursin with a String and Char needle
@test occursin("o", "foo")
@test occursin('o', "foo")

# contains
@test contains("foo", "o")
@test contains("foo", 'o')
# contains in curried form
@test contains("o")("foo")
@test contains('o')("foo")

@test_throws ErrorException "ab" ∈ "abc"

# issue #15723
@test findfirst(isequal('('), "⨳(") == 4
@test findnext(isequal('('), "(⨳(", 2) == 5
@test findlast(isequal('('), "(⨳(") == 5
@test findprev(isequal('('), "(⨳(", 2) == 1

@test @inferred findall(isequal('a'), "éa") == [3]
@test @inferred findall(isequal('€'), "€€") == [1, 4]
@test @inferred isempty(findall(isequal('é'), ""))

# issue #18109
s_18109 = "fooα🐨βcd3"
@test findlast(isequal('o'), s_18109) == 3
@test findfirst(isequal('d'), s_18109) == 13

# findall (issue #31788)
@testset "findall" begin
    @test findall("fooo", "foo") == UnitRange{Int}[]
    @test findall("ing", "Spinning laughing dancing") == [6:8, 15:17, 23:25]
    @test all(findall("", "foo") .=== [1:0, 2:1, 3:2, 4:3]) # use === to compare empty ranges
    @test findall("αβ", "blαh blαβ blαββy") == findall("αβ", "blαh blαβ blαββy", overlap=true) == [9:11, 16:18]
    @test findall("aa", "aaaaaa") == [1:2, 3:4, 5:6]
    @test findall("aa", "aaaaaa", overlap=true) == [1:2, 2:3, 3:4, 4:5, 5:6]
end

# issue 37280
@testset "UInt8, Int8 vector" begin
    for T in [Int8, UInt8], VT in [Int8, UInt8]
        A = T[0x40, 0x52, 0x62, 0x52, 0x62]

        @test findfirst(VT[0x30], A) === nothing
        @test findfirst(VT[0x52], A) === 2:2
        @test findlast(VT[0x30], A) === nothing
        @test findlast(VT[0x52], A) === 4:4

        pattern = VT[0x52, 0x62]

        @test findfirst(pattern, A) === 2:3
        @test findnext(pattern, A, 2) === 2:3
        @test findnext(pattern, A, 3) === 4:5
        # 1 idx too far is allowed
        @test findnext(pattern, A, length(A)+1) === nothing
        @test_throws BoundsError findnext(pattern, A, -3)
        @test_throws BoundsError findnext(pattern, A, length(A)+2)

        @test findlast(pattern, A) === 4:5
        @test findprev(pattern, A, 3) === 2:3
        @test findprev(pattern, A, 5) === 4:5
        @test findprev(pattern, A, 2) === nothing
        @test findprev(pattern, A, length(A)+1) == findlast(pattern, A)
        @test findprev(pattern, A, length(A)+2) == findlast(pattern, A)
        @test_throws BoundsError findprev(pattern, A, -3)
    end
end

# issue 32568
for T = (UInt, BigInt)
    for x = (4, 5)
        @test eltype(findnext(r"l", astr, T(x))) == Int
        @test findnext(isequal('l'), astr, T(x)) isa Int
        @test findprev(isequal('l'), astr, T(x)) isa Int
        @test findnext('l', astr, T(x)) isa Int
        @test findprev('l', astr, T(x)) isa Int
    end
    for x = (5, 6)
        @test eltype(findprev(",b", "foo,bar,baz", T(x))) == Int
    end
    for x = (7, 8)
        @test eltype(findnext(",b", "foo,bar,baz", T(x))) == Int
        @test findnext(isletter, astr, T(x)) isa Int
        @test findprev(isletter, astr, T(x)) isa Int
    end
end

max_stars_repo_name: vanillajonathan/julia

max_issues_repo_name: vanillajonathan/julia

max_forks_repo_name: vanillajonathan/julia


text:
RESIDUAL_EXPR = Dict{String, Any}()
residual_expr(model::Model) = RESIDUAL_EXPR[String(name(model)) * "_r"]
jacobian_var_expr(model::Model) = RESIDUAL_EXPR[String(name(model)) * "_rz"]
jacobian_data_expr(model::Model) = RESIDUAL_EXPR[String(name(model)) * "_rθ"]

path_robots = @get_scratch!("robots")

robots = [hopper, hopper1, biped, quadruped, quadruped4, halfquadruped, halfcheetah, halfcheetah4, box, particle, centroidal_quadruped, point_foot_quadruped]

for robot in robots
    path = joinpath(path_robots, String(name(robot)) * ".jld2")

    if !isfile(path)
        # kinematics
        contact_kinematics = eval(Symbol(String(name(robot)) * "_contact_kinematics"))
        contact_kinematics_jacobians = eval(Symbol(String(name(robot)) * "_contact_kinematics_jacobians"))

        # codegen
        r_model, rz_model, rθ_model = codegen_residual(eval(robot), codegen_dynamics(eval(robot))..., contact_kinematics, contact_kinematics_jacobians)
        @save path r_model rz_model rθ_model
    else
        @load path r_model rz_model rθ_model
    end

    RESIDUAL_EXPR[String(name(robot)) * "_r"] = eval(r_model)
    RESIDUAL_EXPR[String(name(robot)) * "_rz"] = eval(rz_model)
    RESIDUAL_EXPR[String(name(robot)) * "_rθ"] = eval(rθ_model)
end


text:
module PoissonDGTests

using Test
using Gridap
import Gridap: ∇
using LinearAlgebra

#domain = (0,1,0,1)
#partition = (4,4)
#model = CartesianDiscreteModel(domain,partition)
#const h = (domain[2]-domain[1]) / partition[1]

using Gridap.Geometry: DiscreteModelMock
model = DiscreteModelMock()
const h = 1

order = 2
const γ = 10

trian = get_triangulation(model)
degree = order
quad = CellQuadrature(trian,degree)

btrian = BoundaryTriangulation(model)
bdegree = order
bquad = CellQuadrature(btrian,bdegree)
const bn = get_normal_vector(btrian)

strian = SkeletonTriangulation(model)
sdegree = order
squad = CellQuadrature(strian,sdegree)
const sn = get_normal_vector(strian)

u_scal(x) = x[1]^2 + x[2]
∇u_scal(x) = VectorValue( 2*x[1], one(x[2]) )
Δu_scal(x) = 2
f_scal(x) = - Δu_scal(x)
∇(::typeof(u_scal)) = ∇u_scal

T = Float64
u = u_scal
f = f_scal

V = TestFESpace(
 model=model,
 order=order,
 reffe=:Lagrangian,
 conformity=:L2,
 valuetype=T)

U = TrialFESpace(V,u)

a(u,v) = ∇(v)⋅∇(u)
l(v) = v*f
t_Ω = AffineFETerm(a,l,trian,quad)

a_Γd(u,v) = (γ/h)*v*u  - v*(bn⋅∇(u)) - (bn⋅∇(v))*u
l_Γd(v) = (γ/h)*v*u - (bn⋅∇(v))*u
t_Γd = AffineFETerm(a_Γd,l_Γd,btrian,bquad)

a_Γ(u,v) = (γ/h)*jump(v*sn)⋅jump(u*sn) - jump(v*sn)⋅mean(∇(u)) -  mean(∇(v))⋅jump(u*sn)
t_Γ = LinearFETerm(a_Γ,strian,squad)

op = AffineFEOperator(U,V,t_Ω,t_Γ,t_Γd)

uh = solve(op)

e = u - uh

l2(u) = inner(u,u)
sh1(u) = a(u,u)
h1(u) = sh1(u) + l2(u)

el2 = sqrt(sum( integrate(l2(e),trian,quad) ))
eh1 = sqrt(sum( integrate(h1(e),trian,quad) ))
ul2 = sqrt(sum( integrate(l2(uh),trian,quad) ))
uh1 = sqrt(sum( integrate(h1(uh),trian,quad) ))

@test el2/ul2 < 1.e-8
@test eh1/uh1 < 1.e-7

end # module


text:
#concordance dict between ANZSIC divisions (19 sectors) and various other industry classifications
using XLSX, ExcelReaders, DataFrames, Tables, JuMP, Ipopt, NamedArrays, DelimitedFiles, CSV;

#filepath cross system compatability code
if Sys.KERNEL === :NT || Sys.KERNEL === :Windows
    pathmark = "\\";
else
    pathmark = "/";
end

#19 Sector to 4 Sector
from19To4 = Dict("A"=> "Primary",
"B" => "Primary",
"C" => "Secondary",
"D" => "Secondary",
"E" => "Secondary",
"F" => "Tertiary",
"G" => "Tertiary",
"H" => "Tertiary",
"I" => "Tertiary",
"J" => "Tertiary",
"K" => "Tertiary",
"L" => "Tertiary",
"M" => "Tertiary",
"N" => "Tertiary",
"O" => "Tertiary",
"P" => "Tertiary",
"Q" => "Tertiary",
"R" => "Tertiary",
"S" => "Tertiary")

#IOIG to 19 Sector
IOSource = ExcelReaders.readxlsheet("data"*pathmark*"5209055001DO001_201819.xls", "Table 5");
IOIG = IOSource[4:117, 1];
ANZSICDiv = ["Agriculture, forestry and fishing", "Mining", "Manufacturing", "Electricity, gas, water and waste services",
"Construction", "Wholesale trade", "Retail trade", "Accomodation and food services",
"Transport, postal and warehousing", "Information media and telecommunications", "Financial and insurance services",
"Rental, hiring and real estate services", "Professional, scientific and technical services",
"Administrative and support services", "Public administration and safety", "Education and training",
"Health care and social assistance", "Arts and recreation services", "Other services"];
ANZSICDivShort = ["AgrForestFish", "Mining", "Manufacturing", "Utilities", "Construction", "Wholesale", "Retail", "AccomFoodServ",
"Transport&Ware", "Communications", "Finance&Insur", "RealEstate", "BusinessServ", "Admin", "PublicAdminSafe",
"Education", "Health&Social", "Arts&Rec", "OtherServices"];
ANZSICDivByLetter =["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S"];
from19ToInd = Dict{String, Int64}();
for i in eachindex(ANZSICDivByLetter);
    from19ToInd[ANZSICDivByLetter[i]] = Int(i);
end
IOIGTo19 = Dict{Float64, String}();
for i in [1:1:114;];
    test = trunc(IOIG[i]/100);
    if 1 <= test <= 5
        IOIGTo19[IOIG[i]]="A"
    elseif 6 <= test <= 10;
        IOIGTo19[IOIG[i]]="B"
    elseif 11 <= test <= 25;
        IOIGTo19[IOIG[i]]="C"
    elseif 26 <= test <= 29;
        IOIGTo19[IOIG[i]]="D"
    elseif 30 <= test <= 32;
        IOIGTo19[IOIG[i]]="E"
    elseif 33 <= test <= 38;
        IOIGTo19[IOIG[i]]="F"
    elseif 39 <= test <= 43;
        IOIGTo19[IOIG[i]]="G"
    elseif 44 <= test <= 45;
        IOIGTo19[IOIG[i]]="H"
    elseif 46 <= test <= 53;
        IOIGTo19[IOIG[i]]="I"
    elseif 54 <= test <= 60;
        IOIGTo19[IOIG[i]]="J"
    elseif 62 <= test <= 64;
        IOIGTo19[IOIG[i]]="K"
    elseif 66 <= test <= 67;
        IOIGTo19[IOIG[i]]="L"
    elseif 69 <= test <= 70;
        IOIGTo19[IOIG[i]]="M"
    elseif 72 <= test <= 73;
        IOIGTo19[IOIG[i]]="N"
    elseif 75 <= test <= 77;
        IOIGTo19[IOIG[i]]="O"
    elseif 80 <= test <= 82;
        IOIGTo19[IOIG[i]]="P"
    elseif 84 <= test <= 87;
        IOIGTo19[IOIG[i]]="Q"
    elseif 89 <= test <= 92;
        IOIGTo19[IOIG[i]]="R"
    elseif 94 <= test <= 96;
        IOIGTo19[IOIG[i]]="S"
    else
        print("ERROR: An input has fallen outside of the range of categories")
    end
end

#ISIC 4.0 To 19 Sectors
ANZSICISICSource = CSV.read("data"*pathmark*"ANZSIC06-ISIC3pt1.csv", DataFrame);
ANZSIC19 = ANZSICISICSource[6:1484, 1][findall(x -> typeof(x)<:String, ANZSICISICSource[6:1484, 4])];
ISIC = ANZSICISICSource[6:1484, 4][findall(x -> typeof(x)<:String, ANZSICISICSource[6:1484, 4])];
for i in eachindex(ISIC);
    ISIC[i]=strip(ISIC[i], ['p']);
end
ISICTo19 = Dict(ISIC .=> ANZSIC19);

#NAIC2007 To 19 Sectors via ISIC 4.0
NAICSISICSource = ExcelReaders.readxlsheet("data"*pathmark*"2007_NAICS_to_ISIC_4.xls", "NAICS 07 to ISIC 4 technical");
NAICS = string.(Int.(NAICSISICSource[4:1768,1]));
ISICAsANZSIC = NAICSISICSource[4:1768,3];
ISICAsANZSIC = string.(ISICAsANZSIC);
containsX = findall( x -> occursin("X", x), ISICAsANZSIC);
ISICAsANZSIC[containsX] = replace.(ISICAsANZSIC[containsX], "X" => "1");
ISICAsANZSIC = parse.(Float64, ISICAsANZSIC);
NAICSANZSIC19 = string.(zeros(length(ISICAsANZSIC)));
for i in eachindex(ISICAsANZSIC);
    NAICSANZSIC19[i] = ISICTo19[lpad(Int(ISICAsANZSIC[i]),4,"0")];
end
NAICS07To19 = Dict(NAICS .=> NAICSANZSIC19);

#NAIC2002 To 19 Sectors via NAIC2007
NAICS02To07 = CSV.read("data"*pathmark*"2002_to_2007_NAICS.csv", DataFrame);
NAICS02To0702 = string.(NAICS02To07[3:1202, 1]);
NAICS02To0707 = string.(NAICS02To07[3:1202, 3]);
NAICS07As19 = string.(zeros(length(NAICS02To0707)));
for i in eachindex(NAICS02To0707);
    NAICS07As19[i] = NAICS07To19[NAICS02To0707[i]];
end
NAICS02To19 = Dict(NAICS02To0702 .=> NAICS07As19);

#NAIC1997 To 19 Sectors via NAIC2002
NAICS97To02 = CSV.read("data"*pathmark*"1997_NAICS_to_2002_NAICS.csv", DataFrame);
NAICS97To0297 = string.(NAICS97To02[1:1355, 1]);
NAICS97To0202 = string.(NAICS97To02[1:1355, 3]);
NAICS02As19 = string.(zeros(length(NAICS97To0202)));
for i in eachindex(NAICS97To0202);
    NAICS02As19[i] = NAICS02To19[NAICS97To0202[i]];
end
NAICS97To19 = Dict(NAICS97To0297 .=> NAICS02As19);
NAICS97To0297Trunc = first.(string.(NAICS97To02[1:1355, 1]),4);
NAICS97To19Trunc = Dict(NAICS97To0297Trunc .=> NAICS02As19);

#Comm180 To 19 Sectors via NAIC 1997
NAICS97ToComm180 = CSV.read("data"*pathmark*"NAICS_to_Comm180.csv", DataFrame);
NAICS97ToComm18097 = first.([NAICS97ToComm180[1:90,4];NAICS97ToComm180[1:89,9]],4);
containsStar = findall( x -> occursin("*", x), NAICS97ToComm18097);
NAICS97ToComm18097[containsStar] = replace.(NAICS97ToComm18097[containsStar], "*" => "");
tooShort = findall( x -> occursin(",", x), NAICS97ToComm18097);
NAICS97ToComm18097[tooShort] = first.(NAICS97ToComm18097[tooShort],2);
NAICS97ToComm180180 = [NAICS97ToComm180[1:90,2];NAICS97ToComm180[1:89,7]];
containsStar = findall( x -> occursin("*", x), NAICS97ToComm180180);
NAICS97ToComm180180[containsStar] = replace.(NAICS97ToComm180180[containsStar], "*" => "");
containsSpace = findall( x -> occursin(" ", x), NAICS97ToComm180180);
NAICS97ToComm180180[containsSpace] = replace.(NAICS97ToComm180180[containsSpace], " " => "");
NAICS97As19 = string.(zeros(length(NAICS97ToComm18097)));
for i in eachindex(NAICS97ToComm18097);
    NAICS97ToComm18097[i] = rpad(parse(Int64, NAICS97ToComm18097[i]),4,"1");
end
Invalid4Dig = findall( x -> occursin("2311", x), NAICS97ToComm18097);
NAICS97ToComm18097[Invalid4Dig].=["2331"];
for i in eachindex(NAICS97ToComm18097);
    NAICS97As19[i] = NAICS97To19Trunc[NAICS97ToComm18097[i]];
end
Comm180To19=Dict(NAICS97ToComm180180 .=> NAICS97As19);

#Final concordance
finalConcordance = [NAICS97ToComm180180 NAICS97As19];
writedlm("data"*pathmark*"Comm180To19Concordance.csv", finalConcordance, ',');

max_stars_repo_name: uq-aibe/Capital

max_issues_repo_name: uq-aibe/Capital

max_forks_repo_name: uq-aibe/Capital


text:
JuMP.num_variables(m::AbstractBilevelModel) = JuMP.num_variables(bilevel_model(m))
_plural(n) = (isone(n) ? "" : "s")
function JuMP.show_constraints_summary(io::IO, model::BilevelModel)
    JuMP.show_constraints_summary(io, Upper(model))
    JuMP.show_constraints_summary(io, Lower(model), true)
end
function JuMP.show_constraints_summary(io::IO, model::UpperModel)
    n = JuMP.num_constraints(model)
    println(io, "Upper Constraint", _plural(n), ": ", n)
end
function JuMP.show_constraints_summary(io::IO, model::LowerModel, line_break = false)
    n = JuMP.num_constraints(model)
    print(io, "Lower Constraint", _plural(n), ": ", n, ifelse(line_break, "\n",""))
end
JuMP.show_backend_summary(io::IO, model::InnerBilevelModel) = JuMP.show_backend_summary(io, model.m)
function JuMP.show_backend_summary(io::IO, model::BilevelModel)
    println(io, "Bilevel Model")
    println(io, "Solution method: ", model.mode)
    if model.solver === nothing
        print(io, "No solver attached")
    else
        name = JuMP.solver_name(model::BilevelModel)
        print(io, "Solver name: ", name)
    end
end
function JuMP.solver_name(model::BilevelModel)
    name = try
        MOI.get(model.solver, MOI.SolverName())::String
    catch ex
        if isa(ex, ArgumentError)
            return "SolverName() attribute not implemented by the optimizer."
        else
            rethrow(ex)
        end
    end
end

function JuMP.show_objective_function_summary(io::IO, model::UpperModel)
    println(io, "Upper objective function type: \n",
            JuMP.objective_function_type(model))
end
function JuMP.show_objective_function_summary(io::IO, model::LowerModel)
    println(io, "Lower objective function type: \n",
            JuMP.objective_function_type(model))
end
function JuMP.show_objective_function_summary(io::IO, model::BilevelModel)
    JuMP.show_objective_function_summary(io, Upper(model))
    JuMP.show_objective_function_summary(io, Lower(model))
end


text:
# Windows:
# set JULIA_NUM_THREADS=4

# Linux:
# export JULIA_NUM_THREADS=4

using Random

Threads.nthreads()

Threads.@threads for i in 1:10
    println("i = $i on thread $(Threads.threadid())")
end

Threads.@threads for i in 1:10
    println(Threads.threadid()=>pointer_from_objref(Random.default_rng()))
end

function fib1(n)
    if n < 2
        return n
    end
    return fib1(n - 1) + fib1(n - 2)
end

function fib2(n)
    if n < 2
        return n
    end
    t = Threads.@spawn fib2(n - 2)
    return fib2(n - 1) + fetch(t)
end

function fib3(n, cutoff)
    if n < cutoff
        return fib1(n)
    end
    t = Threads.@spawn fib3(n - 2, cutoff)
    return fib3(n - 1, cutoff) + fetch(t)
end

fib1(31)
fib2(31)
fib3(31, 28)

@time fib1(31)
@time fib2(31)
@time fib3(31, 28)

@time fib1(43)
@time fib3(43, 40)

function f_bad(n)
    x = 0
    Threads.@threads for i in 1:n
        x += rand() < 0.5
    end
    x / n
end

function f_good_slow1(n)
    r = ReentrantLock()
    x = 0
    Threads.@threads for i in 1:n
        lock(r)
        x += rand() < 0.5
        unlock(r)
    end
    x / n
end

function f_good_slow2(n)
    x = Threads.Atomic{Int}(0)
    Threads.@threads for i in 1:n
        Threads.atomic_add!(x, Int(rand() < 0.5))
    end
    x[] / n
end

function f_good_slow3(n)
    x = zeros(Int, Threads.nthreads())
    Threads.@threads for i in 1:n
        @inbounds x[Threads.threadid()] += rand() < 0.5
    end
    sum(x) / n
end

function f_good_slow4(n)
    x = zeros(Int, 4*Threads.nthreads())
    Threads.@threads for i in 1:n
        @inbounds x[4*Threads.threadid()] += rand() < 0.5
    end
    sum(x) / n
end

function f_good_fast1(n)
    nt = Threads.nthreads()
    x = zeros(Int, nt)
    Threads.@threads for i in 1:nt
        tid = Threads.threadid()
        v = 0
        for j in 1:(div(n, nt) + (tid <= mod(n, nt)))
            v += rand() < 0.5
        end
        x[tid] = v
    end
    sum(x) / n
end

function f_good_fast2(n)
    nt = Threads.nthreads()
    x = 0
    r = ReentrantLock()
    Threads.@threads for i in 1:nt
        tid = Threads.threadid()
        v = 0
        for j in 1:(div(n, nt) + (tid <= mod(n, nt)))
            v += rand() < 0.5
        end
        lock(r)
        x += v
        unlock(r)
    end
    x / n
end

f_bad(10^8)
f_good_slow1(10^6)
f_good_slow2(10^8)
f_good_slow3(10^8)
f_good_slow4(10^8)
f_good_fast1(10^8)
f_good_fast2(10^8)

@time f_bad(10^8)
@time f_good_slow1(10^6)
@time f_good_slow2(10^8)
@time f_good_slow3(10^8)
@time f_good_slow4(10^8)
@time f_good_fast1(10^8)
@time f_good_fast2(10^8)

max_stars_repo_name: bkamins/WarszawskieForumJulia

max_issues_repo_name: bkamins/WarszawskieForumJulia

max_forks_repo_name: bkamins/WarszawskieForumJulia


text:
# Here the different standard solvers in the ODE packages are setup.
module Solvers
using Requires
using IVPTestSuite

const adaptive = true
const nonadaptive = false

const allsolvers = Dict{Any,Solver}() # to hold all solvers

# helper
function nonmod_fn{N,T}(tc::TestCase{N,T})
    fn(t,y) = (out = tc.fn!(); tc.fn!(t,y,out); out)
    return fn
end
function nonmod_jac{N,T}(tc::TestCase{N,T})
    jac(t,y) = (out = tc.jac!(); tc.jac!(t,y,out); out)
    return jac
end
function nonmod_mass{N,T}(tc::TestCase{N,T})
    mass(t,y) = (out = tc.mass!(); tc.mass!(t,y,out); out)
    return mass
end

include("ODE.jl")
include("DASSL.jl")
include("Sundials.jl")

end # module


text:
module BirkhoffDecomposition

    using JuMP
    using Clp
    using Random
    using SparseArrays

    function __init__()

    end

    include("functionsBD.jl")
    include("birkdecomp.jl")
    include("extremepoints.jl")
    include("stepsizes.jl")

    export randomDoublyStochasticMatrix
    export birkdecomp

end # module


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

module CPUID

export cpu_isa

"""
    ISA(features::Set{UInt32})

A structure which represents the Instruction Set Architecture (ISA) of a
computer.  It holds the `Set` of features of the CPU.

The numerical values of the features are automatically generated from the C
source code of Julia and stored in the `features_h.jl` Julia file.
"""
struct ISA
    features::Set{UInt32}
end

Base.:<=(a::ISA, b::ISA) = a.features <= b.features
Base.:<(a::ISA,  b::ISA) = a.features <  b.features
Base.isless(a::ISA,  b::ISA) = a < b

include("../features_h.jl")

# Keep in sync with `arch_march_isa_mapping`.
const ISAs_by_family = Dict(
    "i686" => [
        # Source: https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html.
        # Implicit in all sets, because always required by Julia: mmx, sse, sse2
        "pentium4" => ISA(Set{UInt32}()),
        "prescott" => ISA(Set((JL_X86_sse3,))),
    ],
    "x86_64" => [
        # Source: https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html.
        # Implicit in all sets, because always required by x86-64 architecture: mmx, sse, sse2
        "x86_64" => ISA(Set{UInt32}()),
        "core2" => ISA(Set((JL_X86_sse3, JL_X86_ssse3))),
        "nehalem" => ISA(Set((JL_X86_sse3, JL_X86_ssse3, JL_X86_sse41, JL_X86_sse42, JL_X86_popcnt))),
        "sandybridge" => ISA(Set((JL_X86_sse3, JL_X86_ssse3, JL_X86_sse41, JL_X86_sse42, JL_X86_popcnt, JL_X86_avx, JL_X86_aes, JL_X86_pclmul))),
        "haswell" => ISA(Set((JL_X86_movbe, JL_X86_sse3, JL_X86_ssse3, JL_X86_sse41, JL_X86_sse42, JL_X86_popcnt, JL_X86_avx, JL_X86_avx2, JL_X86_aes, JL_X86_pclmul, JL_X86_fsgsbase, JL_X86_rdrnd, JL_X86_fma, JL_X86_bmi, JL_X86_bmi2, JL_X86_f16c))),
        "skylake" => ISA(Set((JL_X86_movbe, JL_X86_sse3, JL_X86_ssse3, JL_X86_sse41, JL_X86_sse42, JL_X86_popcnt, JL_X86_avx, JL_X86_avx2, JL_X86_aes, JL_X86_pclmul, JL_X86_fsgsbase, JL_X86_rdrnd, JL_X86_fma, JL_X86_bmi, JL_X86_bmi2, JL_X86_f16c, JL_X86_rdseed, JL_X86_adx, JL_X86_prfchw, JL_X86_clflushopt, JL_X86_xsavec, JL_X86_xsaves))),
        "skylake_avx512" => ISA(Set((JL_X86_movbe, JL_X86_sse3, JL_X86_ssse3, JL_X86_sse41, JL_X86_sse42, JL_X86_popcnt, JL_X86_pku, JL_X86_avx, JL_X86_avx2, JL_X86_aes, JL_X86_pclmul, JL_X86_fsgsbase, JL_X86_rdrnd, JL_X86_fma, JL_X86_bmi, JL_X86_bmi2, JL_X86_f16c, JL_X86_rdseed, JL_X86_adx, JL_X86_prfchw, JL_X86_clflushopt, JL_X86_xsavec, JL_X86_xsaves, JL_X86_avx512f, JL_X86_clwb, JL_X86_avx512vl, JL_X86_avx512bw, JL_X86_avx512dq, JL_X86_avx512cd))),
    ],
    "armv6l" => [
        # The only armv6l processor we know of that runs Julia on armv6l
        # We don't have a good way to tell the different armv6l variants apart through features,
        # and honestly we don't care much since it's basically this one chip that people want to use with Julia.
        "arm1176jzfs" => ISA(Set{UInt32}()),
    ],
    "armv7l" => [
        "armv7l" => ISA(Set{UInt32}()),
        "armv7l+neon" => ISA(Set((JL_AArch32_neon,))),
        "armv7l+neon+vfpv4" => ISA(Set((JL_AArch32_neon, JL_AArch32_vfp4))),
    ],
    "aarch64" => [
        # Implicit in all sets, because always required: fp, asimd
        "armv8.0-a" => ISA(Set{UInt32}()),
        "armv8.1-a" => ISA(Set((JL_AArch64_v8_1a, JL_AArch64_lse, JL_AArch64_crc, JL_AArch64_rdm))),
        "armv8.2-a+crypto" => ISA(Set((JL_AArch64_v8_2a, JL_AArch64_lse, JL_AArch64_crc, JL_AArch64_rdm, JL_AArch64_aes, JL_AArch64_sha2))),
        "a64fx" => ISA(Set((JL_AArch64_v8_2a, JL_AArch64_lse, JL_AArch64_crc, JL_AArch64_rdm, JL_AArch64_sha2, JL_AArch64_ccpp, JL_AArch64_complxnum, JL_AArch64_fullfp16, JL_AArch64_sve))),
        "apple_m1" => ISA(Set((JL_AArch64_v8_5a, JL_AArch64_lse, JL_AArch64_crc, JL_AArch64_rdm, JL_AArch64_aes, JL_AArch64_sha2, JL_AArch64_sha3, JL_AArch64_ccpp, JL_AArch64_complxnum, JL_AArch64_fp16fml, JL_AArch64_fullfp16, JL_AArch64_dotprod, JL_AArch64_rcpc, JL_AArch64_altnzcv))),
    ],
    "powerpc64le" => [
        # We have no way to test powerpc64le features yet, so we're only going to declare the lowest ISA:
        "power8" => ISA(Set{UInt32}()),
    ]
)

# Test a CPU feature exists on the currently-running host
test_cpu_feature(feature::UInt32) = ccall(:jl_test_cpu_feature, Bool, (UInt32,), feature)

# Normalize some variation in ARCH values (which typically come from `uname -m`)
function normalize_arch(arch::String)
    arch = lowercase(arch)
    if arch ∈ ("amd64",)
        arch = "x86_64"
    elseif arch ∈ ("i386", "i486", "i586")
        arch = "i686"
    elseif arch ∈ ("armv6",)
        arch = "armv6l"
    elseif arch ∈ ("arm", "armv7", "armv8", "armv8l")
        arch = "armv7l"
    elseif arch ∈ ("arm64",)
        arch = "aarch64"
    elseif arch ∈ ("ppc64le",)
        arch = "powerpc64le"
    end
    return arch
end

let
    # Collect all relevant features for the current architecture, if any.
    FEATURES = UInt32[]
    arch = normalize_arch(String(Sys.ARCH))
    if arch in keys(ISAs_by_family)
        for isa in ISAs_by_family[arch]
            unique!(append!(FEATURES, last(isa).features))
        end
    end

    # Use `@eval` to inline the list of features.
    @eval function cpu_isa()
        return ISA(Set{UInt32}(feat for feat in $(FEATURES) if test_cpu_feature(feat)))
    end
end

"""
    cpu_isa()

Return the [`ISA`](@ref) (instruction set architecture) of the current CPU.
"""
cpu_isa

end # module CPUID

max_stars_repo_name: Physolia/julia

max_issues_repo_name: Eurus-Holmes/julia

max_forks_repo_name: Nexuscompute/julia


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

using Markdown
using InteractiveUtils

# ╔═╡ 48b0d87e-6d87-4ea4-8ff2-8a0bd1622e06
begin
	using PyCall
	using PyPlot
end

# ╔═╡ f71a4046-2d1e-43eb-ab58-9abfb71838bd
md"
# Simulation of bacterial chemotaxis using the Metropolis algorithm"

# ╔═╡ 92d70ea7-a645-4b86-8b52-13c0d7e8cebf
md"## Gradient concentration"

# ╔═╡ cad72d1c-fe96-11eb-31d4-bb1ecc023f48
begin
	g_00(x) = 0;
	g_0001(x) = -0.0006/(0.715*exp(-0.0056*x)+0.684)+0.00093;
	g_001(x) = -0.009/(1.027*exp(-0.005*x)+1)+0.0095;   ## concentration = 0.01 ##
	g_01(x) = -0.09/(1.34*exp(-0.005*x)+1.04)+0.092;     ## concentration = 0.1 ##
	g_1(x) = -0.9/(1.5*exp(-0.0054*x)+1.03)+0.9;    ## concentration = 1 ##
end;

# ╔═╡ b2f71336-c09d-4ef4-81a4-baf5844ae1aa
md"## Metropolis algorithm"

# ╔═╡ 4c445682-10be-4ed6-b4a4-5da9a02bdd99
function metropolis(A,B,g,vit,c_dis,x0,beta,h,c)
    l = vit
    r = rand(0:360)
    r_metr = rand()
    r_rej = rand()
	## function H ##
    k = 1
    a = 0.5;

    Hx = -2*(0.03*c/(c+0.03)^2)^a*(g(B)/c)
    Hy = -2*(0.03*c/(c+0.03)^2)^a*(g(B+l*sind(r))/c)

    m = (g(0)+g(600))/2
	## metropolis algorithm ##
    if sind(r)<=0
        if B <= -l*sind(r)
            B = 0
        else
            B = B + l*sind(r)
        end
        if A + l*cosd(r) <= 0
                A = 0
        elseif A + l*cosd(r) >= 10
                A = 10
        else
            A = A + l*cosd(r)
        end
    else
         if exp((-beta)*x0*(Hy-Hx)) >= r_metr
            if B >= h - l*sind(r)
                B = h
            else
                B = B + l*sind(r)
            end
            if A + l*cosd(r) <= 0
                A = 0
            elseif A + l*cosd(r) >= 10
                A = 10
            else
                A = A + l*cosd(r)
            end
        else
            if r_rej >= 1/2
                A = A
                B = B
            else
                A = A
                B = B
            end
        end
    end
    return [A,B]
end;

# ╔═╡ 80a0102d-4845-4a6f-bd98-7dd48df95665
md"## Simulation"

# ╔═╡ 80a80780-d053-4a60-be57-6d51661b7aa0
begin
	time = 1000;
	nbr_cell = 400;
	nbr_sim = 1;

	haut = 100.0;
	long = 100.0;
	v = 15;

	x0 = 300000;
	c_dis = 30;

	b_001 = 0.000013;
	b_01  = 0.000013;
	b_1   = 0.000013;

	k_001 = 2;
	k_01 = 2;
	k_1 = 2;

	t_001 = 0.5;
	t_01 = 0.5;
	t_1 = 0.5;

	c_001 = 0.00236;
	c_01 = 0.0268;
	c_1 = 0.279;

	c_c = -0.000009
end;

# ╔═╡ a43b128a-9c98-46bc-82f1-20fa7ac04951
begin
	res01 = []
	list01 = [[rand(0:0.0001:0.01,nbr_cell),rand(24.9:0.01:25.1,nbr_cell)]]
	for t in 1:time
		beta01 = b_01/(1+0.1*exp(-k_01*(t/50-t_01)))
		new_list01 = [[],[]]
		for i in 1:nbr_cell
			A_01 = list01[end][1][i]
			B_01 = list01[end][2][i];
	        metro01 = metropolis(A_01,B_01,g_00,v,c_dis,x0,beta01,haut,c_01);
	        new_list01[1]=append!(new_list01[1],[metro01[1]]);
	        new_list01[2]=append!(new_list01[2],[metro01[2]]);
		end
		append!(list01,[new_list01])
	end
	append!(res01,list01)
end;

# ╔═╡ 212fe946-ee00-44c4-8139-d07afcfba191
md"## Plot"

# ╔═╡ f8df5757-9f83-4555-b637-409af08b3a11
begin
	plt.scatter(res01[5][1],res01[5][2],s=5,color="green",zorder=9)
	plt.gca().set_aspect("equal")
	plt.draw()
	plt.show()
end

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
PyCall = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
PyPlot = "d330b81b-6aea-500a-939a-2ce795aea3ee"

[compat]
PyCall = "~1.92.3"
PyPlot = "~2.9.0"
"""

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

[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"

[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"

[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"

[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"

[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"

[[Conda]]
deps = ["JSON", "VersionParsing"]
git-tree-sha1 = "299304989a5e6473d985212c28928899c74e9421"
uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d"
version = "1.5.2"

[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"

[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"

[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"

[[LaTeXStrings]]
git-tree-sha1 = "c7f1c695e06c01b95a67f0cd1d34994f3e7db104"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.2.1"

[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"

[[LinearAlgebra]]
deps = ["Libdl", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"

[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "0fb723cd8c45858c22169b2e42269e53271a6df7"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.7"

[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"

[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"

[[OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"

[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "477bf42b4d1496b454c10cce46645bb5b8a0cf2c"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.0.2"

[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"

[[PyCall]]
deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Serialization", "VersionParsing"]
git-tree-sha1 = "169bb8ea6b1b143c5cf57df6d34d022a7b60c6db"
uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
version = "1.92.3"

[[PyPlot]]
deps = ["Colors", "LaTeXStrings", "PyCall", "Sockets", "Test", "VersionParsing"]
git-tree-sha1 = "67dde2482fe1a72ef62ed93f8c239f947638e5a2"
uuid = "d330b81b-6aea-500a-939a-2ce795aea3ee"
version = "2.9.0"

[[Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"

[[Reexport]]
git-tree-sha1 = "5f6c21241f0f655da3952fd60aa18477cf96c220"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.1.0"

[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"

[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"

[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"

[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"

[[VersionParsing]]
git-tree-sha1 = "80229be1f670524750d905f8fc8148e5a8c4537f"
uuid = "81def892-9a0e-5fdd-b105-ffc91e053289"
version = "1.2.0"

[[libblastrampoline_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
"""

# ╔═╡ Cell order:
# ╟─f71a4046-2d1e-43eb-ab58-9abfb71838bd
# ╠═48b0d87e-6d87-4ea4-8ff2-8a0bd1622e06
# ╟─92d70ea7-a645-4b86-8b52-13c0d7e8cebf
# ╠═cad72d1c-fe96-11eb-31d4-bb1ecc023f48
# ╟─b2f71336-c09d-4ef4-81a4-baf5844ae1aa
# ╠═4c445682-10be-4ed6-b4a4-5da9a02bdd99
# ╟─80a0102d-4845-4a6f-bd98-7dd48df95665
# ╠═80a80780-d053-4a60-be57-6d51661b7aa0
# ╠═a43b128a-9c98-46bc-82f1-20fa7ac04951
# ╟─212fe946-ee00-44c4-8139-d07afcfba191
# ╠═f8df5757-9f83-4555-b637-409af08b3a11
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002

max_stars_repo_name: Flamanjaune/PHD-Thesis

max_issues_repo_name: Flamanjaune/PHD-Thesis

max_forks_repo_name: Flamanjaune/PHD-Thesis