text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: cloudsearch_domain
using AWS.Compat
using AWS.UUIDs

"""
    search(q)
    search(q, params::Dict{String,<:Any})

Retrieves a list of documents that match the specified search criteria. How you specify the
search criteria depends on which query parser you use. Amazon CloudSearch supports four
query parsers:  simple: search all text and text-array fields for the specified string.
Search for phrases, individual terms, and prefixes.  structured: search specific fields,
construct compound queries using Boolean operators, and use advanced features such as term
boosting and proximity searching. lucene: specify search criteria using the Apache Lucene
query parser syntax. dismax: specify search criteria using the simplified subset of the
Apache Lucene query parser syntax defined by the DisMax query parser.  For more
information, see Searching Your Data in the Amazon CloudSearch Developer Guide. The
endpoint for submitting Search requests is domain-specific. You submit search requests to a
domain's search endpoint. To get the search endpoint for your domain, use the Amazon
CloudSearch configuration service DescribeDomains action. A domain's endpoints are also
displayed on the domain dashboard in the Amazon CloudSearch console.

# Arguments
- `q`: Specifies the search criteria for the request. How you specify the search criteria
  depends on the query parser used for the request and the parser options specified in the
  queryOptions parameter. By default, the simple query parser is used to process requests. To
  use the structured, lucene, or dismax query parser, you must also specify the queryParser
  parameter.  For more information about specifying search criteria, see Searching Your Data
  in the Amazon CloudSearch Developer Guide.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"cursor"`: Retrieves a cursor value you can use to page through large result sets. Use
  the size parameter to control the number of hits to include in each response. You can
  specify either the cursor or start parameter in a request; they are mutually exclusive. To
  get the first cursor, set the cursor value to initial. In subsequent requests, specify the
  cursor value returned in the hits section of the response.  For more information, see
  Paginating Results in the Amazon CloudSearch Developer Guide.
- `"expr"`: Defines one or more numeric expressions that can be used to sort results or
  specify search or filter criteria. You can also specify expressions as return fields.  You
  specify the expressions in JSON using the form {\"EXPRESSIONNAME\":\"EXPRESSION\"}. You can
  define and use multiple expressions in a search request. For example:
  {\"expression1\":\"_score*rating\", \"expression2\":\"(1/rank)*year\"}   For information
  about the variables, operators, and functions you can use in expressions, see Writing
  Expressions in the Amazon CloudSearch Developer Guide.
- `"facet"`: Specifies one or more fields for which to get facet information, and options
  that control how the facet information is returned. Each specified field must be
  facet-enabled in the domain configuration. The fields and options are specified in JSON
  using the form
  {\"FIELD\":{\"OPTION\":VALUE,\"OPTION:\"STRING\"},\"FIELD\":{\"OPTION\":VALUE,\"OPTION\":\"S
  TRING\"}}. You can specify the following faceting options:   buckets specifies an array of
  the facet values or ranges to count. Ranges are specified using the same syntax that you
  use to search for a range of values. For more information, see  Searching for a Range of
  Values in the Amazon CloudSearch Developer Guide. Buckets are returned in the order they
  are specified in the request. The sort and size options are not valid if you specify
  buckets.   size specifies the maximum number of facets to include in the results. By
  default, Amazon CloudSearch returns counts for the top 10. The size parameter is only valid
  when you specify the sort option; it cannot be used in conjunction with buckets.   sort
  specifies how you want to sort the facets in the results: bucket or count. Specify bucket
  to sort alphabetically or numerically by facet value (in ascending order). Specify count to
  sort by the facet counts computed for each facet value (in descending order). To retrieve
  facet counts for particular values or ranges of values, use the buckets option instead of
  sort.    If no facet options are specified, facet counts are computed for all field values,
  the facets are sorted by facet count, and the top 10 facets are returned in the results. To
  count particular buckets of values, use the buckets option. For example, the following
  request uses the buckets option to calculate and return facet counts by decade.
  {\"year\":{\"buckets\":[\"[1970,1979]\",\"[1980,1989]\",\"[1990,1999]\",\"[2000,2009]\",\"[2
  010,}\"]}}  To sort facets by facet count, use the count option. For example, the following
  request sets the sort option to count to sort the facet values by facet count, with the
  facet values that have the most matching documents listed first. Setting the size option to
  3 returns only the top three facet values.  {\"year\":{\"sort\":\"count\",\"size\":3}}  To
  sort the facets by value, use the bucket option. For example, the following request sets
  the sort option to bucket to sort the facet values numerically by year, with earliest year
  listed first.   {\"year\":{\"sort\":\"bucket\"}}  For more information, see Getting and
  Using Facet Information in the Amazon CloudSearch Developer Guide.
- `"fq"`: Specifies a structured query that filters the results of a search without
  affecting how the results are scored and sorted. You use filterQuery in conjunction with
  the query parameter to filter the documents that match the constraints specified in the
  query parameter. Specifying a filter controls only which matching documents are included in
  the results, it has no effect on how they are scored and sorted. The filterQuery parameter
  supports the full structured query syntax.  For more information about using filters, see
  Filtering Matching Documents in the Amazon CloudSearch Developer Guide.
- `"highlight"`: Retrieves highlights for matches in the specified text or text-array
  fields. Each specified field must be highlight enabled in the domain configuration. The
  fields and options are specified in JSON using the form
  {\"FIELD\":{\"OPTION\":VALUE,\"OPTION:\"STRING\"},\"FIELD\":{\"OPTION\":VALUE,\"OPTION\":\"S
  TRING\"}}. You can specify the following highlight options:   format: specifies the format
  of the data in the text field: text or html. When data is returned as HTML, all
  non-alphanumeric characters are encoded. The default is html.   max_phrases: specifies the
  maximum number of occurrences of the search term(s) you want to highlight. By default, the
  first occurrence is highlighted.   pre_tag: specifies the string to prepend to an
  occurrence of a search term. The default for HTML highlights is &lt;em&gt;. The
  default for text highlights is *.   post_tag: specifies the string to append to an
  occurrence of a search term. The default for HTML highlights is &lt;/em&gt;. The
  default for text highlights is *.   If no highlight options are specified for a field, the
  returned field text is treated as HTML and the first match is highlighted with emphasis
  tags: &lt;em>search-term&lt;/em&gt;. For example, the following request
  retrieves highlights for the actors and title fields.  { \"actors\": {}, \"title\":
  {\"format\": \"text\",\"max_phrases\": 2,\"pre_tag\": \"\",\"post_tag\": \"\"} }
- `"partial"`: Enables partial results to be returned if one or more index partitions are
  unavailable. When your search index is partitioned across multiple search instances, by
  default Amazon CloudSearch only returns results if every partition can be queried. This
  means that the failure of a single search instance can result in 5xx (internal server)
  errors. When you enable partial results, Amazon CloudSearch returns whatever results are
  available and includes the percentage of documents searched in the search results
  (percent-searched). This enables you to more gracefully degrade your users' search
  experience. For example, rather than displaying no results, you could display the partial
  results and a message indicating that the results might be incomplete due to a temporary
  system outage.
- `"q.options"`: Configures options for the query parser specified in the queryParser
  parameter. You specify the options in JSON using the following form
  {\"OPTION1\":\"VALUE1\",\"OPTION2\":VALUE2\"...\"OPTIONN\":\"VALUEN\"}. The options you can
  configure vary according to which parser you use:  defaultOperator: The default operator
  used to combine individual terms in the search string. For example: defaultOperator: 'or'.
  For the dismax parser, you specify a percentage that represents the percentage of terms in
  the search string (rounded down) that must match, rather than a default operator. A value
  of 0% is the equivalent to OR, and a value of 100% is equivalent to AND. The percentage
  must be specified as a value in the range 0-100 followed by the percent (%) symbol. For
  example, defaultOperator: 50%. Valid values: and, or, a percentage in the range 0%-100%
  (dismax). Default: and (simple, structured, lucene) or 100 (dismax). Valid for: simple,
  structured, lucene, and dismax. fields: An array of the fields to search when no fields are
  specified in a search. If no fields are specified in a search and this option is not
  specified, all text and text-array fields are searched. You can specify a weight for each
  field to control the relative importance of each field when Amazon CloudSearch calculates
  relevance scores. To specify a field weight, append a caret (^) symbol and the weight to
  the field name. For example, to boost the importance of the title field over the
  description field you could specify: \"fields\":[\"title^5\",\"description\"]. Valid
  values: The name of any configured field and an optional numeric value greater than zero.
  Default: All text and text-array fields. Valid for: simple, structured, lucene, and dismax.
  operators: An array of the operators or special characters you want to disable for the
  simple query parser. If you disable the and, or, or not operators, the corresponding
  operators (+, |, -) have no special meaning and are dropped from the search string.
  Similarly, disabling prefix disables the wildcard operator (*) and disabling phrase
  disables the ability to search for phrases by enclosing phrases in double quotes. Disabling
  precedence disables the ability to control order of precedence using parentheses. Disabling
  near disables the ability to use the ~ operator to perform a sloppy phrase search.
  Disabling the fuzzy operator disables the ability to use the ~ operator to perform a fuzzy
  search. escape disables the ability to use a backslash () to escape special characters
  within the search string. Disabling whitespace is an advanced option that prevents the
  parser from tokenizing on whitespace, which can be useful for Vietnamese. (It prevents
  Vietnamese words from being split incorrectly.) For example, you could disable all
  operators other than the phrase operator to support just simple term and phrase queries:
  \"operators\":[\"and\",\"not\",\"or\", \"prefix\"]. Valid values: and, escape, fuzzy, near,
  not, or, phrase, precedence, prefix, whitespace. Default: All operators and special
  characters are enabled. Valid for: simple. phraseFields: An array of the text or text-array
  fields you want to use for phrase searches. When the terms in the search string appear in
  close proximity within a field, the field scores higher. You can specify a weight for each
  field to boost that score. The phraseSlop option controls how much the matches can deviate
  from the search string and still be boosted. To specify a field weight, append a caret (^)
  symbol and the weight to the field name. For example, to boost phrase matches in the title
  field over the abstract field, you could specify: \"phraseFields\":[\"title^3\", \"plot\"]
  Valid values: The name of any text or text-array field and an optional numeric value
  greater than zero. Default: No fields. If you don't specify any fields with phraseFields,
  proximity scoring is disabled even if phraseSlop is specified. Valid for: dismax.
  phraseSlop: An integer value that specifies how much matches can deviate from the search
  phrase and still be boosted according to the weights specified in the phraseFields option;
  for example, phraseSlop: 2. You must also specify phraseFields to enable proximity scoring.
  Valid values: positive integers. Default: 0. Valid for: dismax. explicitPhraseSlop: An
  integer value that specifies how much a match can deviate from the search phrase when the
  phrase is enclosed in double quotes in the search string. (Phrases that exceed this
  proximity distance are not considered a match.) For example, to specify a slop of three for
  dismax phrase queries, you would specify \"explicitPhraseSlop\":3. Valid values: positive
  integers. Default: 0. Valid for: dismax. tieBreaker: When a term in the search string is
  found in a document's field, a score is calculated for that field based on how common the
  word is in that field compared to other documents. If the term occurs in multiple fields
  within a document, by default only the highest scoring field contributes to the document's
  overall score. You can specify a tieBreaker value to enable the matches in lower-scoring
  fields to contribute to the document's score. That way, if two documents have the same max
  field score for a particular term, the score for the document that has matches in more
  fields will be higher. The formula for calculating the score with a tieBreaker is (max
  field score) + (tieBreaker) * (sum of the scores for the rest of the matching fields). Set
  tieBreaker to 0 to disregard all but the highest scoring field (pure max):
  \"tieBreaker\":0. Set to 1 to sum the scores from all fields (pure sum): \"tieBreaker\":1.
  Valid values: 0.0 to 1.0. Default: 0.0. Valid for: dismax.
- `"q.parser"`: Specifies which query parser to use to process the request. If queryParser
  is not specified, Amazon CloudSearch uses the simple query parser.  Amazon CloudSearch
  supports four query parsers:   simple: perform simple searches of text and text-array
  fields. By default, the simple query parser searches all text and text-array fields. You
  can specify which fields to search by with the queryOptions parameter. If you prefix a
  search term with a plus sign (+) documents must contain the term to be considered a match.
  (This is the default, unless you configure the default operator with the queryOptions
  parameter.) You can use the - (NOT), | (OR), and * (wildcard) operators to exclude
  particular terms, find results that match any of the specified terms, or search for a
  prefix. To search for a phrase rather than individual terms, enclose the phrase in double
  quotes. For more information, see Searching for Text in the Amazon CloudSearch Developer
  Guide.   structured: perform advanced searches by combining multiple expressions to define
  the search criteria. You can also search within particular fields, search for values and
  ranges of values, and use advanced options such as term boosting, matchall, and near. For
  more information, see Constructing Compound Queries in the Amazon CloudSearch Developer
  Guide.   lucene: search using the Apache Lucene query parser syntax. For more information,
  see Apache Lucene Query Parser Syntax.   dismax: search using the simplified subset of the
  Apache Lucene query parser syntax defined by the DisMax query parser. For more information,
  see DisMax Query Parser Syntax.
- `"return"`: Specifies the field and expression values to include in the response.
  Multiple fields or expressions are specified as a comma-separated list. By default, a
  search response includes all return enabled fields (_all_fields). To return only the
  document IDs for the matching documents, specify _no_fields. To retrieve the relevance
  score calculated for each document, specify _score.
- `"size"`: Specifies the maximum number of search hits to include in the response.
- `"sort"`: Specifies the fields or custom expressions to use to sort the search results.
  Multiple fields or expressions are specified as a comma-separated list. You must specify
  the sort direction (asc or desc) for each field; for example, year desc,title asc. To use a
  field to sort results, the field must be sort-enabled in the domain configuration. Array
  type fields cannot be used for sorting. If no sort parameter is specified, results are
  sorted by their default relevance scores in descending order: _score desc. You can also
  sort by document ID (_id asc) and version (_version desc). For more information, see
  Sorting Results in the Amazon CloudSearch Developer Guide.
- `"start"`: Specifies the offset of the first search hit you want to return. Note that the
  result set is zero-based; the first result is at index 0. You can specify either the start
  or cursor parameter in a request, they are mutually exclusive.  For more information, see
  Paginating Results in the Amazon CloudSearch Developer Guide.
- `"stats"`: Specifies one or more fields for which to get statistics information. Each
  specified field must be facet-enabled in the domain configuration. The fields are specified
  in JSON using the form: {\"FIELD-A\":{},\"FIELD-B\":{}} There are currently no options
  supported for statistics.
"""
search(q; aws_config::AbstractAWSConfig=global_aws_config()) = cloudsearch_domain("GET", "/2013-01-01/search?format=sdk&pretty=true", Dict{String, Any}("q"=>q); aws_config=aws_config)
search(q, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cloudsearch_domain("GET", "/2013-01-01/search?format=sdk&pretty=true", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("q"=>q), params)); aws_config=aws_config)

"""
    suggest(q, suggester)
    suggest(q, suggester, params::Dict{String,<:Any})

Retrieves autocomplete suggestions for a partial query string. You can use suggestions
enable you to display likely matches before users finish typing. In Amazon CloudSearch,
suggestions are based on the contents of a particular text field. When you request
suggestions, Amazon CloudSearch finds all of the documents whose values in the suggester
field start with the specified query string. The beginning of the field must match the
query string to be considered a match.  For more information about configuring suggesters
and retrieving suggestions, see Getting Suggestions in the Amazon CloudSearch Developer
Guide.  The endpoint for submitting Suggest requests is domain-specific. You submit suggest
requests to a domain's search endpoint. To get the search endpoint for your domain, use the
Amazon CloudSearch configuration service DescribeDomains action. A domain's endpoints are
also displayed on the domain dashboard in the Amazon CloudSearch console.

# Arguments
- `q`: Specifies the string for which you want to get suggestions.
- `suggester`: Specifies the name of the suggester to use to find suggested matches.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"size"`: Specifies the maximum number of suggestions to return.
"""
suggest(q, suggester; aws_config::AbstractAWSConfig=global_aws_config()) = cloudsearch_domain("GET", "/2013-01-01/suggest?format=sdk&pretty=true", Dict{String, Any}("q"=>q, "suggester"=>suggester); aws_config=aws_config)
suggest(q, suggester, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cloudsearch_domain("GET", "/2013-01-01/suggest?format=sdk&pretty=true", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("q"=>q, "suggester"=>suggester), params)); aws_config=aws_config)

"""
    upload_documents(content-_type, documents)
    upload_documents(content-_type, documents, params::Dict{String,<:Any})

Posts a batch of documents to a search domain for indexing. A document batch is a
collection of add and delete operations that represent the documents you want to add,
update, or delete from your domain. Batches can be described in either JSON or XML. Each
item that you want Amazon CloudSearch to return as a search result (such as a product) is
represented as a document. Every document has a unique ID and one or more fields that
contain the data that you want to search and return in results. Individual documents cannot
contain more than 1 MB of data. The entire batch cannot exceed 5 MB. To get the best
possible upload performance, group add and delete operations in batches that are close the
5 MB limit. Submitting a large volume of single-document batches can overload a domain's
document service.  The endpoint for submitting UploadDocuments requests is domain-specific.
To get the document endpoint for your domain, use the Amazon CloudSearch configuration
service DescribeDomains action. A domain's endpoints are also displayed on the domain
dashboard in the Amazon CloudSearch console.  For more information about formatting your
data for Amazon CloudSearch, see Preparing Your Data in the Amazon CloudSearch Developer
Guide. For more information about uploading data for indexing, see Uploading Data in the
Amazon CloudSearch Developer Guide.

# Arguments
- `content-_type`: The format of the batch you are uploading. Amazon CloudSearch supports
  two document batch formats:  application/json application/xml
- `documents`: A batch of documents formatted in JSON or HTML.

"""
upload_documents(Content_Type, documents; aws_config::AbstractAWSConfig=global_aws_config()) = cloudsearch_domain("POST", "/2013-01-01/documents/batch?format=sdk", Dict{String, Any}("documents"=>documents, "headers"=>Dict{String, Any}("Content-Type"=>Content_Type)); aws_config=aws_config)
upload_documents(Content_Type, documents, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = cloudsearch_domain("POST", "/2013-01-01/documents/batch?format=sdk", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("documents"=>documents, "headers"=>Dict{String, Any}("Content-Type"=>Content_Type)), params)); aws_config=aws_config)


text:
GaussianProcessRegressor_ = SKGP.GaussianProcessRegressor
@sk_reg mutable struct GaussianProcessRegressor <: MMI.Deterministic
    kernel::Any               = nothing
    alpha::Union{Float64,AbstractArray} = 1.0e-10
    optimizer::Any            = "fmin_l_bfgs_b"
    n_restarts_optimizer::Int = 0
    normalize_y::Bool         = false
    copy_X_train::Bool        = true
    random_state::Any         = nothing
end
MMI.fitted_params(model::GaussianProcessRegressor, (fitresult, _, _)) = (
    X_train = fitresult.X_train_,
    y_train = fitresult.y_train_,
    kernel  = fitresult.kernel_,
    L       = fitresult.L_,
    alpha   = fitresult.alpha_,
    log_marginal_likelihood_value = fitresult.log_marginal_likelihood_value_
    )

metadata_model(GaussianProcessRegressor,
    input   = Table(Continuous),
    target  = AbstractVector{Continuous},
    weights = false,
    descr   = "Gaussian process regressor."
    )

# ============================================================================
GaussianProcessClassifier_ = SKGP.GaussianProcessClassifier
@sk_clf mutable struct GaussianProcessClassifier <: MMI.Probabilistic
    kernel::Any           = nothing
    optimizer::Any        = "fmin_l_bfgs_b"
    n_restarts_optimizer::Int = 0
    copy_X_train::Bool    = true
    random_state::Any     = nothing
    max_iter_predict::Int = 100::(_ > 0)
    warm_start::Bool      = false
    multi_class::String   = "one_vs_rest"::(_ in ("one_vs_one", "one_vs_rest"))
end
MMI.fitted_params(m::GaussianProcessClassifier, (f, _, _)) = (
    kernel    = f.kernel_,
    log_marginal_likelihood_value = f.log_marginal_likelihood_value_,
    classes   = f.classes_,
    n_classes = f.n_classes_
    )
metadata_model(GaussianProcessClassifier,
    input   = Table(Continuous),
    target  = AbstractVector{<:Finite},
    weights = false,
    descr   = "Gaussian process classifier."
    )

ext: jl


text:
using ITensors
using LinearAlgebra
using QuadGK

function ising_mpo(
  pair_sₕ::Pair{<:Index,<:Index},
  pair_sᵥ::Pair{<:Index,<:Index},
  β::Real,
  J::Real=1.0;
  sz::Bool=false,
)
  sₕ, sₕ′ = pair_sₕ
  sᵥ, sᵥ′ = pair_sᵥ
  @assert dim(sₕ) == dim(sᵥ)
  d = dim(sₕ)
  T = ITensor(sₕ, sₕ′, sᵥ, sᵥ′)
  for i in 1:d
    T[i, i, i, i] = 1.0
  end
  if sz
    T[1, 1, 1, 1] = -1.0
  end
  s̃ₕ, s̃ₕ′, s̃ᵥ, s̃ᵥ′ = sim.((sₕ, sₕ′, sᵥ, sᵥ′))
  T̃ = T * δ(sₕ, s̃ₕ) * δ(sₕ′, s̃ₕ′) * δ(sᵥ, s̃ᵥ) * δ(sᵥ′, s̃ᵥ′)

  # Alternative method
  #Q = [exp(β * J) exp(-β * J); exp(-β * J) exp(β * J)]
  #X = √Q

  f(λ₊, λ₋) = [
    (λ₊ + λ₋)/2 (λ₊ - λ₋)/2
    (λ₊ - λ₋)/2 (λ₊ + λ₋)/2
  ]
  λ₊ = √(exp(β * J) + exp(-β * J))
  λ₋ = √(exp(β * J) - exp(-β * J))
  X = f(λ₊, λ₋)
  Xₕ = itensor(vec(X), s̃ₕ, sₕ)
  Xₕ′ = itensor(vec(X), s̃ₕ′, sₕ′)
  Xᵥ = itensor(vec(X), s̃ᵥ, sᵥ)
  Xᵥ′ = itensor(vec(X), s̃ᵥ′, sᵥ′)
  return T̃ * Xₕ′ * Xᵥ′ * Xₕ * Xᵥ
end

function ising_mpo(sₕ::Index, sᵥ::Index, args...; kwargs...)
  return ising_mpo(sₕ => sₕ', sᵥ => sᵥ', args...; kwargs...)
end

function ising_mpo_dual(
  sh::Tuple{Index,Index}, sv::Tuple{Index,Index}, β::Real, J::Real=1.0
)
  d = dim(sh[1])
  T = ITensor(sh[1], sh[2], sv[1], sv[2])
  sig(s) = 1.0 - 2.0 * (s - 1)
  E0 = -4.0
  for s1 in 1:d, s2 in 1:d, s3 in 1:d, s4 in 1:d
    E = sig(s1) * sig(s2) + sig(s2) * sig(s3) + sig(s3) * sig(s4) + sig(s4) * sig(s1)
    val = exp(-β * (E - E0))
    T[sh[1] => s1, sv[2] => s2, sh[2] => s3, sv[1] => s4] = val
  end
  return T
end

function ising_partition(sh, sv, β)
  ny, nx = size(sh)
  T = Matrix{ITensor}(undef, ny, nx)
  for iy in 1:ny, ix in 1:nx
    ixp = per(ix + 1, nx)
    iyp = per(iy + 1, ny)
    T[iy, ix] = ising_mpo(sh[iy, ix] => sh[iy, ixp], sv[iy, ix] => sv[iyp, ix], β)
  end
  return T
end

#
# Exact results
#

const βc = 0.5 * log(√2 + 1)

function ising_free_energy(β::Real, J::Real=1.0)
  k = β * J
  c = cosh(2 * k)
  s = sinh(2 * k)
  xmin = 0.0
  xmax = π
  integrand(x) = log(c^2 + √(s^4 + 1 - 2 * s^2 * cos(x)))
  integral, err = quadgk(integrand, xmin, xmax)::Tuple{Float64,Float64}
  return -(log(2) + integral / π) / (2 * β)
end

function ising_magnetization(β::Real)
  β > βc && return (1 - sinh(2 * β)^(-4))^(1 / 8)
  return 0.0
end


text:
#=

utils.jl
========
    A collection of useful methods that are used in the module.

    Methods:
    -------

Author: Fady Shoukry
Date: 01/30/2016
=#
function createSymsBlock{T<:Any}(modelname::Symbol, syms_dict::Dict{Symbol}{T})
    """
    Return a dynamically generated block of code that, when evaluated, will
    define variables for each key in syms_dict
    """
    blk = Expr(:block)
    for (key,val) in syms_dict
        push!(blk.args, :($key = $val))
    end
    blk
end

function createConstraintsBlock(modelname::Symbol, constraints::Array{Expr})
    """
    Return a dynamically generated block of code that, when evaluated, will add
    all the constraints to the model required
    """
    blk = Expr(:block)
    # First replace all symbols
    for expr in constraints
        str = string(expr)
        push!(blk.args, quote
                            try
                                JuMP.@constraint($modelname, $expr)
                            catch e
                                JuMP.@NLconstraint($modelname, $expr)
                                warn($str, " is a non-linear constraint")
                            end
                        end)
    end
    blk
end

function createVarsBlock(modelname::Symbol, vars::Vector)
    """
    Return a dynamically generated block of code that, when evaluated, will add
    all the variables to the model required
    """
    blk = Expr(:block)
    # First replace all symbols
    for var in vars
        push!(blk.args, :(JuMP.@variable($modelname, $var)))
    end
    blk
end

function createJuMPModelGenFunc{T<:Any}(vars::Vector, sense::Symbol,
    objective::Expr, constraints::Array{Expr}, syms_dict::Dict{Symbol}{T})
    """
    Dynamically generate and return an anonymous function that creates
    and returns the final JuMP model
    """
    model_sym = :model
    syms_blk = createSymsBlock(model_sym, syms_dict)
    objective_ex = :(JuMP.@objective($model_sym, $sense, $objective))
    vars_blk = createVarsBlock(model_sym, vars)
    constraints_blk = createConstraintsBlock(model_sym, constraints)
    @eval function (solver)
        $model_sym = JuMP.Model(solver = solver)
        $syms_blk
        $vars_blk
        $objective_ex
        $constraints_blk
        $model_sym
    end
end


text:
using Test, GeneticAlgorithm

STRING_TO_FIND = "hello"

function createGeneExample()
    return rand(STRING_TO_FIND)
end

function fitnessExample(ind)
    allDifferent = filter(((a,b),) -> a != b, collect(zip(STRING_TO_FIND, ind)))
    return length(allDifferent)
end

@test join(runGA(fitnessExample, createGeneExample, 5, maxNumberOfIterations=200, logging=false)[1]) == "hello"


text:
<<<<<<< HEAD
function modelLoad(file::AbstractString)
  mdl = GLTF.load("models/" * "$file")
  println("models/" * "$file")

  for b in mdl.buffers
    mdlBuff = [
      read("models/" * b.uri)]
  end

  oc = occursion()
  ff = findfirst()
  srchName(x, key) =  x[
    ff(oc(key, x.name)),x]

  mdlPos = srchName(mdl.accessors, "positions")
  mdlInd = srchName(mdl.accessors, "indices")
  mdlTex = srchName(mdl.accessors, "texcoords")
  mdlNorm = srchName(mdl.accessors, "normals")

  posBV = mdl.bufferViews[mdlPos.bufferView]
  indBV = mdl.bufferViews[mdlInd.bufferView]
  texBV = mdl.bufferViews[mdlTex.bufferView]
  normBV = mdl.bufferViews[mdlNorm.bufferView]

  posBuff = mdlBuff[posBV.buffer]
  indBuff = mdlBuff[posBV.buffer]
  texBuff = mdlBuff[posBV.buffer]
  normBuff = mdlBuff[posBV.buffer]

  posVBO = GLuinit(0)
  indVBO = GLuint(0)
  texVBO = GLuint(0)

  @c glGenBuffers(1, &posVBO)
  @c glGenBuffers(1, &indVBO)
  @c glGenBuffers(1, &texVBO)
  @c glGenBuffers(1, &normVBO)

  glBindBuffer(posBV.target, posVBO)
  glBindBuffer(indBV.target, indVBO)
  glBindBuffer(texBV.target, texVBO)
  glBindBuffer(normBV.target, normVBO)

  glBufferData(posBV.target,
     posBV.bytelength, C_NULL, GL_STATIC_DRAW)
  glBufferData(indBV.target,
     indBV.bytelength, C_NULL, GL_STATIC_DRAW)
  glBufferData(texBV.target,
     texBV.bytelength, C_NULL, GL_STATIC_DRAW)
  glBufferData(normBV.target,
     normBV.bytelength, C_NULL, GL_STATIC_DRAW)

  @c glBufferSubData(posBV.target, 0, posBV.byteLength,
    &posBuff[posBV.byteOffset])
  @c glBufferSubData(indBV.target, 0, indBV.byteLength,
    &indBuff[indBV.byteOffset])
  @c glBufferSubData(texBV.target, 0, texBV.byteLength,
    &texBuff[texBV.byteOffset])
  @c glBufferSubData(normBV.target, 0, normBV.byteLength,
    &normBuff[normBV.byteOffset])

  vao = GLuint(0)
  @c glGenVertexArrays(1, &vao)
  glBindVertexArray(vao)

  glBindBuffer(posBV.target, posVBO)
  glBindBuffer(texBV.target, texVBO)
  glBindBuffer(normBV.target, normVBO)

  glVertexAttribPointer(0, 3, pos.componentType, pos.normalized,
    posBV.byteStride, Ptr{Cvoid}(pos.byteOffset))
  glVertexAttribPointer(1, 3, tex.componentType, pos.normalized,
    texBV.byteStride, Ptr{Cvoid}(pos.byteOffset))
  glVertexAttribPointer(2, 3, norm.componentType, pos.normalized,
    normBV.byteStride, Ptr{Cvoid}(pos.byteOffset))

  return (vao, indBV, indVBO)
end

=======
include("globVar.jl")

using Logging
using Dates

>>>>>>> 5f9517fcfc507bc9c83bc0ca5755ab4a4d01f653

function errPrint(lvl::Int, msg::AbstractString)
  if(lvl == 0)
    @info "$(Dates.now()) | $msg"
    return end
  if(lvl == 1)
    @warn "$(Dates.now()) | $msg"
    return end
  if(lvl == 2)
    @error "$(Dates.now()) | $msg"
    return end
end


text:
# automatically generated by the FlatBuffers compiler, do not modify

MyGame.eval(quote

mutable struct InParentNamespace
end
FlatBuffers.@ALIGN(InParentNamespace, 1)

InParentNamespace(buf::AbstractVector{UInt8}) = FlatBuffers.read(InParentNamespace, buf)
InParentNamespace(io::IO) = FlatBuffers.deserialize(io, InParentNamespace)

end)

max_stars_repo_name: rjkat/flatbuffers-julia

max_issues_repo_name: rjkat/flatbuffers-julia

max_forks_repo_name: rjkat/flatbuffers-julia


text:
export find_interval_ls
# shoud have it's own stopping for finding an interval
function find_interval_ls(h :: LineModel, stop_ls :: LS_Stopping;
                          φ_dφ :: Function = (x, y) -> phi_dphi(x, y),
                          t₀ :: Float64 = 0.0, inc0 :: Float64 = 1.0,
                          τ₀ :: Float64 = 1.0e-4, τ₁ :: Float64 = 0.9999,
                          maxiter :: Int = 100, verboseLS :: Bool = false,
                          kwargs...)

  iter = 1
  inc = inc0
  state = copy(stop_ls.current_state)
  h₀, g₀ = state.h₀, state.g₀

  φt₀ = 0.0                            # φ(0)=0             by definition
  dφt₀ = (1.0 - τ₀) * g₀               # φ''(0)=(1.0-τ₀)*g₀ by definition
  sd = -sign(dφt₀)
  t₁ = t₀ + sd * inc
  update!(state, x = t₁)
  φt1, dφt1 = φ_dφ(h, state; kwargs...)

  ɛa = (τ₁ - τ₀) * g₀
  ɛb = -(τ₁ + τ₀)*g₀

  verboseLS &&
    @printf("  iter t        φt        dφt         t1        φt1        dφt1\n")
  verboseLS &&
    @printf("%4d %7.2e %7.2e  %7.2e  %7.2e  %7.2e  %7.2e \n",
            iter, t₀, φt₀, dφt₀, t₁, φt1, dφt1)

  while (dφt1 * sd < 0.0) && (φt1 < φt₀) & (iter < maxiter)
    inc = inc * 4
    t₀ = t₁; φt₀ = φt1; dφt₀ = dφt1
    t₁ = t₀ + sd * inc
    update(state, x = t₁)
    φt1, dφt1 = φ_dφ(h, state; kwargs...)
    iter = iter + 1
    verboseLS && @printf("%4d %7.2e %7.2e  %7.2e  %7.2e  %7.2e  %7.2e \n",
                         iter, t₀,φt₀,dφt₀,t₁,φt1,dφt1)

  end

  while (dφt1 * sd<0.0) & (iter<maxiter)
    tₘ = (t₁ + t₀) / 2
    update!(state, x = tₘ)
    φₘ, dφₘ = φ_dφ(h, state; kwargs...)
    if φₘ * sd > 0.0
      t₁ = tₘ; φt1 = φₘ; dφt1 = dφₘ
    else
      if φₘ < φt₀
        t₀ = tₘ; φt₀ = φₘ; dφt₀ = dφₘ
      else
        t₁ = tₘ; φt1 = φₘ; dφt1 = dφₘ
      end
    end
    iter = iter + 1
    verboseLS && @printf("%4d %7.2e %7.2e  %7.2e  %7.2e  %7.2e  %7.2e \n", iter, t₀,φt₀,dφt₀,t₁,φt1,dφt1)
  end

  ta = min(t₀, t₁); tb = max(t₀, t₁)

  if ta == t₁
    φta = φt1; dφta = dφt1
    φtb = φt₀; dφtb = dφt₀
  else
    φta = φt₀; dφta = dφt₀
    φtb = φt1; dφtb = dφt1
  end

  return (ta, φta, dφta, tb, φtb, dφtb)

end


text:
# planar versions of tensor operations add!, trace! and contract!
planar_add!(α, tsrc::AbstractTensorMap{S},
            β, tdst::AbstractTensorMap{S, N₁, N₂},
            p1::IndexTuple{N₁}, p2::IndexTuple{N₂}) where {S, N₁, N₂} =
    add_transpose!(α, tsrc, β, tdst, p1, p2)

function planar_trace!(α, tsrc::AbstractTensorMap{S},
                       β, tdst::AbstractTensorMap{S, N₁, N₂},
                       p1::IndexTuple{N₁}, p2::IndexTuple{N₂},
                       q1::IndexTuple{N₃}, q2::IndexTuple{N₃}) where {S, N₁, N₂, N₃}
    if BraidingStyle(sectortype(S)) == Bosonic()
        return trace!(α, tsrc, β, tdst, p1, p2, q1, q2)
    end

    @boundscheck begin
        all(i->space(tsrc, p1[i]) == space(tdst, i), 1:N₁) ||
            throw(SpaceMismatch("trace: tsrc = $(codomain(tsrc))←$(domain(tsrc)),
                    tdst = $(codomain(tdst))←$(domain(tdst)), p1 = $(p1), p2 = $(p2)"))
        all(i->space(tsrc, p2[i]) == space(tdst, N₁+i), 1:N₂) ||
            throw(SpaceMismatch("trace: tsrc = $(codomain(tsrc))←$(domain(tsrc)),
                    tdst = $(codomain(tdst))←$(domain(tdst)), p1 = $(p1), p2 = $(p2)"))
        all(i->space(tsrc, q1[i]) == dual(space(tsrc, q2[i])), 1:N₃) ||
            throw(SpaceMismatch("trace: tsrc = $(codomain(tsrc))←$(domain(tsrc)),
                    q1 = $(q1), q2 = $(q2)"))
    end

    if iszero(β)
        fill!(tdst, β)
    elseif β != 1
        rmul!(tdst, β)
    end
    pdata = (p1..., p2...)
    for (f1, f2) in fusiontrees(tsrc)
        for ((f1′, f2′), coeff) in planar_trace(f1, f2, p1, p2, q1, q2)
            TO._trace!(α*coeff, tsrc[f1, f2], true, tdst[f1′, f2′], pdata, q1, q2)
        end
    end
    return tdst
end

function planar_contract!(α, A::AbstractTensorMap{S}, B::AbstractTensorMap{S},
                            β, C::AbstractTensorMap{S},
                            oindA::IndexTuple, cindA::IndexTuple,
                            oindB::IndexTuple, cindB::IndexTuple,
                            p1::IndexTuple, p2::IndexTuple,
                            syms::Union{Nothing, NTuple{3, Symbol}} = nothing) where {S}

    codA, domA = codomainind(A), domainind(A)
    codB, domB = codomainind(B), domainind(B)
    oindA, cindA, oindB, cindB =
        reorder_indices(codA, domA, codB, domB, oindA, cindA, oindB, cindB, p1, p2)

    if oindA == codA && cindA == domA
        A′ = A
    else
        if isnothing(syms)
            A′ = TO.similar_from_indices(eltype(A), oindA, cindA, A, :N)
        else
            A′ = TO.cached_similar_from_indices(syms[1], eltype(A), oindA, cindA, A, :N)
        end
        add_transpose!(true, A, false, A′, oindA, cindA)
    end
    if cindB == codB && oindB == domB
        B′ = B
    else
        if isnothing(syms)
            B′ = TO.similar_from_indices(eltype(B), cindB, oindB, B, :N)
        else
            B′ = TO.cached_similar_from_indices(syms[2], eltype(B), cindB, oindB, B, :N)
        end
        add_transpose!(true, B, false, B′, cindB, oindB)
    end
    mul!(C, A′, B′, α, β)
    return C
end

# auxiliary routines
_cyclicpermute(t::Tuple) = (Base.tail(t)..., t[1])
_cyclicpermute(t::Tuple{}) = ()

function reorder_indices(codA, domA, codB, domB, oindA, oindB, p1, p2)
    N₁ = length(oindA)
    N₂ = length(oindB)
    @assert length(p1) == N₁ && all(in(p1), 1:N₁)
    @assert length(p2) == N₂ && all(in(p2), N₁ .+ (1:N₂))
    oindA2 = TupleTools.getindices(oindA, p1)
    oindB2 = TupleTools.getindices(oindB, p2 .- N₁)
    indA = (codA..., reverse(domA)...)
    indB = (codB..., reverse(domB)...)
    # cycle indA to be of the form (oindA2..., reverse(cindA2)...)
    while length(oindA2) > 0 && indA[1] != oindA2[1]
        indA = _cyclicpermute(indA)
    end
    # cycle indB to be of the form (cindB2..., reverse(oindB2)...)
    while length(oindB2) > 0 && indB[end] != oindB2[1]
        indB = _cyclicpermute(indB)
    end
    for i = 2:N₁
        @assert indA[i] == oindA2[i]
    end
    for j = 2:N₂
        @assert indB[end + 1 - j] == oindB2[j]
    end
    Nc = length(indA) - N₁
    @assert Nc == length(indB) - N₂
    pc = ntuple(identity, Nc)
    cindA2 = reverse(TupleTools.getindices(indA, N₁ .+ pc))
    cindB2 = TupleTools.getindices(indB, pc)
    return oindA2, cindA2, oindB2, cindB2
end

function reorder_indices(codA, domA, codB, domB, oindA, cindA, oindB, cindB, p1, p2)
    oindA2, cindA2, oindB2, cindB2 =
        reorder_indices(codA, domA, codB, domB, oindA, oindB, p1, p2)

    #if oindA or oindB are empty, then reorder indices can only order it correctly up to a cyclic permutation!
    if isempty(oindA2) && !isempty(cindA)
         # isempty(cindA) is a cornercase which I'm not sure if we can encounter
        hit = cindA[findfirst(==(first(cindB2)), cindB)]
        while hit != first(cindA2)
            cindA2 = _cyclicpermute(cindA2)
        end
    end
    if isempty(oindB2) && !isempty(cindB)
        hit = cindB[findfirst(==(first(cindA2)), cindA)]
        while hit != first(cindB2)
            cindB2 = _cyclicpermute(cindB2)
        end
    end
    @assert TupleTools.sort(cindA) == TupleTools.sort(cindA2)
    @assert TupleTools.sort(tuple.(cindA2, cindB2)) == TupleTools.sort(tuple.(cindA, cindB))
    return oindA2, cindA2, oindB2, cindB2
end


text:
platforms_and_sources = Dict(
    Platform("x86_64", "linux") => [
        ArchiveSource("https://developer.nvidia.com/compute/machine-learning/nccl/secure/2.12.7/agnostic/x64/nccl_2.12.7-1+cuda11.6_x86_64.txz",
                      "632521d1f1be9322f18234827027c6484beb3ccb35056a21569072c52b4416ce")],
    Platform("powerpc64le", "linux") => [
        ArchiveSource("https://developer.nvidia.com/compute/machine-learning/nccl/secure/2.12.7/agnostic/ppc64le/nccl_2.12.7-1+cuda11.6_ppc64le.txz",
                      "b01a3ee30908784c84db2de11765a54a4394267210d2a98a22de542e3695042b")],
    Platform("aarch64", "linux") => [
        ArchiveSource("https://developer.nvidia.com/compute/machine-learning/nccl/secure/2.12.7/agnostic/aarch64sbsa/nccl_2.12.7-1+cuda11.6_aarch64.txz",
                      "4520e4a99d3715edc3cfac849ce950d35e6ef18d9584b015c191e0ad7f132011")],
)

max_stars_repo_name: MichelJuillard/Yggdrasil

max_issues_repo_name: MichelJuillard/Yggdrasil

max_forks_repo_name: MichelJuillard/Yggdrasil


text:
using AWSTools.EC2: instance_metadata, instance_availability_zone, instance_region

@testset "EC2" begin
    @testset "instance_metadata" begin
        r = HTTP.Response("{}")  # Instance identity document is JSON
        apply(instance_metadata_patch(r)) do
            @test instance_metadata("/latest/dynamic/instance-identity/document") == "{}"
        end
    end

    @testset "instance_availability_zone" begin
        r = HTTP.Response("us-east-1a")
        apply(instance_metadata_patch(r)) do
            @test instance_availability_zone() == "us-east-1a"
        end
    end

    @testset "instance_region" begin
        r = HTTP.Response("us-east-1a")
        apply(instance_metadata_patch(r)) do
            @test instance_region() == "us-east-1"
        end
    end
end


text:
#===============================================================================

    Defines a container for multiple recordings of discrete-time observations
    of diffusion processes. The main object is `AllObservations`

===============================================================================#
const _PARAM_DEPEND_ENTRY_TYPE = Vector{Pair{Int64, Symbol}}
const _OBS_DEPEND_ENTRY_TYPE = Vector{Tuple{Int64,Int64,Int64}}

const _PARAM_DEPEND_TYPE = Dict{Symbol,_PARAM_DEPEND_ENTRY_TYPE}
const _OBS_DEPEND_TYPE = Dict{Symbol,_OBS_DEPEND_ENTRY_TYPE}

const _PARAM_REV_DEPEND_TYPE = Vector{Vector{Tuple{Symbol,Symbol}}}
const _OBS_REV_DEPEND_TYPE = Vector{Vector{Vector{Tuple{Symbol,Int64}}}}

#NOTE this function must be overwritten from `Main`.
var_parameter_names(::Any) = nothing

"""
    build_recording(P, obs, t0, x0_prior)

A utility function that creates an appropriate `NamedTuple` that represents a
single recording.
"""
build_recording(P, obs, t0, x0_prior) = (P=P, obs=obs, t0=t0, x0_prior=x0_prior)

"""
    build_recording(
        ::Type{K}, tt, observs::Vector, P, t0, x0_prior; kwargs...
    ) where K
A utility function for building a recording. Times of recordings are assumed to
be stored in `tt` and their values in `observs`. `K` is the type of observation
(for instance `LinearGsnObs`). `kwargs` are name arguments that are passed to
every single initializer of `K`.
"""
function build_recording(
        ::Type{K}, tt, observs::Vector, P, t0, x0_prior; kwargs...
    ) where K
    (
        P = P,
        obs = [K(t, obs; kwargs...) for (t,obs) in zip(tt, observs)],
        t0 = t0,
        x0_prior = x0_prior,
    )
end

@doc raw"""
    struct AllObservations
        recordings::Vector{Any}
        param_depend::Dict{Symbol,Vector{Pair{Int64, Symbol}}}
        obs_depend::Dict{Symbol,Vector{Tuple{Int64,Int64,Int64}}}
        param_depend_rev::Vector{Vector{Tuple{Symbol,Symbol}}}
        obs_depend_rev::Vector{Vector{Vector{Tuple{Symbol,Int64}}}}
    end

A struct gathering multiple observations of diffusion processes. Additionaly,
the interdependence structure between parameters shared between various
diffusions laws used to generate the recorded data is kept.
- `recordings`: collects all recordings
- `param_depend`: is a dictionary with
    - keys: parameter labels
    - values: vectors that collect all indices of recordings whose laws depend
              on a corresponding parameter (in fact collects `Pairs`:
              `idx-of-a-recording => name-of-parameter`).
- `obs_depend`: does the same as `param_depend` but for observations.
                In this case values are vectors that collect `Tuple`s in a
                format:
                `(idx-of-a-recording, idx-of-an-observation,
                idx-of-parameter-in-θ-vector)`.
- `param_depend_rev`: gives for each recording a list of **variable** parameters
                      that its law depends on. These are given in a format
                      `global-param-name => local-param-name`.
!!! note
    We use the term variable to refer to those parameters that are returned
    after a call `var_parameter_names(typeof(P))`.

- `obs_depend_rev`: does the same as `param_depend_rev` but for the
                    observations. These are given in a format
                    `global-param-name => local-param-idx`.

----

    AllObservations(;P=nothing, obs=nothing, t0=nothing, x0_prior=nothing)

Default constructor creating either an empty `AllObservations` object,
or initiating it immediately with a single recording where the target comes
from the law `P`, the observations are stored in `obs` and the observed
process was started at time `t0` from som position which we put a prior
`x0_prior` on.

    AllObservations(recording::NamedTuple)

Constructor creating an `AllObservations` object and initiating it
immediately with a single recording where the target comes
from the law `recording.P`, the observations are stored in `recording.obs`
and the starting point is at time `recording.t0` and has a prior `x0_prior`.
"""
struct AllObservations
    recordings::Vector{Any}
    param_depend::_PARAM_DEPEND_TYPE
    obs_depend::_OBS_DEPEND_TYPE
    param_depend_rev::_PARAM_REV_DEPEND_TYPE
    obs_depend_rev::_OBS_REV_DEPEND_TYPE

    function AllObservations(;
            P=nothing,
            obs=nothing,
            t0=nothing,
            x0_prior=nothing
        )
        nothing_passed = all(v->v===nothing, [P, obs, t0, x0_prior])
        nothing_passed && return new{}(
            [],
            _PARAM_DEPEND_TYPE(),
            _OBS_DEPEND_TYPE(),
            _PARAM_REV_DEPEND_TYPE(undef,0),
            _OBS_REV_DEPEND_TYPE(undef,0)
        )
        @assert all(v->v!=nothing, [P, obs, t0, x0_prior])
        AllObservations(build_recording(P, obs, t0, x0_prior))
    end

    function AllObservations(recording::NamedTuple)
        check_recording_format(recording)
        new{}(
            [recording],
            _PARAM_DEPEND_TYPE(),
            _OBS_DEPEND_TYPE(),
            _PARAM_REV_DEPEND_TYPE(undef,0),
            _OBS_REV_DEPEND_TYPE(undef,0)
        )
    end
end

"""
    check_recording_format(::T) where T<:NamedTuple

Check whether the namedtuple has fields `P`, `obs`, `t0` and `x0_prior` that
each recording must have.
"""
function check_recording_format(::T) where T<:NamedTuple
    @assert hasfield(T, :P)
    @assert hasfield(T, :obs)
    @assert hasfield(T, :t0)
    @assert hasfield(T, :x0_prior)
end

"""
    add_recordings!(
        all_obs::AllObservations,
        recordings::AbstractArray{<:NamedTuple}
    )

Add multiple new recordings `recordings` to an observations container `all_obs`.
"""
function add_recordings!(
        all_obs::AllObservations,
        recordings::AbstractArray{<:NamedTuple}
    )
    for recording in recordings
        add_recording!(all_obs, recording)
    end
end

"""
    add_recording!(all_obs::AllObservations, recording::NamedTuple)

Add a new recording `recording` to an observations container `all_obs`.
"""
function add_recording!(all_obs::AllObservations, recording::NamedTuple)
    check_recording_format(recording)
    push!(all_obs.recordings, recording)
end

"""
    add_dependency!(all_obs::AllObservations, dep::Dict)

Add a dependency structure `dep` between parameters shared across various laws
and observations used to generate various recordings stored in an observations
container `all_obs`.
"""
function add_dependency!(all_obs::AllObservations, dep::Dict)
    existing_keys_param = keys(all_obs.param_depend)
    existing_keys_obs = keys(all_obs.obs_depend)
    for key in keys(dep)
        add_a_single_dependency!(
            all_obs,
            key,
            dep[key],
            existing_keys_param,
            existing_keys_obs
        )
    end
end

function add_a_single_dependency!(
        all_obs::AllObservations,
        key,
        val::Vector{Tuple{Int64, Int64, Int64}},
        ::Any,
        existing_keys
    )
    if key in existing_keys
        println(
            "Warning! depenendency for $key is already defined. ",
            "Appending with new info..."
        )
    else
        all_obs.obs_depend[key] = _OBS_DEPEND_ENTRY_TYPE(undef, 0)
    end
    push!(all_obs.obs_depend[key], val)
end

function add_a_single_dependency!(
        all_obs::AllObservations,
        key,
        val::Vector{<:Union{Pair{Int64, Symbol}, Tuple{Int64, Symbol}}},
        existing_keys,
        ::Any
    )
    if key in existing_keys
        println(
            "Warning! depenendency for $key is already defined. ",
            "Appending with new info..."
        )
    else
        all_obs.param_depend[key] = _PARAM_DEPEND_ENTRY_TYPE(undef, 0)
    end
    foo(x)=Pair(x...)
    append!(all_obs.param_depend[key], foo.(val))
end

@doc raw"""
    initialize(all_obs::AllObservations)

Split the recordings at the times of full observations to make full use of the
Markov property (and make the code readily parallelisable). Introduce all
*variable* parameters that were not mentioned in the current dependency
dictionary. Create internal dictionaries `all_obs.param_depend_rev` and
`all_obs.obs_depend_rev`.
"""
function initialize(all_obs::AllObservations)
    full_p_dep, full_o_dep = fill_dependency_for_unspec_params_and_obs(all_obs)
    out = AllObservations()
    old_to_new_idx = Dict{Int64,Vector{Int64}}()
    old_to_new_obs_idx = Dict{Tuple{Int64,Int64},Tuple{Int64,Int64}}()
    counter = 1

    for (rec_idx, recording) in enumerate(all_obs.recordings)
        counter = split_recording!(
            rec_idx,
            recording,
            counter,
            out,
            old_to_new_idx,
            old_to_new_obs_idx
        )
    end
    new_param_and_obs_dependence!(
        out,
        full_p_dep,
        full_o_dep,
        old_to_new_idx,
        old_to_new_obs_idx
    )
    reverse_param_and_obs_dep!(out)
    out, old_to_new_idx
end

"""
    fill_dependency_for_unspec_params(all_obs::AllObservations)

Fill the `all_obs.depen_param` dictionary with all parameters that are not
shared between recordings.
"""
function fill_dependency_for_unspec_params_and_obs(all_obs::AllObservations)
    new_param_entries = fill_dependency_for_unspec_params(all_obs)
    new_obs_entries = fill_dependency_for_unspec_obs(all_obs)
    (
        merge(all_obs.param_depend, new_param_entries),
        merge(all_obs.obs_depend, new_obs_entries)
    )
end

function fill_dependency_for_unspec_params(all_obs::AllObservations)
    accounted_for_entries = Iterators.flatten(values(all_obs.param_depend))
    new_entries = _PARAM_DEPEND_TYPE()

    for (rec_idx, recording) in enumerate(all_obs.recordings)
        # retreive all of the variable parameter names
        p_names = var_parameter_names(recording.P)
        for p_name in p_names
            entry = (rec_idx => p_name)
            if !(entry in accounted_for_entries)
                new_entries[Symbol("REC$(rec_idx)_", p_name)] = [entry]
            end
        end
    end
    new_entries
end

function fill_dependency_for_unspec_obs(all_obs::AllObservations)
    accounted_for_entries = Iterators.flatten(values(all_obs.obs_depend))
    new_entries = _OBS_DEPEND_TYPE()

    for (rec_idx, recording) in enumerate(all_obs.recordings)
        for (obs_idx, obs) in enumerate(recording.obs)
            obs_positions = var_parameter_pos(obs)
            for obs_pos in obs_positions
                entry = (rec_idx, obs_idx, obs_pos)
                if !(entry in accounted_for_entries)
                    new_entries[Symbol(
                        "REC$(rec_idx)_OBS$(obs_idx)_",
                        obs_pos
                    )] = [entry]
                end
            end
        end
    end
    new_entries
end

"""
    split_recording!(
            recording_idx,
            recording,
            counter,
            out::AllObservations,
            old_to_new_idx,
            old_to_new_obs_idx,
        )

Split a single record `recording` at the times of full observations. Save new,
splitted recordings in the struct `out.` Keep account of the changed indices
of the recordings for the `recording index <---> parameter dependence` pairs by
updating a suitable dictionary `old_to_new_idx`, starting the new recording's
index at an offset `counter`.
"""
function split_recording!(
        recording_idx,
        recording,
        counter,
        out::AllObservations,
        old_to_new_idx,
        old_to_new_obs_idx,
    )
    t0 = recording.t0
    x0_prior = deepcopy(recording.x0_prior)
    N = length(recording.obs)
    start_idx = 1

    for i in 1:N
        obs = recording.obs[i]
        if (obs.full_obs || i == N)
            new_recording = (
                P = deepcopy(recording.P),
                obs = deepcopy(recording.obs[start_idx:i]),
                t0 = t0,
                x0_prior = x0_prior,
            )
            add_recording!(out, new_recording)

            if haskey(old_to_new_idx, recording_idx)
                push!(old_to_new_idx[recording_idx], counter)
            else
                old_to_new_idx[recording_idx] = [counter]
            end

            for j in start_idx:i
                old_to_new_obs_idx[(recording_idx, j)] = (counter, j-start_idx+1)
            end

            counter += 1
            start_idx = i+1
            t0 = obs.t
            x0_prior = KnownStartingPt(obs.obs)
        end
    end
    counter
end

"""
    new_param_and_obs_dependence!(
        out,
        old_p_dep,
        old_o_dep,
        old_to_new_idx,
        old_to_new_obs_idx
    )

TODO refresh Define a new parameter dependence structure by using an old parameter dependence
saved in `old_dep` and deducing the changed indices of affected recording by
following the `old_to_new_idx` dictionary. The new dependency is saved directly
to `out` structure.
"""
function new_param_and_obs_dependence!(
        out,
        old_p_dep,
        old_o_dep,
        old_to_new_idx,
        old_to_new_obs_idx
    )
    new_p_dep = new_param_dependence!(old_p_dep, old_to_new_idx)
    new_o_dep = new_obs_dependence!(old_o_dep, old_to_new_obs_idx)
    add_dependency!(out, new_p_dep)
    add_dependency!(out, new_o_dep)
end

"""
    new_param_dependence!(old_dep, old_to_new_idx)

Create a new interdependency dictionary for the parameters from the old one
`old_dep` and the dictionary `old_to_new_idx` that kept track of the changes.

# Examples
```julia
old_dep = Dict(
    :A => [(1, :a), (2, :a1)],
    :B => [(1, :b), (3, :bbb)],
)
old_to_new_idx = Dict(
    1 => [1, 2], # observation 1 was split into two
    2 => [3, 4, 5], # observation 2 was split into three
    3 => [6],
)

new_dep = new_param_dependence!(old_dep, old_to_new_idx)

new_dep == Dict(
    :A => [1=>:a, 2=>:a, 3=>:a1, 4=>:a1, 5=>:a1],
    :B => [1=>:b, 2=>:b, 6=>:bbb],
)
```
"""
function new_param_dependence!(old_dep, old_to_new_idx)
    new_dep = _PARAM_DEPEND_TYPE()
    for key in keys(old_dep)
        new_entry = _PARAM_DEPEND_ENTRY_TYPE(undef, 0)
        for old_connector in old_dep[key]
            old_rec_idx, p_symbol = old_connector
            new_connectors = [
                (new_rec_idx => p_symbol)
                for new_rec_idx in old_to_new_idx[old_rec_idx]
            ]
            append!(new_entry, collect(new_connectors))
        end
        new_dep[key] = new_entry
    end
    new_dep
end

"""
    new_obs_dependence!(old_dep, old_to_new_idx)

Create a new interdependency dictionary for the observations from the old one
`old_dep` and the dictionary `old_to_new_idx` that kept track of the changes.

# Example
```julia
old_dep = Dict(
    :A => [(1, 2, 1), (1, 3, 2), (2, 1, 1)],
    :B => [(2, 2, 2), (3, 2, 1)],
)
old_to_new_idx = Dict(
    (1,1) => (1, 1), # obs (1,1) becomes (1,1)
    (1,2) => (1, 2),
    (1,3) => (2, 1), # obs (1,3) becomes (2,1)
    (2,1) => (3, 1),
    (2,2) => (4, 1),
    (2,3) => (5, 1),
    (3,1) => (6, 1),
    (3,2) => (6, 2),
)

new_dep = new_obs_dependence!(old_dep, old_to_new_idx)

new_dep == Dict(
    :A => [(1, 2, 1), (2, 1, 2), (3, 1, 1)],
    :B => [(4, 1, 2), (6, 2, 1)]
)
```
"""
function new_obs_dependence!(old_dep, old_to_new_idx)
    new_dep = _OBS_DEPEND_TYPE()
    for key in keys(old_dep)
        new_entry = _OBS_DEPEND_ENTRY_TYPE(undef, 0)
        for old_connector in old_dep[key]
            old_rec_idx, old_obs_idx, obs_idx = old_connector
            new_rec_idx, new_obs_idx = old_to_new_idx[(old_rec_idx, old_obs_idx)]
            append!(new_entry, [(new_rec_idx, new_obs_idx, obs_idx)])
        end
        new_dep[key] = new_entry
    end
    new_dep
end

function reverse_param_and_obs_dep!(out)
    reverse_param_dep!(out)
    reverse_obs_dep!(out)
end

function reverse_param_dep!(out)
    recs = out.recordings
    resize!(out.param_depend_rev, length(recs))
    for (i, rec) in enumerate(recs)
        out.param_depend_rev[i] = Tuple{Symbol,Symbol}[]
    end
    for key in keys(out.param_depend)
        vals = out.param_depend[key]
        for val in vals
            push!(out.param_depend_rev[val[1]], (key, val[2]))
        end
    end
end

function reverse_obs_dep!(out)
    recs = out.recordings
    resize!(out.obs_depend_rev, length(recs))
    for (i, rec) in enumerate(recs)
        N = length(rec.obs)
        out.obs_depend_rev[i] = Vector{Vector{Tuple{Symbol,Int64}}}(undef, N)
        for j in 1:N
            out.obs_depend_rev[i][j] = Tuple{Symbol,Int64}[]
        end
    end
    for key in keys(out.obs_depend)
        vals = out.obs_depend[key]
        for val in vals
            push!(out.obs_depend_rev[(val[1], val[2])], (key, val[3]))
        end
    end
end


text:
# Automatically generated using Clang.jl

const NK_UNDEFINED = -(Float32(1.0))
const NK_UTF_INVALID = 0xfffd
const NK_UTF_SIZE = 4
const NK_INPUT_MAX = 16
const NK_MAX_NUMBER_BUFFER = 64
const NK_SCROLLBAR_HIDING_TIMEOUT = Float32(4.0)

# Skipping MacroDefinition: NK_FLAG ( x ) ( 1 << ( x ) )
# Skipping MacroDefinition: NK_STRINGIFY ( x ) # x
# Skipping MacroDefinition: NK_MACRO_STRINGIFY ( x ) NK_STRINGIFY ( x )
# Skipping MacroDefinition: NK_STRING_JOIN_IMMEDIATE ( arg1 , arg2 ) arg1 ## arg2
# Skipping MacroDefinition: NK_STRING_JOIN_DELAY ( arg1 , arg2 ) NK_STRING_JOIN_IMMEDIATE ( arg1 , arg2 )
# Skipping MacroDefinition: NK_STRING_JOIN ( arg1 , arg2 ) NK_STRING_JOIN_DELAY ( arg1 , arg2 )
# Skipping MacroDefinition: NK_UNIQUE_NAME ( name ) NK_STRING_JOIN ( name , __LINE__ )
# Skipping MacroDefinition: NK_STATIC_ASSERT ( exp ) typedef char NK_UNIQUE_NAME ( _dummy_array ) [ ( exp ) ? 1 : - 1 ]
# Skipping MacroDefinition: NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY ( __LINE__ )
# Skipping MacroDefinition: NK_MIN ( a , b ) ( ( a ) < ( b ) ? ( a ) : ( b ) )
# Skipping MacroDefinition: NK_MAX ( a , b ) ( ( a ) < ( b ) ? ( b ) : ( a ) )
# Skipping MacroDefinition: NK_CLAMP ( i , v , x ) ( NK_MAX ( NK_MIN ( v , x ) , i ) )

# const NK_INT8 = int8_t
# const NK_UINT8 = uint8_t
# const NK_INT16 = int16_t
# const NK_UINT16 = uint16_t
# const NK_INT32 = int32_t
# const NK_UINT32 = uint32_t
# const NK_SIZE_TYPE = uintptr_t
# const NK_POINTER_TYPE = uintptr_t

# Skipping MacroDefinition: nk_foreach ( c , ctx ) for ( ( c ) = nk__begin ( ctx ) ; ( c ) != 0 ; ( c ) = nk__next ( ctx , c ) )
# Skipping MacroDefinition: nk_draw_foreach ( cmd , ctx , b ) for ( ( cmd ) = nk__draw_begin ( ctx , b ) ; ( cmd ) != 0 ; ( cmd ) = nk__draw_next ( cmd , b , ctx ) )
nk_tree_push(ctx, type, title, state) = nk_tree_push_hashed(ctx, type, title, state, string(@__LINE__), length(string(@__LINE__)), @__LINE__)
# Skipping MacroDefinition: nk_tree_push_id ( ctx , type , title , state , id ) nk_tree_push_hashed ( ctx , type , title , state , NK_FILE_LINE , nk_strlen ( NK_FILE_LINE ) , id )
# Skipping MacroDefinition: nk_tree_image_push ( ctx , type , img , title , state ) nk_tree_image_push_hashed ( ctx , type , img , title , state , NK_FILE_LINE , nk_strlen ( NK_FILE_LINE ) , __LINE__ )
# Skipping MacroDefinition: nk_tree_image_push_id ( ctx , type , img , title , state , id ) nk_tree_image_push_hashed ( ctx , type , img , title , state , NK_FILE_LINE , nk_strlen ( NK_FILE_LINE ) , id )
# Skipping MacroDefinition: nk_tree_element_push ( ctx , type , title , state , sel ) nk_tree_element_push_hashed ( ctx , type , title , state , sel , NK_FILE_LINE , nk_strlen ( NK_FILE_LINE ) , __LINE__ )
# Skipping MacroDefinition: nk_tree_element_push_id ( ctx , type , title , state , sel , id ) nk_tree_element_push_hashed ( ctx , type , title , state , sel , NK_FILE_LINE , nk_strlen ( NK_FILE_LINE ) , id )

const NK_TEXTEDIT_UNDOSTATECOUNT = 99
const NK_TEXTEDIT_UNDOCHARCOUNT = 999

# Skipping MacroDefinition: NK_VERTEX_LAYOUT_END NK_VERTEX_ATTRIBUTE_COUNT , NK_FORMAT_COUNT , 0
# Skipping MacroDefinition: nk_draw_list_foreach ( cmd , can , b ) for ( ( cmd ) = nk__draw_list_begin ( can , b ) ; ( cmd ) != 0 ; ( cmd ) = nk__draw_list_next ( cmd , b , can ) )

const NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS = 16
const NK_CHART_MAX_SLOT = 4
const NK_WINDOW_MAX_NAME = 64
const NK_BUTTON_BEHAVIOR_STACK_SIZE = 8
const NK_FONT_STACK_SIZE = 8
const NK_STYLE_ITEM_STACK_SIZE = 16
const NK_FLOAT_STACK_SIZE = 32
const NK_VECTOR_STACK_SIZE = 16
const NK_FLAGS_STACK_SIZE = 32
const NK_COLOR_STACK_SIZE = 32

# Skipping MacroDefinition: NK_CONFIGURATION_STACK_TYPE ( prefix , name , type ) struct nk_config_stack_ ## name ## _element { prefix ## _ ## type * address ; prefix ## _ ## type old_value ; }
# Skipping MacroDefinition: NK_CONFIG_STACK ( type , size ) struct nk_config_stack_ ## type { int head ; struct nk_config_stack_ ## type ## _element elements [ size ] ; }
# Skipping MacroDefinition: NK_VALUE_PAGE_CAPACITY ( ( ( NK_MAX ( sizeof ( struct nk_window ) , sizeof ( struct nk_panel ) ) / sizeof ( nk_uint ) ) ) / 2 )

const NK_PI = Float32(3.141592654)
const NK_MAX_FLOAT_PRECISION = 2

# Skipping MacroDefinition: NK_UNUSED ( x ) ( ( void ) ( x ) )
# Skipping MacroDefinition: NK_SATURATE ( x ) ( NK_MAX ( 0 , NK_MIN ( 1.0f , x ) ) )
# Skipping MacroDefinition: NK_LEN ( a ) ( sizeof ( a ) / sizeof ( a ) [ 0 ] )
# Skipping MacroDefinition: NK_ABS ( a ) ( ( ( a ) < 0 ) ? - ( a ) : ( a ) )
# Skipping MacroDefinition: NK_BETWEEN ( x , a , b ) ( ( a ) <= ( x ) && ( x ) < ( b ) )
# Skipping MacroDefinition: NK_INBOX ( px , py , x , y , w , h ) ( NK_BETWEEN ( px , x , x + w ) && NK_BETWEEN ( py , y , y + h ) )
# Skipping MacroDefinition: NK_INTERSECT ( x0 , y0 , w0 , h0 , x1 , y1 , w1 , h1 ) ( ! ( ( ( x1 > ( x0 + w0 ) ) || ( ( x1 + w1 ) < x0 ) || ( y1 > ( y0 + h0 ) ) || ( y1 + h1 ) < y0 ) ) )
# Skipping MacroDefinition: NK_CONTAINS ( x , y , w , h , bx , by , bw , bh ) ( NK_INBOX ( x , y , bx , by , bw , bh ) && NK_INBOX ( x + w , y + h , bx , by , bw , bh ) )
# Skipping MacroDefinition: nk_vec2_sub ( a , b ) nk_vec2 ( ( a ) . x - ( b ) . x , ( a ) . y - ( b ) . y )
# Skipping MacroDefinition: nk_vec2_add ( a , b ) nk_vec2 ( ( a ) . x + ( b ) . x , ( a ) . y + ( b ) . y )
# Skipping MacroDefinition: nk_vec2_len_sqr ( a ) ( ( a ) . x * ( a ) . x + ( a ) . y * ( a ) . y )
# Skipping MacroDefinition: nk_vec2_muls ( a , t ) nk_vec2 ( ( a ) . x * ( t ) , ( a ) . y * ( t ) )
# Skipping MacroDefinition: nk_ptr_add ( t , p , i ) ( ( t * ) ( ( void * ) ( ( nk_byte * ) ( p ) + ( i ) ) ) )
# Skipping MacroDefinition: nk_ptr_add_const ( t , p , i ) ( ( const t * ) ( ( const void * ) ( ( const nk_byte * ) ( p ) + ( i ) ) ) )
# Skipping MacroDefinition: nk_zero_struct ( s ) nk_zero ( & s , sizeof ( s ) )
# Skipping MacroDefinition: NK_UINT_TO_PTR ( x ) ( ( void * ) ( __PTRDIFF_TYPE__ ) ( x ) )
# Skipping MacroDefinition: NK_PTR_TO_UINT ( x ) ( ( nk_size ) ( __PTRDIFF_TYPE__ ) ( x ) )
# Skipping MacroDefinition: NK_ALIGN_PTR ( x , mask ) ( NK_UINT_TO_PTR ( ( NK_PTR_TO_UINT ( ( nk_byte * ) ( x ) + ( mask - 1 ) ) & ~ ( mask - 1 ) ) ) )
# Skipping MacroDefinition: NK_ALIGN_PTR_BACK ( x , mask ) ( NK_UINT_TO_PTR ( ( NK_PTR_TO_UINT ( ( nk_byte * ) ( x ) ) & ~ ( mask - 1 ) ) ) )
# Skipping MacroDefinition: NK_OFFSETOF ( st , m ) ( ( nk_ptr ) & ( ( ( st * ) 0 ) -> m ) )
# Skipping MacroDefinition: NK_CONTAINER_OF ( ptr , type , member ) ( type * ) ( ( void * ) ( ( char * ) ( 1 ? ( ptr ) : & ( ( type * ) 0 ) -> member ) - NK_OFFSETOF ( type , member ) ) )
# Skipping MacroDefinition: NK_ALIGNOF ( t ) ( ( char * ) ( & ( ( struct { char c ; t _h ; } * ) 0 ) -> _h ) - ( char * ) 0 )

const nk_char = Int8
const nk_uchar = UInt8
const nk_byte = UInt8
const nk_short = Int16
const nk_ushort = UInt16
const nk_int = Int32
const nk_uint = UInt32
const nk_size = Csize_t
const nk_ptr = Csize_t
const nk_hash = nk_uint
const nk_flags = nk_uint
const nk_rune = nk_uint
const _dummy_array422 = NTuple{1, UInt8}
const _dummy_array423 = NTuple{1, UInt8}
const _dummy_array424 = NTuple{1, UInt8}
const _dummy_array425 = NTuple{1, UInt8}
const _dummy_array426 = NTuple{1, UInt8}
const _dummy_array427 = NTuple{1, UInt8}
const _dummy_array428 = NTuple{1, UInt8}
const _dummy_array429 = NTuple{1, UInt8}
const _dummy_array430 = NTuple{1, UInt8}

struct nk_buffer_marker
    active::Cint
    offset::nk_size
end

struct nk_handle
    id::Cint
end

const nk_plugin_alloc = Ptr{Cvoid}
const nk_plugin_free = Ptr{Cvoid}

struct nk_allocator
    userdata::nk_handle
    alloc::nk_plugin_alloc
    free::nk_plugin_free
end

@cenum(nk_allocation_type,
    NK_BUFFER_FIXED = 0,
    NK_BUFFER_DYNAMIC = 1,
)

struct nk_memory
    ptr::Ptr{Cvoid}
    size::nk_size
end

struct nk_buffer
    marker::NTuple{2, nk_buffer_marker}
    pool::nk_allocator
    type::nk_allocation_type
    memory::nk_memory
    grow_factor::Cfloat
    allocated::nk_size
    needed::nk_size
    calls::nk_size
    size::nk_size
end

struct nk_rect
    x::Cfloat
    y::Cfloat
    w::Cfloat
    h::Cfloat
end

struct nk_command_buffer
    base::Ptr{nk_buffer}
    clip::nk_rect
    use_clipping::Cint
    userdata::nk_handle
    _begin::nk_size
    _end::nk_size
    last::nk_size
end

struct nk_draw_command
    elem_count::UInt32
    clip_rect::nk_rect
    texture::nk_handle
end

@cenum(nk_anti_aliasing,
    NK_ANTI_ALIASING_OFF = 0,
    NK_ANTI_ALIASING_ON = 1,
)

struct nk_vec2
    x::Cfloat
    y::Cfloat
end

struct nk_draw_null_texture
    texture::nk_handle
    uv::nk_vec2
end

@cenum(nk_draw_vertex_layout_attribute,
    NK_VERTEX_POSITION = 0,
    NK_VERTEX_COLOR = 1,
    NK_VERTEX_TEXCOORD = 2,
    NK_VERTEX_ATTRIBUTE_COUNT = 3,
)
@cenum(nk_draw_vertex_layout_format,
    NK_FORMAT_SCHAR = 0,
    NK_FORMAT_SSHORT = 1,
    NK_FORMAT_SINT = 2,
    NK_FORMAT_UCHAR = 3,
    NK_FORMAT_USHORT = 4,
    NK_FORMAT_UINT = 5,
    NK_FORMAT_FLOAT = 6,
    NK_FORMAT_DOUBLE = 7,
    NK_FORMAT_COLOR_BEGIN = 8,
    NK_FORMAT_R8G8B8 = 8,
    NK_FORMAT_R16G15B16 = 9,
    NK_FORMAT_R32G32B32 = 10,
    NK_FORMAT_R8G8B8A8 = 11,
    NK_FORMAT_B8G8R8A8 = 12,
    NK_FORMAT_R16G15B16A16 = 13,
    NK_FORMAT_R32G32B32A32 = 14,
    NK_FORMAT_R32G32B32A32_FLOAT = 15,
    NK_FORMAT_R32G32B32A32_DOUBLE = 16,
    NK_FORMAT_RGB32 = 17,
    NK_FORMAT_RGBA32 = 18,
    NK_FORMAT_COLOR_END = 18,
    NK_FORMAT_COUNT = 19,
)

struct nk_draw_vertex_layout_element
    attribute::nk_draw_vertex_layout_attribute
    format::nk_draw_vertex_layout_format
    offset::nk_size
end

struct nk_convert_config
    global_alpha::Cfloat
    line_AA::nk_anti_aliasing
    shape_AA::nk_anti_aliasing
    circle_segment_count::UInt32
    arc_segment_count::UInt32
    curve_segment_count::UInt32
    null::nk_draw_null_texture
    vertex_layout::Ptr{nk_draw_vertex_layout_element}
    vertex_size::nk_size
    vertex_alignment::nk_size
end

@cenum(nk_style_item_type,
    NK_STYLE_ITEM_COLOR = 0,
    NK_STYLE_ITEM_IMAGE = 1,
)

struct nk_image
    handle::nk_handle
    w::UInt16
    h::UInt16
    region::NTuple{4, UInt16}
end

struct nk_style_item_data
    image::nk_image
end

struct nk_style_item
    type::nk_style_item_type
    data::nk_style_item_data
end

const nk_plugin_paste = Ptr{Cvoid}
const nk_plugin_copy = Ptr{Cvoid}

struct nk_clipboard
    userdata::nk_handle
    paste::nk_plugin_paste
    copy::nk_plugin_copy
end

struct nk_str
    buffer::nk_buffer
    len::Cint
end

const nk_plugin_filter = Ptr{Cvoid}

struct nk_text_undo_record
    where::Cint
    insert_length::Int16
    delete_length::Int16
    char_storage::Int16
end

struct nk_text_undo_state
    undo_rec::NTuple{99, nk_text_undo_record}
    undo_char::NTuple{999, nk_rune}
    undo_point::Int16
    redo_point::Int16
    undo_char_point::Int16
    redo_char_point::Int16
end

struct nk_text_edit
    clip::nk_clipboard
    string::nk_str
    filter::nk_plugin_filter
    scrollbar::nk_vec2
    cursor::Cint
    select_start::Cint
    select_end::Cint
    mode::Cuchar
    cursor_at_end_of_line::Cuchar
    initialized::Cuchar
    has_preferred_x::Cuchar
    single_line::Cuchar
    active::Cuchar
    padding1::Cuchar
    preferred_x::Cfloat
    undo::nk_text_undo_state
end

struct nk_draw_list
    clip_rect::nk_rect
    circle_vtx::NTuple{12, nk_vec2}
    config::nk_convert_config
    buffer::Ptr{nk_buffer}
    vertices::Ptr{nk_buffer}
    elements::Ptr{nk_buffer}
    element_count::UInt32
    vertex_count::UInt32
    cmd_count::UInt32
    cmd_offset::nk_size
    path_count::UInt32
    path_offset::UInt32
    line_AA::nk_anti_aliasing
    shape_AA::nk_anti_aliasing
end

const nk_text_width_f = Ptr{Cvoid}
const nk_query_font_glyph_f = Ptr{Cvoid}

struct nk_user_font
    userdata::nk_handle
    height::Cfloat
    width::nk_text_width_f
    query::nk_query_font_glyph_f
    texture::nk_handle
end

@cenum(nk_panel_type,
    NK_PANEL_NONE = 0,
    NK_PANEL_WINDOW = 1,
    NK_PANEL_GROUP = 2,
    NK_PANEL_POPUP = 4,
    NK_PANEL_CONTEXTUAL = 16,
    NK_PANEL_COMBO = 32,
    NK_PANEL_MENU = 64,
    NK_PANEL_TOOLTIP = 128,
)

struct nk_scroll
    x::nk_uint
    y::nk_uint
end

struct nk_menu_state
    x::Cfloat
    y::Cfloat
    w::Cfloat
    h::Cfloat
    offset::nk_scroll
end

@cenum(nk_panel_row_layout_type,
    NK_LAYOUT_DYNAMIC_FIXED = 0,
    NK_LAYOUT_DYNAMIC_ROW = 1,
    NK_LAYOUT_DYNAMIC_FREE = 2,
    NK_LAYOUT_DYNAMIC = 3,
    NK_LAYOUT_STATIC_FIXED = 4,
    NK_LAYOUT_STATIC_ROW = 5,
    NK_LAYOUT_STATIC_FREE = 6,
    NK_LAYOUT_STATIC = 7,
    NK_LAYOUT_TEMPLATE = 8,
    NK_LAYOUT_COUNT = 9,
)

struct nk_row_layout
    type::nk_panel_row_layout_type
    index::Cint
    height::Cfloat
    min_height::Cfloat
    columns::Cint
    ratio::Ptr{Cfloat}
    item_width::Cfloat
    item_height::Cfloat
    item_offset::Cfloat
    filled::Cfloat
    item::nk_rect
    tree_depth::Cint
    templates::NTuple{16, Cfloat}
end

@cenum(nk_chart_type,
    NK_CHART_LINES = 0,
    NK_CHART_COLUMN = 1,
    NK_CHART_MAX = 2,
)

struct nk_color
    r::nk_byte
    g::nk_byte
    b::nk_byte
    a::nk_byte
end

struct nk_chart_slot
    type::nk_chart_type
    color::nk_color
    highlight::nk_color
    min::Cfloat
    max::Cfloat
    range::Cfloat
    count::Cint
    last::nk_vec2
    index::Cint
end

struct nk_chart
    slot::Cint
    x::Cfloat
    y::Cfloat
    w::Cfloat
    h::Cfloat
    slots::NTuple{4, nk_chart_slot}
end

struct nk_panel
    type::nk_panel_type
    flags::nk_flags
    bounds::nk_rect
    offset_x::Ptr{nk_uint}
    offset_y::Ptr{nk_uint}
    at_x::Cfloat
    at_y::Cfloat
    max_x::Cfloat
    footer_height::Cfloat
    header_height::Cfloat
    border::Cfloat
    has_scrolling::UInt32
    clip::nk_rect
    menu::nk_menu_state
    row::nk_row_layout
    chart::nk_chart
    buffer::Ptr{nk_command_buffer}
    parent::Ptr{nk_panel}
end

struct nk_key
    down::Cint
    clicked::UInt32
end

struct nk_keyboard
    keys::NTuple{30, nk_key}
    text::NTuple{16, UInt8}
    text_len::Cint
end

struct nk_mouse_button
    down::Cint
    clicked::UInt32
    clicked_pos::nk_vec2
end

struct nk_mouse
    buttons::NTuple{4, nk_mouse_button}
    pos::nk_vec2
    prev::nk_vec2
    delta::nk_vec2
    scroll_delta::nk_vec2
    grab::Cuchar
    grabbed::Cuchar
    ungrab::Cuchar
end

struct nk_input
    keyboard::nk_keyboard
    mouse::nk_mouse
end

struct nk_cursor
    img::nk_image
    size::nk_vec2
    offset::nk_vec2
end

struct nk_style_text
    color::nk_color
    padding::nk_vec2
end

struct nk_style_button
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    text_background::nk_color
    text_normal::nk_color
    text_hover::nk_color
    text_active::nk_color
    text_alignment::nk_flags
    border::Cfloat
    rounding::Cfloat
    padding::nk_vec2
    image_padding::nk_vec2
    touch_padding::nk_vec2
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

struct nk_style_toggle
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    cursor_normal::nk_style_item
    cursor_hover::nk_style_item
    text_normal::nk_color
    text_hover::nk_color
    text_active::nk_color
    text_background::nk_color
    text_alignment::nk_flags
    padding::nk_vec2
    touch_padding::nk_vec2
    spacing::Cfloat
    border::Cfloat
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

struct nk_style_selectable
    normal::nk_style_item
    hover::nk_style_item
    pressed::nk_style_item
    normal_active::nk_style_item
    hover_active::nk_style_item
    pressed_active::nk_style_item
    text_normal::nk_color
    text_hover::nk_color
    text_pressed::nk_color
    text_normal_active::nk_color
    text_hover_active::nk_color
    text_pressed_active::nk_color
    text_background::nk_color
    text_alignment::nk_flags
    rounding::Cfloat
    padding::nk_vec2
    touch_padding::nk_vec2
    image_padding::nk_vec2
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

@cenum(nk_symbol_type,
    NK_SYMBOL_NONE = 0,
    NK_SYMBOL_X = 1,
    NK_SYMBOL_UNDERSCORE = 2,
    NK_SYMBOL_CIRCLE_SOLID = 3,
    NK_SYMBOL_CIRCLE_OUTLINE = 4,
    NK_SYMBOL_RECT_SOLID = 5,
    NK_SYMBOL_RECT_OUTLINE = 6,
    NK_SYMBOL_TRIANGLE_UP = 7,
    NK_SYMBOL_TRIANGLE_DOWN = 8,
    NK_SYMBOL_TRIANGLE_LEFT = 9,
    NK_SYMBOL_TRIANGLE_RIGHT = 10,
    NK_SYMBOL_PLUS = 11,
    NK_SYMBOL_MINUS = 12,
    NK_SYMBOL_MAX = 13,
)

struct nk_style_slider
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    bar_normal::nk_color
    bar_hover::nk_color
    bar_active::nk_color
    bar_filled::nk_color
    cursor_normal::nk_style_item
    cursor_hover::nk_style_item
    cursor_active::nk_style_item
    border::Cfloat
    rounding::Cfloat
    bar_height::Cfloat
    padding::nk_vec2
    spacing::nk_vec2
    cursor_size::nk_vec2
    show_buttons::Cint
    inc_button::nk_style_button
    dec_button::nk_style_button
    inc_symbol::nk_symbol_type
    dec_symbol::nk_symbol_type
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

struct nk_style_progress
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    cursor_normal::nk_style_item
    cursor_hover::nk_style_item
    cursor_active::nk_style_item
    cursor_border_color::nk_color
    rounding::Cfloat
    border::Cfloat
    cursor_border::Cfloat
    cursor_rounding::Cfloat
    padding::nk_vec2
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

struct nk_style_scrollbar
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    cursor_normal::nk_style_item
    cursor_hover::nk_style_item
    cursor_active::nk_style_item
    cursor_border_color::nk_color
    border::Cfloat
    rounding::Cfloat
    border_cursor::Cfloat
    rounding_cursor::Cfloat
    padding::nk_vec2
    show_buttons::Cint
    inc_button::nk_style_button
    dec_button::nk_style_button
    inc_symbol::nk_symbol_type
    dec_symbol::nk_symbol_type
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

struct nk_style_edit
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    scrollbar::nk_style_scrollbar
    cursor_normal::nk_color
    cursor_hover::nk_color
    cursor_text_normal::nk_color
    cursor_text_hover::nk_color
    text_normal::nk_color
    text_hover::nk_color
    text_active::nk_color
    selected_normal::nk_color
    selected_hover::nk_color
    selected_text_normal::nk_color
    selected_text_hover::nk_color
    border::Cfloat
    rounding::Cfloat
    cursor_size::Cfloat
    scrollbar_size::nk_vec2
    padding::nk_vec2
    row_padding::Cfloat
end

struct nk_style_property
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    label_normal::nk_color
    label_hover::nk_color
    label_active::nk_color
    sym_left::nk_symbol_type
    sym_right::nk_symbol_type
    border::Cfloat
    rounding::Cfloat
    padding::nk_vec2
    edit::nk_style_edit
    inc_button::nk_style_button
    dec_button::nk_style_button
    userdata::nk_handle
    draw_begin::Ptr{Cvoid}
    draw_end::Ptr{Cvoid}
end

struct nk_style_chart
    background::nk_style_item
    border_color::nk_color
    selected_color::nk_color
    color::nk_color
    border::Cfloat
    rounding::Cfloat
    padding::nk_vec2
end

struct nk_style_tab
    background::nk_style_item
    border_color::nk_color
    text::nk_color
    tab_maximize_button::nk_style_button
    tab_minimize_button::nk_style_button
    node_maximize_button::nk_style_button
    node_minimize_button::nk_style_button
    sym_minimize::nk_symbol_type
    sym_maximize::nk_symbol_type
    border::Cfloat
    rounding::Cfloat
    indent::Cfloat
    padding::nk_vec2
    spacing::nk_vec2
end

struct nk_style_combo
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    border_color::nk_color
    label_normal::nk_color
    label_hover::nk_color
    label_active::nk_color
    symbol_normal::nk_color
    symbol_hover::nk_color
    symbol_active::nk_color
    button::nk_style_button
    sym_normal::nk_symbol_type
    sym_hover::nk_symbol_type
    sym_active::nk_symbol_type
    border::Cfloat
    rounding::Cfloat
    content_padding::nk_vec2
    button_padding::nk_vec2
    spacing::nk_vec2
end

@cenum(nk_style_header_align,
    NK_HEADER_LEFT = 0,
    NK_HEADER_RIGHT = 1,
)

struct nk_style_window_header
    normal::nk_style_item
    hover::nk_style_item
    active::nk_style_item
    close_button::nk_style_button
    minimize_button::nk_style_button
    close_symbol::nk_symbol_type
    minimize_symbol::nk_symbol_type
    maximize_symbol::nk_symbol_type
    label_normal::nk_color
    label_hover::nk_color
    label_active::nk_color
    align::nk_style_header_align
    padding::nk_vec2
    label_padding::nk_vec2
    spacing::nk_vec2
end

struct nk_style_window
    header::nk_style_window_header
    fixed_background::nk_style_item
    background::nk_color
    border_color::nk_color
    popup_border_color::nk_color
    combo_border_color::nk_color
    contextual_border_color::nk_color
    menu_border_color::nk_color
    group_border_color::nk_color
    tooltip_border_color::nk_color
    scaler::nk_style_item
    border::Cfloat
    combo_border::Cfloat
    contextual_border::Cfloat
    menu_border::Cfloat
    group_border::Cfloat
    tooltip_border::Cfloat
    popup_border::Cfloat
    min_row_height_padding::Cfloat
    rounding::Cfloat
    spacing::nk_vec2
    scrollbar_size::nk_vec2
    min_size::nk_vec2
    padding::nk_vec2
    group_padding::nk_vec2
    popup_padding::nk_vec2
    combo_padding::nk_vec2
    contextual_padding::nk_vec2
    menu_padding::nk_vec2
    tooltip_padding::nk_vec2
end

struct nk_style
    font::Ptr{nk_user_font}
    cursors::NTuple{7, Ptr{nk_cursor}}
    cursor_active::Ptr{nk_cursor}
    cursor_last::Ptr{nk_cursor}
    cursor_visible::Cint
    text::nk_style_text
    button::nk_style_button
    contextual_button::nk_style_button
    menu_button::nk_style_button
    option::nk_style_toggle
    checkbox::nk_style_toggle
    selectable::nk_style_selectable
    slider::nk_style_slider
    progress::nk_style_progress
    property::nk_style_property
    edit::nk_style_edit
    chart::nk_style_chart
    scrollh::nk_style_scrollbar
    scrollv::nk_style_scrollbar
    tab::nk_style_tab
    combo::nk_style_combo
    window::nk_style_window
end

@cenum(nk_button_behavior,
    NK_BUTTON_DEFAULT = 0,
    NK_BUTTON_REPEATER = 1,
)

struct nk_config_stack_style_item_element
    address::Ptr{nk_style_item}
    old_value::nk_style_item
end

struct nk_config_stack_style_item
    head::Cint
    elements::NTuple{16, nk_config_stack_style_item_element}
end

struct nk_config_stack_float_element
    address::Ptr{Cfloat}
    old_value::Cfloat
end

struct nk_config_stack_float
    head::Cint
    elements::NTuple{32, nk_config_stack_float_element}
end

struct nk_config_stack_vec2_element
    address::Ptr{nk_vec2}
    old_value::nk_vec2
end

struct nk_config_stack_vec2
    head::Cint
    elements::NTuple{16, nk_config_stack_vec2_element}
end

struct nk_config_stack_flags_element
    address::Ptr{nk_flags}
    old_value::nk_flags
end

struct nk_config_stack_flags
    head::Cint
    elements::NTuple{32, nk_config_stack_flags_element}
end

struct nk_config_stack_color_element
    address::Ptr{nk_color}
    old_value::nk_color
end

struct nk_config_stack_color
    head::Cint
    elements::NTuple{32, nk_config_stack_color_element}
end

struct nk_config_stack_user_font_element
    address::Ptr{Ptr{nk_user_font}}
    old_value::Ptr{nk_user_font}
end

struct nk_config_stack_user_font
    head::Cint
    elements::NTuple{8, nk_config_stack_user_font_element}
end

struct nk_config_stack_button_behavior_element
    address::Ptr{nk_button_behavior}
    old_value::nk_button_behavior
end

struct nk_config_stack_button_behavior
    head::Cint
    elements::NTuple{8, nk_config_stack_button_behavior_element}
end

struct nk_configuration_stacks
    style_items::nk_config_stack_style_item
    floats::nk_config_stack_float
    vectors::nk_config_stack_vec2
    flags::nk_config_stack_flags
    colors::nk_config_stack_color
    fonts::nk_config_stack_user_font
    button_behaviors::nk_config_stack_button_behavior
end

struct nk_table
    seq::UInt32
    size::UInt32
    keys::NTuple{51, nk_hash}
    values::NTuple{51, nk_uint}
    next::Ptr{nk_table}
    prev::Ptr{nk_table}
end

struct nk_page_data
    tbl::nk_table
end

struct nk_page_element
    data::nk_page_data
    next::Ptr{nk_page_element}
    prev::Ptr{nk_page_element}
end

struct nk_page
    size::UInt32
    next::Ptr{nk_page}
    win::NTuple{1, nk_page_element}
end

struct nk_pool
    alloc::nk_allocator
    type::nk_allocation_type
    page_count::UInt32
    pages::Ptr{nk_page}
    freelist::Ptr{nk_page_element}
    capacity::UInt32
    size::nk_size
    cap::nk_size
end

struct nk_property_state
    active::Cint
    prev::Cint
    buffer::NTuple{64, UInt8}
    length::Cint
    cursor::Cint
    select_start::Cint
    select_end::Cint
    name::nk_hash
    seq::UInt32
    old::UInt32
    state::Cint
end

struct nk_popup_buffer
    _begin::nk_size
    parent::nk_size
    last::nk_size
    _end::nk_size
    active::Cint
end

struct nk_popup_state{nk_window}
    win::Ptr{nk_window}
    type::nk_panel_type
    buf::nk_popup_buffer
    name::nk_hash
    active::Cint
    combo_count::UInt32
    con_count::UInt32
    con_old::UInt32
    active_con::UInt32
    header::nk_rect
end

struct nk_edit_state
    name::nk_hash
    seq::UInt32
    old::UInt32
    active::Cint
    prev::Cint
    cursor::Cint
    sel_start::Cint
    sel_end::Cint
    scrollbar::nk_scroll
    mode::Cuchar
    single_line::Cuchar
end

struct nk_window
    seq::UInt32
    name::nk_hash
    name_string::NTuple{64, UInt8}
    flags::nk_flags
    bounds::nk_rect
    scrollbar::nk_scroll
    buffer::nk_command_buffer
    layout::Ptr{nk_panel}
    scrollbar_hiding_timer::Cfloat
    property::nk_property_state
    popup::nk_popup_state
    edit::nk_edit_state
    scrolled::UInt32
    tables::Ptr{nk_table}
    table_count::UInt32
    next::Ptr{nk_window}
    prev::Ptr{nk_window}
    parent::Ptr{nk_window}
end

struct nk_context
    input::nk_input
    style::nk_style
    memory::nk_buffer
    clip::nk_clipboard
    last_widget_state::nk_flags
    button_behavior::nk_button_behavior
    stacks::nk_configuration_stacks
    delta_time_seconds::Cfloat
    draw_list::nk_draw_list
    text_edit::nk_text_edit
    overlay::nk_command_buffer
    build::Cint
    use_pool::Cint
    pool::nk_pool
    _begin::Ptr{nk_window}
    _end::Ptr{nk_window}
    active::Ptr{nk_window}
    current::Ptr{nk_window}
    freelist::Ptr{nk_page_element}
    count::UInt32
    seq::UInt32
end

const nk_style_slide = Cvoid

struct nk_colorf
    r::Cfloat
    g::Cfloat
    b::Cfloat
    a::Cfloat
end

struct nk_vec2i
    x::Int16
    y::Int16
end

struct nk_recti
    x::Int16
    y::Int16
    w::Int16
    h::Int16
end

const nk_glyph = NTuple{4, UInt8}

@cenum(nk_heading,
    NK_UP = 0,
    NK_RIGHT = 1,
    NK_DOWN = 2,
    NK_LEFT = 3,
)
@cenum(nk_modify,
    NK_FIXED = 0,
    NK_MODIFIABLE = 1,
)
@cenum(nk_orientation,
    NK_VERTICAL = 0,
    NK_HORIZONTAL = 1,
)
@cenum(nk_collapse_states,
    NK_MINIMIZED = 0,
    NK_MAXIMIZED = 1,
)
@cenum(nk_show_states,
    NK_HIDDEN = 0,
    NK_SHOWN = 1,
)
@cenum(nk_chart_event,
    NK_CHART_HOVERING = 1,
    NK_CHART_CLICKED = 2,
)
@cenum(nk_color_format,
    NK_RGB = 0,
    NK_RGBA = 1,
)
@cenum(nk_popup_type,
    NK_POPUP_STATIC = 0,
    NK_POPUP_DYNAMIC = 1,
)
@cenum(nk_layout_format,
    NK_DYNAMIC = 0,
    NK_STATIC = 1,
)
@cenum(nk_tree_type,
    NK_TREE_NODE = 0,
    NK_TREE_TAB = 1,
)
@cenum(nk_keys,
    NK_KEY_NONE = 0,
    NK_KEY_SHIFT = 1,
    NK_KEY_CTRL = 2,
    NK_KEY_DEL = 3,
    NK_KEY_ENTER = 4,
    NK_KEY_TAB = 5,
    NK_KEY_BACKSPACE = 6,
    NK_KEY_COPY = 7,
    NK_KEY_CUT = 8,
    NK_KEY_PASTE = 9,
    NK_KEY_UP = 10,
    NK_KEY_DOWN = 11,
    NK_KEY_LEFT = 12,
    NK_KEY_RIGHT = 13,
    NK_KEY_TEXT_INSERT_MODE = 14,
    NK_KEY_TEXT_REPLACE_MODE = 15,
    NK_KEY_TEXT_RESET_MODE = 16,
    NK_KEY_TEXT_LINE_START = 17,
    NK_KEY_TEXT_LINE_END = 18,
    NK_KEY_TEXT_START = 19,
    NK_KEY_TEXT_END = 20,
    NK_KEY_TEXT_UNDO = 21,
    NK_KEY_TEXT_REDO = 22,
    NK_KEY_TEXT_SELECT_ALL = 23,
    NK_KEY_TEXT_WORD_LEFT = 24,
    NK_KEY_TEXT_WORD_RIGHT = 25,
    NK_KEY_SCROLL_START = 26,
    NK_KEY_SCROLL_END = 27,
    NK_KEY_SCROLL_DOWN = 28,
    NK_KEY_SCROLL_UP = 29,
    NK_KEY_MAX = 30,
)
@cenum(nk_buttons,
    NK_BUTTON_LEFT = 0,
    NK_BUTTON_MIDDLE = 1,
    NK_BUTTON_RIGHT = 2,
    NK_BUTTON_DOUBLE = 3,
    NK_BUTTON_MAX = 4,
)
@cenum(nk_convert_result,
    NK_CONVERT_SUCCESS = 0,
    NK_CONVERT_INVALID_PARAM = 1,
    NK_CONVERT_COMMAND_BUFFER_FULL = 2,
    NK_CONVERT_VERTEX_BUFFER_FULL = 4,
    NK_CONVERT_ELEMENT_BUFFER_FULL = 8,
)
@cenum(nk_command_type,
    NK_COMMAND_NOP = 0,
    NK_COMMAND_SCISSOR = 1,
    NK_COMMAND_LINE = 2,
    NK_COMMAND_CURVE = 3,
    NK_COMMAND_RECT = 4,
    NK_COMMAND_RECT_FILLED = 5,
    NK_COMMAND_RECT_MULTI_COLOR = 6,
    NK_COMMAND_CIRCLE = 7,
    NK_COMMAND_CIRCLE_FILLED = 8,
    NK_COMMAND_ARC = 9,
    NK_COMMAND_ARC_FILLED = 10,
    NK_COMMAND_TRIANGLE = 11,
    NK_COMMAND_TRIANGLE_FILLED = 12,
    NK_COMMAND_POLYGON = 13,
    NK_COMMAND_POLYGON_FILLED = 14,
    NK_COMMAND_POLYLINE = 15,
    NK_COMMAND_TEXT = 16,
    NK_COMMAND_IMAGE = 17,
    NK_COMMAND_CUSTOM = 18,
)

struct nk_command
    type::nk_command_type
    next::nk_size
end

@cenum(nk_panel_flags,
    NK_WINDOW_BORDER = 1,
    NK_WINDOW_MOVABLE = 2,
    NK_WINDOW_SCALABLE = 4,
    NK_WINDOW_CLOSABLE = 8,
    NK_WINDOW_MINIMIZABLE = 16,
    NK_WINDOW_NO_SCROLLBAR = 32,
    NK_WINDOW_TITLE = 64,
    NK_WINDOW_SCROLL_AUTO_HIDE = 128,
    NK_WINDOW_BACKGROUND = 256,
    NK_WINDOW_SCALE_LEFT = 512,
    NK_WINDOW_NO_INPUT = 1024,
)

struct nk_list_view
    _begin::Cint
    _end::Cint
    count::Cint
    total_height::Cint
    ctx::Ptr{nk_context}
    scroll_pointer::Ptr{nk_uint}
    scroll_value::nk_uint
end

@cenum(nk_widget_layout_states,
    NK_WIDGET_INVALID = 0,
    NK_WIDGET_VALID = 1,
    NK_WIDGET_ROM = 2,
)
@cenum(nk_widget_states,
    NK_WIDGET_STATE_MODIFIED = 2,
    NK_WIDGET_STATE_INACTIVE = 4,
    NK_WIDGET_STATE_ENTERED = 8,
    NK_WIDGET_STATE_HOVER = 16,
    NK_WIDGET_STATE_ACTIVED = 32,
    NK_WIDGET_STATE_LEFT = 64,
    NK_WIDGET_STATE_HOVERED = 18,
    NK_WIDGET_STATE_ACTIVE = 34,
)
@cenum(nk_text_align,
    NK_TEXT_ALIGN_LEFT = 1,
    NK_TEXT_ALIGN_CENTERED = 2,
    NK_TEXT_ALIGN_RIGHT = 4,
    NK_TEXT_ALIGN_TOP = 8,
    NK_TEXT_ALIGN_MIDDLE = 16,
    NK_TEXT_ALIGN_BOTTOM = 32,
)
@cenum(nk_text_alignment,
    NK_TEXT_LEFT = 17,
    NK_TEXT_CENTERED = 18,
    NK_TEXT_RIGHT = 20,
)
@cenum(nk_edit_flags,
    NK_EDIT_DEFAULT = 0,
    NK_EDIT_READ_ONLY = 1,
    NK_EDIT_AUTO_SELECT = 2,
    NK_EDIT_SIG_ENTER = 4,
    NK_EDIT_ALLOW_TAB = 8,
    NK_EDIT_NO_CURSOR = 16,
    NK_EDIT_SELECTABLE = 32,
    NK_EDIT_CLIPBOARD = 64,
    NK_EDIT_CTRL_ENTER_NEWLINE = 128,
    NK_EDIT_NO_HORIZONTAL_SCROLL = 256,
    NK_EDIT_ALWAYS_INSERT_MODE = 512,
    NK_EDIT_MULTILINE = 1024,
    NK_EDIT_GOTO_END_ON_ACTIVATE = 2048,
)
@cenum(nk_edit_types,
    NK_EDIT_SIMPLE = 512,
    NK_EDIT_FIELD = 608,
    NK_EDIT_BOX = 1640,
    NK_EDIT_EDITOR = 1128,
)
@cenum(nk_edit_events,
    NK_EDIT_ACTIVE = 1,
    NK_EDIT_INACTIVE = 2,
    NK_EDIT_ACTIVATED = 4,
    NK_EDIT_DEACTIVATED = 8,
    NK_EDIT_COMMITED = 16,
)
@cenum(nk_style_colors,
    NK_COLOR_TEXT = 0,
    NK_COLOR_WINDOW = 1,
    NK_COLOR_HEADER = 2,
    NK_COLOR_BORDER = 3,
    NK_COLOR_BUTTON = 4,
    NK_COLOR_BUTTON_HOVER = 5,
    NK_COLOR_BUTTON_ACTIVE = 6,
    NK_COLOR_TOGGLE = 7,
    NK_COLOR_TOGGLE_HOVER = 8,
    NK_COLOR_TOGGLE_CURSOR = 9,
    NK_COLOR_SELECT = 10,
    NK_COLOR_SELECT_ACTIVE = 11,
    NK_COLOR_SLIDER = 12,
    NK_COLOR_SLIDER_CURSOR = 13,
    NK_COLOR_SLIDER_CURSOR_HOVER = 14,
    NK_COLOR_SLIDER_CURSOR_ACTIVE = 15,
    NK_COLOR_PROPERTY = 16,
    NK_COLOR_EDIT = 17,
    NK_COLOR_EDIT_CURSOR = 18,
    NK_COLOR_COMBO = 19,
    NK_COLOR_CHART = 20,
    NK_COLOR_CHART_COLOR = 21,
    NK_COLOR_CHART_COLOR_HIGHLIGHT = 22,
    NK_COLOR_SCROLLBAR = 23,
    NK_COLOR_SCROLLBAR_CURSOR = 24,
    NK_COLOR_SCROLLBAR_CURSOR_HOVER = 25,
    NK_COLOR_SCROLLBAR_CURSOR_ACTIVE = 26,
    NK_COLOR_TAB_HEADER = 27,
    NK_COLOR_COUNT = 28,
)
@cenum(nk_style_cursor,
    NK_CURSOR_ARROW = 0,
    NK_CURSOR_TEXT = 1,
    NK_CURSOR_MOVE = 2,
    NK_CURSOR_RESIZE_VERTICAL = 3,
    NK_CURSOR_RESIZE_HORIZONTAL = 4,
    NK_CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT = 5,
    NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT = 6,
    NK_CURSOR_COUNT = 7,
)

struct nk_user_font_glyph
    uv::NTuple{2, nk_vec2}
    offset::nk_vec2
    width::Cfloat
    height::Cfloat
    xadvance::Cfloat
end

@cenum(nk_font_coord_type,
    NK_COORD_UV = 0,
    NK_COORD_PIXEL = 1,
)

struct nk_baked_font
    height::Cfloat
    ascent::Cfloat
    descent::Cfloat
    glyph_offset::nk_rune
    glyph_count::nk_rune
    ranges::Ptr{nk_rune}
end

struct nk_font_glyph
    codepoint::nk_rune
    xadvance::Cfloat
    x0::Cfloat
    y0::Cfloat
    x1::Cfloat
    y1::Cfloat
    w::Cfloat
    h::Cfloat
    u0::Cfloat
    v0::Cfloat
    u1::Cfloat
    v1::Cfloat
end

struct nk_font_config
    next::Ptr{nk_font_config}
    ttf_blob::Ptr{Cvoid}
    ttf_size::nk_size
    ttf_data_owned_by_atlas::Cuchar
    merge_mode::Cuchar
    pixel_snap::Cuchar
    oversample_v::Cuchar
    oversample_h::Cuchar
    padding::NTuple{3, Cuchar}
    size::Cfloat
    coord_type::nk_font_coord_type
    spacing::nk_vec2
    range::Ptr{nk_rune}
    font::Ptr{nk_baked_font}
    fallback_glyph::nk_rune
    n::Ptr{nk_font_config}
    p::Ptr{nk_font_config}
end

struct nk_font
    next::Ptr{nk_font}
    handle::nk_user_font
    info::nk_baked_font
    scale::Cfloat
    glyphs::Ptr{nk_font_glyph}
    fallback::Ptr{nk_font_glyph}
    fallback_codepoint::nk_rune
    texture::nk_handle
    config::Ptr{nk_font_config}
end

@cenum(nk_font_atlas_format,
    NK_FONT_ATLAS_ALPHA8 = 0,
    NK_FONT_ATLAS_RGBA32 = 1,
)

struct nk_font_atlas
    pixel::Ptr{Cvoid}
    tex_width::Cint
    tex_height::Cint
    permanent::nk_allocator
    temporary::nk_allocator
    custom::nk_recti
    cursors::NTuple{7, nk_cursor}
    glyph_count::Cint
    glyphs::Ptr{nk_font_glyph}
    default_font::Ptr{nk_font}
    fonts::Ptr{nk_font}
    config::Ptr{nk_font_config}
    font_num::Cint
end

struct nk_memory_status
    memory::Ptr{Cvoid}
    type::UInt32
    size::nk_size
    allocated::nk_size
    needed::nk_size
    calls::nk_size
end

@cenum(nk_buffer_allocation_type,
    NK_BUFFER_FRONT = 0,
    NK_BUFFER_BACK = 1,
    NK_BUFFER_MAX = 2,
)
@cenum(nk_text_edit_type,
    NK_TEXT_EDIT_SINGLE_LINE = 0,
    NK_TEXT_EDIT_MULTI_LINE = 1,
)
@cenum(nk_text_edit_mode,
    NK_TEXT_EDIT_MODE_VIEW = 0,
    NK_TEXT_EDIT_MODE_INSERT = 1,
    NK_TEXT_EDIT_MODE_REPLACE = 2,
)

struct nk_command_scissor
    header::nk_command
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
end

struct nk_command_line
    header::nk_command
    line_thickness::UInt16
    _begin::nk_vec2i
    _end::nk_vec2i
    color::nk_color
end

struct nk_command_curve
    header::nk_command
    line_thickness::UInt16
    _begin::nk_vec2i
    _end::nk_vec2i
    ctrl::NTuple{2, nk_vec2i}
    color::nk_color
end

struct nk_command_rect
    header::nk_command
    rounding::UInt16
    line_thickness::UInt16
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    color::nk_color
end

struct nk_command_rect_filled
    header::nk_command
    rounding::UInt16
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    color::nk_color
end

struct nk_command_rect_multi_color
    header::nk_command
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    left::nk_color
    top::nk_color
    bottom::nk_color
    right::nk_color
end

struct nk_command_triangle
    header::nk_command
    line_thickness::UInt16
    a::nk_vec2i
    b::nk_vec2i
    c::nk_vec2i
    color::nk_color
end

struct nk_command_triangle_filled
    header::nk_command
    a::nk_vec2i
    b::nk_vec2i
    c::nk_vec2i
    color::nk_color
end

struct nk_command_circle
    header::nk_command
    x::Int16
    y::Int16
    line_thickness::UInt16
    w::UInt16
    h::UInt16
    color::nk_color
end

struct nk_command_circle_filled
    header::nk_command
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    color::nk_color
end

struct nk_command_arc
    header::nk_command
    cx::Int16
    cy::Int16
    r::UInt16
    line_thickness::UInt16
    a::NTuple{2, Cfloat}
    color::nk_color
end

struct nk_command_arc_filled
    header::nk_command
    cx::Int16
    cy::Int16
    r::UInt16
    a::NTuple{2, Cfloat}
    color::nk_color
end

struct nk_command_polygon
    header::nk_command
    color::nk_color
    line_thickness::UInt16
    point_count::UInt16
    points::NTuple{1, nk_vec2i}
end

struct nk_command_polygon_filled
    header::nk_command
    color::nk_color
    point_count::UInt16
    points::NTuple{1, nk_vec2i}
end

struct nk_command_polyline
    header::nk_command
    color::nk_color
    line_thickness::UInt16
    point_count::UInt16
    points::NTuple{1, nk_vec2i}
end

struct nk_command_image
    header::nk_command
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    img::nk_image
    col::nk_color
end

const nk_command_custom_callback = Ptr{Cvoid}

struct nk_command_custom
    header::nk_command
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    callback_data::nk_handle
    callback::nk_command_custom_callback
end

struct nk_command_text
    header::nk_command
    font::Ptr{nk_user_font}
    background::nk_color
    foreground::nk_color
    x::Int16
    y::Int16
    w::UInt16
    h::UInt16
    height::Cfloat
    length::Cint
    string::NTuple{1, UInt8}
end

@cenum(nk_command_clipping,
    NK_CLIPPING_OFF = 0,
    NK_CLIPPING_ON = 1,
)

const nk_draw_index = nk_ushort

@cenum(nk_draw_list_stroke,
    NK_STROKE_OPEN = 0,
    NK_STROKE_CLOSED = 1,
)
@cenum(nk_panel_set,
    NK_PANEL_SET_NONBLOCK = 240,
    NK_PANEL_SET_POPUP = 244,
    NK_PANEL_SET_SUB = 246,
)
@cenum(nk_window_flags,
    NK_WINDOW_PRIVATE = 2048,
    NK_WINDOW_DYNAMIC = 2048,
    NK_WINDOW_ROM = 4096,
    NK_WINDOW_NOT_INTERACTIVE = 5120,
    NK_WINDOW_HIDDEN = 8192,
    NK_WINDOW_CLOSED = 16384,
    NK_WINDOW_MINIMIZED = 32768,
    NK_WINDOW_REMOVE_ROM = 65536,
)


text:
#=

  Euler #28 in Julia.

  Problem 28:
  """
  Starting with the number 1 and moving to the right in a clockwise
  direction a 5 by 5 spiral is formed as follows:

     21 22 23 24 25
     20  7  8  9 10
     19  6  1  2 11
     18  5  4  3 12
     17 16 15 14 13

  It can be verified that the sum of the numbers on the diagonals is 101.

  What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
  """

  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#

include("Euler.jl")

#
function euler28a()
    s = 1
    n = 3
    while n <= 1001
        s += 4*n^2 - 6*n+6
        n+=2
    end
    return s
end

run_euler(euler28a)

max_stars_repo_name: Wikunia/hakank

max_issues_repo_name: Wikunia/hakank

max_forks_repo_name: Wikunia/hakank


text:
using StanSample, MCMCChains, StatsPlots

ProjDir = @__DIR__

#=
with pm.Model() as m:
    d = pm.Gamma('theta', 1, 1)          # prior distribution
    pm.Poisson('d0', d, observed = d0)   # likelihood
    samples = pm.sample(10000)           # draw samples from the posterior
=#

demand_model = "
data {
  int<lower=1> N;
  int<lower=0> d[N];
}
parameters {
  real<lower=0> theta;
}
model {
  theta ~ gamma(1,1);
  d ~ poisson(theta);
}
";

d = [20, 28, 24, 20, 23]        # observed demand samples
demand_data = Dict(
  :N => length(d),
  :d => d
)

# Keep tmpdir across multiple runs to prevent re-compilation
tmpdir = joinpath(@__DIR__, "tmp")

sm = SampleModel("demand-price-model", demand_model)

rc = stan_sample(sm; data=demand_data)

if success(rc)
  # Convert to an MCMCChains.Chains object
  chns = read_samples(sm; output_format=:mcmcchains)
  show(chns)
  plot(chns)
  savefig(joinpath(@__DIR__, "fig_01.png"))
end


text: Dict{String,Any}("a" => Dict{String,Any}())

max_stars_repo_name: vanillajonathan/julia

max_issues_repo_name: vanillajonathan/julia

max_forks_repo_name: vanillajonathan/julia


text:
using AsciiDocTools
using Test

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

max_stars_repo_name: ordovician/AsciiDocTools

max_issues_repo_name: ordovician/AsciiDocTools

max_forks_repo_name: ordovician/AsciiDocTools


text:
using GADM
using Test
using DataDeps
using ArchGDAL
using GeoInterface
using Tables

# DataDeps always downloads the data if it doesn't exist
ENV["DATADEPS_ALWAYS_ACCEPT"] = true

testfiles = [
    "GADM.jl",
]

@testset "GADM.jl" begin
  for testfile in testfiles
    include(testfile)
  end
end