text:
# In[1]:

arr=[12,56,32,86,23,87]

# In[2]:

#sequential search is the easiest
#basically it is doing a traversal on all items
function sequential_search(target,arr)
    for i in arr
        if i==target
            return true
        end
    end
    return false
end

# In[3]:

sequential_search(23,arr)

# In[4]:

#binary search is a lil more efficient in a way
#the trouble is that it only works on a sorted list
#when the list is large, sorting could take more time than traversal
#sequential search may be a better choice
function binary_search(target,arr)

    array=sort(arr)

    #unlike python
    #julia starts from 1 to end
    left=1
    right=length(array)

    #for binary search
    #we create the first and the last index
    #binary search starts from the middle
    #if the middle value is larger, we search the lower half, vice versa
    #we do the same trick on the lower half recursively
    while left<=right

        #to get the middle point of any length
        #we need to get the half of the sum of first and last index
        #we use (left+right)/2 to get the middle value for any length
        #we rounddown the number and make sure it is int32
        ind=Int32(round((left+right)/2,RoundDown))

        #if the middle value is smaller than the target
        #we search the upper half
        #we set left=ind+1
        #cuz ind has already been checked
        #we just need the lower limit to get the middle next value
        if target>array[ind]

            #crucial
            #the left has to add one
            #so that the left can surpass the right
            #if nothing is found
            left=ind+1

        elseif target==array[ind]
            return true

        #vice versa
        else

            #the same applies to right
            right=ind-1
        end

    end
    return false

end

# In[5]:

binary_search(22,arr)

max_stars_repo_path: sequential and binary search.jl

max_stars_repo_name: je-suis-tm/search-and-sort

max_issues_repo_path: sequential and binary search.jl

max_issues_repo_name: HafizSabia/search-and-sort

max_forks_repo_path: sequential and binary search.jl

max_forks_repo_name: HafizSabia/search-and-sort


text:
abstract type AbstractAWSConfig end
mutable struct AWSConfig <: AbstractAWSConfig
    credentials::Union{AWSCredentials,Nothing}
    region::String
    output::String
end

credentials(aws::AWSConfig) = aws.credentials
region(aws::AWSConfig) = aws.region

function AWSConfig(;
    profile=nothing, creds=AWSCredentials(; profile=profile), region=nothing, output="json"
)
    region = @something region aws_get_region(; profile=profile)
    return AWSConfig(creds, region, output)
end

"""
    aws_user_arn(aws::AWSConfig) -> String

Retrieve the `User ARN` from the `AWSConfig`, if not present query STS to update the
`user_arn`.

# Arguments
- `aws::AWSConfig`: AWSConfig used to retrieve the user arn
"""
function aws_user_arn(aws::AWSConfig)
    creds = aws.credentials

    if isempty(creds.user_arn)
        _update_creds!(aws)
    end

    return creds.user_arn
end

"""
    aws_account_number(aws::AWSConfig) -> String

Retrieve the `AWS account number` from the `AWSConfig`, if not present query STS to update
the `AWS account number`.

# Arguments
- `aws::AWSConfig`: AWSConfig used to retrieve the AWS account number
"""
function aws_account_number(aws::AWSConfig)
    creds = aws.credentials

    if isempty(creds.account_number)
        _update_creds!(aws)
    end

    return creds.account_number
end

function _update_creds!(aws_config::AWSConfig)
    response = AWSServices.sts(
        "GetCallerIdentity";
        aws_config=aws_config,
        feature_set=FeatureSet(; use_response_type=true),
    )
    dict = parse(response)["GetCallerIdentityResult"]
    creds = aws_config.credentials

    creds.user_arn = dict["Arn"]
    creds.account_number = dict["Account"]

    return creds
end

ext: jl


text:
"""
    get_sdf(contact, x, q)

    returns the signed distance for a contact

    contact: ContactConstraint
    x: body position
    q: body orientation
"""
function get_sdf(contact::ContactConstraint{T,N,Nc,Cs}, x::AbstractVector{T},
    q::Quaternion{T}) where {T,N,Nc,Cs<:Contact{T,N}}
    model = contact.model
    return model.collision.contact_normal * (x + vector_rotate(model.collision.contact_origin, q)) - model.collision.contact_radius
end

function get_sdf(mechanism::Mechanism{T,Nn,Ne,Nb,Ni}, storage::Storage{T,N}) where {T,Nn,Ne,Nb,Ni,N}
    d = []
    for contact in mechanism.contacts
        ibody = get_body(mechanism, contact.parent_id).id - Ne
        push!(d, [get_sdf(contact, storage.x[ibody][i], storage.q[ibody][i]) for i = 1:N])
    end
    return d
end

"""
    contact_location(contact, x, q)

    location of contact point in world coordinates

    contact: ContactConstraint
    x: body position
    q: body orientation
"""
function contact_location(contact::ContactConstraint{T,N,Nc,Cs}, x::AbstractVector{T},
    q::Quaternion{T}) where {T,N,Nc,Cs<:Contact{T,N}}
    model = contact.model
    return x + vector_rotate(model.collision.contact_origin, q) - model.collision.contact_normal' * model.collision.contact_radius
end

function contact_location(contact::ContactConstraint{T,N,Nc,Cs},
    body::Body) where {T,N,Nc,Cs<:Contact{T,N}}
    x = body.state.x2
    q = body.state.q2
    return contact_location(contact, x, q)
end

function contact_location(mechanism::Mechanism, contact::ContactConstraint)
    body = mechanism.bodies[findfirst(x -> x.id == contact.parent_id, mechanism.bodies)]
    return contact_location(contact, body)
end

function contact_location(mechanism::Mechanism)
    return [contact_location(mech, contact) for contact in mechanism.contacts]
end


text:
@graphs begin
	################################################################################
	@node select_action_corr = Start() -> threat_check
	@node threat_check = JumpToGraph("threat_exposed") -> a1

	########################################
	@node a1 = Dummy() -> a1_1
	@node a1_1 = SetActiveDie('C', may_use_ring = true) -> [next = a1_2, no_die = a2]
	@node a1_2 = SetActiveDie('P', may_use_ring = true) -> [next = a1_cond, no_die = a2]
	@node a1_cond = BinaryCondition("""
									The Fellowship is on the Mordor track or is revealed.
									And, a character card is held.
									""") -> [n_true = a1_jump, n_false = a2]
	@node a1_jump = JumpToGraph("event_cards_corruption") -> a2

	#######################################
	@node a2 = Dummy() -> a2_1
	@node a2_1 = SetActiveDie('C') -> [next = a2_cond, no_die = a3]
	@node a2_cond = BinaryCondition("""
									The Fellowship is in a region with no Nazgûl and which Nazgûl can move to.
									""") -> [n_true = a2_jump, n_false = a3]
	@node a2_jump = JumpToGraph("character_move") -> a3

	#######################################
	@node a3 = Dummy() -> a3_1
	@node a3_1 = SetActiveDie('C', may_use_ring = true) -> [next = a3_cond, no_die = a4]
	@node a3_cond = BinaryCondition("""
									The Which King is in play and not in a *mobile* army but is able to create or join one.
									""") -> [n_true = a3_jump, n_false = a4]
	@node a3_jump = JumpToGraph("character_which_king") -> a4

	########################################
	@node a4 = Dummy() -> a4_1
	@node a4_1 = SetActiveDie('M', may_use_ring = true) -> [next = a4_jump, no_die = a5]
	@node a4_jump = JumpToGraph("muster_minion") -> a5

	########################################
	@node a5 = Dummy() -> a5_1
	@node a5_1 = SetActiveDie('M') -> [next = a5_jump, no_die = a6]
	@node a5_jump = JumpToGraph("muster_politics") -> a6

	########################################
	@node a6 = Dummy() -> a6_1_ring
	@node a6_1_ring = SetActiveDie('C', may_use_ring = true) -> [next = a6_cond_ring, no_die = a6_2_ring]
	@node a6_2_ring = SetActiveDie('A', may_use_ring = true) -> [next = a6_cond_ring, no_die = a7]
	@node a6_cond_ring = BinaryCondition("""
										 A *mobile* army is adjacent to its *target*.
										 And, the *target* gives enough points to win or the Fellowship is on the Mordor track.
										 """) -> [n_true = a6_jump_1_die_ring, n_false = a6_1_no_ring]
	@node a6_jump_1_die_ring = SetActiveDie('C', may_use_ring = true) -> [next = a6_jump_1_ring, no_die = a6_jump_2_die_ring]
	@node a6_jump_1_ring = JumpToGraph("character_army") -> a6_jump_2_die_ring
	@node a6_jump_2_die_ring = SetActiveDie('A', may_use_ring = true) -> [next = a6_jump_2_ring, no_die = a7]
	@node a6_jump_2_ring = JumpToGraph("movement_attack_basic") -> a7

	@node a6_1_no_ring = SetActiveDie('C') -> [next = a6_cond_no_ring, no_die = a6_2_no_ring]
	@node a6_2_no_ring = SetActiveDie('A') -> [next = a6_cond_no_ring, no_die = a7]
	@node a6_cond_no_ring = BinaryCondition("""
											A *mobile* army is adjacent to its *target*.
											And, the *target* is in a nation at war and not under siege.
											""") -> [n_true = a6_jump_1_die_no_ring, n_false = a7]
	@node a6_jump_1_die_no_ring = SetActiveDie('C') -> [next = a6_jump_1_no_ring, no_die = a6_jump_2_die_no_ring]
	@node a6_jump_1_no_ring = JumpToGraph("character_army") -> a6_jump_2_die_no_ring
	@node a6_jump_2_die_no_ring = SetActiveDie('A') -> [next = a6_jump_2_no_ring, no_die = a7]
	@node a6_jump_2_no_ring = JumpToGraph("movement_attack_basic") -> a7

	########################################
	@node a7 = Dummy() -> a7_1
	@node a7_1 = BinaryCondition("The Shadow player is allowed to pass.") -> [n_true = a7_action, n_false = a8]
	@node a7_action = PerformAction("Pass") -> a7_end
	@node a7_end = End() -> []

	########################################
	@node a8 = Dummy() -> a8_1
	@node a8_1 = SetActiveDie('C') -> [next = a8_jump_1, no_die = a8_2]
	@node a8_jump_1 = JumpToGraph("event_cards_preferred") -> a8_2
	@node a8_2 = SetActiveDie('P') -> [next = a8_jump_2, no_die = a9]
	@node a8_jump_2 = JumpToGraph("event_cards_preferred") -> a9

	########################################
	@node a9 = Dummy() -> a9_1
	@node a9_1 = SetActiveDie('C') -> [next = a9_cond, no_die = a9_2]
	@node a9_2 = SetActiveDie('A') -> [next = a9_cond, no_die = a10]
	@node a9_cond = BinaryCondition("""
									A *mobile* army is adjacent to its *target* that is not under siege.
									""") -> [n_true = a9_jump_1_die, n_false = a10]
	@node a9_jump_1_die = SetActiveDie('C') -> [next = a9_jump_1, no_die = a9_jump_2_die]
	@node a9_jump_1 = JumpToGraph("character_army") -> a9_jump_2_die
	@node a9_jump_2_die = SetActiveDie('A') -> [next = a9_jump_2, no_die = a10]
	@node a9_jump_2 = JumpToGraph("movement_attack_besiege") -> a9_jump_3
	@node a9_jump_3 = JumpToGraph("movement_attack_corr") -> a10

	#######################################
	@node a10 = Dummy() -> a10_start
	@node a10_start = SetActiveDie('P') -> [next = a10_1, no_die = a11]
	@node a10_1 = JumpToGraph("event_cards_preferred") -> a10_2
	@node a10_2 = JumpToGraph("event_cards_general") -> a11

	########################################
	@node a11 = Dummy() -> a11_1
	@node a11_1 = SetActiveDie('A') -> [next = a11_action, no_die = a12]
	@node a11_action = JumpToGraph("movement_attack_corr") -> a12

	########################################
	@node a12 = Dummy() -> a12_start
	@node a12_start = SetActiveDie('C') -> [next = a12_1, no_die = a13]
	@node a12_1 = JumpToGraph("character_army") -> a13

	########################################
	@node a13 = Dummy() -> a13_start
	@node a13_start = SetActiveDie('M') -> [next = a13_1, no_die = a14]
	@node a13_1 = JumpToGraph("muster_minion") -> a13_2
	@node a13_2 = JumpToGraph("muster_politics") -> a13_3
	@node a13_3 = JumpToGraph("muster_muster") -> a14

	# From here on we retry everything but are allowed to use a ring

	#######################################
	@node a14 = Dummy() -> a14_1
	@node a14_1 = SetActiveDie('C', may_use_ring=true) -> [next = a14_cond, no_die = a15]
	@node a14_cond = BinaryCondition("""
									 The Fellowship is in a region with no Nazgûl which a Nazgûl can move to.
									 """) -> [n_true = a14_jump, n_false = a15]
	@node a14_jump = JumpToGraph("character_move") -> a15

	########################################
	@node a15 = Dummy() -> a15_1
	@node a15_1 = SetActiveDie('M', may_use_ring=true) -> [next = a15_jump, no_die = a16]
	@node a15_jump = JumpToGraph("muster_politics") -> a16

	########################################
	@node a16 = Dummy() -> a16_1

	@node a16_1 = SetActiveDie('C', may_use_ring=true) -> [next = a16_cond, no_die = a16_2]
	@node a16_2 = SetActiveDie('A', may_use_ring=true) -> [next = a16_cond, no_die = a17]
	@node a16_cond = BinaryCondition("""
									 A *mobile* army is adjacent to its *target*.
									 And, the *target* is in a nation at war and not under siege.
									 """) -> [n_true = a16_jump_1_die, n_false = a17]
	@node a16_jump_1_die = SetActiveDie('C', may_use_ring=true) -> [next = a16_jump_1, no_die = a16_jump_2_die]
	@node a16_jump_1 = JumpToGraph("character_army") -> a16_jump_2_die
	@node a16_jump_2_die = SetActiveDie('A', may_use_ring=true) -> [next = a16_jump_2, no_die = a17]
	@node a16_jump_2 = JumpToGraph("movement_attack_basic") -> a17

	########################################
	@node a17 = Dummy() -> a17_1
	@node a17_1 = SetActiveDie('C', may_use_ring=true) -> [next = a17_jump_1, no_die = a17_2]
	@node a17_jump_1 = JumpToGraph("event_cards_preferred") -> a17_2
	@node a17_2 = SetActiveDie('P', may_use_ring=true) -> [next = a17_jump_2, no_die = a18]
	@node a17_jump_2 = JumpToGraph("event_cards_preferred") -> a18

	########################################
	@node a18 = Dummy() -> a18_1
	@node a18_1 = SetActiveDie('C', may_use_ring=true) -> [next = a18_cond, no_die = a18_2]
	@node a18_2 = SetActiveDie('A', may_use_ring=true) -> [next = a18_cond, no_die = a19]
	@node a18_cond = BinaryCondition("""
									A *mobile* army is adjacent to its *target* that is not under siege.
									""") -> [n_true = a18_jump_1_die, n_false = a19]
	@node a18_jump_1_die = SetActiveDie('C', may_use_ring=true) -> [next = a18_jump_1, no_die = a18_jump_2_die]
	@node a18_jump_1 = JumpToGraph("character_army") -> a18_jump_2_die
	@node a18_jump_2_die = SetActiveDie('A', may_use_ring=true) -> [next = a18_jump_2, no_die = a19]
	@node a18_jump_2 = JumpToGraph("movement_attack_besiege") -> a18_jump_3
	@node a18_jump_3 = JumpToGraph("movement_attack_corr") -> a19

	#######################################
	@node a19 = Dummy() -> a19_start
	@node a19_start = SetActiveDie('P', may_use_ring=true) -> [next = a19_1, no_die = a20]
	@node a19_1 = JumpToGraph("event_cards_preferred") -> a19_2
	@node a19_2 = JumpToGraph("event_cards_general") -> a20

	########################################
	@node a20 = Dummy() -> a20_1
	@node a20_1 = SetActiveDie('A', may_use_ring=true) -> [next = a20_action, no_die = a21]
	@node a20_action = JumpToGraph("movement_attack_corr") -> a21

	########################################
	@node a21 = Dummy() -> a21_start
	@node a21_start = SetActiveDie('C', may_use_ring=true) -> [next = a21_1, no_die = a22]
	@node a21_1 = JumpToGraph("character_army") -> a22

	########################################
	@node a22 = Dummy() -> a22_start
	@node a22_start = SetActiveDie('M', may_use_ring=true) -> [next = a22_1, no_die = a23]
	@node a22_1 = JumpToGraph("muster_minion") -> a22_2
	@node a22_2 = JumpToGraph("muster_politics") -> a22_3
	@node a22_3 = JumpToGraph("muster_muster") -> a23

	# No action found and end

	########################################
	@node a23 = Dummy() -> a23_1
	@node a23_1 = CheckStrategy("military") -> [n_true = a23_mili, n_false = a23_corr]
	@node a23_mili = PerformAction("""
								   Queller failed to find an action. Discard a random Character or Event die if possible, otherwise discard a random die (do not discard a die set aside for later use).
								   """) -> a23_dice
	@node a23_corr = PerformAction("""
								   Queller failed to find an action. Discard a random Army, Muster, Muster/Army or Event die if possible, otherwise discard a random die (do not discard a die set aside for later use).
								   """) -> a23_dice
	@node a23_dice = GetAvailableDice("""
									  After discarding the random die, input the remaining available dice here (not counting dice set aside for later use).
									  """) -> a_end
	@node a_end = End() -> []

end

max_stars_repo_name: mvmorin/queller-bot

max_issues_repo_name: mvmorin/queller-bot

max_forks_repo_name: mvmorin/queller-bot


text:
module PeriodicCells

using StaticArrays
using DocStringExtensions

export Cell

"""

$(TYPEDEF)

Structure that contains the cell data.

"""
struct Cell{N,T}
  sides::SVector{N,T}
  angles::SVector{N,T}
  origin::SVector{N,T}
end

"""

```
function wrap!(x::AbstractVector, sides::AbstractVector, center::AbstractVector)
```

Functions that wrap the coordinates They modify the coordinates of the input vector.
Wrap to a given center of coordinates

"""
function wrap!(x::AbstractVector, cell::Cell, center::AbstractVector)
  for i in eachindex(x)
    x[i] = wrapone(x[i],cell.sides,center)
  end
  return nothing
end

@inline function wrapone(x::AbstractVector, cell::Cell, center::AbstractVector)
  s = @. (x-center)%sides
  s = @. wrapx(s,sides) + center
  return s
end

@inline function wrapx(x,s)
  if x > s/2
    x = x - s
  elseif x < -s/2
    x = x + s
  end
  return x
end

"""

```
wrap!(x::AbstractVector, cell::Cell)
```

Wrap to origin (slightly cheaper).

"""
function wrap!(x::AbstractVector, cell::Cell)
  for i in eachindex(x)
    x[i] = wrapone(x[i],cell.sides)
  end
  return nothing
end

@inline function wrapone(x::AbstractVector, cell::Cell)
  s = @. x%sides
  s = @. wrapx(s,cell.sides)
  return s
end

end # module PeriodicCells


text:
print("Insert the variable name: ")

variable   = Symbol(readline(STDIN))
expression = quote
    $variable = 42
    println("Inside quote:")
    @show $variable
end

eval(expression)

println("Outside quote:")
@show variable
println("If I named the variable x:")
@show x

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
using PerfChecker
using Test

# include("compositional_networks.jl")

include("pattern_folds.jl")


text:
using Test
using LogicCircuits
using ProbabilisticCircuits
using DataFrames: DataFrame
using CUDA

include("../helper/gpu.jl")

@testset "MAP regression test" begin
    a,b = pos_literals(ProbCircuit, 2)
    circuit = 0.6 * (a * (.5 * b + .5 * -b)) + .4 * (-a * (0.9 * b + .1 * -b))
    no_data = DataFrame(Union{Bool,Missing}[missing missing], :auto)
    maps, mappr = MAP(circuit, no_data)
    @test mappr[1] ≈ log(0.4 * 0.9)
    @test maps[1,1] == false && maps[1,2] == true
    @test mappr ≈ map_prob(circuit, no_data)

     # same MAP states on CPU and GPU
    cpu_gpu_agree(no_data) do d
        MAP(circuit, d)[1]
    end

    # same MAP probabilities on CPU and GPU
    cpu_gpu_agree_approx(no_data) do d
        MAP(circuit, d)[2]
    end

    # same MAP probabilities on CPU and GPU
    cpu_gpu_agree_approx(no_data) do d
        map_prob(circuit, d)
    end

    complete_states = DataFrame([true true; true false; false true; false false], :auto)
    mar = MAR(circuit, complete_states)
    @test all(mappr .> mar .- 1e-6)
end

@testset "MAP" begin

    prob_circuit = zoo_psdd("little_4var.psdd");

    data_full = generate_data_all(num_variables(prob_circuit))

    map, mappr = MAP(prob_circuit, data_full)

    @test map == data_full
    @test mappr ≈ map_prob(prob_circuit, data_full)

    evipr = EVI(prob_circuit, data_full)
    @test mappr ≈ evipr atol=1e-6

    data_marg = DataFrame([false false false false;
                      false true true false;
                      false false true true;
                      false false false missing;
                      missing true false missing;
                      missing missing missing missing;
                      false missing missing missing], :auto)

    map, mappr = MAP(prob_circuit, data_marg)

    @test all(zip(eachcol(map), eachcol(data_marg))) do (cf,cm)
        all(zip(cf, cm)) do (f,m)
            ismissing(m) || f == m
        end
    end

    mar = MAR(prob_circuit, data_marg)

    @test all(mar .> mappr .- 1e-6)

    map, mappr = MAP(prob_circuit, false, false, false, missing)
    @test map == [false, false, false, true]
    @test mappr ≈ -1.2729657

    # same MAP states on CPU and GPU
    cpu_gpu_agree(data_full) do d
        MAP(prob_circuit, d)[1]
    end

    # same MAP probabilities on CPU and GPU
    cpu_gpu_agree_approx(data_full) do d
        MAP(prob_circuit, d)[2]
    end

    # same MAP probabilities on CPU and GPU
    cpu_gpu_agree_approx(data_full) do d
        map_prob(prob_circuit, d)
    end

    # same MAP states on CPU and GPU
    cpu_gpu_agree(data_marg) do d
        MAP(prob_circuit, d)[1]
    end

    # same MAP probabilities on CPU and GPU
    cpu_gpu_agree_approx(data_marg) do d
        MAP(prob_circuit, d)[2]
    end

    # same MAP probabilities on CPU and GPU
    cpu_gpu_agree_approx(data_marg) do d
        map_prob(prob_circuit, d)
    end

end


text:
# MIT License
#
# Copyright (c) 2020 Joshua E Gentry

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
using Test

# -------------------------------------------------------------------------------------------------
# Test tess_text()
@testset "tess_text" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_text(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_text(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_text(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_text()
@testset "tess_hocr" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_hocr(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_hocr(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_hocr(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_alto()
@testset "tess_alto" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_alto(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_alto(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_alto(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_tsv()
@testset "tess_tsv" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_tsv(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_tsv(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_tsv(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_tsv()
@testset "tess_parsed_tsv" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_parsed_tsv(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    local result = tess_parsed_tsv(inst)
    @test result != nothing
    @test isempty(result) == false
    @suppress @test_nowarn show(result[1])

    local result = tess_parsed_tsv(inst, 2) == nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_parsed_tsv(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_text_box()
@testset "tess_text_box" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_text_box(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_text_box(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_text_box(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_word_box()
@testset "tess_word_box" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_word_box(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_word_box(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_word_box(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_lstm_box()
@testset "tess_lstm_box" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_lstm_box(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_lstm_box(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_lstm_box(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_unlv()
@testset "tess_unlv" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_unlv(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_unlv(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_unlv(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_unlv_latin1()
@testset "tess_unlv_latin1" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_unlv_latin1(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_unlv_latin1(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_unlv_latin1(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_confidences()
@testset "tess_confidences" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @suppress @test tess_confidences(inst) == nothing
    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)
    @test tess_recognize(inst) == true
    @test tess_confidences(inst) != nothing

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_confidences(inst)) == nothing
end

# -------------------------------------------------------------------------------------------------
# Test tess_resolution()
@testset "tess_resolution" begin
    local inst = TessInst("eng", datadir)
    local pix = pix_with()

    @test_nowarn tess_image(inst, pix)
    @test_nowarn tess_resolution(inst, 72)

    local err = "Instance has been freed."
    tess_delete!(inst)
    @test (@test_logs (:error, err) tess_resolution(inst, 72)) == nothing
end


text:
export TracyWidom

struct TracyWidom <: ContinuousUnivariateDistribution
    beta::Integer
end

function cdf(d::TracyWidom, x::Real)
    cdf(RandomMatrices.TracyWidom, x, beta=d.beta)
end

_TWfs = Dict()

function _TWf(x, beta)
    if !(beta in keys(_TWfs))
        dom = Chebyshev(-5..5)
        D = Derivative(dom)
        _TWfs[beta] = D * Fun(x -> cdf(RandomMatrices.TracyWidom, x, beta=beta), dom)
    end
    _TWfs[beta](x)
end

function pdf(d::TracyWidom, x::Real)
    _TWf(x, d.beta)
end

_TWinvs = Dict()

function _TWinv(t, beta)
    (0 < t < 1) || throw(DomainError(t))

    if !(beta in keys(_TWinvs))
        # bounds outside which we use limiting representation
        u = 4
        l = -5

        # TODO: make a more principled grid using tail behaviour
        n = 1000
        y = range(l, u, length=n)
        x = cdf(RandomMatrices.TracyWidom, y, beta=1)

        # Transform limiting ends to maintain differentiability
        righta = pdf(TracyWidom(beta), u)/(beta * sqrt(u) * exp(-beta * u^(3/2)*2/3))
        rightb = x[end] - righta * (1 - exp(-beta * u^(3/2) * 2/3))

        lefta = pdf(TracyWidom(beta), l)/(beta * l^2/8 * exp(beta * l^3/24))
        leftb = x[1] - lefta * exp(-beta * abs(l)^3/24)

        itp = interpolate((x,), y, Gridded(Linear()))

        _TWinvs[beta] = [righta, rightb, x[end], lefta, leftb, x[1], itp]
    end

    # TODO: make the indexing less terrible
    if t > _TWinvs[beta][3]
        s = (t - _TWinvs[beta][2])/_TWinvs[beta][1]
        return (log(1/(1 - s)) * 3/(2 * beta))^(2/3)
    elseif t < _TWinvs[beta][6]
        s = (t - _TWinvs[beta][5])/_TWinvs[beta][4]
        return -(log(1/s) * 24/beta)^(1/3)
    else
        return _TWinvs[beta][end](t)
    end

end

function quantile(d::TracyWidom, q::Real)
    _TWinv(q, d.beta)
end


text:
abstract type AbstractSmoothing <: AbstractPolicy end

# function smooth!(smoothing::AbstractSmoothing,x::AbstractVector,gprev::AbstractVector,gcurr::AbstractVector)
#     error("No defined smooth! function for smoothing policy ", typeof(smoothing))
# end

function smooth!() end

function smooth_wrapper(klocal::Cint, kglobal::Cint, xbegin::Ptr{Cdouble},
                        xend::Ptr{Cdouble}, gprev_b::Ptr{Cdouble}, gcurr_b::Ptr{Cdouble},
                        smooth_data::Ptr{Cvoid})
    smooth_policy = unsafe_pointer_to_objref(smooth_data)::AbstractSmoothing
    ptrdiff = Int(xend - xbegin)
    N = divrem(ptrdiff, sizeof(Cdouble))[1]
    x = unsafe_wrap(Array, xbegin, N)
    gprev = unsafe_wrap(Array, gprev_b, N)
    gcurr = unsafe_wrap(Array, gcurr_b, N)
    smooth!(smooth_policy, klocal, kglobal, x, gprev, gcurr)
    return gcurr_b + ptrdiff
end

module Smoothing

using Parameters
using POLO: AbstractSmoothing, AbstractPolicyParameters
import POLO: initialize!, smooth!

function initialize!(policy::AbstractSmoothing,x₀::Vector{Float64})
    nothing
end

include("none.jl")
include("adagrad.jl")
include("adadelta.jl")
include("rmsprop.jl")

end


text:
f = [1,1]
for i in 1:100
    if (f[i]+f[i+1]) > 1000
        break
    end
    push!(f,f[i]+f[i+1])
end
print(vec(f))


text:
#########################################################
# Hinge Loss
#
# L(\hat{y},y) = 1/2N \sum_{i=1}^N (1-y_i \hat{y}_i)
#########################################################
@defstruct HingeLossLayer Layer (
    name :: AbstractString = "hinge-loss",
    (weight :: AbstractFloat = 1.0, weight >= 0),
    (bottoms :: Vector{Symbol} = Symbol[], length(bottoms) == 2),
)

@characterize_layer(HingeLossLayer,
    has_loss  => true,
    can_do_bp => true,
    is_sink   => true,
    has_stats => true,
)

type HingeLossLayerState{T} <: LayerState
    layer :: HingeLossLayer
    loss  :: T

    loss_accum :: T
    n_accum    :: Int

#     # a helper blob used to compute the loss without destroying
#     # the prediction results passed up
#     pred_copy :: Blob
#     bp_mask :: Blob

    # a helper blob used to compute the loss
    loss_blob :: Blob
end

function setup(backend::Backend, layer::HingeLossLayer, inputs::Vector{Blob}, diffs::Vector{Blob})
    data_type = eltype(inputs[1])
#     pred_copy = make_blob(backend, data_type, size(inputs[1])...)
#     bp_mask = make_blob(backend, Bool, size(inputs[1])...)
    loss_blob = make_blob(backend, data_type, 1)

    state = HingeLossLayerState(layer, zero(data_type), zero(data_type), 0, loss_blob)#, pred_copy, bp_mask)
    return state
end
function shutdown(backend::Backend, state::HingeLossLayerState)
#     destroy(state.pred_copy)
#     destroy(state.bp_mask)
  destroy(state.loss_blob)
  nothing
end
function reset_statistics(state::HingeLossLayerState)
    state.n_accum = 0
    state.loss_accum = zero(typeof(state.loss_accum))
end
function dump_statistics(storage, state::HingeLossLayerState, show::Bool)
    update_statistics(storage, "$(state.layer.name)-hinge-loss", state.loss_accum)

    if show
        loss = @sprintf("%.4f", state.loss_accum)
        @info("  Hinge-loss (avg over $(state.n_accum)) = $loss")
    end
end

function forward(backend::CPUBackend, state::HingeLossLayerState, inputs::Vector{Blob})
  pred  = inputs[1]
  label = inputs[2]

  data_type = eltype(pred)
  n = length(pred)

  state.loss = zero(data_type)
  for i=1:n
    loss = one(data_type) - pred.data[i]*label.data[i]
    if loss > zero(data_type)
      state.loss += loss
    end
  end
  state.loss /= convert(data_type, get_num(pred))

  # accumulate statistics
  state.loss_accum = (state.loss_accum*state.n_accum + state.loss*get_num(pred)) / (state.n_accum+get_num(pred))
  state.n_accum += get_num(pred)
end

function backward(backend::CPUBackend, state::HingeLossLayerState, inputs::Vector{Blob}, diffs::Vector{Blob})
  const pred = inputs[1]
  const label = inputs[2]

  const data_type = eltype(pred)
  const n = length(pred)
  const num = get_num(pred)

  if isa(diffs[1], CPUBlob)
    erase!(diffs[1])
    for i = 1:n
      if pred.data[i]*label.data[i] < one(data_type)
        diffs[1].data[i] = convert(data_type, -state.layer.weight/num) * label.data[i]
        end
    end
  end

  if isa(diffs[2], CPUBlob)
    erase!(diffs[2])
    for i = 1:n
      if pred.data[i]*label.data[i] < one(data_type)
        diffs[2].data[i] = convert(data_type, -state.layer.weight/num) * pred.data[i]
        end
    end
  end

end


text:
module test_helpers

include("../../src/helpers.jl")
using .helpers
using Test

function test_helper_functions()
	@test helpers.jdn_to_ordinal(2447977) == 726552

	@test helpers.ordinal_to_jdn(726552) == 2447977

	@test helpers.jdn_to_rjd(2456087) == 56087

	@test helpers.rjd_to_jdn(56087) == 2456087
end
end

max_stars_repo_name: ceferisbarov/hijri-converter

max_issues_repo_name: ceferisbarov/hijri-converter


text:
module Pseudopotentials

export PerdewZunger,
    VoskoWilkNusair,
    PerdewBurkeErnzerhof,
    PBE,
    PerdewBurkeErnzerhofRevisedForSolids,
    PBEsol,
    BeckeLeeYangParr,
    BLYP,
    PerdewWang91,
    TaoPerdewStaroverovScuseria,
    TPSS,
    Coulomb,
    KresseJoubert,
    Blöchl,
    TroullierMartins,
    BacheletHamannSchlüter,
    BHS,
    VonBarthCar,
    Vanderbilt,
    RappeRabeKaxirasJoannopoulos,
    RRKJ,
    RappeRabeKaxirasJoannopoulosUltrasoft,
    RRKJUs,
    ValenceCoreState,
    SemicoreState,
    CoreState,
    NonLinearCoreCorrection,
    NLCC
export download_potential

"""
    Pseudopotential

Represent any pseudopotential file.
"""
abstract type Pseudopotential end

"""
    ExchangeCorrelationFunctional

Represent exchange-correlation functional types.
"""
abstract type ExchangeCorrelationFunctional end
abstract type LocalDensityApproximation <: ExchangeCorrelationFunctional end
abstract type GeneralizedGradientApproximation <: ExchangeCorrelationFunctional end
abstract type MetaGGA <: ExchangeCorrelationFunctional end
abstract type Hybrid <: ExchangeCorrelationFunctional end
struct PerdewZunger <: LocalDensityApproximation end
struct VoskoWilkNusair <: LocalDensityApproximation end
struct PerdewBurkeErnzerhof <: GeneralizedGradientApproximation end
struct PerdewBurkeErnzerhofRevisedForSolids <: GeneralizedGradientApproximation end
struct BeckeLeeYangParr <: Hybrid end
struct PerdewWang91 <: GeneralizedGradientApproximation end
struct TaoPerdewStaroverovScuseria <: MetaGGA end
struct Coulomb <: ExchangeCorrelationFunctional end
const PBE = PerdewBurkeErnzerhof
const PBEsol = PerdewBurkeErnzerhofRevisedForSolids
const BLYP = BeckeLeeYangParr
const TPSS = TaoPerdewStaroverovScuseria

"""
    Pseudization

Represent the pseudization types.
"""
abstract type Pseudization end
abstract type NormConserving <: Pseudization end
abstract type Ultrasoft <: Pseudization end
abstract type AllElectron <: Pseudization end
abstract type ProjectorAugmentedWaves <: AllElectron end
struct KresseJoubert <: ProjectorAugmentedWaves end
struct Blöchl <: ProjectorAugmentedWaves end
struct TroullierMartins <: NormConserving end
struct BacheletHamannSchlüter <: NormConserving end
struct VonBarthCar <: NormConserving end
struct Vanderbilt <: Ultrasoft end
struct RappeRabeKaxirasJoannopoulos <: NormConserving end
struct RappeRabeKaxirasJoannopoulosUltrasoft <: Ultrasoft end
const BHS = BacheletHamannSchlüter
const RRKJ = RappeRabeKaxirasJoannopoulos
const RRKJUs = RappeRabeKaxirasJoannopoulosUltrasoft

struct CoreHole
    half::Bool
end

abstract type ValenceCoreState end
struct SemicoreState <: ValenceCoreState
    orbital::Char
end
struct CoreState <: ValenceCoreState
    orbital::Char
end
struct NonLinearCoreCorrection <: ValenceCoreState end
const NLCC = NonLinearCoreCorrection

function Base.show(
    io::IO,
    x::Union{ExchangeCorrelationFunctional,Pseudization,ValenceCoreState},
)
    print(IOContext(io, :limit => true), string(x))
end

Base.string(x::ExchangeCorrelationFunctional) = string(typeof(x))
Base.string(x::PerdewBurkeErnzerhof) = "PBE"
Base.string(x::PerdewBurkeErnzerhofRevisedForSolids) = "PBEsol"
Base.string(x::BeckeLeeYangParr) = "BLYP"
Base.string(x::TaoPerdewStaroverovScuseria) = "TPSS"
Base.string(x::Pseudization) = string(typeof(x))
Base.string(x::TroullierMartins) = "TM"
Base.string(x::BacheletHamannSchlüter) = "BHS"
Base.string(x::RappeRabeKaxirasJoannopoulos) = "RRKJ"
Base.string(x::RappeRabeKaxirasJoannopoulosUltrasoft) = "RRKJUs"
Base.string(x::SemicoreState) = "Semicore($(x.orbital))"
Base.string(x::CoreState) = "Core($(x.orbital))"
Base.string(x::NonLinearCoreCorrection) = "NLCC"

function download_potential end

end


text:
module ForneyLab

using Base.Meta: parse
using Base64: base64encode
using LinearAlgebra: diag, det, tr, cholesky, pinv, PosDefException
using SparseArrays: spzeros
using SpecialFunctions: digamma, erfc, logfactorial, logabsgamma, logabsbeta, gamma, loggamma, erf
using LinearAlgebra: Diagonal, Hermitian, isposdef, ishermitian, I, tr, logdet
using InteractiveUtils: subtypes
using Printf: @sprintf
using StatsFuns: logmvgamma, betainvcdf, gammainvcdf, poisinvcdf, normlogcdf, normcdf, normpdf
using ForwardDiff
using Roots: find_zero
using StatsBase: Weights
using PositiveFactorizations
using DataStructures: Queue, enqueue!, dequeue!

import Statistics: mean, var, cov
import Base: +, -, *, ^, ==, <<, exp, convert, show, prod!
import LinearAlgebra: dot, cholesky
import StatsBase: sample

# Helpers
include("helpers.jl")
include("dependency_graph.jl")

# High level abstracts
abstract type AbstractEdge end # An Interface belongs to an Edge, so AbstractEdge has to be defined before Interface
abstract type Region end # A Variable and Cluster are both Regions
abstract type AbstractVariable <: Region end

# Low-level internals
include("factor_node.jl")
include("interface.jl")
include("probability_distribution.jl")
include("edge.jl")
include("variable.jl")

# Factor nodes
include("factor_nodes/clamp.jl")
include("factor_nodes/equality.jl")
include("factor_nodes/addition.jl")
include("factor_nodes/multiplication.jl")
include("factor_nodes/exponential.jl")
include("factor_nodes/gaussian_mean_variance.jl")
include("factor_nodes/gaussian_mean_precision.jl")
include("factor_nodes/gaussian_weighted_mean_precision.jl")
include("factor_nodes/gaussian.jl")
include("factor_nodes/gamma.jl")
include("factor_nodes/log_normal.jl")
include("factor_nodes/wishart.jl")
include("factor_nodes/bernoulli.jl")
include("factor_nodes/categorical.jl")
include("factor_nodes/sample_list.jl")
include("factor_nodes/contingency.jl")
include("factor_nodes/transition.jl")
include("factor_nodes/beta.jl")
include("factor_nodes/dirichlet.jl")
include("factor_nodes/gaussian_mixture.jl")
include("factor_nodes/transition_mixture.jl")
include("factor_nodes/probit.jl")
include("factor_nodes/logit.jl")
include("factor_nodes/softmax.jl")
include("factor_nodes/dot_product.jl")
include("factor_nodes/poisson.jl")
include("factor_nodes/nonlinear.jl")
include("factor_nodes/moment_constraint.jl")
include("factor_nodes/chance_constraint.jl")
include("factor_nodes/point_mass_constraint.jl")

# Factor graph
include("factor_graph.jl")

# Composite nodes
include("factor_nodes/composite.jl")

# Generic methods
include("algorithms/cluster.jl")
include("message_passing.jl")
include("marginals.jl")

# Utils
include("visualization.jl")

# Algorithms
include("algorithms/posterior_factor.jl")
include("algorithms/posterior_factorization.jl")
include("algorithms/inference_algorithm.jl")
include("algorithms/joint_marginals.jl")
include("algorithms/sum_product.jl")
include("algorithms/naive_variational_bayes.jl")
include("algorithms/structured_variational_bayes.jl")
include("algorithms/expectation_propagation.jl")

# Assemblers
include("engines/message_passing_assemblers.jl")
include("engines/free_energy_assemblers.jl")

# Update rules
include("update_rules/clamp.jl")
include("update_rules/equality.jl")
include("update_rules/addition.jl")
include("update_rules/multiplication.jl")
include("update_rules/exponential.jl")
include("update_rules/gaussian_mean_variance.jl")
include("update_rules/gaussian_mean_precision.jl")
include("update_rules/gaussian_weighted_mean_precision.jl")
include("update_rules/gamma.jl")
include("update_rules/log_normal.jl")
include("update_rules/wishart.jl")
include("update_rules/bernoulli.jl")
include("update_rules/categorical.jl")
include("update_rules/transition.jl")
include("update_rules/beta.jl")
include("update_rules/dirichlet.jl")
include("update_rules/gaussian_mixture.jl")
include("update_rules/transition_mixture.jl")
include("update_rules/probit.jl")
include("update_rules/logit.jl")
include("update_rules/softmax.jl")
include("update_rules/dot_product.jl")
include("update_rules/poisson.jl")
include("update_rules/moment_constraint.jl")
include("update_rules/chance_constraint.jl")
include("update_rules/point_mass_constraint.jl")
include("update_rules/nonlinear_unscented.jl")
include("update_rules/nonlinear_sampling.jl")
include("update_rules/nonlinear_extended.jl")
include("update_rules/sample_list.jl")

*(x::ProbabilityDistribution, y::ProbabilityDistribution) = prod!(x, y) # * operator for probability distributions

# include("docstrings.jl")

# Engines
include("engines/julia/julia.jl")

end # module ForneyLab


text:
"""The `MarkerFilter` compares the configured marker value against the marker that is included in the `Event`.
A match occurs when the marker matches the Event's marker.

Default values: `match` is `NEUTRAL`, `mismatch` is `DENY`.
"""
type MarkerFilter <: Filter
    marker::Symbol
    match::FilterResult.ResultType
    mismatch::FilterResult.ResultType
    state::LifeCycle.State
    MarkerFilter(marker::Symbol, match::FilterResult.ResultType, mismatch::FilterResult.ResultType) =
        new(marker, match, mismatch, LifeCycle.INITIALIZED)
end
MarkerFilter(marker::Symbol) = MarkerFilter(marker, FilterResult.NEUTRAL, FilterResult.DENY)

function MarkerFilter(config::Dict{AbstractString,Any})
    if !haskey(config, "marker")
        error(LOGGER, "No marker found. `marker` parameter is required for `MarkerFilter`")
        return nothing
    end
    fmarker = symbol(config["marker"])
    rmatch = if haskey(config, "match")
        evaltype(config["match"], "FilterResult")
    else
        FilterResult.NEUTRAL
    end
    rmismatch = if haskey(config, "mismatch")
        evaltype(config["mismatch"], "FilterResult")
    else
        FilterResult.DENY
    end
    MarkerFilter(fmarker, rmatch, rmismatch)
end
MarkerFilter(;kwargs...) = map(e->(string(e[1]),e[2]), kwargs) |> Dict{AbstractString,Any} |> MarkerFilter

"Make the filter available for use."
function start(flt::MarkerFilter)
    state!(flt, LifeCycle.STARTED)
end

"Disable the filter."
function stop(flt::MarkerFilter)
    state!(flt, LifeCycle.STOPPED)
end

filter{E <: Event}(flt::MarkerFilter, evnt::E) = filter(flt, marker(evnt))
filter(flt::MarkerFilter, level::Level.EventLevel, marker::MARKER, msg) = filter(flt, marker)
filter(flt::MarkerFilter, mkr::MARKER) = (!isnull(mkr) && get(mkr) == flt.marker) ? flt.match : flt.mismatch


text:
using PGFPlotsX, FileIO, StringBuilders, LaTeXTabulars

function getmozaik(n, w, h)
    ratio = w/h
    mh = ceil(Int, sqrt(n*ratio))
    nw = round(Int, mh/ratio)
    while nw*mh < n
        mh += 1
    end
    nw, mh
end

function errorcm(file, ϵ)
    pixel = Prolonged([0 0 0; ϵ 0 0])
    cm = calibrate(file, pixel)
    norm(diff(cm.data[:,1:2], dims = 1))
end

function PGFPlotsX.print_tex(::Type{String}, plot)
    io = IOBuffer()
    print_tex(io, plot)
    strip(String(take!(io)))
end

escape4latex(x) = replace(x, r"([#$%^&_{}~\\])" => s"\\\1")#SubstitutionString("\\\\\\1"))
# x = """# \$ % ^ & _ { } ~ \\ """
# escape4latex(x)

getcomments(c::Calibration) = latex_tabular(String, Tabular("l p{5cm}"),
                                            [Rule(:top),
                                             ["Source", "Comment"],
                                             Rule(:mid),
                                             ["Overall", escape4latex(c.comment)],
                                             ["Intrinsic", escape4latex(c.intrinsic.comment)],
                                             ["Video (intrinsic)", escape4latex(c.intrinsic.video.comment)],
                                             ["Extrinsic", escape4latex(c.extrinsic.comment)],
                                             ["Video (extrinsic)", escape4latex(c.extrinsic.video.comment)],
                                             Rule(:bottom)])
#=getcomments(c::Calibration) = latex_tabular(String, Tabular("l p{5cm}"),
                                            [Rule(:top),
                                             ["Source", "Comment"],
                                             Rule(:mid),
                                             ["Overall", "\\detokenize{$(c.comment)}"],
                                             ["Intrinsic", "\\detokenize{$(c.intrinsic.comment)}"],
                                             ["Video (intrinsic)", "\\detokenize{$(c.intrinsic.video.comment)}"],
                                             ["Extrinsic", "\\detokenize{$(c.extrinsic.comment)}"],
                                             ["Video (extrinsic)", "\\detokenize{$(c.extrinsic.video.comment)}"],
                                             Rule(:bottom)])=#

getcomments(c::Calibration{Missing, T}) where {T} = latex_tabular(String, Tabular("l p{5cm}"),
                                                                  [Rule(:top),
                                                                   ["Source", "Comment"],
                                                                   Rule(:mid),
                                                                   ["Overall", escape4latex(c.comment)],
                                                                   ["Extrinsic", escape4latex(c.extrinsic.comment)],
                                                                   ["Video (extrinsic)", escape4latex(c.extrinsic.video.comment)],
                                                                   Rule(:bottom)])

#=getcomments(c::Calibration{Missing, T}) where {T} = latex_tabular(String, Tabular("l p{5cm}"),
                                                                  [Rule(:top),
                                                                   ["Source", "Comment"],
                                                                   Rule(:mid),
                                                                   ["Overall", "\\detokenize{$(c.comment)}"],
                                                                   ["Extrinsic", "\\detokenize{$(c.extrinsic.comment)}"],
                                                                   ["Video (extrinsic)", "\\detokenize{$(c.extrinsic.video.comment)}"],
                                                                   Rule(:bottom)])=#

function getintrinsicplot(path, w, h)
    intrinsic = [joinpath(path, file) for file in readdir(path) if "extrinsic.png" ≠ file]
    n = length(intrinsic)
    nw, mh = getmozaik(n, w, h)
    gp = @pgf GroupPlot(
                        {
                         group_style =
                         {
                          group_size = "$nw by $mh"#, vertical_sep = "1mm", horizontal_sep = "1mm"
                         },
                         width = "\\linewidth/$nw", height = "\\linewidth/$mh", enlargelimits=false, axis_equal_image, hide_axis
                        })
    @pgf for imgname in intrinsic
        push!(gp, {}, Plot(Graphics({xmin=1,xmax=w,ymin=1,ymax=h}, imgname)))
    end
    name = tempname()*".tikz"
    pgfsave(name, gp)
    name
end
function getextrinsicplot(path, w, h)
    extrinsic = joinpath(path, "extrinsic.png")
    @pgf p = Axis({
                   enlargelimits=false, axis_equal_image, hide_axis#, width = "$(textwidth)mm"
                  }, Plot(Graphics({xmin=1,xmax=w,ymin=1,ymax=h}, extrinsic)))
    name = tempname()*".tikz"
    pgfsave(name, p)
    name
end

function _getplots(c::Calibration, calibfile, ϵpixel)
    path = joinpath(coffeesource, "calibration_images", string(hash(c)))
    h, w = size(FileIO.load(joinpath(path, "extrinsic.png")))
    extrinsicplot = getextrinsicplot(path, w, h)
    ϵcm = errorcm(calibfile, ϵpixel)
    errorstable = latex_tabular(String, Tabular("lll"),
                                [Rule(:top),
                                 ["", "pixel", "cm"],
                                 Rule(:mid),
                                 ["Mean erros", round(ϵpixel, digits = 3), round(ϵcm, digits = 3)],
                                 Rule(:bottom)])
    path, w, h, extrinsicplot, errorstable
end

function getplots(c::Calibration{Missing, T}, calibfile, ϵpixel) where {T}
    path, w, h, extrinsicplot, errorstable =  _getplots(c, calibfile, ϵpixel)
    commentstable = getcomments(c)
    extrinsicplot, errorstable, commentstable, false
end
function getplots(c::Calibration, calibfile, ϵpixel)
    path, w, h, extrinsicplot, errorstable =  _getplots(c, calibfile, ϵpixel)
    intrinsicplot = getintrinsicplot(path, w, h)
    commentstable = getcomments(c)
    extrinsicplot, errorstable, commentstable, true, intrinsicplot
end

function calibrationquality!(template_tex, c, calibfile, ϵpixel, pois, calibnumber)
    template_tex = replace(template_tex, "{{pois}}" => pois)
    template_tex = replace(template_tex, "{{calibnumber}}" => calibnumber)
    for (old, new) in zip(("{{extrinsicplot}}", "{{errorstable}}", "{{calibrationcommentstable}}", "{{isintrinsic}}", "{{intrinsicplot}}"), getplots(c, calibfile, ϵpixel))
        template_tex = replace(template_tex, old => print_tex(String, new))
    end
    template_tex
end

function getcomments(x::Dict{Symbol, POI{T}}) where {T}
    rows = Vector{Vector{String}}()
    for (k, v) in x
        append!(rows, [[string(k), "Overall ", escape4latex(v.data.comment)], [string(k), "Video ", escape4latex(v.data.video.comment)]])
    end
    latex_tabular(String, Tabular("l l p{5cm}"),
                  [Rule(:top),
                   ["POI", "Source", "Comment"],
                   Rule(:mid),
                   rows...,
                   Rule(:bottom)])
end

_isinstantaneous(_::POI{C, Temporal{V, I}}) where {C <: Calibration, V <: AbstractTimeLine, I <: Instantaneous} = true
_isinstantaneous(_) = false

function clickquality(template_tex, temporalpois, pixelpois)
    pois = filter(_isinstantaneous∘last, temporalpois)
    n = length(pois)
    imgname = tempname()*".jpg"
    extract(imgname, last(first(pois)).data, coffeesource)
    h, w = size(FileIO.load(imgname))
    nw, mh = getmozaik(n, w, h)
    gp = @pgf GroupPlot(
                        {
                         group_style =
                         {
                          group_size="$nw by $mh"#, vertical_sep = "1mm", horizontal_sep = "1mm"
                         },
                         width = "\\linewidth/$nw", height = "\\linewidth/$mh", enlargelimits=false, axis_equal_image, hide_axis, y_dir = "reverse"
                        });
    @pgf for (poitype, p) in pois
        imgname = tempname()*".jpg"
        extract(imgname, p.data, coffeesource)
        f1 = Plot(Graphics({xmin=1,xmax=w,ymin=1,ymax=h}, imgname))
        x, y, t = pixelpois[poitype].data.data
        f2 = Plot({only_marks, "red", mark_size="0.1pt"}, Table([x], [y]))
        α = atand(y - h/2, w/2 - x)
        push!(gp, {}, f1, f2, "\\node[inner sep=2, pin={[pin edge={<-, red,thick}, fill = white, draw = red]$α:$poitype}] at ($x, $y) {};")
    end
    name = tempname()*".tikz"
    pgfsave(name, gp)
    template_tex = replace(template_tex,  "{{clickquality}}" => name)
    replace(template_tex,  "{{clickcomments}}" => print_tex(String, getcomments(temporalpois)))
end

plot(x::Instantaneous{Array{Float64,2}}) = @pgf PlotInc({only_marks}, Table(x.data[1:1], x.data[2:2]))
plot(x::Prolonged{Array{Float64,2}}) = @pgf PlotInc({no_markers}, Table(x.data[:,1], x.data[:,2]))

function calibratedtrackquality(template_tex, pixelpois, cmpois)
    @pgf gp = GroupPlot(
                        {legend_style =
                         {
                          at = Coordinate(0.5, -0.15),
                          anchor = "north",
                          legend_columns = -1,
                          draw="none"
                         },
                         group_style =
                         {
                          group_size="2 by 1",
                         },
                         xmajorgrids, ymajorgrids, width = "\\linewidth/2", height = "\\linewidth/2", axis_equal
                        })
    @pgf push!(gp, {title = "Raw", xlabel = "X (pixel)", ylabel = "Y (pixel)"})#, legend_to_name = "grouplegend"})
    for (k, v) in pixelpois
        push!(gp, plot(v.data), LegendEntry(string(k)))
    end
    @pgf push!(gp, {title = "Calibrated", "yticklabel pos=right", xlabel = "X (cm)", ylabel = "Y (cm)"})
    for (k, v) in cmpois
        push!(gp, plot(v))
    end
    name = tempname()*".tikz"
    pgfsave(name, gp)
    replace(template_tex,  "{{calibratedpois}}" => name)
end

function smoothquality(template_tex, cmtrack, smtrack)
    sm = vcat(smtrack.homing, smtrack.searching)
    p = @pgf Axis(
                  {legend_style =
                   {
                    at = Coordinate(0.5, -0.15),
                    anchor = "north",
                    legend_columns = -1,
                    draw="none"
                   },
                   xmajorgrids,
                   ymajorgrids,
                   "ytick distance=25",
                   "xtick distance=25",
                   axis_equal,
                   scale_only_axis,
                   xlabel = "X (cm)",
                   ylabel = "Y (cm)",
                  },
                  PlotInc({only_marks, mark_size=2, opacity = 0.25, draw_opacity=0}, Table(cmtrack[:,1], cmtrack[:,2])),
                  PlotInc({thick, no_markers}, Table(first.(sm), last.(sm))),
                  Legend("calibrated", "smoothed")
                 )
    name = tempname()*".tikz"
    pgfsave(name, p)
    replace(template_tex, "{{smoothquality}}" => name)
end

function turningpointquality(template_tex, track)
    nsearching = min(length(track.searching), 25)
    sm = vcat(track.homing, track.searching[1:nsearching])

    p = @pgf Axis(
                  {smooth, legend_style =
                   {
                    at = Coordinate(0.5, -0.15),
                    anchor = "north",
                    legend_columns = -1,
                    draw="none"
                   },
                   xmajorgrids,
                   ymajorgrids,
                   "ytick distance=25",
                   "xtick distance=25",
                   axis_equal,
                   scale_only_axis,
                   xlabel = "X (cm)",
                   ylabel = "Y (cm)",
                  },
                  PlotInc({
                           no_markers,
                           mesh,
                           """colormap={}{
                           color(0cm)=(black!10);
                           color(1cm)=(black);
                           }""",
                           ultra_thick,
                          }, Table({
                                    point_meta = raw"\thisrow{c}"
                                   },
                                   x = first.(sm), y = last.(sm), c = range(0, step = track.Δt, length = length(sm)))),
                  PlotInc({only_marks}, Table(track.homing[end][1:1], track.homing[end][2:2])),
                  Legend(["Track", "Turning point"])
                 )
    name = tempname()*".tikz"
    pgfsave(name, p)
    replace(template_tex, "{{turningpointquality}}" => name)
end

function plotquality(temporalpois, pixelpois, nameerror, cmpois, track, runcomment, targetfile)
    c2pois = Dict{Calibration, String}()
    for (k,v) in temporalpois
        if haskey(c2pois, v.calib)
            c2pois[v.calib] *= ", $k"
        else
            c2pois[v.calib] = string(k)
        end
    end

    io = IOBuffer()
    for (i, (c, v)) in enumerate(c2pois)
        calib_template = read("/home/yakir/dungProject/DungAnalyse/src/calibrations.tex", String)
        println(io, calibrationquality!(calib_template, c, nameerror[c]..., v, i))
    end
    calibrations = String(take!(io))

    template_tex = read("/home/yakir/dungProject/DungAnalyse/src/qualityreport.tex", String)

    template_tex = replace(template_tex,  "{{calibrations}}" => calibrations)

    template_tex = clickquality(template_tex, temporalpois, pixelpois)

    template_tex = calibratedtrackquality(template_tex, pixelpois, cmpois)

    template_tex = smoothquality(template_tex, cmpois[:track].data, track)

    template_tex = turningpointquality(template_tex, track)

    template_tex = replace(template_tex,  "{{runcomment}}" => runcomment)

    base = tempname()
    texfile = "$base.tex"
    write(texfile, template_tex)
    latex_success, log, latexcmd = PGFPlotsX.run_latex_once(texfile, latexengine(), vcat(PGFPlotsX.DEFAULT_FLAGS, PGFPlotsX.CUSTOM_FLAGS))
    if latex_success
        mv("$base.pdf", targetfile, force=true)
    else
        error("failed to compile latex file $base.tex")
    end
end


text:
"""
    find_smallest_nonelement(array::Array{Int64,1})

Returns the smallest number of a sorted array that cannot be represented as sum of subset of
elements from this array.

# Arguments
- `array::Array{Int64,1}`: Unsorted array

# Examples
```julia-repl
julia> import ClassicAlgorithmsCollections
julia> arr = [1, 2, 5, 10, 20, 40]
julia> ClassicAlgorithmsCollections.find_smallest_nonelement(arr)
4
```
"""
function find_smallest_nonelement(array::Array{Int64,1})

    result = 1
    for i in 1:length(array)
        if array[i] <= result
            result += array[i]
        else
            break
        end
    end
    return result
end

max_stars_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_issues_repo_name: Anselmoo/ClassicAlgorithmsCollections

max_forks_repo_name: Anselmoo/ClassicAlgorithmsCollections