text:
module PixelCoordinates

using Markdown
using Cairo
using ComplexVisual
@ComplexVisual.import_huge

import Main.DocGenerator: DocSource, DocCreationEnvironment, DocContext,
        Document, substitute_marker_in_markdown, create_doc_icon, append_md

"""
Use a `CV_Math2DCanvas`, an axis grid painter and  ad-hoc painting with
Cairo to show/simulate a zoomed/enlarged `CV_Std2DCanvas` pixel canvas .
"""
function visualize_pixelcanvas(layout)
    res = 70
    can = CV_Math2DCanvas(0.0 + 0.0im + 1.0*(-1.0 + 1.0im)/res,
                          6.0 - 6.0im + 1.0*( 1.0 - 1.0im)/res, res)
    can_l = cv_add_canvas!(layout, can, (0,0), (0,0))
    grid_painter = CV_GridPainter(0:6, -6:0)
    grid_style = cv_color(0.7, 0.7, 0.7) → cv_op_source → cv_linewidth(1)
    cv_create_context(can) do con
        set_operator(con.ctx, Cairo.OPERATOR_SOURCE)

        set_source_rgb(con.ctx, 0, 0.7, 0)
        rectangle(con.ctx, 1, -5,  4,  2)
        fill(con.ctx)

        set_source_rgb(con.ctx, 0.7, 0, 0)
        rectangle(con.ctx, 2, -1,  1,  1)
        fill(con.ctx)

        cv_paint(con, grid_style ↦ grid_painter)
    end
    return can, can_l
end

"""
show axis for "pixel-coordinate" system.
"""
function create_axis(layout, can_l)
    arr = Vector{CV_2DLayoutPosition}()

    label_style = cv_black → cv_fontface("sans-serif") → cv_fontsize(15)
    app = CV_TickLabelAppearance(; label_style, tick_length=10)

    ticks = tuple(map(f -> CV_TickLabel(f, string(Int(-f))), 0.0:-1.0:-6.0)...)
    push!(arr, cv_ticks_labels(layout, can_l, cv_west, (CV_Ruler(ticks, app),)))
    push!(arr, cv_ticks_labels(layout, can_l, cv_east, (CV_Ruler(ticks, app),)))

    ticks = cv_format_ticks("%.0f", 0.0:1.0:6.0...)
    push!(arr, cv_ticks_labels(layout, can_l, cv_north, (CV_Ruler(ticks, app),)))
    push!(arr, cv_ticks_labels(layout, can_l, cv_south, (CV_Ruler(ticks, app),)))

    return arr
end

"""
# [![./PixelCoordinates_docicon.png]({image_from_canvas: get_doc_icon()}) Pixel Coordinates](./PixelCoordinates.md)

## Axes directions and integer coordinates

For the layout process and for low level painting operations (typically using
Cairo) pixel coordinates are used. Let's have a look at the pixel
coordinate system.

![./PixelCoordinates01.png]({image_from_canvas: explain_pixel_coordinates()})

The horizontal axis points from west to east and the vertical axis
points from north to south. Integer coordinates, e.g. `(2,0)`, are located
at the zero-width "gap" between pixels.

In the figure above, the red pixel is described by the rectangle
with the two corners `(2,0)` and `(3,1)`.

## "left", "right", "top" and "bottom"

So far the words "left", "right", "top" and "bottom" were avoided. Because
a `CV_Rectangle` is defined by the "top left" and "bottom right" corner, we
have to define them.

In the horizontal direction we say "x1 is left of x2" (or "x2 is right of x1")
if `x1 < x2`.

In the vertical direction we say "y1 is below y2" (or "y2 is above y1")
if `y1 < y2`.

With this definition in mind (together with the north to south direction
of the vertical axis) to "top left" corner of the red pixel is `(2,1)` and
the "bottom right" corner of the red pixel is `(3,0)`.

## Examples with `CV_Rectangle`

There more ways to describe a rectangle. The constructor for `CV_Rectangle`
and `cv_rect_blwh` which have the form [with `{T<:Real}`]

```julia
    CV_Rectangle(top::T, left::T, bottom::T, right::T)
    cv_rect_blwh(::Type{T}, bottom, left, width, height)
```

So the red and green rectangles in the example above can be constructed with

```julia
rect_red1 = CV_Rectangle(1, 2, 0, 3)
rect_red2 = cv_rect_blwh(Int, 0, 2, 1, 1)

rect_green1 = CV_Rectangle(5, 1, 3, 5)
rect_green2 = cv_rect_blwh(Int, 3, 1, 4, 2)
```
"""
function explain_pixel_coordinates()
    layout = CV_2DLayout()

    can, can_l = visualize_pixelcanvas(layout)
    all_axis = create_axis(layout, can_l)

    cv_add_padding!(layout, 15)
    can_layout = cv_canvas_for_layout(layout)
    cv_create_context(can_layout) do con
        can_l(con)
        for axis in all_axis
            axis(con)
        end
    end

    return can_layout
end

function get_doc_icon()
    src_canvas = explain_pixel_coordinates()
    icon = create_doc_icon(src_canvas, cv_rect_blwh(Int32, 0, 80, 200, 200))
    return icon
end

function create_document(doc_env::DocCreationEnvironment)
    doc_source = DocSource("PixelCoordinates", @__MODULE__)
    context = DocContext(doc_env, doc_source)

    md = Markdown.MD()
    for part in (explain_pixel_coordinates, )
        part_md = Base.Docs.doc(part)
        substitute_marker_in_markdown(context, part_md)

        append_md(md, part_md)
    end

    doc = Document(doc_source, md)
    return doc
end

end

# vim:syn=julia:cc=79:fdm=marker:sw=4:ts=4:


text:
"""
Returns the variance of data

"""
function Statistics.var(data1::TD)
	σ=0.0
	μ=Statistics.mean(data1)
	n=0
	for ifield = 1:length(data1.fields), iss = 1:data1.acqgeom.nss
		for ir = 1:data1.acqgeom.nr[iss], it = 1:length(data1.tgrid)
			n += 1
			σ += (data1.d[iss, ifield][it, ir]-μ)^2
		end
	end
	return σ*inv(n)
end

function Statistics.mean(data1::TD)
	n=0
	μ=0.0
	for ifield = 1:length(data1.fields), iss = 1:data1.acqgeom.nss
		for ir = 1:data1.acqgeom.nr[iss], it = 1:length(data1.tgrid)
			n += 1
			μ += data1.d[iss, ifield][it, ir]
		end
	end
	return μ*inv(n)
end

ext: jl


text:
struct Discretization{DecompositionType}
  lu_decomposition::DecompositionType   # LU decomposition of system matrix
  num_steps_year::Int64                 # Number of time steps per astronomical year
  mesh::Mesh
  model::Model                          # Physical model
  annual_temperature::Array{Float64, 2} # Annual temperature at every time step in an astronomical year
  rhs::Vector{Float64}
  last_rhs::Vector{Float64}
end

function Discretization(mesh, model, num_steps_year; run_garbage_collector = true)
    lu_decomposition = compute_lu_matrices(mesh, model, num_steps_year)

    if run_garbage_collector
      GC.gc()
    end

    annual_temperature = fill(5.0, mesh.dof, num_steps_year) # Magic initialization
    rhs     = zeros(mesh.dof)  # TODO: The EBM Fortran code initializes the RHS to zero... Maybe we want to initialize it differently
    last_rhs = zeros(mesh.dof)

    Discretization(lu_decomposition, num_steps_year, mesh, model, annual_temperature, rhs, last_rhs)
end

Base.size(discretization::Discretization) = size(discretization.mesh)

function Base.show(io::IO, discretization::Discretization)
  nx, ny = size(discretization)
  print(io, "Discretization() with ", nx, "×", ny, " degrees of freedom")
end

function compute_lu_matrices(mesh, model, num_steps_year)
  mat = compute_matrix(mesh,num_steps_year,model)
  lu_decomposition = lu(mat)
  return lu_decomposition
end


text:
module External

using Highlights
using Highlights.Lexers
using Highlights.Tokens

abstract type CommentLexer <: AbstractLexer end

@lexer CommentLexer Dict(
    :name => "Comments",
    :description => "A C-style comment lexer.",
    :tokens => Dict(
        :root => [
            (r"//.*\n", COMMENT_SINGLE),
            (r"/\*",    COMMENT_MULTILINE,   :multiline_comments),
            (r"[^/]+",  TEXT)
        ],
        :multiline_comments => [
            (r"/\*",     COMMENT_MULTILINE,  :__push__),
            (r"\*/",     COMMENT_MULTILINE,  :__pop__),
            (r"[^/\*]+", COMMENT_MULTILINE),
        ],
    )
)

end


text:
function maxdiff(x::AbstractArray, y::AbstractArray)
    res = real(zero(x[1] - y[1]))
    @inbounds for i in 1:length(x)
        delta = abs(x[i] - y[i])
        if delta > res
            res = delta
        end
    end
    return res
end


text:
"""
Implementing the algorithm in C. E. Rasmussen & C. K. I. Williams, Gaussian
Processes for Machine Learning ch.2, pp.19. to verify the result from
gaussian_process.jl.
"""

using JLD2, NetCDF, Statistics, LinearAlgebra, Plots
include("kernels.jl")
include("gaussian_process.jl")
include("../les/get_les_data.jl")
include("../les/custom_avg.jl")

filename = "general_strat_16_profiles.jld2"
data = get_les_data(filename);

V = data.T
t = data.t
Nz, Nt = size(V)

D = 16 # gridpoints
zavg = custom_avg(data.z, D) # compress z vector to D values
vavg = [custom_avg(V[:,j], D) for j in 1:Nt] # compress variable array to D values per time
x = vavg[1:(Nt-1)] # (v₀, v₁, ... ,v_(Nt-1)) (Nt-1)-length array of D-length inputs
y = vavg[2:Nt]     # (v₁, v₂, ... ,v_Nt    ) (Nt-1)-length array of D-length targets

# reserve 25% of data for training, but across the entire time interval
total_set = 1:(Nt-1)
training_set = 1:4:(Nt-1)
verification_set = setdiff(total_set, training_set)

n = length(training_set) # num. training points
x_train = x[training_set]
y_train = y[training_set]

kernel = SquaredExponentialKernelI(1000.0,1.0) #[γ,σ]

t_to_compare = 100 # pick a test point that's not in the training data

#### From scratch - to predict the whole temperature profile, so D=16 independent GPs

k = kernel_function(kernel)
K = [k(x_train[i], x_train[j]) for i in 1:n, j in 1:n] # n x n
CK = cholesky(K + maximum(K)*sqrt(eps(1.0))*I) # n x n
CK = Array(CK) # n x n

y = hcat(y_train...)' # n x D

# α = CK' \ (CK \ y_s)
α = (CK \ y)

# pick a test point that's not in the training points
x_star = x[t_to_compare] # ℝ^D
# vector of covariances between x_star and the training points
k_star = [k(x_star,x_train[i]) for i in 1:n] # ℝ^n
y_prediction = k_star' * α # ℝ^D

println("y prediction for t=$(t_to_compare) according to from_scratch: $(y_prediction)")
## using gaussian_process.jl
𝒢 = construct_gpr(x_train, y_train, kernel)
y_prediction_s = prediction([x_star], 𝒢)

println("y prediction for t=$(t_to_compare) according to gaussian_process.jl: $(y_prediction_s)")
### using GaussianProcesses.jl package

using GaussianProcesses

x_validation = x[verification_set]
xs_verification = Array(hcat(x_validation...))

xs = Array(hcat(x_train...)) # n x D
ys = Array(hcat(y_train...)) # n x D

# gp = GPE(xs,ys[i,:],MeanZero(),SE(20,20) )
# μ, variance = predict_f(gp,xs_verification);

x_all = Array(hcat(x...)) # n+n* x D
y_prediction_ss = zeros(16)
for i in 1:16

    gp = GPE(xs,ys[i,:],MeanZero(),SE(1000.0,1.0) )
    μ_all, variance_all = predict_f(gp,x_all);
    y_prediction_ss[i] = μ_all[t_to_compare]

end
println("y prediction for t=$(t_to_compare) according to GaussianProcesses.jl: $(y_prediction_ss)")

# Optimise the hyperparameters of Gaussian process gp based on type II maximum likelihood estimation
# optimize!(gp)
println(gp.mll)

total_mll = sum([ GPE(xs,ys[i,:],MeanZero(),SE(1000.0,1.0) ).mll for i in 1:16])
println("mean log marginal likelihood according to GaussianProcesses.jl: $(total_mll/16)")
# mcmc(gp; kern=true)

#### BELOW - same code, but just for one GP instead of 16 -- predicting just one value (the fourth) in the temperature profile

# get k(x,x') function from kernel object
k = kernel_function(kernel)
# fill kernel matrix with values
K = [k(x_train[i], x_train[j]) for i in 1:n, j in 1:n] # n x n
# make Cholesky factorization work by adding a small amount to the diagonal
CK = cholesky(K + maximum(K)*sqrt(eps(1.0))*I) # n x n
CK = Array(CK) # n x n
y_s = hcat(y_train...)' # n x D

# predict just fourth point
y = y_s[:,4] # ℝ^n

# α_s = CK' \ (CK \ y_s)
# α = CK' \ (CK \ y)
α = (CK \ y) # ℝ^n

# pick a test point that's not in the training points
x_star = x[100] # ℝ^D

# vector of covariances between x_star and training points in x_train
k_star = zeros(n) # ℝ^n
for i in 1:n
    k_star[i]=k(x_star,x_train[i])
end

y_prediction = k_star' * α # ℝ

# using gaussian_process.jl

𝒢 = construct_gpr(x_train, y_train, kernel)

y_prediction_s = prediction([x_star], 𝒢)[4]

mean_loss = mean_log_marginal_loss(y_train,𝒢)

y_prediction == y_prediction_s # true ✓

max_stars_repo_name: adelinehillier/LearnConvection

max_issues_repo_name: adelinehillier/LearnConvection

max_forks_repo_name: adelinehillier/LearnConvection


text:
function readcpp(io::IO,
                 ::Type{Vector{T}};
                 kwargs...) where {T}
  format = get(kwargs,:format,"v3")
  v = Vector{T}()
  if format=="v3"
    size = read(io,UInt64)
    resize!(v,size)
    for n=1:size
      v[n] = readcpp(io,T;kwargs...)
    end
  else
    throw(ArgumentError("read Vector: format=$format not supported"))
  end
  return v
end


text:
#------------------------------------------------------------------------------#
#                                    Module                                    #
#------------------------------------------------------------------------------#

"""
# Description

    module basicTensor

Basic tensor module.

# Usage

This module is automatically `include`d by the `iso`, and by the `orθ` packages,
which are automatically `include`d by the `IsoOrthoTensor` package.

```julia-repl
julia> using IsoOrthoTensor

julia> typeof(IOT.basicTensor)
Module

```
"""
module basicTensor

#------------------------------------------------------------------------------#
#                                   Exports                                    #
#------------------------------------------------------------------------------#

# Basic Tensor Union type
export Tensor

# Kronecker delta tensor in 1 to 3 Euclidean dimensions, fast and safe versions
export fK, K

#------------------------------------------------------------------------------#
#                                 Union Types                                  #
#------------------------------------------------------------------------------#

Tensor{T} = Union{T,Array{T}}

#------------------------------------------------------------------------------#
#                                  Constants                                   #
#------------------------------------------------------------------------------#

const δ = (1, [[1 0]; [0 1]], [[1 0 0]; [0 1 0]; [0 0 1]])

#------------------------------------------------------------------------------#
#                                  Functions                                   #
#------------------------------------------------------------------------------#

"""
    fK(D::Int64 = 2)::Tensor{Int64}

Fast (no ckecks) `Int64` Kronecker  δ  tensor  in  a  `D`-dimensional  Euclidean
space, `D ∈ [1, 3]`.

This function is not exported and must be called from outside the module with  a
fully qualified name:

```julia-repl
julia> IOT.iso.fK(2)
2×2 Array{Int64,2}:
 1  0
 0  1

```
"""
fK(D::Int64 = 2)::Tensor{Int64} = δ[D]

"""
    K(D::Int64 = 2)::Tensor{Int64}

Returns the  Kronecker  Delta  tensor  in  a  `D`-dimensional  Euclidean  space,
checking bounds on `D`, i.e., whether `D ∈ [1, 3].`

```julia-repl
julia> K(3)
3×3 Array{Int64,2}:
 1  0  0
 0  1  0
 0  0  1

```
"""
function K(D::Int64 = 2)::Tensor{Int64}
    D <= 0 || D >= 4 ?
        throw(DomainError("dimension D = $D outside the valid domain [1, 3]")) :
        fK(D)
end

end


text:
module TestJultran
using Jultran
using FactCheck

facts("matches values computed from pytran") do
    κ = compute_κs(:co2, [600], 260, 1.e4)[1]
    println(κ)
    @fact abs(κ - 11.2) < 0.01 => true
end

end


text:
#!/usr/bin/env julia

using Distributed
addprocs(${ncpus})

@everywhere using FlashWeave

using CSV
using DataFrames

# data
data_path = "${otu_file}"
new_data_path = "${otu_file.baseName}.tsv"
if data_path != new_data_path
    cp(data_path, new_data_path, force=true, follow_symlinks=true)
end
metadata_path = "${sample_metadata}"
metadata = CSV.read(metadata_path, DataFrame; transpose=true)
new_metadata_path = "${sample_metadata.baseName}_transposed.tsv"
CSV.write(new_metadata_path, metadata; delim="\\t")

# options
sensitive = ${sensitive}
heterogeneous = ${heterogeneous}
FDR = ${fdr_correction}

netw_results = learn_network(
new_data_path,
new_metadata_path,
sensitive=sensitive,
heterogeneous=heterogeneous,
FDR=FDR,
transposed=true,
)

# You need to use networkx to export the .gml to table
output_file = "${meta.id}_network.gml"
save_network(output_file, netw_results)

max_stars_repo_name: segrelab/MiCoNE

max_issues_repo_name: segrelab/MiCoNE

max_forks_repo_name: segrelab/MiCoNE


text:
"""
A candidate satisfies our constraints if it does:

1. Does not contain any character that's globally banned.
2. Does not contain a character that differs from known exact matches.
3. Does not contain a character a position i that differs from the local ban list.
4. Has at least as many copies of every character as our lower bound requires.
"""
function satisfies_constraints(candidate::Candidate, constraints::Constraints)
    for i in 1:5
        char = candidate.chars[i]

        if constraints.global_ban[char]
            return false
        end

        if constraints.is_exact_match[i] && char != constraints.match[i]
            return false
        end

        if constraints.local_ban[i][char]
            return false
        end
    end

    counts = LetterCounts(candidate)
    for c in 'a':'z'
        if counts[c] < constraints.lower_bound[c]
            return false
        end
    end

    return true
end


text:
using ParamLevelSet
using jInv.Mesh
using LinearAlgebra
using SparseArrays
using Test

plotting = false;
if plotting
	using jInvVis
	using PyPlot
end

println("~~~~~~~~~~~~~~~~Testing Mesh Free extended RBFs.~~~~~~~~~~~~~~~~~~")

n = [32,32,32];

Mesh = getRegularMesh([0.0;3.0;0.0;3.0;0.0;3.0],n);
midmesh = [(Mesh.domain[2]+Mesh.domain[1]/2) ; (Mesh.domain[4]+Mesh.domain[3]/2); (Mesh.domain[5]+Mesh.domain[6]/2)];
lenmesh = [(Mesh.domain[2]-Mesh.domain[1]) ; (Mesh.domain[4]-Mesh.domain[3]); (Mesh.domain[6]-Mesh.domain[5])];
numParamOfRBF = 10;
nRBF = 5
m5 = zeros(nRBF*5);
m10 = zeros(nRBF*numParamOfRBF);

for k=1:nRBF
	offset10 = (k-1)*numParamOfRBF + 1;
	m10[offset10] = randn();
	beta = max(abs(randn()),0.5);
	# println(beta)
	# m10[offset10+1] = beta; m10[offset10+4] = beta; m10[offset10+6] = beta; ## for the L version.
	m10[offset10+1] = beta^2; m10[offset10+4] = beta^2; m10[offset10+6] = beta^2; ## for the A version.
	m10[(offset10+7):(offset10+9)] = midmesh + 0.1*lenmesh.*randn(size(lenmesh));
	offset5 = (k-1)*5 + 1;
	m5[offset5] = m10[offset10];
	m5[offset5+1] = beta;
	m5[(offset5+2):(offset5+4)] = m10[(offset10+7):(offset10+9)];
end

u5, = MeshFreeParamLevelSetModelFunc(Mesh,m5;computeJacobian=0,numParamOfRBF = 5);
u10, = MeshFreeParamLevelSetModelFunc(Mesh,m10;computeJacobian=0,numParamOfRBF = 10);
if norm(u5-u10) > 1e-5
	error(string("This should be zero: ",norm(u5-u10)));
end

n = [32,32,32];
Mesh = getRegularMesh([0.0;5.0;0.0;5.0;0.0;5.0],n);
midmesh = [(Mesh.domain[2]+Mesh.domain[1])/2 ; (Mesh.domain[4]+Mesh.domain[3])/2; (Mesh.domain[5]+Mesh.domain[6])/2];
lenmesh = [(Mesh.domain[2]-Mesh.domain[1]) ; (Mesh.domain[4]-Mesh.domain[3]); (Mesh.domain[6]-Mesh.domain[5])];
numParamOfRBF = 10;
nRBF = 5
m = zeros(nRBF*numParamOfRBF);

for k=1:nRBF
	offset = (k-1)*numParamOfRBF + 1;
	m[offset] = randn();
	A = randn(3,3); A = 0.5*A'*A + 0.5*Matrix(1.0I,3,3); #A = eye(3) + 1e-5;
	m[(offset+1):(offset+6)] = A[tril(A).!=0.0];
	m[(offset+7):(offset+9)] = midmesh + 0.05*lenmesh.*randn(size(lenmesh));
end
u, = MeshFreeParamLevelSetModelFunc(Mesh,m;computeJacobian=0,numParamOfRBF = 10);
ufull, = ParamLevelSetModelFunc(Mesh,m;computeJacobian=0,numParamOfRBF = 10);
@test norm(u-ufull) < 1e-8

if plotting
	figure()
	u = reshape(u,tuple(Mesh.n...));
	plotModel(u)
end

sigmaH = getDefaultHeaviside();
us, = MeshFreeParamLevelSetModelFunc(Mesh,m;computeJacobian=0,sigma = sigmaH,numParamOfRBF = 10);
if plotting
	figure()
	plotModel(us)
end

bf = 1;
dm = 0.01*zeros(length(m));

for k=1:nRBF
	offset = (k-1)*numParamOfRBF + 1;
	dm[offset] = 0.01*randn();
	dm[(offset+1):(offset+6)] = 0.01*randn(6);# 0.01*[randn(); randn(); 0.0; randn(); 0.0; randn()];#
	dm[(offset+7):(offset+9)] = 0.01*randn(3)
end

hh = 1.0;

u0,JBuilder = MeshFreeParamLevelSetModelFunc(Mesh,m;computeJacobian=1,bf = bf,numParamOfRBF = 10);
J0 = getSparseMatrix(JBuilder);
ufull,JBuilder = ParamLevelSetModelFunc(Mesh,m;computeJacobian=1,bf = bf,numParamOfRBF = 10);
Jfull = getSparseMatrix(JBuilder);

@test norm(Jfull - J0,1) < 1e-8

for k=0:8
	hhh = (0.5^k)*hh;
	ut = MeshFreeParamLevelSetModelFunc(Mesh,m+ hhh*dm;computeJacobian=0,bf = bf,numParamOfRBF = 10)[1];
	println("norm(ut-u0): ",norm(ut[:]-u0[:]),", norm(ut - u0 - J0*dm): ",norm(ut[:] - u0[:] - J0*hhh*dm));
end

println("With Heaviside func");

hh = 1.0;
u0,JBuilder = MeshFreeParamLevelSetModelFunc(Mesh,m;computeJacobian=1,sigma=sigmaH,bf = bf,numParamOfRBF = 10);
J0 = getSparseMatrix(JBuilder);
for k=0:8
	hhh = (0.5^k)*hh;
    ut = MeshFreeParamLevelSetModelFunc(Mesh,m + hhh*dm;computeJacobian=0,sigma=sigmaH,bf = bf,numParamOfRBF = 10)[1];
	println("norm(ut-u0): ",norm(ut[:]-u0[:]),", norm(ut - u0 - J0*dm): ",norm(ut[:] - u0[:] - hhh*(J0*dm)));
end


text:
function smooth_max(k_smooth::Float64, level_sideline)

    # Compute lateral noise
    smooth_max = maximum(level_sideline) + 1/k_smooth.*log(sum(exp.(k_smooth*(level_sideline.-maximum(level_sideline)))))

    # Return
    return smooth_max
end

max_stars_repo_name: MIT-LAE/pyNA

max_issues_repo_name: MIT-LAE/pyNA

max_forks_repo_name: MIT-LAE/pyNA


text:
# Command: Is Element Selected
"""
	isselected(element::Element)::Bool

The Is Element Selected command determines if the referenced element is selected or not.
This operation only makes sense on input elements of the Checkbox and Radio Button states, or on option elements.
"""
function isselected(element::Element)::Bool
    @unpack addr, id = element.session
    element_id = element.id
    response = HTTP.get(
        "$addr/session/$id/element/$element_id/selected",
        [("Content-Type" => "application/json")],
    )
    @assert response.status == 200
    JSON3.read(response.body).value
end


text:
struct RS{bits} <: Encoding
    key::MbedTLS.PKContext
    is_private_key::Bool
end

alg(::RS{bits}) where {bits} = "RS$(bits)"

"RSASSA using SHA-256 hash algorithm"
const RS256 = RS{256}

"RSASSA using SHA-384 hash algorithm"
const RS384 = RS{384}

md_hash_alg(::RS256) = MbedTLS.MD_SHA256
md_hash_alg(::RS384) = MbedTLS.MD_SHA384

function RS{bits}(key_filepath::AbstractString) where {bits}
    @assert isfile(key_filepath) "Key file $key_filepath not found."
    key_as_bytes = read(open(key_filepath, "r"))
    key_as_string = String(copy(key_as_bytes))
    context = MbedTLS.PKContext()

    if startswith(key_as_string, "-----BEGIN PUBLIC KEY-----")
        # public key
        MbedTLS.parse_public_key!(context, key_as_bytes)
        return RS{bits}(context, false)
    elseif startswith(key_as_string, "-----BEGIN RSA PRIVATE KEY-----")
        # private key
        MbedTLS.parse_key!(context, key_as_bytes)
        return RS{bits}(context, true)
    else
        error("$key_filepath is not a valid RSA public or private key.")
    end
end

function sign(encoding::RS, data)
    @assert encoding.is_private_key "Must sign using a private key."
    md = md_hash_alg(encoding)
    signature = MbedTLS.sign(encoding.key, md, MbedTLS.digest(md, data), MersenneTwister(0))
    return base64url_encode(signature)
end

function has_valid_signature(encoding::RS, header_and_claims_encoded::AbstractString, signature_encoded::AbstractString) :: Bool
    try
        md = md_hash_alg(encoding)
        _hash = MbedTLS.digest(md, header_and_claims_encoded)
        return MbedTLS.verify(encoding.key, md, _hash, base64url_decode(signature_encoded)) == 0
    catch e
        return false
    end
end


text:
using Test
# Works on 5/18/21

# Tests the results of doing all mutations on a simple chromosome.
funcs = default_funcs(2)
c = circuit((1,2), ((3,XOR,2,1), (4,AND,2,2)))
@test mutate_all(c,funcs) == map(x->[MyInt(x)],
  [0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x00, 0x05, 0x05, 0x0a, 0x0a, 0x08, 0x02, 0x08, 0x02])

# Tests when insert_gate_prob==1.0 and delete_gate_prob==1.0
p = Parameters(2,1,3,2)
c = random_chromosome(p)
new_c = mutate_chromosome!(deepcopy(c),funcs,insert_gate_prob=1.0)[1]
@test num_mutate_locations(new_c,funcs) == 12
@test new_c.params.numinteriors == length(new_c.interiors)
@test length(new_c.interiors) == p.numinteriors + 1
new_c = mutate_chromosome!(deepcopy(c),funcs,delete_gate_prob=1.0)[1]
@test new_c.params.numinteriors == length(new_c.interiors)
@test length(new_c.interiors) == p.numinteriors - 1
# c.params.numinteriors must be greater than c.param.numinputs for the above test to work.

# Shows the results of mutating a specific chromosome
# Not deterministic
function test_mutate( )
  p = Parameters(2,1,2,2)
  funcs = default_funcs(p.numinputs)
  c = circuit((1,2), ((3,XOR,2,1), (4,AND,2,2)))
  @test num_mutate_locations(c,funcs) == 6
  print_circuit(c);
  for i = 1:num_mutate_locations( c, funcs )
    sav_c = deepcopy(c)
    mutate_chromosome!(c,funcs,i)
    print_circuit(c)
    c = sav_c
  end
end


text:
"""
    kompsimp(f,a,b,M)
adalah fungsi yang digunakan untuk menghitung nilai integral `f` secara numerik
pada interval `[a,b]` menggunakan komposit Simpson dengan `M` sub-interval.

# Example
```jl
julia> a = 1; b = 6;

julia> f(x) = 2+sin(2*sqrt(x));

julia> y = kompsimp(f,a,b,10)
8.183447496636239
```
return solusi `y`
"""
function kompsimp(f,a,b,M)
  h = (b-a)/(2*M);
  s1 = 0;   s2 = 0;
  for k = 1:M
    x = a + (2*k-1)*h;
    s1 = s1 + f(x);
  end
  for k = 1:M-1
    x = a + (2*k)*h;
    s2 = s2 + f(x);
  end
  y = h/3*(f(a)+f(b)+4*s1+2*s2)
end