text:
export AtmosFilterPerturbations

import ..Mesh.Filters:
    AbstractFilterTarget,
    vars_state_filtered,
    compute_filter_argument!,
    compute_filter_result!

struct AtmosFilterPerturbations{M} <: AbstractFilterTarget
    atmos::M
end

vars_state_filtered(target::AtmosFilterPerturbations, FT) =
    vars_state(target.atmos, Prognostic(), FT)

function compute_filter_argument!(
    target::AtmosFilterPerturbations,
    filter_state::Vars,
    state::Vars,
    aux::Vars,
)
    # copy the whole state
    parent(filter_state) .= parent(state)
    # remove reference state
    filter_state.ρ -= aux.ref_state.ρ
    filter_state.energy.ρe -= aux.ref_state.ρe
    if !(moisture_model(target.atmos) isa DryModel)
        filter_state.moisture.ρq_tot -= aux.ref_state.ρq_tot
    end
    if (moisture_model(target.atmos) isa NonEquilMoist)
        filter_state.moisture.ρq_liq -= aux.ref_state.ρq_liq
        filter_state.moisture.ρq_ice -= aux.ref_state.ρq_ice
    end
end
function compute_filter_result!(
    target::AtmosFilterPerturbations,
    state::Vars,
    filter_state::Vars,
    aux::Vars,
)
    # copy the whole filter state
    parent(state) .= parent(filter_state)
    # add reference state
    state.ρ += aux.ref_state.ρ
    state.energy.ρe += aux.ref_state.ρe
    if !(moisture_model(target.atmos) isa DryModel)
        state.moisture.ρq_tot += aux.ref_state.ρq_tot
    end
    if (moisture_model(target.atmos) isa NonEquilMoist)
        filter_state.moisture.ρq_liq += aux.ref_state.ρq_liq
        filter_state.moisture.ρq_ice += aux.ref_state.ρq_ice
    end
end


text:
include("decisions.jl")
include("affine.jl")
include("quadratic.jl")
include("operators.jl")
include("mutable_arithmetics.jl")

ext: jl


text: Dict{String, Any}("nest" => Any[Any[Any[Dict{String, Any}("value" => "a", "type" => "string")], Any[Dict{String, Any}("value" => "1", "type" => "integer"), Dict{String, Any}("value" => "2", "type" => "integer"), Any[Dict{String, Any}("value" => "3", "type" => "integer")]]]])


text:
module StateNamePuzzle

const realnames = ["Alabama", "Alaska", "Arizona", "Arkansas", "California",
"Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine",
"Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri",
"Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
"New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee",
"Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia",
"Wisconsin", "Wyoming"]

const fictitious = ["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]

function combine(a::AbstractString, b::AbstractString)
    chars = vcat(collect(Char, a), collect(Char, b))
    sort!(chars)
    return join(chars)
end

function solve(input::Vector{<:AbstractString})
    dict = Dict{String,String}()
    for state in input
        key = replace(state, " ", "") |> lowercase
        if !haskey(dict, key)
            dict[key] = state
        end
    end
    keyset = collect(keys(dict))
    solutions = String[]
    duplicates = String[]
    for i in eachindex(keyset), j in (i+1):endof(keyset)
        len1 = length(keyset[i]) + length(keyset[j])
        combined1 = combine(keyset[i], keyset[j])
        for k in eachindex(keyset), l in k+1:endof(keyset)
            k ∈ (i, j) && continue
            l ∈ (i, j) && continue
            len2 = length(keyset[k]) + length(keyset[l])
            len1 != len2 && continue
            combined2 = combine(keyset[k], keyset[l])
            if combined1 == combined2
                f1 = dict[keyset[i]] * " + " * dict[keyset[j]]
                f2 = dict[keyset[k]] * " + " * dict[keyset[l]]
                f3 = f1 * " = " * f2
                f3 ∈ duplicates && continue
                push!(solutions, f3)
                f4 = f2 * " = " * f1
                push!(duplicates, f4)
            end
        end
    end
    return sort!(solutions)
end

end  # module StateNamePuzzle

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# Julia wrapper for header: /usr/include/scip/cons_logicor.h
# Automatically generated using Clang.jl wrap_c

function SCIPincludeConshdlrLogicor(scip)
    ccall((:SCIPincludeConshdlrLogicor, libscip), SCIP_RETCODE, (Ptr{SCIP_},), scip)
end

function SCIPcreateConsLogicor(scip, cons, name, nvars, vars, initial, separate, enforce, check, propagate, _local, modifiable, dynamic, removable, stickingatnode)
    ccall((:SCIPcreateConsLogicor, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_CONS}}, Cstring, Cint, Ptr{Ptr{SCIP_VAR}}, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32), scip, cons, name, nvars, vars, initial, separate, enforce, check, propagate, _local, modifiable, dynamic, removable, stickingatnode)
end

function SCIPcreateConsBasicLogicor(scip, cons, name, nvars, vars)
    ccall((:SCIPcreateConsBasicLogicor, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{Ptr{SCIP_CONS}}, Cstring, Cint, Ptr{Ptr{SCIP_VAR}}), scip, cons, name, nvars, vars)
end

function SCIPaddCoefLogicor(scip, cons, var)
    ccall((:SCIPaddCoefLogicor, libscip), SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_CONS}, Ptr{SCIP_VAR}), scip, cons, var)
end

function SCIPgetNVarsLogicor(scip, cons)
    ccall((:SCIPgetNVarsLogicor, libscip), Cint, (Ptr{SCIP_}, Ptr{SCIP_CONS}), scip, cons)
end

function SCIPgetVarsLogicor(scip, cons)
    ccall((:SCIPgetVarsLogicor, libscip), Ptr{Ptr{SCIP_VAR}}, (Ptr{SCIP_}, Ptr{SCIP_CONS}), scip, cons)
end

function SCIPgetDualsolLogicor(scip, cons)
    ccall((:SCIPgetDualsolLogicor, libscip), Cdouble, (Ptr{SCIP_}, Ptr{SCIP_CONS}), scip, cons)
end

function SCIPgetDualfarkasLogicor(scip, cons)
    ccall((:SCIPgetDualfarkasLogicor, libscip), Cdouble, (Ptr{SCIP_}, Ptr{SCIP_CONS}), scip, cons)
end

function SCIPgetRowLogicor(scip, cons)
    ccall((:SCIPgetRowLogicor, libscip), Ptr{SCIP_ROW}, (Ptr{SCIP_}, Ptr{SCIP_CONS}), scip, cons)
end


text:
# # Data structures
#
# Once we start working with many pieces of data at once, it will be convenient for us to store data in structures like arrays or dictionaries (rather than just relying on variables).

#
# Types of data structures covered:
# 1. Tuples
# 2. Named Tuples
# 3. Dictionaries
#
#

# As an overview, tuples and arrays are both ordered sequences of elements (so we can index into them). Dictionaries and arrays are both mutable.
# We'll explain this more below!

#-

# ## Tuples
#
# We can create a tuple by enclosing an ordered collection of elements in `( )`.
#
# Syntax:

# ```julia
# (item1, item2, ...)```

myfavoriteanimals = ("penguins", "cats", "sugargliders")

# We can index into this tuple,

myfavoriteanimals[1]

# but since tuples are immutable, we can't update it

myfavoriteanimals[1] = "otters"

# ## Now in 1.0: NamedTuples
#
# As you might guess, `NamedTuple`s are just like `Tuple`s except that each element additionally has a name! They have a special syntax using `=` inside a tuple:
#
# ```julia
# (name1 = item1, name2 = item2, ...)
# ```

myfavoriteanimals = (bird = "penguins", mammal = "cats", marsupial = "sugargliders")

# Like regular `Tuples`, `NamedTuples` are ordered, so we can retrieve their elements via indexing:

myfavoriteanimals[1]

# They also add the special ability to access values by their name:

myfavoriteanimals.bird

# ## Dictionaries
#
# If we have sets of data related to one another, we may choose to store that data in a dictionary. We can create a dictionary using the `Dict()` function, which we can initialize as an empty dictionary or one storing key, value pairs.
#
# Syntax:
# ```julia
# Dict(key1 => value1, key2 => value2, ...)```
#
# A good example is a contacts list, where we associate names with phone numbers.

myphonebook = Dict("Jenny" => "867-5309", "Ghostbusters" => "555-2368")

# In this example, each name and number is a "key" and "value" pair. We can grab Jenny's number (a value) using the associated key

myphonebook["Jenny"]

# We can add another entry to this dictionary as follows

myphonebook["Kramer"] = "555-FILK"

# Let's check what our phonebook looks like now...

myphonebook

# We can delete Kramer from our contact list - and simultaneously grab his number - by using `pop!`

pop!(myphonebook, "Kramer")

#-

myphonebook

# Unlike tuples and arrays, dictionaries are not ordered. So, we can't index into them.

myphonebook[1]

# In the example above, `julia` thinks you're trying to access a value associated with the key `1`.

#-

# ### Exercises

@assert a_ray == [1, 2, 3]

# #### 3.2
# Try to add "Emergency" as key to `myphonebook` with the value `string(911)` with the following code
# ```julia
# myphonebook["Emergency"] = 911
# ```
#
# Why doesn't this work?

# #### 3.3
# Create a new dictionary called `flexible_phonebook` that has Jenny's number stored as an integer and Ghostbusters' number stored as a string with the following code
#
# ```julia
# flexible_phonebook = Dict("Jenny" => 8675309, "Ghostbusters" => "555-2368")
# ```

#-

@assert flexible_phonebook == Dict("Jenny" => 8675309, "Ghostbusters" => "555-2368")

# #### 3.4
# Add the key "Emergency" with the value `911` (an integer) to `flexible_phonebook`.

#-

@assert haskey(flexible_phonebook, "Emergency")

#-

@assert flexible_phonebook["Emergency"] == 911

# #### 3.5
# Why can we add an integer as a value to `flexible_phonebook` but not `myphonebook`? How could we have initialized `myphonebook` so that it would accept integers as values?

# Please click on `Validate` button at the top, upon completion of the excercise

max_stars_repo_path: Courses/Introduction to Julia/04. Data structures.jl

max_stars_repo_name: fercarozzi/JuliaAcademyMaterials

max_issues_repo_name: fercarozzi/JuliaAcademyMaterials

max_forks_repo_name: fercarozzi/JuliaAcademyMaterials


text:
# Tests whether risk regions calculate the correct transformed distance
# Results come from previous Python implementation of Risk regions
using LinearAlgebra: diagm
using DelimitedFiles: readdlm

function test_points(Ω::EllipticalRiskRegion, file_name::String)
    res = readdlm(file_name)
    for i in 1:size(res,1)
        row = res[i,:]
        x, dist = row[1:end-1], row[end]
        @test transformed_size(Ω, x) ≈ dist atol=1e-2
    end
end

print("\tTest 1...")
K₁ = FiniteCone(-Array{Float64}(I, 2, 2))
μ₁ = [0.0, 0.0]
Σ₁ = [[2.0, 0.0] [0.0, 2.0]]
Ω₁ = EllipticalRiskRegion(μ₁, Σ₁, K₁, 1.0)
test_points(Ω₁, "results_1.txt")
print("success!\n")

print("\tTest 2...")
K₂ = FiniteCone(-Array{Float64}(I, 3, 3))
μ₂ = [1.0, -0.5, 3.0]
Σ₂ = diagm(0=>[1.0, 2.0, 4.0])
Ω₂ = EllipticalRiskRegion(μ₂, Σ₂, K₂, 1.0)
test_points(Ω₂, "results_2.txt")
print("success!\n")

print("\tTest 3...")
K₃ = FiniteCone(-Array{Float64}(I, 3, 3))
μ₃ = [1.0, -0.5, 3.0]
Σ₃ = [2.0 0.5 0.0;
      0.5 2.5 0.0;
      0.0 0.0 4.0]
Ω₃ = EllipticalRiskRegion(μ₃, Σ₃, K₃, 1.0)
test_points(Ω₃, "results_3.txt")
print("success!\n")

print("\tTest 5...")
K₅ = FiniteCone(-[[1.0, 1.0, 0.0] [0.0, 1.0, -0.5] [1.0, 0.0, 1.0]])
μ₅ = [1.0, -0.5, 3.0]
Σ₅ = [2.0 0.5 0.0;
      0.5 2.5 0.0;
      0.0 0.0 4.0]
Ω₅ = EllipticalRiskRegion(μ₅, Σ₅, K₅, 1.0)
test_points(Ω₅, "results_5.txt")
print("success!\n")


text:
module BSplineKit

export Derivative

using Reexport

include("BandedTensors/BandedTensors.jl")
@reexport using .BandedTensors

include("DifferentialOps/DifferentialOps.jl")
using .DifferentialOps

include("BoundaryConditions/BoundaryConditions.jl")
@reexport using .BoundaryConditions

include("BSplines/BSplines.jl")
@reexport using .BSplines

include("Splines/Splines.jl")
@reexport using .Splines

include("Recombinations/Recombinations.jl")
@reexport using .Recombinations

include("Collocation/Collocation.jl")
@reexport using .Collocation

include("Galerkin/Galerkin.jl")
@reexport using .Galerkin

include("SplineInterpolations/SplineInterpolations.jl")
@reexport using .SplineInterpolations

include("SplineApproximations/SplineApproximations.jl")
@reexport using .SplineApproximations

end

max_stars_repo_name: jipolanco/BasisSplines

max_issues_repo_name: jipolanco/BasisSplines

max_forks_repo_name: jipolanco/BasisSplines


text:
# Julia wrapper for header: /usr/local/include/cpl_error.h
# Automatically generated using Clang.jl wrap_c, version 0.0.0

"""
    CPLEmergencyError(const char * pszMessage) -> void

Fatal error when things are bad.

### Parameters
* **pszMessage**: the error message to report.
"""
function CPLEmergencyError(arg1)
    ccall((:CPLEmergencyError, libgdal), Void, (Cstring,), arg1)
end

"""
    CPLErrorReset() -> void

Erase any traces of previous errors.
"""
function CPLErrorReset()
    ccall((:CPLErrorReset, libgdal), Void, ())
end

"""
    CPLGetLastErrorNo() -> CPLErrorNum

Fetch the last error number.

### Returns
the error number of the last error to occur, or CPLE_None (0) if there are no posted errors.
"""
function CPLGetLastErrorNo()
    ccall((:CPLGetLastErrorNo, libgdal), CPLErrorNum, ())
end

"""
    CPLGetLastErrorType() -> CPLErr

Fetch the last error type.

### Returns
the error type of the last error to occur, or CE_None (0) if there are no posted errors.
"""
function CPLGetLastErrorType()
    ccall((:CPLGetLastErrorType, libgdal), CPLErr, ())
end

"""
    CPLGetLastErrorMsg() -> const char *

Get the last error message.

### Returns
the last error message, or NULL if there is no posted error message.
"""
function CPLGetLastErrorMsg()
    ccall((:CPLGetLastErrorMsg, libgdal), Cstring, ())
end

"""
    CPLGetErrorHandlerUserData(void) -> void *

Fetch the user data for the error context.

### Returns
the user data pointer for the error context
"""
function CPLGetErrorHandlerUserData()
    ccall((:CPLGetErrorHandlerUserData, libgdal), Ptr{Void}, ())
end

"""
    CPLErrorSetState(CPLErr eErrClass,
                     CPLErrorNum err_no,
                     const char * pszMsg) -> void

Restore an error state, without emitting an error.
"""
function CPLErrorSetState(eErrClass::CPLErr, err_no::CPLErrorNum, pszMsg)
    ccall((:CPLErrorSetState, libgdal), Void, (CPLErr, CPLErrorNum, Cstring), eErrClass, err_no, pszMsg)
end

"""
    CPLCleanupErrorMutex() -> void
"""
function CPLCleanupErrorMutex()
    ccall((:CPLCleanupErrorMutex, libgdal), Void, ())
end

"""
    CPLLoggingErrorHandler(CPLErr eErrClass,
                           CPLErrorNum nError,
                           const char * pszErrorMsg) -> void

Error handler that logs into the file defined by the CPL_LOG configuration option, or stderr otherwise.
"""
function CPLLoggingErrorHandler(arg1::CPLErr, arg2::CPLErrorNum, arg3)
    ccall((:CPLLoggingErrorHandler, libgdal), Void, (CPLErr, CPLErrorNum, Cstring), arg1, arg2, arg3)
end

"""
    CPLDefaultErrorHandler(CPLErr eErrClass,
                           CPLErrorNum nError,
                           const char * pszErrorMsg) -> void

Default error handler.
"""
function CPLDefaultErrorHandler(arg1::CPLErr, arg2::CPLErrorNum, arg3)
    ccall((:CPLDefaultErrorHandler, libgdal), Void, (CPLErr, CPLErrorNum, Cstring), arg1, arg2, arg3)
end

"""
    CPLQuietErrorHandler(CPLErr eErrClass,
                         CPLErrorNum nError,
                         const char * pszErrorMsg) -> void

Error handler that does not do anything, except for debug messages.
"""
function CPLQuietErrorHandler(arg1::CPLErr, arg2::CPLErrorNum, arg3)
    ccall((:CPLQuietErrorHandler, libgdal), Void, (CPLErr, CPLErrorNum, Cstring), arg1, arg2, arg3)
end

"""
    CPLTurnFailureIntoWarning(int bOn) -> void

Whether failures should be turned into warnings.
"""
function CPLTurnFailureIntoWarning(bOn::Cint)
    ccall((:CPLTurnFailureIntoWarning, libgdal), Void, (Cint,), bOn)
end

"""
    CPLSetErrorHandler(CPLErrorHandler pfnErrorHandlerNew) -> CPLErrorHandler

Install custom error handler.

### Parameters
* **pfnErrorHandlerNew**: new error handler function.

### Returns
returns the previously installed error handler.
"""
function CPLSetErrorHandler(arg1::CPLErrorHandler)
    ccall((:CPLSetErrorHandler, libgdal), CPLErrorHandler, (CPLErrorHandler,), arg1)
end

"""
    CPLSetErrorHandlerEx(CPLErrorHandler pfnErrorHandlerNew,
                         void * pUserData) -> CPLErrorHandler

Install custom error handle with user's data.

### Parameters
* **pfnErrorHandlerNew**: new error handler function.
* **pUserData**: User data to carry along with the error context.

### Returns
returns the previously installed error handler.
"""
function CPLSetErrorHandlerEx(arg1::CPLErrorHandler, arg2)
    ccall((:CPLSetErrorHandlerEx, libgdal), CPLErrorHandler, (CPLErrorHandler, Ptr{Void}), arg1, arg2)
end

"""
    CPLPushErrorHandler(CPLErrorHandler pfnErrorHandlerNew) -> void

Push a new CPLError handler.

### Parameters
* **pfnErrorHandlerNew**: new error handler function.
"""
function CPLPushErrorHandler(arg1::CPLErrorHandler)
    ccall((:CPLPushErrorHandler, libgdal), Void, (CPLErrorHandler,), arg1)
end

"""
    CPLPushErrorHandlerEx(CPLErrorHandler pfnErrorHandlerNew,
                          void * pUserData) -> void

Push a new CPLError handler with user data on the error context.

### Parameters
* **pfnErrorHandlerNew**: new error handler function.
* **pUserData**: User data to put on the error context.
"""
function CPLPushErrorHandlerEx(arg1::CPLErrorHandler, arg2)
    ccall((:CPLPushErrorHandlerEx, libgdal), Void, (CPLErrorHandler, Ptr{Void}), arg1, arg2)
end

"""
    CPLSetCurrentErrorHandlerCatchDebug(int bCatchDebug) -> void

Set if the current error handler should intercept debug messages, or if they should be processed by the previous handler.

### Parameters
* **bCatchDebug**: FALSE if the current error handler should not intercept debug messages
"""
function CPLSetCurrentErrorHandlerCatchDebug(bCatchDebug::Cint)
    ccall((:CPLSetCurrentErrorHandlerCatchDebug, libgdal), Void, (Cint,), bCatchDebug)
end

"""
    CPLPopErrorHandler() -> void

Pop error handler off stack.
"""
function CPLPopErrorHandler()
    ccall((:CPLPopErrorHandler, libgdal), Void, ())
end

"""
    _CPLAssert(const char * pszExpression,
               const char * pszFile,
               int iLine) -> void

Report failure of a logical assertion.
"""
function _CPLAssert(arg1, arg2, arg3::Cint)
    ccall((:_CPLAssert, libgdal), Void, (Cstring, Cstring, Cint), arg1, arg2, arg3)
end


text:
using LazyArrays, FillArrays, Test
import LazyArrays: materialize, broadcasted, DefaultApplyStyle, Applied,
            ApplyArray, ApplyMatrix, ApplyVector, LazyArrayApplyStyle

@testset "Applied" begin
    @test applied(exp,1) isa Applied{DefaultApplyStyle}

    @test apply(randn) isa Float64

    @test materialize(applied(*, 1)) == apply(*,1) == 1

    @test apply(exp, 1) === exp(1)
    @test apply(exp, broadcasted(+, 1, 2)) === apply(exp, applied(+, 1, 2)) === exp(3)
end

@testset "ApplyArray" begin
    A = randn(2,2)
    M = ApplyMatrix(exp, A)
    @test eltype(M) == eltype(Applied(M)) == Float64
    @test M == exp(A)
    @test ndims(M) == 2
    @test axes(M) == (Base.OneTo(2), Base.OneTo(2))

    b = randn(2)
    c = ApplyVector(*, ApplyMatrix(exp, A), b)

    @test axes(c) == (Base.OneTo(2),)

    @test c[1] == c[1,1]
    @test exp(A)*b ≈ c

    @test ApplyArray(+,[1,2],[3,4]) == ApplyVector(+,[1,2],[3,4]) == ApplyArray(+,[1,2],[3,4])

    @test LazyArrays.rowsupport(Diagonal(1:10),3) == 3:3
    M = ApplyArray(*, Ones(100_000_000,100_000_000), Diagonal(1:100_000_000))
    @test M[1,1] === 1.0
    @test M[1:10,1:10] == ones(10,10)*Diagonal(1:10)

    M = copy(Applied{LazyArrayApplyStyle}(exp, (A,)))
    @test M isa ApplyArray
    @test M == exp(A)
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 ObjectReplicationPolicyFilter <: SwaggerModel
    prefixMatch::Any # spec type: Union{ Nothing, Vector{String} } # spec name: prefixMatch
    minCreationTime::Any # spec type: Union{ Nothing, String } # spec name: minCreationTime

    function ObjectReplicationPolicyFilter(;prefixMatch=nothing, minCreationTime=nothing)
        o = new()
        validate_property(ObjectReplicationPolicyFilter, Symbol("prefixMatch"), prefixMatch)
        setfield!(o, Symbol("prefixMatch"), prefixMatch)
        validate_property(ObjectReplicationPolicyFilter, Symbol("minCreationTime"), minCreationTime)
        setfield!(o, Symbol("minCreationTime"), minCreationTime)
        o
    end
end # type ObjectReplicationPolicyFilter

const _property_map_ObjectReplicationPolicyFilter = Dict{Symbol,Symbol}(Symbol("prefixMatch")=>Symbol("prefixMatch"), Symbol("minCreationTime")=>Symbol("minCreationTime"))
const _property_types_ObjectReplicationPolicyFilter = Dict{Symbol,String}(Symbol("prefixMatch")=>"Vector{String}", Symbol("minCreationTime")=>"String")
Base.propertynames(::Type{ ObjectReplicationPolicyFilter }) = collect(keys(_property_map_ObjectReplicationPolicyFilter))
Swagger.property_type(::Type{ ObjectReplicationPolicyFilter }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ObjectReplicationPolicyFilter[name]))}
Swagger.field_name(::Type{ ObjectReplicationPolicyFilter }, property_name::Symbol) =  _property_map_ObjectReplicationPolicyFilter[property_name]

function check_required(o::ObjectReplicationPolicyFilter)
    true
end

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


text:
using Logging

export shouldlog, min_enabled_level, catch_exceptions

struct AvailabilityLogger <: AbstractLogger
    stream::IO
end

# AvailabilityLogger(stream::IO=stderr, level=Info) = AvailabilityLogger(stream, level, Dict{Any,Int}())

shouldlog(logger::AvailabilityLogger, level, _module, group, id) =
    get(logger.message_limits, id, 1) > 0

min_enabled_level(logger::AvailabilityLogger) = logger.min_level

catch_exceptions(logger::AvailabilityLogger) = false

function handle_message(logger::AvailabilityLogger, level, message, _module, group, id,
                        filepath, line; maxlog=nothing, kwargs...)
    if maxlog !== nothing && maxlog isa Integer
        remaining = get!(logger.message_limits, id, maxlog)
        logger.message_limits[id] = remaining - 1
        remaining > 0 || return
    end
    buf = IOBuffer()
    iob = IOContext(buf, logger.stream)
    levelstr = level == Warn ? "Warning" : string(level)
    msglines = split(chomp(string(message)), '\n')
    println(iob, "┌ ", levelstr, ": ", msglines[1])
    for i in 2:length(msglines)
        println(iob, "│ ", msglines[i])
    end
    for (key, val) in kwargs
        println(iob, "│   ", key, " = ", val)
    end
    println(iob, "└ @ ", something(_module, "nothing"), " ",
            something(filepath, "nothing"), ":", something(line, "nothing"))
    write(logger.stream, take!(buf))
    nothing
end

max_stars_repo_name: kawadesumit/availability

max_issues_repo_name: kawadesumit/availability

max_forks_repo_name: kawadesumit/availability


text:
## Packages
using NLsolve
using Plots
using Parameters

## Files
include("Tauchen.jl")
include("NewtonRoot.jl")

## Parameters
Model = @with_kw (θ = 0.35, # capital share
    δ = 0.0464, # depreciation rate
    γ_z = 0.016, # growth rate of productivity
    γ_n = 0.015, # growth rate of population
    β = 0.9722, # discount rate
    β_hat = β*(1+γ_n), # detrended discount rate
    ψ = 2.24, # labor coefficient
    ρ = 0.2,# autocorr of productivity process
    σ = 0.5, # stand. dev. for productivity process
    nz = 5, # number of states for productivity
    μ_z = 0.0, # mean of productivity process
    zGrid = exp.(Tauchen(μ_z,ρ,σ,nz)[1]), # grid for productivity process
    P_z = Tauchen(μ_z,ρ,σ,nz)[2]) # transition matrix

## Get the Steady-State level of capital from a Nonlinear solver
function getSS(md)
    @unpack θ,ψ,δ,β_hat,γ_n,γ_z = md

    function ee!(eq,x)
        k=(x[1])
        h=(x[2])
        eq[1]=β_hat*(θ*k^(θ-1)*h^(1-θ)+1-δ)-(1+γ_n)*(1+γ_z)
        eq[2]=(-(ψ/(1-h)))+((1-θ)*(k^θ)*(h^(-θ)))/((k^θ)*(h^(1-θ))-(1+γ_n)*(1+γ_z)*k+(1-δ)*k)
    end

    S = nlsolve(ee!, [0.5,0.5],ftol = :1.0e-9, method = :trust_region , autoscale = true);
    kss = S.zero[1];
    hss = S.zero[2];
    lss = 1-hss;
    css = (kss^θ)*((exp(0)*hss)^(1-θ))-(1+γ_n)*(1+γ_z)*kss+(1-δ)*kss;

    return kss,hss,lss,css
end

# Solve h from intratemporal equation over the grids
function geth(md,nk,kGrid)

    @unpack θ,ψ,γ_n,γ_z,δ,nz,zGrid = md

    h_star = zeros(nk,nk,nz);

    for i = 1:nk
        for j = 1:nk
            for k = 1:nz
                intra(h) = (ψ/(1-θ))*((kGrid[i]^θ)*((zGrid[k]*h)^(1-θ))-(1+γ_n)*(1+γ_z)*kGrid[j]+(1-δ)*kGrid[i])+((h-1)*(kGrid[i]^θ)*(zGrid[k]^(1-θ))*(h^(-θ)))
                h = NewtonRoot(h -> intra(h),0.5)
                if h > 1
                    h_star[i,j,k] = 0.9999;
                else
                    h_star[i,j,k] = h;
                end
            end
        end
    end

    return h_star

end

# Precalculate return value
function getrt(md,nk,kGrid)

    @unpack θ,ψ,γ_n,γ_z,δ,nz,zGrid = md

    h_star = geth(md,nk,kGrid)
    rt = zeros(nk,nk,nz);

    for i = 1:nk
        for j = 1:nk
            for k = 1:nz
                c = (kGrid[i]^θ)*((zGrid[k]*h_star[i,j,k])^(1-θ))-(1+γ_n)*(1+γ_z)*kGrid[j]+(1-δ)*kGrid[i];
                if c <= 0
                    rt[i,j,k] = -100.0;
                else
                    rt[i,j,k] = log(c)+ψ*log(1-h_star[i,j,k]);
                end
            end
        end
    end

    return rt,h_star

end

# Main loop
function VFI(md,nk,kGrid)
    @unpack θ,ψ,γ_n,γ_z,δ,nz,zGrid,β_hat,P_z = md

    #Preallocate memories
    V_old = zeros(nk,nz);
    V_new = zeros(nk,nz);
    argmax = Array{Int64,2}(undef,nk,nz);

    kpol = zeros(nk,nz);
    hpol = zeros(nk,nz);
    cpol = zeros(nk,nz);

    maxDiff = 10.0;
    tol = 1.0e-10;
    iter = 0;

    rt,h_star = getrt(md,nk,kGrid);

    while maxDiff > tol
        iter = iter+1;
        println("Current iteration: $iter")

        EV = V_old*P_z';
        for i = 1:nk, k = 1:nz
            V_new[i,k],argmax[i,k] = findmax(rt[i,:,k].+β_hat*EV[:,k]);
        end

        maxDiff = maximum(abs.(V_new-V_old));
        println("maxDiff = $maxDiff")
        V_old = copy(V_new);
    end

    for i = 1:nk,j = 1:nz
        kpol[i,j] = kGrid[argmax[i,j]];
        hpol[i,j] = h_star[i,argmax[i,j],j];
        cpol[i,j] = (kGrid[i]^θ)*(zGrid[j]*hpol[i,j])^(1-θ)-(1+γ_n)*(1+γ_z)*kpol[i,j]+(1-δ)*kGrid[i];
    end

    return V_new,kpol,hpol,cpol
end


text:
#= This script defines the function in order to interpolate variables from
one grid (u,v,T,q) to another (u,v,T,q), due to the staggered Arakawa C-grid.
    The notation is Iab where a ∈ {u,v,T,q} and b ∈ {u,v,T,q}, with a being
    the departure grid and b the destination grid.
This interpolation is a 2-point averaging with coefficients (1/2,1/2) for
    ITu,ITv,IuT,IvT,Iqu,Iqv,Ivq,Iuq
and a 4-point averaging with coefficients (1/4,1/4,1/4,1/4) for
    ITq,IqT,Iuv,Ivu.
Each function takes the return variable as first argument and the variable to be
interpolated as second argument. =#

# ------------- 2-point interpolation between T and u or v. -----------------

function ITu_nonperiodic!(u::AbstractMatrix,T::AbstractMatrix)
    #= Interpolates a variable T from the T-grid to a variable u on the u-grid. =#
    @views u[:,:] .= one_half*(T[2:end,:] .+ T[1:end-1,:])
end

function ITu_periodic!(u::AbstractMatrix,T::AbstractMatrix)
    #= Interpolates a variable T from the T-grid to a variable u on the u-grid. =#
    @views u[2:end,:] .= one_half*(T[2:end,:] .+ T[1:end-1,:])
    @views u[1,:] .= one_half*(T[1,:] .+ T[end,:])
end

function ITv!(v::AbstractMatrix,T::AbstractMatrix)
    #= Interpolates a variable T from the T-grid to a variable v on the v-grid. =#
    @views v[:,:] .= one_half*(T[:,2:end] .+ T[:,1:end-1])
end

function IuT_nonperiodic!(T::AbstractMatrix,u::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable T on the T-grid. =#
    @views T[2:end-1,:] .= one_half * (u[2:end,:] .+ u[1:end-1,:])
    @views T[1,:] .= one_half * u[1,:]        # +0, kinematic boundary condition
    @views T[end,:] .= one_half * u[end,:]    # +0, kinematic bc
end

function IuT_periodic!(T::AbstractMatrix,u::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable T on the T-grid. =#
    @views T[1:end-1,:] .= one_half*(u[2:end,:] .+ u[1:end-1,:])
    @views T[end,:] .= one_half*(u[1,:]+u[end,:])
end

function IvT!(T::AbstractMatrix,v::AbstractMatrix)
    #= Interpolates a variable v from the v-grid to a variable T on the T-grid. =#
    @views T[:,2:end-1] .= one_half * (v[:,2:end] .+ v[:,1:end-1])
    @views T[:,1] .= one_half * v[:,1]        # +0, kinematic bc
    @views T[:,end] .= one_half * v[:,end]    # +0, kinematic bc
end

# ------------- 2-point interpolation between q and u or v. -----------------

function Iqu_nonperiodic!(u::AbstractMatrix,q::AbstractMatrix)
    #= Interpolates a variable q from the q-grid to a variable u on the u-grid. =#
    @views u[:,:] .= one_half * (q[2:end-1,1:end-1] .+ q[2:end-1,2:end])
end

function Iqu_periodic!(u::AbstractMatrix,q::AbstractMatrix)
    #= Interpolates a variable q from the q-grid to a variable u on the u-grid. =#
    @views u[:,:] .= one_half * (q[:,1:end-1] .+ q[:,2:end])
end

function Iqv_nonperiodic!(v::AbstractMatrix,q::AbstractMatrix)
    #= Interpolates a variable q from the q-grid to a variable v on the v-grid. =#
    @views v[:,:] .= one_half*(q[1:end-1,2:end-1] .+ q[2:end,2:end-1])
end

function Iqv_periodic!(v::AbstractMatrix,q::AbstractMatrix)
    #= Interpolates a variable q from the q-grid to a variable v on the v-grid. =#
    @views v[1:end-1,:] .= one_half * (q[1:end-1,2:end-1] .+ q[2:end,2:end-1])
    @views v[end,:] .= one_half * (q[1,2:end-1] .+ q[end,2:end-1])
end

function Ivq_nonperiodic!(q::AbstractMatrix,v::AbstractMatrix)
    #= Interpolates a variable v from the v-grid to a variable q on the q-grid. =#
    @views q[2:end-1,2:end-1] .= one_half * (v[1:end-1,:] .+ v[2:end,:])
    @views q[1,2:end-1] .= one_minus_α_half * v[1,:]
    @views q[end,2:end-1] .= one_minus_α_half * v[end,:]
    @views q[:,1] .= zeero      # if initialised with zero these lines are redundant
    @views q[:,end] .= zeero
end

function Ivq_periodic!(q::AbstractMatrix,v::AbstractMatrix)
    #= Interpolates a variable v from the v-grid to a variable q on the q-grid. =#
    @views q[2:end,2:end-1] .= one_half * (v[1:end-1,:] .+ v[2:end,:])
    @views q[1,2:end-1] .= one_half * (v[1,:] .+ v[end,:])
    @views q[:,1] .= zeero      # if initialised with zero these lines are redundant
    @views q[:,end] .= zeero
end

function Iuq_nonperiodic!(q::AbstractMatrix,u::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable q on the q-grid. =#
    @views q[2:end-1,2:end-1] .= one_half * (u[:,1:end-1] .+ u[:,2:end])
    @views q[1,:] .= zeero     # if initialised with zero these lines are redundant
    @views q[end,:] .= zeero
    @views q[2:end-1,1] .= one_minus_α_half * u[:,1]
    @views q[2:end-1,end] .= one_minus_α_half * u[:,end]
end

function Iuq_periodic!(q::AbstractMatrix,u::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable q on the q-grid. =#
    @views q[:,2:end-1] .= one_half * (u[:,1:end-1] .+ u[:,2:end])
    @views q[:,1] .= one_minus_α_half * u[:,1]
    @views q[:,end] .= one_minus_α_half * u[:,end]
end

# ------------- 4-point interpolation between (T and q) and (u and v). ---------

function ITq_nonperiodic!(q::AbstractMatrix,T::AbstractMatrix)
    #= Interpolates a variable T from the T-grid to a variable q on the q-grid. =#
    @views q[2:end-1,2:end-1] .= one_quarter * (T[1:end-1,1:end-1] .+ T[1:end-1,2:end] .+ T[2:end,1:end-1] .+ T[2:end,2:end])
    @views q[1,2:end-1] .= one_half * (T[1,1:end-1] .+ T[1,2:end])
    @views q[end,2:end-1] .= one_half * (T[end,1:end-1] .+ T[end,2:end])
    @views q[2:end-1,1] .= one_half * (T[1:end-1,1] .+ T[2:end,1])
    @views q[2:end-1,end] .= one_half * (T[1:end-1,end] .+ T[2:end,end])
    @views q[1,1] .= T[1,1]         # no gradients of T across the boundaries
    @views q[1,end] .= T[1,end]
    @views q[end,1] .= T[end,1]
    @views q[end,end] .= T[end,end]
end

function ITq_periodic!(q::AbstractMatrix,T::AbstractMatrix)
    #= Interpolates a variable T from the T-grid to a variable q on the q-grid. =#
    @views q[2:end,2:end-1] .= one_quarter * (T[1:end-1,1:end-1] .+ T[1:end-1,2:end] .+ T[2:end,1:end-1] .+ T[2:end,2:end])
    @views q[1,2:end-1] .= one_quarter * (T[1,1:end-1] .+ T[1,2:end] .+ T[end,1:end-1] .+ T[end,2:end])
    @views q[2:end,1] .= one_half * (T[1:end-1,1] .+ T[2:end,1])
    @views q[2:end,end] .= one_half * (T[1:end-1,end] .+ T[2:end,end])
    @views q[1,1] .= one_half * (T[1,1] .+ T[end,1])
    @views q[1,end] .= one_half * (T[1,end] .+ T[end,end])
end

function IqT_nonperiodic!(T::AbstractMatrix,q::AbstractMatrix)
    #= Interpolates a variable q from the q-grid to a variable T on the T-grid. =#
    @views T[:,:] .= one_quarter * (q[1:end-1,1:end-1] .+ q[1:end-1,2:end] .+ q[2:end,1:end-1] .+ q[2:end,2:end])
end

function IqT_periodic!(T::AbstractMatrix,q::AbstractMatrix)
    #= Interpolates a variable q from the q-grid to a variable T on the T-grid. =#
    @views T[1:end-1,:] .= one_quarter * (q[1:end-1,1:end-1] .+ q[1:end-1,2:end] .+ q[2:end,1:end-1] .+ q[2:end,2:end])
    @views T[end,:] .= one_quarter * (q[end,1:end-1] .+ q[end,2:end] .+ q[1,1:end-1] .+ q[1,2:end])
end

function Iuv_nonperiodic!(v::AbstractMatrix,u::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable v on the v-grid. =#
    @views v[2:end-1,:] .= one_quarter * (u[1:end-1,1:end-1] .+ u[1:end-1,2:end] .+ u[2:end,1:end-1] .+ u[2:end,2:end])
    @views v[1,:] .= one_quarter * (u[1,1:end-1] .+ u[1,2:end])
    @views v[end,:] .= one_quarter * (u[end,1:end-1] .+ u[end,2:end])
end

function Iuv_periodic!(v::AbstractMatrix,u::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable v on the v-grid. =#
    @views v[1:end-1,:] .= one_quarter * (u[1:end-1,1:end-1] .+ u[1:end-1,2:end] .+ u[2:end,1:end-1] .+ u[2:end,2:end])
    @views v[end,:] .= one_quarter * (u[1,1:end-1] .+ u[1,2:end] .+ u[end,1:end-1] .+ u[end,2:end])
end

function Ivu_nonperiodic!(u::AbstractMatrix,v::AbstractMatrix)
    #= Interpolates a variable v from the v-grid to a variable u on the u-grid. =#
    @views u[:,2:end-1] .= one_quarter * (v[1:end-1,1:end-1] .+ v[1:end-1,2:end] .+ v[2:end,1:end-1] .+ v[2:end,2:end])
    @views u[:,1] .= one_quarter * (v[1:end-1,1] .+ v[2:end,1])
    @views u[:,end] .= one_quarter * (v[1:end-1,end] .+ v[2:end,end])
end

function Ivu_periodic!(u::AbstractMatrix,v::AbstractMatrix)
    #= Interpolates a variable u from the u-grid to a variable v on the v-grid. =#
    @views u[2:end,2:end-1] .= one_quarter * (v[1:end-1,1:end-1] .+ v[1:end-1,2:end] .+ v[2:end,1:end-1] .+ v[2:end,2:end])
    @views u[1,2:end-1] .= one_quarter * (v[1,1:end-1] .+ v[1,2:end] .+ v[end,1:end-1] .+ v[end,2:end])
    @views u[2:end,1] .= one_quarter * (v[1:end-1,1] .+ v[2:end,1])
    @views u[2:end,end] .= one_quarter * (v[1:end-1,end] .+ v[2:end,end])
    @views u[1,1] .= one_quarter * (v[1,1] .+ v[end,1])
    @views u[1,end] .= one_quarter * (v[1,end] .+ v[end,end])
end

max_stars_repo_name: eschnett/juls

max_issues_repo_name: eschnett/juls

max_forks_repo_name: eschnett/juls


text:
module CPUmonitor

    # Modules

    # Types
    include("CPUStat.jl")

    #Functions
    include("monitor.jl")
    include("track.jl")
    include("parselog.jl")

end


text:
#
# The Computer Language Benchmarks Game
# binary-trees benchmark
# http://shootout.alioth.debian.org/u32/performance.php?test=binarytrees
#
# Ported from an OCaml version
#

abstract BTree

type Empty <: BTree
end

type Node <: BTree
    info
    left::BTree
    right::BTree
end

function make(val, d)
    if d == 0
        Node(val, Empty(), Empty())
    else
        nval = val * 2
        Node(val, make(nval-1, d-1), make(nval, d-1))
    end
end

check(t::Empty) = 0
check(t::Node) = t.info + check(t.left) - check(t.right)

function loop_depths(d, min_depth, max_depth)
    for i = 0:div(max_depth - d, 2)
        niter = 1 << (max_depth - d + min_depth)
        c = 0
        for j = 1:niter
            c += check(make(i, d)) + check(make(-i, d))
        end
#        @printf("%i\t trees of depth %i\t check: %i\n", 2*niter, d, c)
        d += 2
    end
end

function binary_trees(N::Int=10)
    const min_depth = 4
    const max_depth = N
    const stretch_depth = max_depth + 1

    # create and check stretch tree
    let c = check(make(0, stretch_depth))
#        @printf("stretch tree of depth %i\t check: %i\n", stretch_depth, c)
    end

    long_lived_tree = make(0, max_depth)

    loop_depths(min_depth, min_depth, max_depth)
#    @printf("long lived tree of depth %i\t check: %i\n", max_depth, check(long_lived_tree))
end

max_stars_repo_name: jakebolewski/julia

max_issues_repo_name: jakebolewski/julia

max_forks_repo_name: jakebolewski/julia


text:
#number of subscribers when the subreddut is identified by its reddit id
#example: the "resumes" subreddit has id=t5_2r0bv
function idsubscribers(id::AbstractString)
	resp=Requests.get("https://www.reddit.com/api/info/.json?id="*id)
	resp=Requests.json(resp)
	resp["data"]["children"][1]["data"]["subscribers"]
end

#number of subscribers when the subreddut is identified by its name
function subscribers(sub::AbstractString)
	resp=Requests.get("https://www.reddit.com/r/"*sub*"/about.json")
	resp=Requests.json(resp)
	resp["data"]["subscribers"]
end

#convert datetime tuple to Unix time used in reddit timestamps
#timestamp intervals in cloudsearch searches is of the form 1420113600..1420200000
reddittime(yyyy,mm,dd,hh,min,sec)=Int(Dates.datetime2unix(DateTime(yyyy,mm,dd,hh,min,sec)))

#count the number of posts (top coded at 100) between two dates on a given subreddit
function countposts(subreddit::AbstractString,firstday::Tuple{Int64,Int64,Int64},lastday::Tuple{Int64,Int64,Int64})
	timestamp=string(reddittime(firstday[1],firstday[2],firstday[3],00,00,00))*".."*string(reddittime(lastday[1],lastday[2],lastday[3],00,00,00))
	url="https://www.reddit.com/r/"*subreddit*"/search.api?rank=title&limit=100&q=timestamp%3A"*timestamp*"&restrict_sr=on&syntax=cloudsearch"
	# println(url)
	resp=Requests.json(get("https://www.reddit.com/r/"*subreddit*"/search.api?rank=title&limit=200&q=timestamp%3A"*timestamp*"&restrict_sr=on&syntax=cloudsearch"));
	length(resp["data"]["children"])
end

#count the number of daily posts (top-coded at 100) for ndays days
function countdailyposts(subreddit::AbstractString,firstday::Date,ndays::Int64=3)
	dates=collect(firstday:firstday+Dates.Day(ndays-1))
	ts=TimeSeries.TimeArray(dates,zeros(length(dates)),["ts"])
	for i=1:ndays
		ts.values[i]=countposts(subreddit,Dates.yearmonthday(dates[i]),Dates.yearmonthday(dates[i]+Dates.Day(1)))
		sleep(.1)
	end
	ts
end

#parse the /about/traffic page of a subreddit
#2nd column is uniques and first columns is pageviews
function traffic(sub::AbstractString)
	resp=Requests.get("https://www.reddit.com/r/"*sub*"/about/traffic.json")
	resp=Requests.json(resp)
	n=length(resp["hour"])
	hourly=Array(Any,n,3)
	for i=1:n
		hourly[i,1]=Dates.unix2datetime(resp["hour"][i][1])
		hourly[i,2]=resp["hour"][i][2]
		hourly[i,3]=resp["hour"][i][3]
	end
	n=length(resp["day"])
	daily=Array(Any,n,3)
	for i=1:n
		daily[i,1]=Dates.Date(Dates.unix2datetime(resp["day"][i][1]))
		daily[i,2]=resp["day"][i][2]
		daily[i,3]=resp["day"][i][3]
	end
	n=length(resp["month"])
	monthly=Array(Any,n,3)
	for i=1:n
		dt=Dates.unix2datetime(resp["month"][i][1])
		monthly[i,1]=string(year(dt))*"-"*string(month(dt))
		monthly[i,2]=resp["month"][i][2]
		monthly[i,3]=resp["month"][i][3]
	end
	hourly,daily,monthly
end


text:
function compute_mutual_information(boundary_ps, applied_p, prior, sigma, interior_q)
  critical_fs = get_critical_values(boundary_ps, applied_p, prior, interior_q)
  compute_mutual_information(critical_fs, prior, sigma)
end

function compute_mutual_information(critical_fs, prior, sigma)
  nu = sigma^2

  belief = prior[:]
  field = critical_fs[:]

  normals = normal_matrix(field, nu)

  compute_mutual_information(belief, normals)
end

function compute_mutual_information(belief::Array{Float64,1},
                                    normals::Array{Float64,2})
  i1 = integral_cross(belief, normals)
  i2 = integral_joint(belief, normals)
  i3 = integral_marginals(belief, normals)

  out::Float64 = -2*log(e, i1) + log(e, i2) + log(e, i3)

  out
end

function normal_matrix(field::Array{Float64,1}, nu::Float64)
  two_nu::Float64 = 2 * nu

  n = length(field)
  normals = zeros(n, n)

  nhalf_over_nu = - 0.5 / two_nu
  over_sqrt2pinu = 1/sqrt(2*pi*two_nu)

  @inbounds for ii = 1:n
    @fastmath @simd for jj = ii+1:n
      normals[jj,ii] = normal(field[ii] - field[jj], nhalf_over_nu, over_sqrt2pinu)
      normals[ii,jj] = normals[jj,ii]
    end
  end

  @inbounds @fastmath @simd for ii = 1:n
    normals[ii,ii] = normal(0.0, nhalf_over_nu, over_sqrt2pinu)
  end

  normals
end

function integral_cross(belief, normals)
  out::Float64 = 0.0

  @inbounds for ii = 1:length(belief)
    @fastmath @simd for jj = 1:length(belief)
      out += belief[ii]^2 * belief[jj] * normals[jj,ii]
    end
  end
  out /= length(belief)^2

  out
end

function integral_joint(belief, normals)
  out::Float64 = 0.0

  @fastmath @inbounds @simd for ii = 1:length(belief)
    out += belief[ii]^2 * normals[ii,ii]
  end
  out /= length(belief)

  out
end

function integral_marginals(belief, normals)
  val1::Float64 = sum(belief.^2) / length(belief)

  val2::Float64 = 0.0
  @inbounds for ii = 1:length(belief)
    @fastmath @simd for jj = 1:length(belief)
      val2 += belief[ii] * belief[jj] * normals[jj,ii]
    end
  end
  val2 /= length(belief)^2

  out::Float64 = val1 * val2

  out
end

max_stars_repo_name: mcorah/CenterOfMass

max_issues_repo_name: mcorah/CenterOfMass

max_forks_repo_name: mcorah/CenterOfMass


text:
# module GCN
using LightGraphs, MetaGraphs, SimpleWeightedGraphs, LinearAlgebra, Flux, GeometricFlux

A = [
    [0.0, 1.0, 0.0, 0.0, 0.0],
    [1.0, 0.0, 1.0, 0.0, 0.0],
    [0.0, 1.0, 0.0, 1.0, 1.0],
    [0.0, 0.0, 1.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 0.0, 0.0],
]

feats = reshape(1:5, :, 1)

function karate_club_graph()
    # Create the set of all members, and the members of each club.
    include("karate_adjacency_matrix.jl")
    G = Graph(adjacency_mat)
end

g = MetaGraph(karate_club_graph())
communities, _ = label_propagation(g)
for (v, community) in enumerate(communities)
    set_prop!(g, v, :community, community)
end

n_classes = length(unique(communities))
labels = onehotbatch(communities, 1:n_classes)

model = Chain(
    GCNConv(g, 1024 => 512, relu),
    Dropout(0.5),
    GCNConv(g, 512 => 128),
    Dense(128, 10),
    softmax,
)

#TODO impl on abstractgraph
# communities=greedy_modularity_communities(g)

## Loss
loss(x, y) = logitcrossentropy(model(x), y)
accuracy(x, y) = mean(onecold(model(x)) .== onecold(y))

## Training
ps = Flux.params(model)
train_X = 1:3
train_Y = [get_prop(g, v, :community) for v in train_X]
train_data = [(train_X, train_y)]

opt = ADAM(0.01)
evalcb() = @show(accuracy(train_X, train_y))

train!(loss, ps, train_data, opt, cb = throttle(evalcb, 10))

# end

max_stars_repo_name: alok/GCN

max_issues_repo_name: alok/GCN

max_forks_repo_name: alok/GCN


text:
using SparseDiffTools
vertices = [10,10,20,20,50]

sources = [[8,5,4,7,8,2,10,4,4,2,2],

        [3,8,3,4,3,2,5,6,1,3,1,4,4,5,6,8,10,2,1,10,1],

        [16,12,8,2,14,20,20,13,11,11,1],

        [9,4,1,8,11,5,13,20,8,3,6,10,17,18,14,6,2,2,14,8,10,8,1,6,16,14,11,3,7,3,1,12,18,1,9,9,19,13,4,19,4],

        [10,41,49,35,13,5,17,6,21,46,49,43,3,16,28,11,45,30,36,3,35,49,40,8,38,49,24,7,24,38,27,41,27,43,47,
        36,48,10,14,31,37,38,5,8,42,18,17,17,49,30,1,34,34,30,19,19,12,1,9,48,33,12,11,37,14,46,30,21,8,44,
        19,19,16,1,32,33,13,30,22,36,16,43,32,25,7,46,48,45,18,1,15,35,5,35,1,44,11,23,31,6,43]]

destinations = [[10,6,2,9,6,10,3,7,10,9,5],

                [4,3,9,7,5,10,4,5,9,2,3,6,2,10,7,5,7,8,2,3,6],

                [18,16,10,1,13,11,12,19,18,6,7],

                [14,16,15,3,17,2,4,15,13,12,18,8,4,19,17,20,20,14,11,2,9,16,2,12,13,8,19,2,14,13,14,9,5,12,17,3,17,1,2,4,20],

                [21,10,7,14,44,38,5,32,16,10,8,9,41,36,45,21,17,18,37,31,11,40,45,17,34,16,25,17,12,50,12,32,5,15,25,1,18,32,
                45,46,22,29,50,10,18,21,21,16,45,49,29,46,22,2,12,13,50,34,4,1,21,32,17,24,12,50,15,7,47,7,7,40,29,15,13,2,22,
                28,28,31,2,1,17,22,35,28,46,31,6,46,29,16,12,17,32,41,40,30,29,47,41]]

coloring = [[1,1,1,3,2,1,1,3,2,2],

        [3,2,1,3,2,1,2,3,2,3],

        [1,2,1,1,1,2,2,1,1,2,1,1,1,2,1,2,1,3,2,2],

        [3,1,2,3,2,3,1,3,3,1,3,1,1,2,1,2,1,1,2,2],

        [3,1,1,1,2,3,3,2,2,1,3,3,3,1,2,3,1,1,1,1,2,2,1,1,3,1,1,1,1,3,2,2,3,1,2,1,3,3,1,2,3,2,1,1,3,4,1,2,1,1]]

v1 = zeros(Int64,0)
v2 = zeros(Int64,0)
v3 = zeros(Int64,0)
v4 = zeros(Int64,0)
v5 = zeros(Int64,0)

a1 = [Vector{Int64}() for _ in 1:vertices[1]]
a2 = [Vector{Int64}() for _ in 1:vertices[2]]
a3 = [Vector{Int64}() for _ in 1:vertices[3]]
a4 = [Vector{Int64}() for _ in 1:vertices[4]]
a5 = [Vector{Int64}() for _ in 1:vertices[5]]

g1 = CGraph(v1,a1)
g2 = CGraph(v2,a2)
g3 = CGraph(v3,a3)
g4 = CGraph(v4,a4)
g5 = CGraph(v5,a5)

graphs = [g1,g2,g3,g4,g5]

for j = 1:5
        for i = 1:vertices[j]
                add_vertex!(graphs[j],i)
        end
end

for j = 1:5
        for i = 1:length(sources[j])
                s = sources[j][i]
                d = destinations[j][i]
                add_edge!(graphs[j],sources[j][i],destinations[j][i])
        end
end


text:
######################
# BASIC VARIABLES
######################

# Variable definition
x = 5
y = "3"
a,b = 3, 5
println(x," ", y," ", a," ", b) # 5 3 3 5

# Double a variable
x = 2x
println(x) # 10

# Make it exponential
x = x^2
println(x) # 100

# Array definition
arr = [1, 2, 3, 4]
println(arr) # [1, 2, 3, 4]

# Dot "." operator
arr .= arr.^2
println(arr) # [1, 4, 9, 16]

# @. macro
@. arr=arr^2
println(arr) # [1, 16, 81, 256]

# Double arr
arr = 2arr # or arr.*2
println(arr) # [2, 32, 162, 512]

# NaN
nan = NaN
println(nan == NaN) # false

######################
# COMPLEX NUMBERS
######################

# Complex number
c1 = 3+2im
c2 = 3-2im
println(c1 * c2) # 13 + 0im

# Adding real and complex number
println(x + c1) # 103+2im

# Adding complex and complex number
println(c2 + 3im) # 3+1im

# Real part
println(real(c1)) # 3

# Imaginary part
println(imag(c2)) # -2

# Complex conjugate
println(conj(c1) == c2) # true

######################
# RATIONAL NUMBERS
######################

# Define rational number
r1 = 4//5
println(r1) # 4//5

# If the numerator and denominator of a rational have common factors,
# they are reduced to lowest terms such that the denominator is non-negative

r2 = 4//8
println(r2) # 1//2

println(r1 == 8//10) # true

max_stars_repo_name: Nikola-Mircic/julia-cheatsheet

max_issues_repo_name: Nikola-Mircic/julia-cheatsheet

max_forks_repo_name: Nikola-Mircic/julia-cheatsheet


text:
# Example for extended source modeling with Flux
# Author: Philipp Witte, pwitte3@gatech.edu
# Date: April 2020
#

using JUDI, SegyIO, JOLI, Flux, JUDI4Flux

# Set up model structure
n = (120, 100)   # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)

# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:, Int(round(end/2)):end] .= 4f0

# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2

# Setup info and model structure
nsrc = 1	# number of sources
model = Model(n, d, o, m)

# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)

# receiver sampling and recording time
time = 1000f0   # receiver recording time [ms]
dt = 1f0    # receiver sampling interval [ms]

# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)

# setup wavelet
f0 = 0.01f0     # MHz
wavelet = ricker_wavelet(time, dt, f0)

# Set up info structure for linear operators
ntComp = get_computational_nt(recGeometry, model)
info = Info(prod(n), nsrc, ntComp)

# return linearized data as Julia array
opt = Options(return_array=true, dt_comp=dt)

# Linear operators
Pr = judiProjection(info, recGeometry)
A_inv = judiModeling(info, model; options=opt)
Pw = judiLRWF(info, wavelet)
F = Pr*A_inv*adjoint(Pw)

#####################################################################################

# Build CNN
n_in = 10
n_out = 8
batchsize = nsrc

conv1 = Conv((3, 3), n_in => 1, stride=1, pad=1)
conv2 = Conv((3, 3), 1 => n_out, stride=1, pad=1)

G = ExtendedQForward(F)
G_T = ExtendedQAdjoint(F)

function network(x, m)
    x = conv1(x)
    x = G(x, m)
    x = G_T(x, m)
    x = conv2(x)
    return x
end

loss(x, m, y) = Flux.mse(network(x, m), y)

x = randn(Float32, n[1], n[2], n_in, batchsize)
m = reshape(m, n[1], n[2], 1, 1)    #
y = randn(Float32, n[1], n[2], n_out, batchsize)

# Compute gradient of parameters
p =  params(x, m, y, conv1, conv2)
gs = gradient(() -> loss(x, m, y), p)

# Access gradients
Δx = gs[x]
Δm = gs[m]
Δy = gs[y]
Δw1 = gs[conv1.weight]
Δb1 = gs[conv1.bias]


text:
# ================================================================
# Template reach set
# ================================================================

"""
    TemplateReachSet{N, VN, TN<:AbstractDirections{N, VN}, SN<:AbstractVector{N}} <: AbstractLazyReachSet{N}

Reach set that stores the support function of a set at a give set of directions.

### Notes

The struct has the following parameters:

- `N`  -- refers to the numerical type of the representation.
- `VN` -- refers to the vector type of the template
- `TN` -- refers to the template type
- `SN` -- vector type that holds the support function evaluations

Concrete subtypes of `AbstractDirections` are defined in the `LazySets` library.

This reach-set implicitly represents a set by a set of directions and support
functions. `set(R::TemplateReachSet)` returns a polyhedron in half-space
representation.

Apart from the getter functions inherited from the `AbstractReachSet` interface,
the following methods are available:

- `directions(R)`           -- return the set of directions normal to the faces of this reach-set
- `support_functions(R)`    -- return the vector of support function evaluations
- `support_functions(R, i)` -- return the `i`-th coordinate of the vector of support function evaluatons
"""
struct TemplateReachSet{N, VN, TN<:AbstractDirections{N, VN}, SN<:AbstractVector{N}} <: AbstractLazyReachSet{N}
    dirs::TN
    sf::SN
    Δt::TimeInterval
end

# constructor from a given set (may overapproximate)
function TemplateReachSet(dirs::AbstractDirections, X::LazySet, Δt::TimeInterval)
    sfunc = [ρ(d, X) for d in dirs]
    return TemplateReachSet(dirs, sfunc, Δt)
end

# constructor from a given reach-set (may overapproximate)
function TemplateReachSet(dirs::AbstractDirections, R::AbstractLazyReachSet)
    return TemplateReachSet(dirs, set(R), tspan(R))
end

# constructor with a time point
function TemplateReachSet(dirs::AbstractDirections{N}, X::LazySet, t::N) where {N}
    return TemplateReachSet(dirs, X, interval(t))
end

# abstract reachset interface
function set(R::TemplateReachSet)
    T = isbounding(R.dirs) ? HPolytope : HPolyhedron
    return T([HalfSpace(di, R.sf[i]) for (i, di) in enumerate(R.dirs)])
end

# FIXME requires adding boundedness property as a type parameter
setrep(::Type{<:TemplateReachSet{N, VN}}) where {N, VN} = HPolyhedron{N, VN}
setrep(::TemplateReachSet{N, VN}) where {N, VN} = HPolyhedron{N, VN}

tspan(R::TemplateReachSet) = R.Δt
tstart(R::TemplateReachSet) = inf(R.Δt)
tend(R::TemplateReachSet) = sup(R.Δt)
dim(R::TemplateReachSet) = dim(R.dirs)
vars(R::TemplateReachSet) = Tuple(Base.OneTo(dim(R)),)

directions(R::TemplateReachSet) = R.dirs
support_functions(R::TemplateReachSet) = R.sf
support_functions(R::TemplateReachSet, i::Int) = R.sf[i]

# get the matrix of support function evaluations, assuming that the vector
# of support function evaluations for the reach-set is a view
function support_function_matrix(R::TemplateReachSet{N, VN, TN, SN}) where {N, VN, TN, SN<:SubArray}
    return R.sf.parent
end

_collect(dirs::AbstractDirections) = collect(dirs)
_collect(dirs::CustomDirections) = dirs.directions

# convenience functions to get support directions of a given set
_getdirs(X::LazySet) = [c.a for c in constraints_list(X)]
LazySets.CustomDirections(X::LazySet) = CustomDirections(_getdirs(X), dim(X)) # TODO may use isboundedtype trait

# overapproximate a given reach-set with a template
function overapproximate(R::AbstractLazyReachSet, dirs::AbstractDirections) where {VN}
    return TemplateReachSet(dirs, R)
end

function overapproximate(R::AbstractLazyReachSet, dirs::Vector{VN}) where {VN}
    return TemplateReachSet(CustomDirections(dirs), R)
end


text:
# Fri 28 Dec 2012 03:51:13 PM EST
#
# NeHe Tut 11 - Flag Effect (Waving Texture)
#
# Q - quit

# load necessary GL/SDL routines

using OpenGL
@OpenGL.version "1.0"
@OpenGL.load
using SDL

# initialize variables

bpp            = 16
wintitle       = "NeHe Tut 11"
icontitle      = "NeHe Tut 11"
width          = 640
height         = 480

points         = Array(Float64,(45,45,3))

for x=1:45
    for y=1:45
        points[x,y,1] = x/5-4.5
        points[x,y,2] = y/5-4.5
        points[x,y,3] = sin((((x/5)*40)/360)*2*pi)
    end
end

wiggle_count       = 0

xrot               = 0
yrot               = 0
zrot               = 0

T0                 = 0
Frames             = 0

keystate_checked   = false
lastkeycheckTime   = 0
key_repeatinterval = 75 #ms

# open SDL window with an OpenGL context

SDL_Init(SDL_INIT_VIDEO)
#videoInfo = SDL_GetVideoInfo()
videoFlags = (SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_RESIZABLE)
#if videoInfo.hw_available
    videoFlags = (videoFlags | SDL_HWSURFACE)
#else
    #videoFlags = (videoFlags | SDL_SWSURFACE)
#end
#if videoInfo.blit_hw
    videoFlags = (videoFlags | SDL_HWACCEL)
#end
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
SDL_SetVideoMode(width, height, bpp, videoFlags)
SDL_WM_SetCaption(wintitle, icontitle)

glViewport(0, 0, width, height)
glClearColor(0.0, 0.0, 0.0, 0.5)
glClearDepth(1.0)
glDepthFunc(GL_LEQUAL)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()

gluPerspective(45.0,width/height,0.1,100.0)

glMatrixMode(GL_MODELVIEW)

# load textures from images

tex   = Array(Uint32,1) # generating 1 texture

img, w, h = glimread(expanduser("~/.julia/SDL/Examples/NeHe/tut11/tim.bmp"))

glGenTextures(1,tex)
glBindTexture(GL_TEXTURE_2D,tex[1])
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, img)

# enable texture mapping

glEnable(GL_TEXTURE_2D)

# enable Polygon filling

glPolygonMode(GL_BACK, GL_FILL)
glPolygonMode(GL_FRONT, GL_LINE)

# main drawing loop

while true
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    glTranslate(0.0, 0.0, -12.0)

    glRotate(xrot,1.0,0.0,0.0)
    glRotate(yrot,0.0,1.0,0.0)
    glRotate(zrot,0.0,0.0,1.0)

    glBindTexture(GL_TEXTURE_2D,tex[1])

    glBegin(GL_QUADS)
        for x=1:44
            for y=1:44
                tex_x  = x/45
                tex_y  = y/45
                tex_xb = (x+1)/45
                tex_yb = (y+1)/45

                glTexCoord(tex_x, tex_y)
                glVertex(points[x,y,1],points[x,y,2],points[x,y,3])
                glTexCoord(tex_x, tex_yb)
                glVertex(points[x,y+1,1],points[x,y+1,2],points[x,y+1,3])
                glTexCoord(tex_xb, tex_yb)
                glVertex(points[x+1,y+1,1],points[x+1,y+1,2],points[x+1,y+1,3])
                glTexCoord(tex_xb, tex_y)
                glVertex(points[x+1,y,1],points[x+1,y,2],points[x+1,y,3])
            end
        end
    glEnd()

    if wiggle_count == 2
        for y=1:45
            hold = points[1,y,3]
            for x=1:44
                points[x,y,3] = points[x+1,y,3]
            end
            points[45,y,3] = hold
        end
        wiggle_count = 0
    end

    wiggle_count +=1

    Frames +=1
    t = SDL_GetTicks()
    if (t - T0) >= 5000
        seconds = (t - T0)/1000
        fps = Frames/seconds
        println("$Frames frames in $seconds seconds = $fps")
        T0 = t
        Frames = 0
    end

    xrot +=0.3
    yrot +=0.2
    zrot +=0.4

    SDL_GL_SwapBuffers()

    SDL_PumpEvents()
    if SDL_GetTicks() - lastkeycheckTime >= key_repeatinterval
        keystate         = SDL_GetKeyState()
        keystate_checked = true
        lastkeycheckTime = SDL_GetTicks()
    end

    # Sampling rates for event processing are so fast that a single key press
    # lasts through several iterations of this loop.  This means that one press
    # can be seen as 50 or more presses by the SDL event system.  To correct
    # for this, we only check keypresses every 75ms.

    if keystate_checked == true
        if keystate[SDLK_q] == true
            break
        end
        keystate_checked = false
    end
end


text:
# Author: Vincent Arel-Bundock
# Contact: varel@umich.edu
# License: BSD-3
# Original code from the python statsmodels project
# https://github.com/statsmodels/statsmodels

function qreg_coef(y::Vector, X::Matrix, q::Real, s::IRLS)
    n, p = size(X)
    xstar = copy(X)
    diff = Inf

    beta0 = Array{Float64}(p)
    beta = Array{Float64}(p)
    xtx = Array{Float64}(p, p)
    xty = Array{Float64}(p)
    xbeta = Array{Float64}(n)
    resid = Array{Float64}(n)

    for itr in 1:s.maxIter
        if diff > s.tol
            copy!(beta0, beta)

            At_mul_B!(xtx, xstar, X)
            At_mul_B!(xty, xstar, y)
            beta = xtx \ xty
            A_mul_B!(xbeta, X, beta)

            for i in 1:n
                @inbounds resid[i] = y[i] - xbeta[i]
            end

            for i in 1:n
                if abs(resid[i]) < s.threshold
                    @inbounds resid[i] = sign(resid[i]) * s.threshold
                end
                if resid[i] < 0
                    @inbounds resid[i] = abs(q * resid[i])
                else
                    @inbounds resid[i] = abs((1 - q) * resid[i])
                end
            end

            broadcast!(/, xstar, X, resid)

            diff = norm(beta0-beta, Inf)
        end
    end
    return beta
end


text:
"""
    Multiquadric(lnℓ::AbstractFloat) <: RadialKernel{SqEuclidean}

TODO
"""
mutable struct Multiquadric{F<:AbstractFloat} <: RadialKernel{SqEuclidean}
    # TODO
end


text:
module PreprocessUnits
  include("sentence_splitter.jl")
  include("tokenizer.jl")
  include("pos_tagger.jl")
end

max_stars_repo_name: LarsWl/DependencyParser

max_issues_repo_name: LarsWl/DependencyParser

max_forks_repo_name: LarsWl/DependencyParser


text:
module Examples
using ProjectManagement

const empty = Project(
    (
        start=0,
        finish=0,
    ),
    [
        :start => :finish,
    ]
)

const onetask = Project(
    (
        start=0,
        a = PertBeta(0,1,2),
        finish=0,
    ),
    [
        :start => :a,
        :a => :finish,
    ]
)

"Two tasks in parellel `:short` and `:long`. `:long` completely controls the timing."
const shortlong = Project(
    (
        start=0,
        short = PertBeta(0,1,2),
        long = PertBeta(10,100,200),
        finish=0,
    ),
    [
        :start .=> [:short, :long];
        [:short, :long] .=> :finish;
    ]
)

const chain = Project(
    (
        start=0,
        a=PertBeta(1,2,3),
        b=PertBeta(10,20,30),
        c=PertBeta(100,200,300),
        finish=0,
    ),
    [
        :start => :a,
        :a => :b,
        :b => :c,
        :c => :finish,
    ]
)

const medium = Project(
    (
        start=0,
        a=PertBeta(2,3,4),
        b=PertBeta(1,2,6),
        c=PertBeta(0,1,2),
        d=PertBeta(0,1,2),
        e=PertBeta(0,1,2),
        f=PertBeta(3.0, 6.5, 13.0),
        g=PertBeta(3.5, 7.5, 14.0),
        h=PertBeta(0, 1, 2),
        j=PertBeta(0, 1, 2),
        finish=0,
    ),
    [
        :start .=> [:a, :b, :c, :d];
        :a => :f;
        :b .=> [:f, :g];
        [:c, :d] .=> :e;
        :e .=> [:f, :g, :h];
        [:f, :g, :h] .=> :j;
        :j => :finish;
    ]
)

end # module


text:
# ======================
# Test property creation
# ======================
X1 = LinearConstraint([1.; zeros(7)], 0.35)
X2 = LinearConstraint([zeros(4); 1.; zeros(3)], 0.45)

p1 = SafeStatesProperty(X1)
p2 = BadStatesProperty(X2)
p3 = Conjunction([p1, p2])
p4 = Disjunction([p1, p2])
p5 = Conjunction([p3, Disjunction([p1, p4]), p2])

@test dim(p1) == dim(p2) == dim(p3) == dim(p4) == dim(p5) == 8


text:
using Test

include("../src/a_star.jl")

@testset "AStar" begin
  include("reachnumber.jl")
  include("maze.jl")
  include("15puzzle.jl")
  include("collatz.jl")
end


text:
"""
	loop constraints
"""

struct LoopDelta <: Constraints
	n
	ineq
	x_idx
	t_idx1
	t_idx2
end

function loop_delta_constraints(model::BipedPinned, x_idx, t_idx1, t_idx2)
	n = length(x_idx)
	ineq = (1:0)
	return LoopDelta(n, ineq, x_idx, t_idx1, t_idx2)
end

function constraints!(c, Z, con::LoopDelta, model::BipedPinned, idx, h, T)
	n = con.n
	a = view(Z, idx.x[con.t_idx1])[con.x_idx]
	b = Δ(view(Z, idx.x[con.t_idx2]))[con.x_idx]

	c[1:n] = b - a

    return nothing
end

function constraints_jacobian!(∇c, Z, con::LoopDelta, model, idx, h, T)
	n = con.n

	shift = 0

	r_idx = 1:con.n
	c_idx = idx.x[con.t_idx2][con.x_idx]
	len = length(r_idx) * length(c_idx)
	∇c[shift .+ (1:len)] = vec(ForwardDiff.jacobian(Δ,
		view(Z, idx.x[con.t_idx2]))[con.x_idx, con.x_idx])
	shift += len

	c_idx = idx.x[con.t_idx1][con.x_idx]
	len = length(r_idx) * length(c_idx)
	∇c[shift .+ (1:len)] = vec(Diagonal(-1.0 * ones(n)))
	shift += len
	return nothing
end

function constraints_sparsity(con::LoopDelta, model, idx, T;
		shift_row = 0, shift_col = 0)
	row = []
    col = []

	n = con.n

	r_idx = shift_row .+ (1:n)

	c_idx = shift_col .+ idx.x[con.t_idx2][con.x_idx]
	row_col!(row, col, r_idx, c_idx)

	c_idx = shift_col .+ idx.x[con.t_idx1][con.x_idx]
	row_col!(row, col, r_idx, c_idx)

    return collect(zip(row, col))
end


text:
include("../emi.jl")
using EMI
using EMI.Draw, EMI.Gmsh

# from .. run as emi-gmsh demos/FILE.JL demos/FILE
# Something like this with ellipse
#   ^
#  / \
# [   ]
#  \ /
#   U

const M, m, dx, dy = 1, 0.8, 0.2, 0.3
@assert M > m
loop = Loop([Line(Point(0, dx+dy+m), Point(0, dy+m)),
             Line(Point(0, dy+m), Point(dy, dy+m)),
             EllipseArc(Point(dy, dy+m), Point(dy+M, dy+m), Point(dy+M, dy)),
             Line(Point(dy+M, dy), Point(dy+M, 0)),
             Line(Point(dy+M, 0), Point(dx+dy+M, 0)),
             Line(Point(dx+dy+M, 0), Point(dx+dy+M, dy)),
             EllipseArc(Point(dx+dy+2*M, dy+m), Point(dx+dy+M, dy+m), Point(dx+dy+M, dy)),
             Line(Point(dx+dy+2*M, dy+m), Point(dx+2*dy+2*M, dy+m)),
             Line(Point(dx+2*dy+2*M, dy+m), Point(dx+2*dy+2*M, dx+dy+m)),
             Line(Point(dx+2*dy+2*M, dx+dy+m), Point(dx+dy+2*M, dx+dy+m)),
             EllipseArc(Point(dx+dy+2*M, dx+dy+m), Point(dx+dy+M, dx+dy+m), Point(dx+dy+M, dx+dy+2*m)),
             Line(Point(dx+dy+M, dx+dy+2*m), Point(dx+dy+M, dx+2*dy+2*m)),
             Line(Point(dx+dy+M, dx+2*dy+2*m), Point(dy+M, dx+2*dy+2*m)),
             Line(Point(dy+M, dx+2*dy+2*m), Point(dy+M, dx+dy+2*m)),
             EllipseArc(Point(dy, dx+dy+m), Point(dy+M, dx+dy+m), Point(dy+M, dx+dy+2*m)),
             Line(Point(dy, dx+dy+m), Point(0, dx+dy+m))])

canvas = Canvas()
canvas = canvas + loop

set_bbox!(canvas, 0.2, 0.3)
gmsh_script(canvas, 0.2)

max_stars_repo_name: MiroK/emi-cylinders

max_issues_repo_name: MiroK/emi-cylinders

max_forks_repo_name: MiroK/emi-cylinders


text:
module CollabUtils2RainbowBerryUnlockCutsceneTrigger

using ..Ahorn, Maple

@mapdef Trigger "CollabUtils2/RainbowBerryUnlockCutsceneTrigger" RainbowBerryUnlockCutsceneTrigger(x::Integer, y::Integer, width::Integer=Maple.defaultTriggerWidth, height::Integer=Maple.defaultTriggerHeight)

const placements = Ahorn.PlacementDict(
    "Rainbow Berry Unlock Cutscene (Collab Utils 2 / READ DOCS)" => Ahorn.EntityPlacement(
        RainbowBerryUnlockCutsceneTrigger,
        "rectangle",
    ),
)

end


text:
include("functions_cvlm.jl")

#Cl_spn,nspn,spn_map,spn_loc,θ,rhs,AIC,AICₜ,AICₘ,Λ,sbar,ebar,ds,Γ,chord,cbar,mbar,nbar,Cl,CL,CDind,CDind_ff,SpnLd = main("input.yaml");
#Px = Py = Pz = Qx = Qy = Qz = zeros(6,6)
sol,Px,Py,Pz,Qx,Qy,Qz,lat2wing_map = main("input.yaml","motion_param.yaml");

nsteps= size(sol.u,1)
xyz = zeros(3,nsteps)
xyz1= zeros(3,nsteps)
for i in 1:nsteps
    xyz[:,i]  = sol.u[i][10:12]
    #xyz1[:,i] = solwing.u[i][10:12]
end

#p = plot3d(2,labels=["Wing+tail" "Wing only"],xlabel="X-coord",ylabel="Y-coord",zlabel="Z-coord",xlim=(minimum(xyz[1,:]),maximum(xyz[1,:])),ylim=(minimum(xyz[2,:]),maximum(xyz[2,:])),zlim=(minimum(xyz[3,:]),maximum(xyz[3,:])),marker=2)
#p = plot3d!(p,2)
p = plot3d(1,labels=["Wing+tail"],xlabel="X-coord",ylabel="Y-coord",zlabel="Z-coord",xlim=(minimum(xyz[1,:]),maximum(xyz[1,:])),ylim=(minimum(xyz[2,:]),maximum(xyz[2,:])),zlim=(minimum(xyz[3,:]),maximum(xyz[3,:])),marker=2)
gif = @gif for i in 1:nsteps
    push!(p,1,xyz[1,i],xyz[2,i],xyz[3,i])
    #push!(p,2,xyz1[1,i],xyz1[2,i],xyz1[3,i])
end every 1

max_stars_repo_name: rohitvuppala/CVLM

max_issues_repo_name: rohitvuppala/CVLM

max_forks_repo_name: rohitvuppala/CVLM


text:
# Geometric spanner functionality

# Returns the edges of a geometric t-spanner for a weighted graph with
# vertices representing the rows of X and edge weights given by the
# L1 distance between vertices
#
# Args:
#   X - n x p matrix of points in R^d
#   t - geometric spanner dilation factor (2.0 by default)
#   valid_edges - an array of vertex index pairs representing the initial
#     edges in the graph; if empty, it is assumed that initial graph is
#     the complete graph on X (empty by default)
function getspanneredges(X::Array{Float64};
                         t::Float64=2.0,
                         valid_edges::Array{Int64,2}=Array{Int64}(0,0))
    n = size(X, 1)
    # Return empty edge set of only one point in X
    n > 1 || return Array{Int64}(0,2)

    p = size(X, 2)
    if p == 1 && isempty(valid_edges)
        # In the univariate complete graph case, return edges between
        # consecutive points in sorted order
        sortorder = sortperm(vec(X))
        return [sortorder[1:n-1] sortorder[2:n]]
    end

    pointlist = vec(X.');
    valid_edges_vec = vec(valid_edges.');
    num_valid_edges = size(valid_edges, 1);
    spannerlib = Libdl.dlopen(libsteinspanner);

    ed = ccall(
        Libdl.dlsym(spannerlib, :prune_edges),
        Ptr{Cint},
        (Ptr{Cdouble}, Cint, Cint, Cdouble, Ptr{Clonglong}, Cint),
        pointlist, n, p, t, valid_edges_vec, num_valid_edges
    );

    numedges = unsafe_load(ed, 1);
    c_edges = Array{Cint}(2*numedges);

    ccall(
        Libdl.dlsym(spannerlib, :load_edges),
        Void,
        (Ptr{Void}, Ptr{Cint}),
        ed, c_edges
    );

    return reshape(c_edges + 1, 2, convert(Int64, numedges)).';
end


text:
infile = "./src/Day10/input.txt"
input = parse.(Int,readlines(infile))

s = sort(input)
push!(s, maximum(s) + 3)
pushfirst!(s, 0)
d = diff(s)
ones = count(i -> i == 1,d)
threes =  count(i -> i == 3,d)
 ones*threes

test1 = sort([16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4 ])
pushfirst!(test1, 0)
diffs = diff(test1)

# from a particular index, count all the ways to get to the end
function countways!(pathdict, adapters, idx)
    if haskey(pathdict, idx)
        return pathdict[idx]
    end
    if idx == length(adapters)
        return 1
    end
    count = 0
    # can hop by size 1?
    if adapters[idx+1] - adapters[idx] <= 3
        # then this hop is valid, and need number of subsequent hops
        count += countways!(pathdict, adapters, idx + 1)
    end
    # can hop by 2 positions?
    if idx+2 <= length(adapters) && adapters[idx + 2] - adapters[idx] <= 3
        # then this hop is valid, and need number of subsequent hops
        count += countways!(pathdict, adapters, idx + 2)
    end
    # can hop by 3  positions?
    if idx+3 <= length(adapters) && adapters[idx + 3] - adapters[idx] <= 3
        # then this hop is valid, and need number of subsequent hops
        count += countways!(pathdict, adapters, idx + 3)
    end
    pathdict[idx] = count
end

pathdict = Dict{Int,Int}()
countways!(pathdict, adapters, 1)


text:
using LinearAlgebra
using LinearMaps
using ProgressMeter

struct HMatrix{T,I} <: LinearMaps.LinearMap{T}
    fullmatrixviews::Vector{FullMatrixView{T,I}}
    matrixviews::Vector{LowRankMatrixView{T,I}}
    rowdim::I
    columndim::I
    nnz::I
    maxrank::I
end

function nnz(hmat::HMatrix) where HT <: HMatrix
    return hmat.nnz
end

function compressionrate(hmat::HT) where HT <: HMatrix
    fullsize = hmat.rowdim*hmat.columndim
    return (fullsize - nnz(hmat))/fullsize
end

import Base.:size

function size(hmat::HMatrix, dim=nothing)
    if dim === nothing
        return (hmat.rowdim, hmat.columndim)
    elseif dim == 1
        return hmat.rowdim
    elseif dim == 2
        return hmat.columndim
    else
        error("dim must be either 1 or 2")
    end
end

function size(hmat::Adjoint{T}, dim=nothing) where T <: HMatrix
    if dim === nothing
        return reverse(size(adjoint(hmat)))
    elseif dim == 1
        return size(adjoint(hmat),2)
    elseif dim == 2
        return size(adjoint(hmat),1)
    else
        error("dim must be either 1 or 2")
    end
end

@views function LinearAlgebra.mul!(y::AbstractVecOrMat, A::HMatrix, x::AbstractVector)
    LinearMaps.check_dim_mul(y, A, x)

    fill!(y, zero(eltype(y)))

    b = zeros(eltype(y), 200)
    c = zeros(eltype(y), size(A,1))

    for fmv in A.fullmatrixviews
        mul!(c[1:size(fmv.matrix,1)], fmv.matrix, x[fmv.rightindices])
        y[fmv.leftindices] .+= c[1:size(fmv.matrix,1)]
        #y[fmv.leftindices] += fmv.matrix * x[fmv.rightindices]
    end

    for lmv in A.matrixviews
        mul!(b[1:size(lmv.rightmatrix,1)], lmv.rightmatrix, x[lmv.rightindices])
        mul!(c[1:size(lmv.leftmatrix,1)], lmv.leftmatrix, b[1:size(lmv.rightmatrix,1)])
        y[lmv.leftindices] .+= c[1:size(lmv.leftmatrix,1)]
    end

    return y
end

@views function LinearAlgebra.mul!(
    y::AbstractVecOrMat,
    transA::LinearMaps.TransposeMap{<:Any,<:HMatrix},
    x::AbstractVector
)
    LinearMaps.check_dim_mul(y, transA, x)

    fill!(y, zero(eltype(y)))

    b = zeros(eltype(y), 200)
    c = zeros(eltype(y), size(transA,1))

    for afmv in transA.lmap.fullmatrixviews
        mul!(c[1:size(transpose(afmv.matrix),1)], transpose(afmv.matrix), x[afmv.leftindices])
        y[afmv.rightindices] .+= c[1:size(adjoint(afmv.matrix),1)]
        #y[afmv.rightindices] += adjoint(afmv.matrix) * x[afmv.leftindices]
    end

    for almv in transA.lmap.matrixviews
        mul!(b[1:size(almv.leftmatrix,2)], transpose(almv.leftmatrix), x[almv.leftindices])
        mul!(
            c[1:size(almv.rightmatrix,2)],
            transpose(almv.rightmatrix),
            b[1:size(almv.leftmatrix,2)]
        )
        y[almv.rightindices] .+= c[1:size(almv.rightmatrix,2)]
        #y[almv.rightindices] += almv.rightmatrix'*(almv.leftmatrix' * x[almv.leftindices])
    end

    return y
end

@views function LinearAlgebra.mul!(
    y::AbstractVecOrMat,
    transA::LinearMaps.AdjointMap{<:Any,<:HMatrix},
    x::AbstractVector
)
    LinearMaps.check_dim_mul(y, transA, x)

    fill!(y, zero(eltype(y)))

    b = zeros(eltype(y), 200)
    c = zeros(eltype(y), size(transA,1))

    for afmv in transA.lmap.fullmatrixviews
        mul!(c[1:size(adjoint(afmv.matrix),1)], adjoint(afmv.matrix), x[afmv.leftindices])
        y[afmv.rightindices] .+= c[1:size(adjoint(afmv.matrix),1)]
        #y[afmv.rightindices] += adjoint(afmv.matrix) * x[afmv.leftindices]
    end

    for almv in transA.lmap.matrixviews
        mul!(b[1:size(almv.leftmatrix,2)], almv.leftmatrix', x[almv.leftindices])
        mul!(
            c[1:size(almv.rightmatrix,2)],
            almv.rightmatrix',
            b[1:size(almv.leftmatrix,2)]
        )
        y[almv.rightindices] .+= c[1:size(almv.rightmatrix,2)]
        #y[almv.rightindices] += almv.rightmatrix'*(almv.leftmatrix' * x[almv.leftindices])
    end

    return y
end

function HMatrix(
    matrixassembler::Function,
    testtree::N,#::BoxTreeNode,
    sourcetree::N;#::BoxTreeNode;
    compressor=:naive,
    tol=1e-4,
    maxrank=100,
    T=ComplexF64,
    I=Int64,
    threading=:single,
    farmatrixassembler=matrixassembler,
    verbose=false,
    svdrecompress=true
) where N <: AbstractNode

    fullinteractions = SVector{2}[]
    compressableinteractions = SVector{2}[]

    computerinteractions!(
        testtree,
        sourcetree,
        fullinteractions,
        compressableinteractions
    )
    fullmatrixviews_perthread = Vector{FullMatrixView{T, I}}[]
    fullmatrixviews = FullMatrixView{T, I}[]

    rowdim = length(testtree.data)
    coldim = length(sourcetree.data)

    nonzeros_perthread = I[]
    nonzeros = 0
    verbose && println("Number of full interactions: ", length(fullinteractions))
    verbose && println(
        "Number of compressable interactions: ",
        length(compressableinteractions)
    )

    if verbose
        p = Progress(length(fullinteractions), desc="Computing full interactions: ")
    end

    if threading == :single
        for fullinteraction in fullinteractions
            nonzeros += length(fullinteraction[1].data)*length(fullinteraction[2].data)
            push!(
                fullmatrixviews,
                getfullmatrixview(
                    matrixassembler,
                    fullinteraction[1],
                    fullinteraction[2],
                    rowdim,
                    coldim,
                    T=T, I=I
                )
            )
            verbose && next!(p)
        end
    elseif threading == :multi
        for i in 1:Threads.nthreads()
            push!(fullmatrixviews_perthread, FullMatrixView{T, I}[])
            push!(nonzeros_perthread, 0)
        end

        Threads.@threads for fullinteraction in fullinteractions
            nonzeros_perthread[Threads.threadid()] +=
                length(fullinteraction[1].data)*length(fullinteraction[2].data)
            push!(
                fullmatrixviews_perthread[Threads.threadid()],
                getfullmatrixview(
                    matrixassembler,
                    fullinteraction[1],
                    fullinteraction[2],
                    rowdim,
                    coldim,
                    T=T, I=I
                )
            )
            verbose && next!(p)
        end

        for i in eachindex(fullmatrixviews_perthread)
            append!(fullmatrixviews, fullmatrixviews_perthread[i])
        end
    end

    matrixviews_perthread = Vector{LowRankMatrixView{T, I}}[]
    matrixviews = LowRankMatrixView{T, I}[]

    if verbose
        p = Progress(length(compressableinteractions), desc="Compressing far interactions: ")
    end

    if threading == :single
        for compressableinteraction in compressableinteractions
            push!(
                matrixviews,
                getcompressedmatrix(
                    farmatrixassembler,
                    compressableinteraction[1],
                    compressableinteraction[2],
                    rowdim,
                    coldim,
                    compressor=compressor,
                    tol=tol,
                    maxrank=maxrank,
                    svdrecompress=svdrecompress,
                    T=T, I=I
                )
            )
            nonzeros += nnz(matrixviews[end])
            verbose && next!(p)
        end
    elseif threading == :multi
        for i in 1:Threads.nthreads()
            push!(matrixviews_perthread, LowRankMatrixView{T, I}[])
        end

        Threads.@threads for compressableinteraction in compressableinteractions
            push!(
                matrixviews_perthread[Threads.threadid()],
                getcompressedmatrix(
                    farmatrixassembler,
                    compressableinteraction[1],
                    compressableinteraction[2],
                    rowdim,
                    coldim,
                    compressor=compressor,
                    tol=tol,
                    maxrank=maxrank,
                    svdrecompress=svdrecompress,
                    T=T,
                    I=I
                )
            )
            nonzeros_perthread[Threads.threadid()] +=
                nnz(matrixviews_perthread[Threads.threadid()][end])
            verbose && next!(p)
        end

        for i in eachindex(matrixviews_perthread)
            append!(matrixviews, matrixviews_perthread[i])
        end
    end

    return HMatrix{T,I}(
        fullmatrixviews,
        matrixviews,
        rowdim,
        coldim,
        nonzeros + sum(nonzeros_perthread),
        maxrank
    )
end

function computerinteractions!(
    testnode,#::BoxTreeNode,
    sourcenode,#::BoxTreeNode,
    fullinteractions,#::Vector{SVector{2,BoxTreeNode}},
    compressableinteractions#::Vector{SVector{2,BoxTreeNode}})
)
    if iscompressable(sourcenode, testnode)
        if sourcenode.level == 0 && testnode.level == 0
            push!(compressableinteractions, SVector(testnode, sourcenode))
            return
        else
            error("We do not expect this behavior")
        end
    end

    if sourcenode.children === nothing && testnode.children === nothing
        push!(fullinteractions, SVector(testnode, sourcenode))
        return
    else
        if sourcenode.children === nothing
            schild = sourcenode
            for tchild in testnode.children
                decide_compression(
                    tchild,
                    schild,
                    fullinteractions,
                    compressableinteractions
                )
            end
        elseif testnode.children === nothing
            tchild = testnode
            for schild in sourcenode.children
                decide_compression(
                    tchild,
                    schild,
                    fullinteractions,
                    compressableinteractions
                )
            end
        else
            for schild in sourcenode.children
                for tchild in testnode.children
                    decide_compression(
                        tchild,
                        schild,
                        fullinteractions,
                        compressableinteractions
                    )
                end
            end
        end
    end
end

function decide_compression(ttchild, sschild, fullinteractions, compressableinteractions)
    if length(ttchild.data) > 0 && length(sschild.data) > 0
        if iscompressable(ttchild, sschild)
            push!(compressableinteractions, SVector(ttchild, sschild))

            return
        else
            computerinteractions!(ttchild,
                                    sschild,
                                    fullinteractions,
                                    compressableinteractions)
        end
    end
end

function iscompressable(sourcenode::BoxTreeNode, testnode::BoxTreeNode)
    mindistance =
        sqrt(length(sourcenode.boundingbox.center))*sourcenode.boundingbox.halflength
    mindistance +=
        sqrt(length(testnode.boundingbox.center))*testnode.boundingbox.halflength

    distance_centers = norm(sourcenode.boundingbox.center - testnode.boundingbox.center)
    if distance_centers > 1.1*mindistance
        return true
    else
        return false
    end
end

function getfullmatrixview(
    matrixassembler,
    testnode,
    sourcenode,
    rowdim,
    coldim;
    T=ComplexF64,
    I=Int64
)
    matrix = zeros(T, length(testnode.data), length(sourcenode.data))
    matrixassembler(matrix, testnode.data, sourcenode.data)

    return FullMatrixView{T,I}(
        matrix,
        sourcenode.data,
        testnode.data,
        rowdim,
        coldim
    )
end

function getcompressedmatrix(
    matrixassembler::Function,
    testnode,
    sourcenode,
    rowdim,
    coldim;
    tol=1e-4,
    maxrank=100,
    compressor=:aca,
    svdrecompress=true,
    T=ComplexF64,
    I=Int64
)

        #U, V = aca_compression2(assembler, kernel, testpoints, sourcepoints,
        #testnode.data, sourcenode.data; tol=tol)
        #println("Confirm level: ", sourcenode.level)
        #print("a")
        #println(typeof(testnode))
        U, V = aca_compression(
            matrixassembler,
            testnode.data,
            sourcenode.data;
            tol=tol,
            maxrank=maxrank,
            svdrecompress=svdrecompress,
            T=T
        )

        lm = LowRankMatrixView{T,I}(
            V,
            U,
            sourcenode.data,
            testnode.data,
            rowdim,
            coldim
        )

    return lm
end

max_stars_repo_name: sbadrian/FastBEAST

max_issues_repo_name: sbadrian/FastBEAST

max_forks_repo_name: sbadrian/FastBEAST


text:
@test 1==1

@test_nowarn GibbsTypePriors.binom(6, 5, GibbsTypePriors.RR)
@test_nowarn GibbsTypePriors.gamma(10)
@test_nowarn GibbsTypePriors.unsigned_Stirling1(10, 5)
@test_nowarn GibbsTypePriors.unsigned_Stirling2(10, 5)
@test GibbsTypePriors.has_reasonable_precision(GibbsTypePriors.RR(6)) == true
@test_nowarn GibbsTypePriors.risingfac(0.5, 10)
@test_nowarn GibbsTypePriors.risingfac(GibbsTypePriors.RR(.6), 10)

max_stars_repo_name: konkam/GibbsTypePriors

max_issues_repo_name: konkam/GibbsTypePriors

max_forks_repo_name: konkam/GibbsTypePriors


text:
using Test
using Impero
using LinearAlgebra

Ω =  Circle(0,2pi) × Interval(-1,1)
t1 = Ω * Interval(-1,1)
∂(Ω)
∂(t1)
info(Ω)

@testset "domain tests" begin
    @test ndims(Ω) == 2
    @test ndims(t1) == 3
    @test Ω.domains[1] == Ω[1]
    @test ndims(∂(Ω)[1]) == 1
    @test ndims(∂(t1)[1]) == 2
end


text:
using CG1D
using Test

@testset "CG1D.jl" begin
    # Write your tests here.
end


text:
# p20.m - 2nd-order wave eq. in 2D via FFT (compare p19.m)

# Grid and initial data:
N = 24; x = y = cheb(N)[2];
dt = 6/N^2;
xx = yy = x[end:-1:1];
plotgap = round(Int,(1/3)/dt); dt = (1/3)/plotgap;
vv = @. exp(-40*((x'-.4)^2 + y^2));
vvold = vv;  clf();

# Time-stepping by leap frog formula:
for n = 0:3*plotgap
    t = n*dt;
    if rem(n+.5,plotgap)<1     # plots at multiples of t=1/3
          i = n/plotgap+1;
          subplot(2,2,i,projection="3d");
          xxx = yyy = -1:1/16:1;
          s = Spline2D(xx,yy,reduce(flipdim,vv,1:2));
          vvv = evalgrid(s,xxx,yyy);
          surf(xxx,yyy,vvv); xlim(-1,1); ylim(-1,1); zlim(-0.15,1);
          view(-37.5,30); title("t = $(signif(t,5))");
    end
    uxx = zeros(N+1,N+1); uyy = zeros(N+1,N+1);
    ii = 2:N;
    for i = 2:N                # 2nd derivs wrt x in each row
          v = vv[i,:]; V = [v;flipdim(v[ii],1)];
          U = real(fft(V));
          W1 = real(ifft(1im*[0:N-1;0;1-N:-1].*U)); # diff wrt theta
          W2 = real(ifft(-[0:N;1-N:-1].^2.*U));     # diff^2 wrt theta
          uxx[i,ii] = W2[ii]./(1-x[ii].^2) - x[ii].*W1[ii]./(1-x[ii].^2).^(3/2);
    end
    for j = 2:N                # 2nd derivs wrt y in each column
          v = vv[:,j]; V = [v; flipdim(v[ii],1)];
          U = real(fft(V));
          W1 = real(ifft(1im*[0:N-1;0;1-N:-1].*U));# diff wrt theta
          W2 = real(ifft(-[0:N;1-N:-1].^2.*U));    # diff^2 wrt theta
          uyy[ii,j] = W2[ii]./(1-y[ii].^2) - y[ii].*W1[ii]./(1-y[ii].^2).^(3/2);
    end
    vvnew = 2*vv - vvold + dt^2*(uxx+uyy);
    vvold = vv; vv = vvnew;
end


text:
function positionTMs!(df, side)

    sub = filter(x -> x.element == "tm", df)
    grps = groupby(sub, :structMap)
    membHeight = 1

    for g in 1:length(grps)

        TempX = grps[g].structMap[1]
        if side == -1
            TempY = 0
        else
            TempY = 1
        end
        n = length(grps[g].res)
        nTurns = floor(n/3) -1

        turn = 1
        count = 1
        resPerTurn = 3

        for residue in 1:n
            x = TempX
            y = TempY
            if count % resPerTurn == 0
                if side == -1
                    TempY = turn * membHeight/nTurns
                else
                    TempY = 1-(turn * membHeight/nTurns)
                end
                TempX = grps[g].structMap[1]
                turn += 1
                count = 0

                if resPerTurn == 3
                    resPerTurn = 4
                    TempX -= 0.1
                else
                    resPerTurn = 3
                end
            else
                TempX += 0.22
                TempY -= 0.02*side
            end
            grps[g][residue, :x] = x
            grps[g][residue, :y] = y

            count += 1
        end
        side *= -1
    end

    df[df[!,:element] .== "tm", :] = transform(grps)
    return df

end


text:
module ThreadedSparseCSR

using LinearAlgebra
using SparseArrays
using SparseMatricesCSR
using Polyester

using SparseMatricesCSR: nzrange
import Base: *
import LinearAlgebra: mul!

abstract type ThreadingBackend end
struct BaseThreads <: ThreadingBackend end
struct PolyesterThreads <: ThreadingBackend end
DefaultThreadingBackend() = PolyesterThreads()

export tmul!, tmul
export bmul!, bmul
export BaseThreads, PolyesterThreads

include("threads_matmul.jl")
include("batch_matmul.jl")
include("multithread_matmul.jl")
include("set_num_threads.jl")
include("init_package.jl")

end


text:
@discord_object struct EmbedThumbnail
    url::String
    proxy_url::String
    height::Int
    width::Int
end


text:
################################################################################
#  Copyright 2021, Tom Van Acker, Arpan Koirala                                #
################################################################################
# StochasticPowerModels.jl                                                     #
# An extention package of PowerModels.jl for Stochastic (Optimal) Power Flow   #
# See http://github.com/timmyfaraday/StochasticPowerModels.jl                  #
################################################################################

# input data
""
function parse_dst(dst, pa, pb, deg)
    dst == "Beta"    && return _PCE.Beta01OrthoPoly(deg, pa, pb; Nrec=5*deg)
    dst == "Normal"  && return _PCE.GaussOrthoPoly(deg; Nrec=5*deg)
    dst == "Uniform" && return _PCE.Uniform01OrthoPoly(deg; Nrec=5*deg)
end

"""
    StochasticPowerModels.build_stochastic_data(data::Dict{String,Any}, deg::Int)

Function to build the multi-network data representative of the polynomial chaos
expansion of a single-network data dictionary.
"""
function build_stochastic_data(data::Dict{String,Any}, deg::Int)
    # add maximum current
    for (nb, branch) in data["branch"]
        f_bus = branch["f_bus"]
        branch["cmax"] = branch["rate_a"] / data["bus"]["$f_bus"]["vmin"]
    end

    # build mop
    opq = [parse_dst(ns[2]["dst"], ns[2]["pa"], ns[2]["pb"], deg) for ns in data["sdata"]]
    mop = _PCE.MultiOrthoPoly(opq, deg)

    # build load matrix
    Nd, Npce = length(data["load"]), mop.dim
    pd, qd = zeros(Nd, Npce), zeros(Nd, Npce)
    for nd in 1:Nd
        # reactive power
        qd[nd,1] = data["load"]["$nd"]["qd"]
        # active power
        nb = data["load"]["$nd"]["load_bus"]
        ni = data["bus"]["$nb"]["dst_id"]
        if ni == 0
            pd[nd,1] = data["load"]["$nd"]["pd"]
        else
            base = data["baseMVA"]
            μ, σ = data["bus"]["$nb"]["μ"] / base, data["bus"]["$nb"]["σ"] / base
            if mop.uni[ni] isa _PCE.GaussOrthoPoly
                pd[nd,[1,ni+1]] = _PCE.convert2affinePCE(μ, σ, mop.uni[ni])
            else
                pd[nd,[1,ni+1]] = _PCE.convert2affinePCE(μ, σ, mop.uni[ni], kind="μσ")
            end
        end
    end

    # replicate the data
    data = _PM.replicate(data, Npce)

    # add the stochastic data
    data["T2"] = _PCE.Tensor(2,mop)
    data["T3"] = _PCE.Tensor(3,mop)
    data["T4"] = _PCE.Tensor(4,mop)
    data["mop"] = mop
    for nw in 1:Npce, nd in 1:Nd
        data["nw"]["$nw"]["load"]["$nd"]["pd"] = pd[nd,nw]
        data["nw"]["$nw"]["load"]["$nd"]["qd"] = qd[nd,nw]
    end

    return data
end

# output data
"""
    StochasticPowerModels.pce_coeff(result, element::String, id::Int, var::String)

Returns all polynomial chaos coefficients associated with the variable `var` of
the `id`th element `element`.
"""
pce_coeff(result, element::String, id::Int, var::String) =
    [nw[2][element]["$id"][var] for nw in sort(collect(result["solution"]["nw"]), by=x->parse(Int,x[1]))]

"""
    StochasticPowerModels.sample(sdata, result, element::String, id::Int, var::String; sample_size::Int=1000)

Return an `sample_size` sample of the variable `var` of the `id`th element
`element`.
"""
sample(result, element::String, id::Int, var::String; sample_size::Int=1000) =
    _PCE.samplePCE(sample_size, pce_coeff(result, element, id, var), result["mop"])

"""
    StochasticPowerModels.density(sdata, result, element::String, id::Int, var::String; sample_size::Int=1000)

Return an kernel density estimate of the variable `var` of the `id`th element
`element`.
"""
density(result, element::String, id::Int, var::String; sample_size::Int=1000) =
    _KDE.kde(sample(result, element, id, var; sample_size=sample_size))

function print_summary(obj::Dict{String,<:Any}; kwargs...)
    if _IM.ismultinetwork(obj)
        for (n,nw) in obj["nw"]
            println("----------------")
            println("PCE index $n")
            _PM.summary(stdout, nw; kwargs...)
        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 EffectiveNetworkSecurityGroup <: SwaggerModel
    networkSecurityGroup::Any # spec type: Union{ Nothing, SubResource } # spec name: networkSecurityGroup
    association::Any # spec type: Union{ Nothing, EffectiveNetworkSecurityGroupAssociation } # spec name: association
    effectiveSecurityRules::Any # spec type: Union{ Nothing, Vector{EffectiveNetworkSecurityRule} } # spec name: effectiveSecurityRules

    function EffectiveNetworkSecurityGroup(;networkSecurityGroup=nothing, association=nothing, effectiveSecurityRules=nothing)
        o = new()
        validate_property(EffectiveNetworkSecurityGroup, Symbol("networkSecurityGroup"), networkSecurityGroup)
        setfield!(o, Symbol("networkSecurityGroup"), networkSecurityGroup)
        validate_property(EffectiveNetworkSecurityGroup, Symbol("association"), association)
        setfield!(o, Symbol("association"), association)
        validate_property(EffectiveNetworkSecurityGroup, Symbol("effectiveSecurityRules"), effectiveSecurityRules)
        setfield!(o, Symbol("effectiveSecurityRules"), effectiveSecurityRules)
        o
    end
end # type EffectiveNetworkSecurityGroup

const _property_map_EffectiveNetworkSecurityGroup = Dict{Symbol,Symbol}(Symbol("networkSecurityGroup")=>Symbol("networkSecurityGroup"), Symbol("association")=>Symbol("association"), Symbol("effectiveSecurityRules")=>Symbol("effectiveSecurityRules"))
const _property_types_EffectiveNetworkSecurityGroup = Dict{Symbol,String}(Symbol("networkSecurityGroup")=>"SubResource", Symbol("association")=>"EffectiveNetworkSecurityGroupAssociation", Symbol("effectiveSecurityRules")=>"Vector{EffectiveNetworkSecurityRule}")
Base.propertynames(::Type{ EffectiveNetworkSecurityGroup }) = collect(keys(_property_map_EffectiveNetworkSecurityGroup))
Swagger.property_type(::Type{ EffectiveNetworkSecurityGroup }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_EffectiveNetworkSecurityGroup[name]))}
Swagger.field_name(::Type{ EffectiveNetworkSecurityGroup }, property_name::Symbol) =  _property_map_EffectiveNetworkSecurityGroup[property_name]

function check_required(o::EffectiveNetworkSecurityGroup)
    true
end

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


text:
using BinaryBuilder

name = "battery_cli"
version = v"0.10.0"

# Collection of sources required to build ghr
sources = [
    GitSource("https://github.com/distatus/battery.git", "aa540e5be8de3bd83449b7a099341109e9ac1153"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/battery/cmd/battery
mkdir -p ${bindir}
go build -o ${bindir}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    ExecutableProduct("battery", :battery),
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; compilers=[:c, :go])

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
using YangSimOpt
#YangSimOpt.greet()
#YangSimOpt.PhotoVotaics.hello()

YangSimOpt.NRELssc.ssc_version()