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

"""
    analyze_document(document, feature_types)
    analyze_document(document, feature_types, params::Dict{String,<:Any})

Analyzes an input document for relationships between detected items.  The types of
information returned are as follows:    Form data (key-value pairs). The related
information is returned in two Block objects, each of type KEY_VALUE_SET: a KEY Block
object and a VALUE Block object. For example, Name: Ana Silva Carolina contains a key and
value. Name: is the key. Ana Silva Carolina is the value.   Table and table cell data. A
TABLE Block object contains information about a detected table. A CELL Block object is
returned for each cell in a table.   Lines and words of text. A LINE Block object contains
one or more WORD Block objects. All lines and words that are detected in the document are
returned (including text that doesn't have a relationship with the value of FeatureTypes).
  Selection elements such as check boxes and option buttons (radio buttons) can be detected
in form data and in tables. A SELECTION_ELEMENT Block object contains information about a
selection element, including the selection status. You can choose which type of analysis to
perform by specifying the FeatureTypes list.  The output is returned in a list of Block
objects.  AnalyzeDocument is a synchronous operation. To analyze documents asynchronously,
use StartDocumentAnalysis. For more information, see Document Text Analysis.

# Arguments
- `document`: The input document as base64-encoded bytes or an Amazon S3 object. If you use
  the AWS CLI to call Amazon Textract operations, you can't pass image bytes. The document
  must be an image in JPEG or PNG format. If you're using an AWS SDK to call Amazon Textract,
  you might not need to base64-encode image bytes that are passed using the Bytes field.
- `feature_types`: A list of the types of analysis to perform. Add TABLES to the list to
  return information about the tables that are detected in the input document. Add FORMS to
  return detected form data. To perform both types of analysis, add TABLES and FORMS to
  FeatureTypes. All lines and words detected in the document are included in the response
  (including text that isn't related to the value of FeatureTypes).

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"HumanLoopConfig"`: Sets the configuration for the human in the loop workflow for
  analyzing documents.
"""
function analyze_document(
    Document, FeatureTypes; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "AnalyzeDocument",
        Dict{String,Any}("Document" => Document, "FeatureTypes" => FeatureTypes);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function analyze_document(
    Document,
    FeatureTypes,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return textract(
        "AnalyzeDocument",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("Document" => Document, "FeatureTypes" => FeatureTypes),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    analyze_expense(document)
    analyze_expense(document, params::Dict{String,<:Any})

Analyzes an input document for financially related relationships between text. Information
is returned as ExpenseDocuments and seperated as follows.    LineItemGroups- A data set
containing LineItems which store information about the lines of text, such as an item
purchased and its price on a receipt.    SummaryFields- Contains all other information a
receipt, such as header information or the vendors name.

# Arguments
- `document`:

"""
function analyze_expense(Document; aws_config::AbstractAWSConfig=global_aws_config())
    return textract(
        "AnalyzeExpense",
        Dict{String,Any}("Document" => Document);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function analyze_expense(
    Document,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return textract(
        "AnalyzeExpense",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("Document" => Document), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    detect_document_text(document)
    detect_document_text(document, params::Dict{String,<:Any})

Detects text in the input document. Amazon Textract can detect lines of text and the words
that make up a line of text. The input document must be an image in JPEG or PNG format.
DetectDocumentText returns the detected text in an array of Block objects.  Each document
page has as an associated Block of type PAGE. Each PAGE Block object is the parent of LINE
Block objects that represent the lines of detected text on a page. A LINE Block object is a
parent for each word that makes up the line. Words are represented by Block objects of type
WORD.  DetectDocumentText is a synchronous operation. To analyze documents asynchronously,
use StartDocumentTextDetection. For more information, see Document Text Detection.

# Arguments
- `document`: The input document as base64-encoded bytes or an Amazon S3 object. If you use
  the AWS CLI to call Amazon Textract operations, you can't pass image bytes. The document
  must be an image in JPEG or PNG format. If you're using an AWS SDK to call Amazon Textract,
  you might not need to base64-encode image bytes that are passed using the Bytes field.

"""
function detect_document_text(Document; aws_config::AbstractAWSConfig=global_aws_config())
    return textract(
        "DetectDocumentText",
        Dict{String,Any}("Document" => Document);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function detect_document_text(
    Document,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return textract(
        "DetectDocumentText",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("Document" => Document), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_document_analysis(job_id)
    get_document_analysis(job_id, params::Dict{String,<:Any})

Gets the results for an Amazon Textract asynchronous operation that analyzes text in a
document. You start asynchronous text analysis by calling StartDocumentAnalysis, which
returns a job identifier (JobId). When the text analysis operation finishes, Amazon
Textract publishes a completion status to the Amazon Simple Notification Service (Amazon
SNS) topic that's registered in the initial call to StartDocumentAnalysis. To get the
results of the text-detection operation, first check that the status value published to the
Amazon SNS topic is SUCCEEDED. If so, call GetDocumentAnalysis, and pass the job identifier
(JobId) from the initial call to StartDocumentAnalysis.  GetDocumentAnalysis returns an
array of Block objects. The following types of information are returned:    Form data
(key-value pairs). The related information is returned in two Block objects, each of type
KEY_VALUE_SET: a KEY Block object and a VALUE Block object. For example, Name: Ana Silva
Carolina contains a key and value. Name: is the key. Ana Silva Carolina is the value.
Table and table cell data. A TABLE Block object contains information about a detected
table. A CELL Block object is returned for each cell in a table.   Lines and words of text.
A LINE Block object contains one or more WORD Block objects. All lines and words that are
detected in the document are returned (including text that doesn't have a relationship with
the value of the StartDocumentAnalysis FeatureTypes input parameter).    Selection elements
such as check boxes and option buttons (radio buttons) can be detected in form data and in
tables. A SELECTION_ELEMENT Block object contains information about a selection element,
including the selection status. Use the MaxResults parameter to limit the number of blocks
that are returned. If there are more results than specified in MaxResults, the value of
NextToken in the operation response contains a pagination token for getting the next set of
results. To get the next page of results, call GetDocumentAnalysis, and populate the
NextToken request parameter with the token value that's returned from the previous call to
GetDocumentAnalysis. For more information, see Document Text Analysis.

# Arguments
- `job_id`: A unique identifier for the text-detection job. The JobId is returned from
  StartDocumentAnalysis. A JobId value is only valid for 7 days.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results to return per paginated call. The largest
  value that you can specify is 1,000. If you specify a value greater than 1,000, a maximum
  of 1,000 results is returned. The default value is 1,000.
- `"NextToken"`: If the previous response was incomplete (because there are more blocks to
  retrieve), Amazon Textract returns a pagination token in the response. You can use this
  pagination token to retrieve the next set of blocks.
"""
function get_document_analysis(JobId; aws_config::AbstractAWSConfig=global_aws_config())
    return textract(
        "GetDocumentAnalysis",
        Dict{String,Any}("JobId" => JobId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_document_analysis(
    JobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "GetDocumentAnalysis",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("JobId" => JobId), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_document_text_detection(job_id)
    get_document_text_detection(job_id, params::Dict{String,<:Any})

Gets the results for an Amazon Textract asynchronous operation that detects text in a
document. Amazon Textract can detect lines of text and the words that make up a line of
text. You start asynchronous text detection by calling StartDocumentTextDetection, which
returns a job identifier (JobId). When the text detection operation finishes, Amazon
Textract publishes a completion status to the Amazon Simple Notification Service (Amazon
SNS) topic that's registered in the initial call to StartDocumentTextDetection. To get the
results of the text-detection operation, first check that the status value published to the
Amazon SNS topic is SUCCEEDED. If so, call GetDocumentTextDetection, and pass the job
identifier (JobId) from the initial call to StartDocumentTextDetection.
GetDocumentTextDetection returns an array of Block objects.  Each document page has as an
associated Block of type PAGE. Each PAGE Block object is the parent of LINE Block objects
that represent the lines of detected text on a page. A LINE Block object is a parent for
each word that makes up the line. Words are represented by Block objects of type WORD. Use
the MaxResults parameter to limit the number of blocks that are returned. If there are more
results than specified in MaxResults, the value of NextToken in the operation response
contains a pagination token for getting the next set of results. To get the next page of
results, call GetDocumentTextDetection, and populate the NextToken request parameter with
the token value that's returned from the previous call to GetDocumentTextDetection. For
more information, see Document Text Detection.

# Arguments
- `job_id`: A unique identifier for the text detection job. The JobId is returned from
  StartDocumentTextDetection. A JobId value is only valid for 7 days.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results to return per paginated call. The largest
  value you can specify is 1,000. If you specify a value greater than 1,000, a maximum of
  1,000 results is returned. The default value is 1,000.
- `"NextToken"`: If the previous response was incomplete (because there are more blocks to
  retrieve), Amazon Textract returns a pagination token in the response. You can use this
  pagination token to retrieve the next set of blocks.
"""
function get_document_text_detection(
    JobId; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "GetDocumentTextDetection",
        Dict{String,Any}("JobId" => JobId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_document_text_detection(
    JobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "GetDocumentTextDetection",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("JobId" => JobId), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    get_expense_analysis(job_id)
    get_expense_analysis(job_id, params::Dict{String,<:Any})

Gets the results for an Amazon Textract asynchronous operation that analyzes invoices and
receipts. Amazon Textract finds contact information, items purchased, and vendor name, from
input invoices and receipts. You start asynchronous invoice/receipt analysis by calling
StartExpenseAnalysis, which returns a job identifier (JobId). Upon completion of the
invoice/receipt analysis, Amazon Textract publishes the completion status to the Amazon
Simple Notification Service (Amazon SNS) topic. This topic must be registered in the
initial call to StartExpenseAnalysis. To get the results of the invoice/receipt analysis
operation, first ensure that the status value published to the Amazon SNS topic is
SUCCEEDED. If so, call GetExpenseAnalysis, and pass the job identifier (JobId) from the
initial call to StartExpenseAnalysis. Use the MaxResults parameter to limit the number of
blocks that are returned. If there are more results than specified in MaxResults, the value
of NextToken in the operation response contains a pagination token for getting the next set
of results. To get the next page of results, call GetExpenseAnalysis, and populate the
NextToken request parameter with the token value that's returned from the previous call to
GetExpenseAnalysis. For more information, see Analyzing Invoices and Receipts.

# Arguments
- `job_id`: A unique identifier for the text detection job. The JobId is returned from
  StartExpenseAnalysis. A JobId value is only valid for 7 days.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of results to return per paginated call. The largest
  value you can specify is 20. If you specify a value greater than 20, a maximum of 20
  results is returned. The default value is 20.
- `"NextToken"`: If the previous response was incomplete (because there are more blocks to
  retrieve), Amazon Textract returns a pagination token in the response. You can use this
  pagination token to retrieve the next set of blocks.
"""
function get_expense_analysis(JobId; aws_config::AbstractAWSConfig=global_aws_config())
    return textract(
        "GetExpenseAnalysis",
        Dict{String,Any}("JobId" => JobId);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function get_expense_analysis(
    JobId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "GetExpenseAnalysis",
        Dict{String,Any}(mergewith(_merge, Dict{String,Any}("JobId" => JobId), params));
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    start_document_analysis(document_location, feature_types)
    start_document_analysis(document_location, feature_types, params::Dict{String,<:Any})

Starts the asynchronous analysis of an input document for relationships between detected
items such as key-value pairs, tables, and selection elements.  StartDocumentAnalysis can
analyze text in documents that are in JPEG, PNG, TIFF, and PDF format. The documents are
stored in an Amazon S3 bucket. Use DocumentLocation to specify the bucket name and file
name of the document.   StartDocumentAnalysis returns a job identifier (JobId) that you use
to get the results of the operation. When text analysis is finished, Amazon Textract
publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic
that you specify in NotificationChannel. To get the results of the text analysis operation,
first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so,
call GetDocumentAnalysis, and pass the job identifier (JobId) from the initial call to
StartDocumentAnalysis. For more information, see Document Text Analysis.

# Arguments
- `document_location`: The location of the document to be processed.
- `feature_types`: A list of the types of analysis to perform. Add TABLES to the list to
  return information about the tables that are detected in the input document. Add FORMS to
  return detected form data. To perform both types of analysis, add TABLES and FORMS to
  FeatureTypes. All lines and words detected in the document are included in the response
  (including text that isn't related to the value of FeatureTypes).

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientRequestToken"`: The idempotent token that you use to identify the start request.
  If you use the same token with multiple StartDocumentAnalysis requests, the same JobId is
  returned. Use ClientRequestToken to prevent the same job from being accidentally started
  more than once. For more information, see Calling Amazon Textract Asynchronous Operations.
- `"JobTag"`: An identifier that you specify that's included in the completion notification
  published to the Amazon SNS topic. For example, you can use JobTag to identify the type of
  document that the completion notification corresponds to (such as a tax form or a receipt).
- `"KMSKeyId"`: The KMS key used to encrypt the inference results. This can be in either
  Key ID or Key Alias format. When a KMS key is provided, the KMS key will be used for
  server-side encryption of the objects in the customer bucket. When this parameter is not
  enabled, the result will be encrypted server side,using SSE-S3.
- `"NotificationChannel"`: The Amazon SNS topic ARN that you want Amazon Textract to
  publish the completion status of the operation to.
- `"OutputConfig"`: Sets if the output will go to a customer defined bucket. By default,
  Amazon Textract will save the results internally to be accessed by the GetDocumentAnalysis
  operation.
"""
function start_document_analysis(
    DocumentLocation, FeatureTypes; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "StartDocumentAnalysis",
        Dict{String,Any}(
            "DocumentLocation" => DocumentLocation, "FeatureTypes" => FeatureTypes
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function start_document_analysis(
    DocumentLocation,
    FeatureTypes,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return textract(
        "StartDocumentAnalysis",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "DocumentLocation" => DocumentLocation, "FeatureTypes" => FeatureTypes
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    start_document_text_detection(document_location)
    start_document_text_detection(document_location, params::Dict{String,<:Any})

Starts the asynchronous detection of text in a document. Amazon Textract can detect lines
of text and the words that make up a line of text.  StartDocumentTextDetection can analyze
text in documents that are in JPEG, PNG, TIFF, and PDF format. The documents are stored in
an Amazon S3 bucket. Use DocumentLocation to specify the bucket name and file name of the
document.   StartTextDetection returns a job identifier (JobId) that you use to get the
results of the operation. When text detection is finished, Amazon Textract publishes a
completion status to the Amazon Simple Notification Service (Amazon SNS) topic that you
specify in NotificationChannel. To get the results of the text detection operation, first
check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call
GetDocumentTextDetection, and pass the job identifier (JobId) from the initial call to
StartDocumentTextDetection. For more information, see Document Text Detection.

# Arguments
- `document_location`: The location of the document to be processed.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientRequestToken"`: The idempotent token that's used to identify the start request.
  If you use the same token with multiple StartDocumentTextDetection requests, the same JobId
  is returned. Use ClientRequestToken to prevent the same job from being accidentally started
  more than once. For more information, see Calling Amazon Textract Asynchronous Operations.
- `"JobTag"`: An identifier that you specify that's included in the completion notification
  published to the Amazon SNS topic. For example, you can use JobTag to identify the type of
  document that the completion notification corresponds to (such as a tax form or a receipt).
- `"KMSKeyId"`: The KMS key used to encrypt the inference results. This can be in either
  Key ID or Key Alias format. When a KMS key is provided, the KMS key will be used for
  server-side encryption of the objects in the customer bucket. When this parameter is not
  enabled, the result will be encrypted server side,using SSE-S3.
- `"NotificationChannel"`: The Amazon SNS topic ARN that you want Amazon Textract to
  publish the completion status of the operation to.
- `"OutputConfig"`: Sets if the output will go to a customer defined bucket. By default
  Amazon Textract will save the results internally to be accessed with the
  GetDocumentTextDetection operation.
"""
function start_document_text_detection(
    DocumentLocation; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "StartDocumentTextDetection",
        Dict{String,Any}("DocumentLocation" => DocumentLocation);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function start_document_text_detection(
    DocumentLocation,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return textract(
        "StartDocumentTextDetection",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("DocumentLocation" => DocumentLocation), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    start_expense_analysis(document_location)
    start_expense_analysis(document_location, params::Dict{String,<:Any})

Starts the asynchronous analysis of invoices or receipts for data like contact information,
items purchased, and vendor names.  StartExpenseAnalysis can analyze text in documents that
are in JPEG, PNG, and PDF format. The documents must be stored in an Amazon S3 bucket. Use
the DocumentLocation parameter to specify the name of your S3 bucket and the name of the
document in that bucket.   StartExpenseAnalysis returns a job identifier (JobId) that you
will provide to GetExpenseAnalysis to retrieve the results of the operation. When the
analysis of the input invoices/receipts is finished, Amazon Textract publishes a completion
status to the Amazon Simple Notification Service (Amazon SNS) topic that you provide to the
NotificationChannel. To obtain the results of the invoice and receipt analysis operation,
ensure that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call
GetExpenseAnalysis, and pass the job identifier (JobId) that was returned by your call to
StartExpenseAnalysis. For more information, see Analyzing Invoices and Receipts.

# Arguments
- `document_location`: The location of the document to be processed.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"ClientRequestToken"`: The idempotent token that's used to identify the start request.
  If you use the same token with multiple StartDocumentTextDetection requests, the same JobId
  is returned. Use ClientRequestToken to prevent the same job from being accidentally started
  more than once. For more information, see Calling Amazon Textract Asynchronous Operations
- `"JobTag"`: An identifier you specify that's included in the completion notification
  published to the Amazon SNS topic. For example, you can use JobTag to identify the type of
  document that the completion notification corresponds to (such as a tax form or a receipt).
- `"KMSKeyId"`: The KMS key used to encrypt the inference results. This can be in either
  Key ID or Key Alias format. When a KMS key is provided, the KMS key will be used for
  server-side encryption of the objects in the customer bucket. When this parameter is not
  enabled, the result will be encrypted server side,using SSE-S3.
- `"NotificationChannel"`: The Amazon SNS topic ARN that you want Amazon Textract to
  publish the completion status of the operation to.
- `"OutputConfig"`: Sets if the output will go to a customer defined bucket. By default,
  Amazon Textract will save the results internally to be accessed by the GetExpenseAnalysis
  operation.
"""
function start_expense_analysis(
    DocumentLocation; aws_config::AbstractAWSConfig=global_aws_config()
)
    return textract(
        "StartExpenseAnalysis",
        Dict{String,Any}("DocumentLocation" => DocumentLocation);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function start_expense_analysis(
    DocumentLocation,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return textract(
        "StartExpenseAnalysis",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("DocumentLocation" => DocumentLocation), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
using ContinuumArrays, QuasiArrays, FillArrays, InfiniteArrays
import QuasiArrays: Inclusion, QuasiDiagonal

using Plots; pyplot();

S = LinearSpline(range(0,1; length=10))
xx = range(0,1; length=1000)

S = Jacobi(true,true)

P = Legendre()
X = QuasiDiagonal(Inclusion(-1..1))

@test X[-1:0.1:1,-1:0.1:1] == Diagonal(-1:0.1:1)

axes(X)
J = pinv(P)*X*P

J - I
Vcat(Hcat(1, Zeros(1,∞)), J)

ext: jl


text:
### Internal ###
# Prioritise left
Base.promote_rule(::Type{<:MagOrRef}, ::Type{<:Union{MagOrRef}}) = Mag
Base.promote_rule(::Type{<:ArfOrRef}, ::Type{<:Union{MagOrRef,ArfOrRef}}) = Arf
Base.promote_rule(::Type{<:ArbOrRef}, ::Type{<:Union{MagOrRef,ArfOrRef,ArbOrRef}}) = Arb
Base.promote_rule(
    ::Type{<:AcbOrRef},
    ::Type{<:Union{MagOrRef,ArfOrRef,ArbOrRef,AcbOrRef}},
) = Acb
Base.promote_rule(::Type{ArbSeries}, ::Type{<:Union{MagOrRef,ArfOrRef,ArbOrRef}}) =
    ArbSeries
Base.promote_rule(
    ::Type{AcbSeries},
    ::Type{<:Union{MagOrRef,ArfOrRef,ArbOrRef,AcbOrRef,ArbSeries}},
) = AcbSeries

# Prioritise right
Base.promote_rule(
    ::Type{<:MagOrRef},
    ::Type{T},
) where {T<:Union{ArfOrRef,ArbOrRef,AcbOrRef,ArbSeries,AcbSeries}} = _nonreftype(T)
Base.promote_rule(
    ::Type{<:ArfOrRef},
    ::Type{T},
) where {T<:Union{ArbOrRef,AcbOrRef,ArbSeries,AcbSeries}} = _nonreftype(T)
Base.promote_rule(::Type{<:ArbOrRef}, ::Type{T}) where {T<:Union{AcbOrRef,AcbSeries}} =
    _nonreftype(T)
Base.promote_rule(::Type{<:AcbOrRef}, ::Type{T}) where {T<:Union{AcbSeries}} =
    _nonreftype(T)
Base.promote_rule(::Type{<:ArbSeries}, ::Type{T}) where {T<:Union{AcbSeries}} =
    _nonreftype(T)

# Make complex
Base.promote_rule(::Type{ArbSeries}, ::Type{<:AcbOrRef}) = AcbSeries

### External ###
# TODO: How should we handle promotions for Mag? The type is very
# limited so it's likely not a good idea to promote everything to it.

# Always prioritise Arb types
Base.promote_rule(::Type{<:MagOrRef}, ::Type{<:Base.GMP.CdoubleMax}) = Mag
Base.promote_rule(::Type{<:ArfOrRef}, ::Type{<:Real}) = Arf
Base.promote_rule(::Type{<:ArbOrRef}, ::Type{<:Real}) = Arb
Base.promote_rule(::Type{<:AcbOrRef}, ::Type{<:Number}) = Acb
Base.promote_rule(::Type{ArbSeries}, ::Type{<:Real}) = ArbSeries
Base.promote_rule(::Type{AcbSeries}, ::Type{<:Number}) = AcbSeries

# Handle BigFloat separately since it also defines a catch all case
Base.promote_rule(
    ::Type{BigFloat},
    ::Type{T},
) where {T<:Union{ArfOrRef,ArbOrRef,AcbOrRef,ArbSeries,AcbSeries}} = _nonreftype(T)

# Arb and ArbSeries should be promoted to Acb and AcbSeries
# respectively together with complex values. Note that Arf is promoted
# to Complex{Arf}.
Base.promote_rule(::Type{<:ArbOrRef}, ::Type{<:Complex}) = Acb
Base.promote_rule(::Type{ArbSeries}, ::Type{<:Complex}) = AcbSeries


text:
rig_key = "realm"
push!(RIGS, rig_key)
#Mappings from DAQ channel to friendlier default names
const realm_mappings = Dict("AO0"=>"axial piezo",
                      "AO1"=>"analogout1",
                      "AI0"=>"axial piezo monitor",
                      "AI1"=>"stimuli",
                      "AI2"=>"analogin1",
                      "AI3"=>"analogin2",
                      "AI4"=>"AI4",
                      "AI5"=>"AI5",
                      "AI6"=>"analogin5",
                      "AI7"=>"analogin6",
                      "AI8"=>"analogin7",
                      "AI9"=>"analogin8",
                      "AI10"=>"analogin9",
                      "AI11"=>"analogin10",
                      "AI12"=>"analogin11",
                      "AI13"=>"analogin12",
                      "AI14"=>"analogin13",
                      "AI15"=>"analogin14",
                      "P0.0"=>"stimulus1",
                      "P0.1"=>"stimulus2",
                      "P0.2"=>"stimulus3",
                      "P0.3"=>"stimulus4",
                      "P0.4"=>"488nm laser shutter",
                      "P0.5"=>"camera1",
                      "P0.6"=>"stimulus5",
                      "P0.7"=>"camera1 frame monitor")

DEFAULT_DAQCHANS_TO_NAMES[rig_key] = realm_mappings
DEFAULT_NAMES_TO_DAQCHANS[rig_key] = dictmap(reverse, realm_mappings)

const realm_aochans = map(x->"AO$(x)", 0:1)
const realm_aichans = map(x->"AI$(x)", 0:15)
const realm_dochans = map(x->"P0.$(x)", 0:6)
const realm_dichans = ["P0.7";]
const realm_pos_ctrl_chans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], ["axial piezo"])
const realm_pos_mon_chans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], ["axial piezo monitor"])
const realm_cam_ctrl_chans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], ["camera1"])
const realm_cam_mon_chans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], ["camera1 frame monitor"])
const realm_laschans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], ["488nm laser shutter"])
const realm_stimchans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], ["stimulus$x" for x = 1:5])
const realm_fixed_names = ["axial piezo", "axial piezo monitor", "488nm laser shutter", "camera1", "camera1 frame monitor", "stimuli"]
const realm_fixed_daqchans = map(x->DEFAULT_NAMES_TO_DAQCHANS[rig_key][x], realm_fixed_names)

AO_CHANS[rig_key] = OrderedSet(realm_aochans)
AI_CHANS[rig_key] = OrderedSet(realm_aichans)
DO_CHANS[rig_key] = OrderedSet(realm_dochans)
DI_CHANS[rig_key] = OrderedSet(realm_dichans)
POS_CONTROL_CHANS[rig_key] = realm_pos_ctrl_chans
POS_MONITOR_CHANS[rig_key] = realm_pos_mon_chans
CAM_CONTROL_CHANS[rig_key] = realm_cam_ctrl_chans
CAM_MONITOR_CHANS[rig_key] = realm_cam_mon_chans
LAS_CONTROL_CHANS[rig_key] = realm_laschans
STIM_CHANS[rig_key] =OrderedSet(realm_stimchans)
GALVO_CONTROL_CHANS[rig_key] = String[]
GALVO_MONITOR_CHANS[rig_key] = String[]
FIXED_NAMES[rig_key] = realm_fixed_names
FIXED_DAQ_CHANS[rig_key] = realm_fixed_daqchans

RIG_CHIP_SIZES[rig_key] = PCO_EDGE_5_5_CHIP_SIZE
RIG_FRAMERATE_FUNCS[rig_key] = PCO_EDGE_5_5_FRAMERATE_FUNC
RIG_ROI_FUNCS[rig_key] = PCO_EDGE_5_5_ROI_FUNC

LASER_ON_TIME[rig_key] = 100 * Unitful.ms
LASER_OFF_TIME[rig_key] = 100 * Unitful.ms

CAMERA_ON_TIME[rig_key] = 19526.0 * Unitful.ns #This is the worst jitter measured with Edge 5.5 and 4.2 cameras, see ImagineInterface issue #18
CAMERA_OFF_TIME[rig_key] = 19526.0 * Unitful.ns #This is the worst jitter measured with Edge 5.5 and 4.2 cameras, see ImagineInterface issue #18

PIEZO_RANGES[rig_key] = (0.0μm .. 400.0μm, 0.0V .. 10.0V)
PIEZO_MAX_SPEED[rig_key] = 2000*Unitful.μm / Unitful.s
AO_RANGE[rig_key] = -10.0V .. 10.0V
AI_RANGE[rig_key] = AO_RANGE[rig_key] #TODO: make sure this is true.  (true if we are recording -10..10V on analog inputs)

max_forks_repo_name: HolyLab/ImagineInterface


text:
__precompile__(true)

module Format

import Base.show

using Printf
const PF = @static VERSION >= v"1.4.0-DEV.180" ? Printf : Base.Printf

_stdout() = stdout
_codeunits(s) = Vector{UInt8}(codeunits(s))
m_eval(expr) = Core.eval(@__MODULE__, expr)

export FormatSpec, FormatExpr, printfmt, printfmtln, format, generate_formatter
export pyfmt, cfmt, fmt
export fmt_default, fmt_default!, reset!, default_spec, default_spec!

# Deal with mess from #16058
# Later, use Strs package!
isdefined(Main, :ASCIIStr) || (const ASCIIStr = String)
isdefined(Main, :UTF8Str)  || (const UTF8Str = String)
isdefined(Main, :AbstractChar) || (const AbstractChar = Char)

include("cformat.jl" )
include("fmtspec.jl")
include("fmtcore.jl")
include("formatexpr.jl")
include("fmt.jl")

end # module Format


text:
module Calculus

export interest, rate

end

end

max_stars_repo_name: jlvvlj/cal

max_issues_repo_name: jlvvlj/cal

max_forks_repo_name: jlvvlj/cal


text:
const MEMPOOL = [Cptr[] for i=1:30]

struct MemPoolMalloc
end

function (::MemPoolMalloc)(::Type{T}, dims::Dims{N}) where {T,N}
    bytesize = prod(dims) * sizeof(T)
    @assert bytesize > 0
    bytesize == 0 && return CuArray(Ptr{T}(C_NULL),dims,getdevice())

    c = log2ceil(bytesize) # 2^c >= bytesize
    bytesize = 1 << c
    ptrs = MEMPOOL[c]
    if isempty(ptrs)
        ptr = Ptr{T}(memalloc(bytesize))
        #status = @apicall_nocheck :cuMemAlloc (Ptr{UInt64},Csize_t) ref bytesize
        #if status != CUDA_SUCCESS
        #    gc()
        #    if isempty(buffer)
        #        dispose(mem)
        #        dptr = memalloc(bytesize)
        #    else
        #        dptr = pop!(buffer)
        #    end
        #else
        #    dptr = ref[]
        #end
    else
        ptr = Ptr{T}(pop!(ptrs))
    end
    arr = CuArray(ptr, dims, getdevice())
    function release(x::CuArray{T}) where T
        bytesize = prod(size(x)) * sizeof(T)
        c = log2ceil(bytesize)
        push!(MEMPOOL[c], Cptr(x.ptr))
    end
    finalizer(release, arr)
    arr
end

function dispose(x::MemPoolMalloc)
    gc()
    for dptrs in x.dptrs
        for dptr in dptrs
            memfree(dptr)
        end
    end
end

function log2ceil(bytesize::Int)
    @assert bytesize > 0
    bytesize -= 1
    x = 1
    while bytesize > 1
        bytesize >>= 1
        x += 1
    end
    x
end


text:
#### State types

export AbstractStateType,
    Prognostic,
    Primitive,
    Auxiliary,
    Gradient,
    GradientFlux,
    GradientLaplacian,
    Hyperdiffusive,
    UpwardIntegrals,
    DownwardIntegrals,
    Entropy

"""
    AbstractStateType

Subtypes of this describe the variables used by different parts of a [`BalanceLaw`](@ref):
- [`Prognostic`](@ref)
- [`Primitive`](@ref)
- [`Auxiliary`](@ref)
- [`Gradient`](@ref)
- [`GradientFlux`](@ref)
- [`GradientLaplacian`](@ref)
- [`Hyperdiffusive`](@ref)
- [`UpwardIntegrals`](@ref)
- [`DownwardIntegrals`](@ref)

See also [`vars_state`](@ref).
"""
abstract type AbstractStateType end

"""
    Prognostic <: AbstractStateType

Prognostic variables in the PDE system,
which are specified by the [`BalanceLaw`](@ref), and
solved for by the ODE solver.
"""
struct Prognostic <: AbstractStateType end

"""
    Primitive <: AbstractStateType

Primitive variables, which are specified
by the [`BalanceLaw`](@ref).
"""
struct Primitive <: AbstractStateType end

"""
    Auxiliary <: AbstractStateType

Auxiliary variables help serve several purposes:

 - Pre-compute and store "expensive" variables,
   for example, quantities computed in vertical
   integrals.
 - Diagnostic exports
"""
struct Auxiliary <: AbstractStateType end

"""
    Gradient <: AbstractStateType

Variables whose gradients must be computed.
"""
struct Gradient <: AbstractStateType end

"""
    GradientFlux <: AbstractStateType

Flux variables, which are functions of gradients.
"""
struct GradientFlux <: AbstractStateType end

"""
    GradientLaplacian <: AbstractStateType

Gradient-Laplacian variables.
"""
struct GradientLaplacian <: AbstractStateType end

"""
    Hyperdiffusive <: AbstractStateType

Hyper-diffusive variables
"""
struct Hyperdiffusive <: AbstractStateType end

"""
    UpwardIntegrals <: AbstractStateType

Variables computed in upward integrals
"""
struct UpwardIntegrals <: AbstractStateType end

"""
    DownwardIntegrals <: AbstractStateType

Variables computed in downward integrals
"""
struct DownwardIntegrals <: AbstractStateType end

"""
    Entropy <: AbstractStateType
Entropy variables
"""
struct Entropy <: AbstractStateType end


text:
"""
    @sync ex

Run expression `ex` and synchronize the GPU afterwards.

See also: [`synchronize`](@ref).
"""
macro sync(ex...)
    # destructure the `@sync` expression
    code = ex[end]
    kwargs = ex[1:end-1]

    # decode keyword arguments
    for kwarg in kwargs
        Meta.isexpr(kwarg, :(=)) || error("Invalid keyword argument $kwarg")
        key, val = kwarg.args
        if key == :blocking
            Base.depwarn("the blocking keyword to @sync has been deprecated", :sync)
        else
            error("Unknown keyword argument $kwarg")
        end
    end

    quote
        local ret = $(esc(code))
        synchronize()
        ret
    end
end

function versioninfo(io::IO=stdout)
    println(io, "CUDA toolkit $(runtime_version().major).$(runtime_version().minor), $(toolkit_origin()) installation")
    if has_nvml()
        print(io, "NVIDIA driver $(NVML.driver_version())")
    else
        print(io, "Unknown NVIDIA driver")
    end
    println(io, ", for CUDA $(system_version().major).$(system_version().minor)")
    println(io, "CUDA driver $(version().major).$(version().minor)")
    println(io)

    println(io, "Libraries: ")
    for lib in (:CUBLAS, :CURAND, :CUFFT, :CUSOLVER, :CUSPARSE)
        mod = getfield(CUDA, lib)
        println(io, "- $lib: ", mod.version())
    end
    println(io, "- CUPTI: ", has_cupti() ? CUPTI.version() : "missing")
    println(io, "- NVML: ", has_nvml() ? NVML.version() : "missing")
    println(io, "- CUDNN: ", has_cudnn() ? "$(CUDNN.version()) (for CUDA $(CUDNN.cuda_version()))" : "missing")
    println(io, "- CUTENSOR: ", has_cutensor() ? "$(CUTENSOR.version()) (for CUDA $(CUTENSOR.cuda_version()))" : "missing")
    println(io)

    println(io, "Toolchain:")
    println(io, "- Julia: $VERSION")
    println(io, "- LLVM: $(LLVM.version())")
    println(io, "- PTX ISA support: $(join(map(ver->"$(ver.major).$(ver.minor)", supported_toolchain().ptx), ", "))")
    println(io, "- Device capability support: $(join(map(ver->"sm_$(ver.major)$(ver.minor)", supported_toolchain().cap), ", "))")
    println(io)

    env = filter(var->startswith(var, "JULIA_CUDA"), keys(ENV))
    if !isempty(env)
        println(io, "Environment:")
        for var in env
            println(io, "- $var: $(ENV[var])")
        end
        println(io)
    end

    devs = devices()
    if isempty(devs)
        println(io, "No CUDA-capable devices.")
    elseif length(devs) == 1
        println(io, "1 device:")
    else
        println(io, length(devs), " devices:")
    end
    for (i, dev) in enumerate(devs)
        if has_nvml()
            mig = uuid(dev) != parent_uuid(dev)
            nvml_gpu = NVML.Device(parent_uuid(dev))
            nvml_dev = NVML.Device(uuid(dev); mig)

            str = NVML.name(nvml_dev)
            cap = NVML.compute_capability(nvml_gpu)
            mem = NVML.memory_info(nvml_dev)
        else
            str = name(dev)
            cap = capability(dev)
            mem = device!(dev) do
                # this requires a device context, so we prefer NVML
                (free=available_memory(), total=total_memory())
            end
        end
        println(io, "  $(i-1): $str (sm_$(cap.major)$(cap.minor), $(Base.format_bytes(mem.free)) / $(Base.format_bytes(mem.total)) available)")
    end
end

# this helper function encodes options for compute-sanitizer useful with Julia applications
function compute_sanitizer_cmd(tool::String="memcheck")
    sanitizer = CUDA.compute_sanitizer()
    `$sanitizer --tool $tool --launch-timeout=0 --target-processes=all --report-api-errors=no`
end

"""
    run_compute_sanitizer([julia_args=``]; [tool="memcheck", sanitizer_args=``])

Run a new Julia session under the CUDA compute-sanitizer tool `tool`. This is useful to
detect various GPU-related issues, like memory errors or race conditions.
"""
function run_compute_sanitizer(julia_args=``; tool::String="memcheck", sanitizer_args=``)
    cmd = Base.julia_cmd()

    # propagate --project
    if Base.JLOptions().project != C_NULL
        push!(test_exeflags.exec, "--project=$(unsafe_string(Base.JLOptions().project))")
    end

    println("Re-starting your active Julia session...")
    run(`$(CUDA.compute_sanitizer_cmd(tool)) $sanitizer_args $cmd $julia_args`)
end


text:
using Pkg; Pkg.activate(".")

using Rocket, AppliSales, AppliAR, AppliGeneralLedger, DataFrames, Query

# remove old stuff
cmd = `rm test_invoicing.txt test_invoicing_paid.txt test_ledger.txt test_journal.txt invoicenbr.txt`
run(cmd)

# create actors
a2 = lambda(
    on_next     = (d) -> begin
        AppliGeneralLedger.process([d])
    end,
    on_error    = (e) -> println(e),
    on_complete = ()  -> println("Completed a2")
)

a1 = lambda(
    on_next     = (d) -> begin
        entries = AppliAR.process([d])
        subscribe!(from(entries), a2)
    end,
    on_error    = (e) -> println(e),
    on_complete = ()  -> println("Completed a1")
)

a3 = lambda(
    on_next     = (d) -> begin
        unpaid_invoices = retrieve_unpaid_invoices()
        entries = AppliAR.process(unpaid_invoices, [d])
        subscribe!(from(entries), a2)
    end,
    on_error    = (e) -> println(e),
    on_complete = ()  -> println("Completed a3")
)

a0 = lambda(
    on_next     = (d) -> begin
        show(d)
        sales = AppliSales.process()
        array_source = from(sales)
        subscribe!(array_source, a1)

        sleep(10)

        try
            rm("./invoicenbr.txt")
            AppliAR.Infrastructure.add_to_file("./invoicenbr.txt", [1000])
        catch e
            AppliAR.Infrastructure.add_to_file("./invoicenbr.txt", [1000])
        end
        stms = AppliAR.read_bank_statements("./bank.csv")
        array_source2 = from(stms)
        s3 = subscribe!(array_source2, a3)
    end,
    on_error    = (e) -> println(e),
    on_complete = ()  -> println("Completed a3")
)

# start application
s0 = subscribe!(from([10]), a0)

using DataFrames

# check data
r2 = AppliGeneralLedger.read_from_file("./test_ledger.txt")
df2 = r2 |> @filter(_.accountid == 1300) |> DataFrame
println("\nAccounts receivable\n===================")
show(df2)

# unpais invoices
r1 = report(path_unpaid="./test_invoicing.txt", path_paid="./test_invoicing_paid.txt")
result = DataFrame(r1)
println("\nUnpaid invoices\n===============")
show(result)

# check general ledger
println("")
include("check_general_ledger.jl")
# end


text:
using SpecTools
using Graphs
using Test, Random

@testset "Base types" begin
  Random.seed!(2151)
  transitions = SpecTools.make_linear_levels(30) |> SpecTools.make_linear_transitions
  @test match_encoding(transitions, [0, 0, 1, 0]) == 1
  # test the matrix-ification of transitions
  tf = features(transitions)
  @test tf[:,1] == [200.0, 1.0, 0.0, 0.0, 1.0, 0.0]
  # test grabbing the upper state energy levels
  @test upper_state_qnos(transitions[1]) == [1, 0]
end

@testset "Graph types" begin
  levels = SpecTools.make_linear_levels(20)
  transitions = SpecTools.make_linear_transitions(levels)
  # test constructing the graph objects
  proj_graph = ProjectedSG(levels, transitions)
  @test proj_graph isa SpecTools.ProjectedSG
  bi_graph = BipartiteSG(levels, transitions)
  @test bi_graph isa SpecTools.BipartiteSG
  levels_graph = LevelsGraph(levels)
  @test levels_graph isa SpecTools.LevelsGraph
end

@testset "Lineshapes" begin
  @test Gaussian(1., 0., 0.5)(0.5) ≈ 0.48394144903
end

@testset "Partition structs" begin
  interp_obj = read_qpart("test.qpart")
  @test interp_obj isa SpecTools.InterpPartitionFunction
end

@testset "Partition function computation" begin
  @test partition_function(10_000, 1, 300f0) == 0.9984015312231446
end

@testset "Read PGopher" begin
  @test ~isempty(read_pgopher_linelist("test.csv"))
  @test ~isempty(read_pgopher_levels("test_levels.out"))
end

@testset "Graph analysis" begin
  levels = SpecTools.make_linear_levels(20)
  sg = LevelsGraph(levels)
  link_nodes_by_Δ!(sg)
  @test Graphs.ne(sg.graph) == 19
end


text:
module TestMeanVar

using DataTools
using DataTools: MeanVarState
using Statistics
using Test
using Transducers: Filter, Map, TeeRF

include("utils.jl")

reduce_bs1(args...; kw...) = reduce(args...; basesize = 1, kw...)

@testset for fold in [foldl, reduce_bs1, reduce]
    foldl = reduce = nothing

    @testset "accessors" begin
        s = fold(meanvar, Filter(isodd), 1:16)
        m, v, c = s
        @test Tuple(s) == (m, v, c) == (8.0, 24.0, 8)
        @test NamedTuple(s) == (mean = m, var = v, count = c)

        s = fold(meanvar, Filter(isodd), 1:10)
        @test mean(s) === mean(1:2:9) === 5.0
        @test var(s) === var(1:2:9) === var(s; corrected = true) === 10.0
        @test var(s; corrected = false) === var(1:2:9; corrected = false) === 8.0

        s = fold(meanvar, Filter(isodd), 1:96)
        @test mean(s) === mean(1:2:95) === 48.0
        @test var(s) === var(1:2:95) === 784.0
        @test std(s) === std(1:2:95) === 28.0
    end

    @testset "TeeRF" begin
        s1, s2 = fold(
            TeeRF(Filter(isodd)'(meanvar), Filter(iseven)'(meanvar)),
            Map(identity),
            1:96,
        )
        @test s1 isa MeanVarState
        @test s2 isa MeanVarState
        @test mean(s1) === 48.0
        @test mean(s2) === 49.0
        @test var(s1) === 784.0
        @test var(s2) === 784.0
    end

    @testset "oncol" begin
        snt = fold(
            oncol(odd = meanvar, even = meanvar),
            Map(x -> (odd = 2x - 1, even = 2x)),
            1:48,
        )
        @test snt.odd isa MeanVarState
        @test snt.even isa MeanVarState
        @test mean(snt.odd) === 48.0
        @test mean(snt.even) === 49.0
        @test var(snt.odd) === 784.0
        @test var(snt.even) === 784.0
    end
end

@testset "show and constructor" begin
    @testset "default type parameters" begin
        s = MeanVarState(mean = 8.0, count = 8, m2 = 168.0)
        @test s === MeanVarState(mean = 8.0, var = 24.0, count = 8)
        str = sprint(show, s; context = :limit => true)
        @test str == "MeanVarState(mean=8.0, var=24.0, count=8)"
        str = sprint(show, s; context = :limit => false)
        @test str == "DataTools.MeanVarState(mean=8.0, var=24.0, count=8, m2=168.0)"
    end

    @testset "non-default type parameters" begin
        s = MeanVarState{Any,Any,Any}(mean = 8.0, var = 24.0, count = 8)
        str = sprint(show, s; context = :limit => true)
        @test str ==ᵣ "MeanVarState{Any,Any,Any}(mean=8.0, var=24.0, count=8)"
        str = sprint(show, s; context = :limit => false)
        @test str ==ᵣ
              "DataTools.MeanVarState{Any,Any,Any}(mean=8.0, var=24.0, count=8, m2=168.0)"
    end
end

end  # module


text:
## port methods of series module of SymPy
## http://docs.sympy.org/0.7.2/modules/series.html

## simple methods (x, args) -> y (y coercion happens via PyCall)
series_sympy_meths = (#:limit
                      :gruntz,
                      :series, :Order, :O,
                      :residue,
                      :fourier_series
                      )

import Base: truncate

if VERSION < v"0.6.0-dev"
    eval(Expr(:import, :Base, :scale))
else
     eval(Expr(:export, :scale))
end
series_object_meths_base = (:truncate,
                            )

series_object_meths = (:shift, :shiftx, :scalex)


text:
#!/usr/bin/env julia

using ArgParse

function gcd(a::Int, b::Int)::Int
    while a != b
        if a > b
            a -= b
        else
            b -= a
        end
    end
    return a
end

function main()
    arg_parser = ArgParseSettings()
    arg_parser.description = "Compute the greatest common divisor of two integers"
    @add_arg_table arg_parser begin
        "a"
            arg_type = Int
            required = true
            help = "first integer"
        "b"
            arg_type = Int
            required = true
            help = "second integer"
    end
    options = parse_args(ARGS, arg_parser)

    println(gcd(options["a"], options["b"]))

    return 0
end

main()


text:
module CUDAdrv

using Printf

const ext = joinpath(dirname(@__DIR__), "deps", "ext.jl")
isfile(ext) || error("CUDAdrv.jl has not been built, please run Pkg.build(\"CUDAdrv\").")
include(ext)
if !configured
    # default (non-functional) values for critical variables,
    # making it possible to _load_ the package at all times.
    const libcuda_version = v"5.5"
    const libcuda_vendor = "none"
    const libcuda_path = nothing
end
const libcuda = libcuda_path

include("base.jl")

# CUDA Driver API wrappers
include("init.jl")
include("errors.jl")
include("version.jl")
include("devices.jl")
include("context.jl")
include(joinpath("context", "primary.jl"))
include("stream.jl")
include("pointer.jl")
include("memory.jl")
include("module.jl")
include("events.jl")
include("execution.jl")
include("profile.jl")

include("deprecated.jl")

end


text:
using Printf

function inter_node_num_mistakes(labels_in_node::AbstractVector{T}) where {T <: Real}
  n = length(labels_in_node)
  n == 0 && return 0  ## Corner case

  n_pos = sum(labels_in_node .== 1)  ## Count the number of 1's (safe loans)
  n_neg = n - n_pos ## or(labels_in_node == -1).sum()

  ## Return the number of mistakes that the majority classifier makes.
  return n_pos ≥ n_neg ? n_neg : n_pos
end

function best_splitting_feature(df::DF, features::Vector{Symbol},
                                target::Symbol) where {DF <: Union{DataFrame, SubDataFrame}}
  best_feature, best_error = nothing, 2
  ## Note: Since error is always ≤ 1, init best_error with something > 1

  num_data_points = size(df)[1]
  for f ∈ features
    l_split = df[df[!, f] .== 0, :]
    r_split = df[df[!, f] .== 1, :]

    l_mistakes = inter_node_num_mistakes(l_split[!, target])
    r_mistakes = inter_node_num_mistakes(r_split[!, target])

    error = (l_mistakes + r_mistakes) / num_data_points
    if error < best_error
      best_error = error
      best_feature = f
    end
  end

  best_feature
end

function create_leaf(target_values;
                     splitting_feature=nothing, left=nothing, right=nothing, is_leaf=true)
  ## Create a leaf node
  leaf = Dict{Symbol, Any}(
                           :splitting_feature => splitting_feature,
                           :prediction => nothing,
                           :left => left,
                           :right => right,
                           :is_leaf => is_leaf,
                           )

  if is_leaf
    ## Count the number of data points that are +1 and -1 in this node.
    num_1s = length(target_values[target_values .== 1, :])
    num_minus_1s = length(target_values[target_values .== -1, :])

    ## For the leaf node, set the prediction to be the majority class.
    ## Store the predicted class (1 or -1) in leaf['prediction']
    leaf[:prediction] = num_1s > num_minus_1s ? 1 : -1
  end

  return leaf
end

function count_nodes(tree)
    isnothing(tree) || tree[:is_leaf] ?
    1 : 1 + count_nodes(tree[:left]) + count_nodes(tree[:right])
end

function count_leaves(tree)
    isnothing(tree) || tree[:is_leaf] ?
    1 : count_nodes(tree[:left]) + count_nodes(tree[:right])
end

function classify(tree, x::DataFrameRow; annotate=false)
  # if the node is a leaf node.
  if tree[:is_leaf]
    annotate && @printf("At leaf, predicting %s\n", tree[:prediction])
    return tree[:prediction]
  end

  ## split on feature.
  split_feature_value = x[tree[:splitting_feature]]
  annotate &&
    @printf("Split on %s => %s\n", tree[:splitting_feature], split_feature_value)

  split_feature_value == 0 ? classify(tree[:left], x; annotate) :
    classify(tree[:right], x; annotate)
end

function eval_classification_error(tree, df::DF,
                                   target::Symbol) where {DF <: Union{DataFrame, SubDataFrame}}
  ## 1. get the predictions
  ŷ = map(x -> classify(tree, x), eachrow(df))

  ## 2. calculate the classification error
  num_mistakes = sum(ŷ .≠ df[!, target])
  return num_mistakes / size(df)[1]
end


text:
using DLMReader, InMemoryDatasets
using Test
dir = joinpath(dirname(pathof(DLMReader)), "..", "test", "csvfiles")
@testset "general usage" begin
    ds = filereader(IOBuffer("a,b\n1,,,2\n3,,,,,,,4\n"), ignorerepeated = true, header = true)
    @test ds == Dataset(a=[1,3], b=[2,4])
    ds = filereader(IOBuffer("a,b\n1,,,2\n3,,,,,,,4.1\n"), ignorerepeated = true, header = true)
    @test ds == Dataset(a=[1,3], b=[2,4.1])
    ds = filereader(IOBuffer("""a,b\n1,,,"HL, WORLD"\n3,,,,,,,"XY"\n"""), ignorerepeated = true, header = true, quotechar = '"')
    @test ds == Dataset(a = [1,3], b = ["HL, WORLD", "XY"])
    ds = filereader(IOBuffer("""a\tb\n1\t\t\t"HL, WORLD"\n3\t\t\t\t\t\t\t"XY"\n"""), ignorerepeated = true, header = true, quotechar = '"', delimiter = '\t')
    @test ds == Dataset(a = [1,3], b = ["HL, WORLD", "XY"])
    ds = filereader(joinpath(dir, "repeat1.csv"), ignorerepeated = true, header = true, quotechar = '"', delimiter = '\t')
    @test ds == Dataset(a = [1,3], b = ["HL, \"WORLD\"", "XY"])
    ds = filereader(joinpath(dir, "repeat2.csv"), ignorerepeated = true, header = true, quotechar = '"', escapechar = '"', delimiter = '\t')
    @test ds == Dataset(a = [1,3], b = ["HL, \"WORLD\"", "XY"])
    ds = filereader(IOBuffer("a,b\n1,2\n"), header = false)
    @test ds == Dataset(x1=["a","1"], x2=["b","2"])
    ds = filereader(joinpath(dir, "d2.csv"), dtformat = Dict(3=>dateformat"y-m-d"), informat = Dict(3=>CHAR_NA!))
    @test ds == Dataset(a = [1,2,2,1], b=[2,3,4,2], c = Date.([missing, "2001-01-02", "2020-04-02", "2000-12-01"]))
    ds = filereader(joinpath(dir, "dlmstr.csv"), dlmstr = "::")
    @test ds == Dataset(a=[12,12], b=[1345,13], C=[15,15], DD=[15,1])
    ds = filereader(joinpath(dir, "dollar.csv"), header = false, delimiter = ' ', informat = Dict(2=>COMMA!))
    @test ds == Dataset(x1 =["id1","id2","id3"], x2=[2000000,34000, missing], x3=[3,4,1])
    ds = filereader(joinpath(dir, "dollar2.csv"), header = false, delimiter=';', informat = Dict(1:2 .=> COMMA!))
    @test ds == Dataset(x1=[1000, 123000,1000], x2=[2000,2,2000], x3=["Hi", "Boy", "Hi"])
    ds = filereader(joinpath(dir, "multi.dat"), delimiter = [',',':',';'])
    @test ds == Dataset(x1=[1,2], x2=[2,4],x3=[123,4], x4=[3,5])
    ds = filereader(joinpath(dir, "t.txt"), dlmstr = "::;;:", quotechar = '"', escapechar = '"', header = false)
    @test ds == Dataset(x1 =["this is tha\" and this", "th\"at\"", missing], x2=[23,25,544],x3=[45,35,454])
    ds = Dataset(x1 = "id" .* string.(rand(1:10, 10000)), x2 = rand(1:100000, 10000), x3 = 1:10000)
    map!(ds, x->rand()<.1 ? missing : x, 1:2)
    _tmp_file = tempname()
    filewriter(_tmp_file, ds, header = false)
    ds2 = filereader(_tmp_file, types = [String, Int, Int], header =false)
    @test ds == ds2
    for i in 1:100
        r_loc = rand(1:10000)
        ds3 = filereader(_tmp_file, types = [String, Int, Int], header =false, skipto = r_loc, limit = 5000)
        @test ds3[1, 3] == r_loc
        @test ds3[end, 3] == min(r_loc+5000-1, nrow(ds))
    end
end

@testset "multiple observations per line" begin
    ds = filereader(IOBuffer("a,b\n1,2\n"), header = false, multiple_obs = true, types = [String, String])
    @test ds == Dataset(x1=["a","1"], x2=["b","2"])
    ds = filereader(joinpath(dir, "t.txt"), dlmstr = "::;;:", quotechar = '"', escapechar = '"', header = false, multiple_obs = true, types = [String, Int, Int])
    @test ds == Dataset(x1 =["this is tha\" and this", "th\"at\"", missing], x2=[23,25,544],x3=[45,35,454])
    ds = filereader(IOBuffer("""a\tb\n1\t\t\t"HL, WORLD"\n3\t\t\t\t\t\t\t"XY"\n"""), ignorerepeated = true, header = false, quotechar = '"', delimiter = '\t', types = [String, String], multiple_obs = true)
    @test ds == Dataset(x1 = ["a","1","3"], x2 = ["b", "HL, WORLD", "XY"])
    @test_throws ArgumentError filereader(IOBuffer("""a\tb\n1\t\t\t"HL, WORLD"\n3\t\t\t\t\t\t\t"XY"\n"""), ignorerepeated = true, header = true, quotechar = '"', delimiter = '\t', types = [String, String], multiple_obs = true)
    ds = filereader(joinpath(dir, "multi2.dat"), types = [Int, Int], delimiter = [',', ';'], header = false, multiple_obs = true)
    @test ds == Dataset(x1=[1,123,4,4,5], x2=[2,3,2,4,missing])
    ds = filereader(joinpath(dir, "multi2.dat"), types = [Int, Float64], delimiter = [',', ';'], header = false, multiple_obs = true)
    @test ds == Dataset(x1=[1,123,4,4,5], x2=[2,3,2,4,missing])
    @test eltype(ds[:,2]) <: Union{Missing, Float64}

    ds = filereader(joinpath(dir, "test1.csv"), types = [Int32, Int32, Date, Float32, Characters{2}], multiple_obs=true, informat = Dict(1:5 .=> CHAR_NA!), header=[:x1, :x2, :x3, :x4, :x5], quotechar = '"')
    @test ds == Dataset([Union{Missing, Int32}[12, 1, 2, missing], Union{Missing, Int32}[12, 2, 4, missing], Union{Missing, Date}[Date("2020-01-01"), Date("2012-01-02"), Date("2005-01-01"), Date("2005-01-01")], Union{Missing, Float32}[1.2f0, 2.3f0, 1.3f0, 1.3f0], Union{Missing, Characters{2, UInt8}}["a1", "a2", "a3", missing]], [:x1, :x2, :x3, :x4, :x5])
    ds = filereader(joinpath(dir, "test1.csv"), types = [Int32, Int32, Date, Float32, String3], multiple_obs=true, informat = Dict(1:5 .=> CHAR_NA!), header=[:x1, :x2, :x3, :x4, :x5], quotechar = '"')
    @test ds == Dataset([Union{Missing, Int32}[12, 1, 2, missing], Union{Missing, Int32}[12, 2, 4, missing], Union{Missing, Date}[Date("2020-01-01"), Date("2012-01-02"), Date("2005-01-01"), Date("2005-01-01")], Union{Missing, Float32}[1.2f0, 2.3f0, 1.3f0, 1.3f0], Union{Missing, Characters{2, UInt8}}["a1", "a2", "a3", missing]], [:x1, :x2, :x3, :x4, :x5])
    ds = filereader(joinpath(dir, "test1.csv"), types = [Int32, Int32, Date, Float32, String], multiple_obs=true, informat = Dict(1:5 .=> CHAR_NA!), header=[:x1, :x2, :x3, :x4, :x5], quotechar = '"')
    @test ds == Dataset([Union{Missing, Int32}[12, 1, 2, missing], Union{Missing, Int32}[12, 2, 4, missing], Union{Missing, Date}[Date("2020-01-01"), Date("2012-01-02"), Date("2005-01-01"), Date("2005-01-01")], Union{Missing, Float32}[1.2f0, 2.3f0, 1.3f0, 1.3f0], Union{Missing, Characters{2, UInt8}}["a1", "a2", "a3", missing]], [:x1, :x2, :x3, :x4, :x5])
end


text:
using BibTeX

function ref_item(ref, infos)
    io = IOBuffer()
    authors_aux = strip.(split(infos["author"], " and "))
    m = size(authors_aux)[1]
    authors = ""
    for j in 1:m
        a = authors_aux[j]
        fullname = reverse(strip.(split(a, ",")))
        n = size(fullname)[1]
        for i in 1:n-1
            authors *= fullname[i]*" "
        end
        authors *= fullname[n]
        if j == m
            authors *= ". "
        else
            authors *= ", "
        end
    end
    url = replace(infos["url"], " " => "")
    write(io, "
")
    write(io, """""")
    write(io, """$(infos["title"])""")
    write(io, "
")
    write(io, """$authors
""")
    write(io, """$(infos["journal"]) ($(infos["year"])). """)
    if haskey(infos, "doi")
        write(io, """DOI:$(infos["doi"]). """)
    end
    write(io, "
")
    write(io, "
")
    return String(take!(io))
end

function hfun_show_refs(refs)
    _, allrefs = parse_bibtex(read(joinpath("_assets", "julialab.bib"), String))
    out = IOBuffer()
    write(out, "
")
    for ref in refs
        infos = get(allrefs, ref, nothing)
        isnothing(infos) && continue
        write(out, ref_item(ref, infos))
    end
    write(out, "
")
    return String(take!(out))
end

function hfun_bar(vname)
  val = Meta.parse(vname[1])
  return round(sqrt(val), digits=2)
end

function hfun_m1fill(vname)
  var = vname[1]
  return pagevar("index", var)
end

function lx_baz(com, _)
  # keep this first line
  brace_content = Franklin.content(com.braces[1]) # input string
  # do whatever you want here
  return uppercase(brace_content)
end


text:
@safetestset "isiban" begin
    using Validator

    @test Validator.isiban("SC52BAHL01031234567890123456USD") === true
    @test Validator.isiban("LC14BOSL123456789012345678901234") === true
    @test Validator.isiban("MT31MALT01100000000000000000123") === true
    @test Validator.isiban("SV43ACAT00000000000000123123") === true
    @test Validator.isiban("EG800002000156789012345180002") === true
    @test Validator.isiban("BE71 0961 2345 6769") === true
    @test Validator.isiban("FR76 3000 6000 0112 3456 7890 189") === true
    @test Validator.isiban("DE91 1000 0000 0123 4567 89") === true
    @test Validator.isiban("GR96 0810 0010 0000 0123 4567 890") === true
    @test Validator.isiban("RO09 BCYP 0000 0012 3456 7890") === true
    @test Validator.isiban("SA44 2000 0001 2345 6789 1234") === true
    @test Validator.isiban("ES79 2100 0813 6101 2345 6789") === true
    @test Validator.isiban("CH56 0483 5012 3456 7800 9") === true
    @test Validator.isiban("GB98 MIDL 0700 9312 3456 78") === true
    @test Validator.isiban("IL170108000000012612345") === true
    @test Validator.isiban("IT60X0542811101000000123456") === true
    @test Validator.isiban("JO71CBJO0000000000001234567890") === true
    @test Validator.isiban("TR320010009999901234567890") === true
    @test Validator.isiban("BR1500000000000010932840814P2") === true
    @test Validator.isiban("LB92000700000000123123456123") === true
    @test Validator.isiban("IR200170000000339545727003") === true
    @test Validator.isiban("MZ97123412341234123412341") === true

    @test Validator.isiban("XX22YYY1234567890123") === false
    @test Validator.isiban("FR14 2004 1010 0505 0001 3") === false
    @test Validator.isiban("FR7630006000011234567890189@") === false
end


text:
"""
Bridges `CP.GlobalCardinality` to `CP.GlobalCardinalityVariable`.
"""
struct GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T} <: MOIBC.AbstractBridge
    vars::Vector{MOI.VariableIndex}
    vars_int::Vector{MOI.ConstraintIndex{MOI.VariableIndex, MOI.Integer}}
    cons_eq::Vector{MOI.ConstraintIndex{MOI.VariableIndex, MOI.EqualTo{T}}}
    con_gcv::MOI.ConstraintIndex{MOI.VectorAffineFunction{T}, CP.GlobalCardinality{CP.VARIABLE_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T}}
end

function MOIBC.bridge_constraint(
    ::Type{GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}},
    model,
    f::MOI.VectorOfVariables,
    s::CP.GlobalCardinality{CP.FIXED_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T},
) where {T}
    return MOIBC.bridge_constraint(
        GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
        model,
        MOI.VectorAffineFunction{T}(f),
        s,
    )
end

function MOIBC.bridge_constraint(
    ::Type{GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}},
    model,
    f::MOI.VectorAffineFunction{T},
    s::CP.GlobalCardinality{CP.FIXED_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T},
) where {T}
    # Create the variables that contain the values that are counted.
    if T <: Integer
        vars, vars_int = MOI.add_constrained_variables(
            model,
            [MOI.Integer() for _ in 1:length(s.values)]
        )
    else
        vars = MOI.add_variables(model, length(s.values))
        vars_int = MOI.ConstraintIndex{MOI.VariableIndex, MOI.Integer}[]
    end

    # Constrain these variables to take the sought (fixed) values.
    cons_eq = [
        MOI.add_constraint(
            model,
            vars[i],
            MOI.EqualTo(s.values[i])
        )
        for i in 1:length(s.values)
    ]

    # Create the new global-cardinality constraint.
    f_scalars = MOIU.scalarize(f)
    con_gcv = MOI.add_constraint(
        model,
        MOIU.vectorize(
            [
                f_scalars...,
                (one(T) .* vars)...
            ]
        ),
        CP.GlobalCardinality{CP.VARIABLE_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T}(s.dimension, length(s.values))
    )

    return GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge(vars, vars_int, cons_eq, con_gcv)
end

function MOI.supports_constraint(
    ::Type{GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}},
    ::Union{Type{MOI.VectorOfVariables}, Type{MOI.VectorAffineFunction{T}}},
    ::Type{CP.GlobalCardinality{CP.FIXED_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T}},
) where {T}
    return true
end

function MOIB.added_constrained_variable_types(::Type{GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}}) where {T <: Integer}
    return [(MOI.Integer,)]
end

function MOIB.added_constrained_variable_types(::Type{GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}}) where {T}
    return Tuple{Type}[]
end

function MOIB.added_constraint_types(::Type{GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}}) where {T}
    return [
        (MOI.VariableIndex, MOI.EqualTo{T}),
        (MOI.VectorAffineFunction{T}, CP.GlobalCardinality{CP.VARIABLE_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T}),
    ]
end

function MOI.get(b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T}, ::MOI.NumberOfVariables) where {T}
    return length(b.vars)
end

function MOI.get(
    b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.NumberOfConstraints{
        MOI.VariableIndex, MOI.Integer,
    },
) where {T}
    return length(b.vars_int)
end

function MOI.get(
    b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.NumberOfConstraints{
        MOI.VariableIndex, MOI.EqualTo{T},
    },
) where {T}
    return length(b.cons_eq)
end

function MOI.get(
    ::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.NumberOfConstraints{
        MOI.VectorAffineFunction{T}, CP.GlobalCardinality{CP.VARIABLE_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T},
    },
) where {T}
    return 1
end

function MOI.get(
    b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.ListOfVariableIndices,
) where {T}
    return copy(b.vars)
end

function MOI.get(
    b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.ListOfConstraintIndices{
        MOI.VariableIndex, MOI.Integer,
    },
) where {T}
    return copy(b.vars_int)
end

function MOI.get(
    b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.ListOfConstraintIndices{
        MOI.VariableIndex, MOI.EqualTo{T},
    },
) where {T}
    return copy(b.cons_eq)
end

function MOI.get(
    b::GlobalCardinalityFixedOpen2GlobalCardinalityVariableOpenBridge{T},
    ::MOI.ListOfConstraintIndices{
        MOI.VectorAffineFunction{T}, CP.GlobalCardinality{CP.VARIABLE_COUNTED_VALUES, CP.OPEN_COUNTED_VALUES, T},
    },
) where {T}
    return [b.con_gcv]
end


text:
module CovPlots

using ..PFB: targets

using Base.Threads
using Printf, Statistics

using CSV
using DataFrames
using HypothesisTests
using StatsPlots

function __init__()
    theme(:ggplot2)
    gr(size=(600, 400) .* 1.2)
end

const UNITKEYS = [:time, :fuzzer, :run]
const VALUECOLS = [:l_per, :l_abs, :b_per, :b_abs]

PALETTE = palette(:seaborn_colorblind)
COLORMAP = Dict("aflnet" => PALETTE.colors.colors[1],
                "aflnet-no-state" => PALETTE.colors.colors[2],
                "aflnwe" => PALETTE.colors.colors[3],
                "aflpp" => PALETTE.colors.colors[8],
                "nyx" => PALETTE.colors.colors[5],
                "nyx-newspec" => PALETTE.colors.colors[6],
                "nyx-balanced" => PALETTE.colors.colors[7],
                "nyx-aggressive" => PALETTE.colors.colors[4])

struct TargetData
    df::DataFrame
    agg::DataFrame
    runslastcov::DataFrame
    target::String
end

"Parse CSV with runs for different fuzzers on a single target"
function getruns(csvpath::String, cutoff::UInt)::Union{TargetData, Nothing}
    df = DataFrame(CSV.File(csvpath))
    println("$csvpath: retrieved $(nrow(df)) rows")
    nrow(df) > 0 || return

    target = unique(df.subject)[1]

    # transform time to relative to the first per run
    udf = unstack(df, UNITKEYS, :cov_type, :cov, allowduplicates=true)
    disallowmissing!(udf)
    fuzzerruns = groupby(udf, [:fuzzer, :run])
    # time from seconds to minutes since first in fuzzer run
    transform!(fuzzerruns, :time => (t -> (t .- minimum(t)) .÷ 60) => :time)

    # fill missing values at all times (i.e. 0 to cutoff)
    filled = DataFrame()
    for gd in fuzzerruns
        fullrun = DataFrame(time=0:cutoff, fuzzer=gd[1, :fuzzer], run=gd[1, :run])
        # pick highest values for the same fuzzer / run / time
        gd = combine(groupby(gd, UNITKEYS), VALUECOLS .=> maximum .=> VALUECOLS)
        # join with full times
        append!(filled, leftjoin(fullrun, gd, on=UNITKEYS))
    end
    sort!(filled, [:fuzzer, :run, :time])
    # forward-fill values
    for col in VALUECOLS
        filled[!, col] = accumulate((n0,n1) -> ismissing(n1) ? n0 : n1,
                                    filled[:, col],
                                    init=zero(eltype(filled[:, col])))
    end
    disallowmissing!(filled)
    TargetData(filled, aggruns(filled), getlatestcov(filled), target)
end

"Aggregate across runs"
aggruns(data::TargetData)::DataFrame = aggruns(data.df)
aggruns(df::DataFrame)::DataFrame =
    combine(groupby(df, [:fuzzer, :time]),
            VALUECOLS .=> repeat([mean, median], 2) .=> VALUECOLS)

"Get latest coverage (`b_abs`) for each run of each fuzzer"
getlatestcov(data::TargetData) = getlatestcov(data.df)
getlatestcov(df::DataFrame) =
    combine(groupby(df, [:fuzzer, :run]), :b_abs => last => :cov)

"Create coverage plot"
function makeplot(data::TargetData, layout::Symbol=:pfb)::Plots.Plot
    fuzzers = unique(data.agg.fuzzer)
    cs = [COLORMAP[f] for f in fuzzers]
    timeformatter(x) = @sprintf("%2.0fh", x ÷ 60)
    if layout == :branches
        p1 = @df data.agg plot(:time, :b_abs, group=:fuzzer, title=data.target, color_palette=cs,
                               legend=:bottomright, linewidth=2, yguide="branches",
                               xformatter=timeformatter)
        get(f) = @view data.runslastcov[data.runslastcov.fuzzer .== f, :]
        tickrotation = 20
        p2 = @df get(fuzzers[1]) boxplot(:fuzzer, :cov, xrotation=tickrotation, xtickfontsize=6,
                                         label=nothing, color=COLORMAP[fuzzers[1]])
        for f in fuzzers[2:end]
            @df get(f) boxplot!(:fuzzer, :cov, xrotation=tickrotation,
                                label=nothing, color=COLORMAP[f])
        end
        @df data.runslastcov dotplot!(:fuzzer, :cov, marker=(:black, stroke(0)), label=nothing)
        return plot(p1, p2)
    elseif layout == :pfb
        yticks = [0:20:100;]
        percformatter = y -> @sprintf("%2.1f%%", y)
        p1 = @df data.agg plot(:time, :b_abs, group=:fuzzer, title=data.target, color_palette=cs,
                               legend=:bottomright, yguide="branches", xformatter=timeformatter)
        p2 = @df data.agg plot(:time, :b_per, group=:fuzzer, title=data.target, color_palette=cs,
                               legend=:best, yformatter=percformatter, xformatter=timeformatter)
        p3 = @df data.agg plot(:time, :l_abs, group=:fuzzer, title=data.target, color_palette=cs,
                               legend=:bottomright, yguide="lines", xformatter=timeformatter)
        p4 = @df data.agg plot(:time, :l_per, group=:fuzzer, title=data.target, color_palette=cs,
                               legend=:best, yformatter=percformatter, xformatter=timeformatter)
        return plot(p1, p2, p3, p4, layout=(2, 2))
    else
        error("Unexpected layout $layout")
    end
end

"Process multiple targets selectable from a menu, given tha parent directory"
function multiple(dir::String, cutoff::UInt;
        layout=:pfb, seldirs=false, latex=false, nyxsumm=true, signconf=0.05)
    options, choices = targets(dir, seldirs)
    length(choices) > 0 || return

    # iterators are not thread safe
    selected = options[collect(choices)]

    outpath_suffix = layout == :branches ? "br" : "all"

    # collect aggregated runs for selected targets
    dfs = Dict()
    sizehint!(dfs, length(selected))
    @threads for targetdir in selected
        if seldirs
            csvpath = joinpath(targetdir, "results.csv")
            outpath = joinpath(dirname(csvpath), "coverage_$outpath_suffix.pdf")
        else
            csvpath = targetdir
            base, _ = splitext(targetdir)
            outpath = base*"_$outpath_suffix.pdf"
        end
        runs = getruns(csvpath, cutoff)
        if runs != nothing
            dfs[csvpath] = (runs, outpath, significance(runs, signconf))
        end
    end

    # the plotting library is not thread safe
    summ = DataFrame()
    for (csvpath, (runs, outpath, sign)) in dfs
        if layout != nothing
            p = makeplot(runs, layout)
            savefig(p, outpath)
        end
        if nyxsumm
            append!(summ, sign[startswith.(sign.vs, "nyx"), :])
        else
            append!(summ, sign)
        end
    end
    sort!(summ, :target)
    io = IOBuffer()
    show(io, MIME("text/"*(latex ? "latex" : "plain")), summ;
         eltypes=false, show_row_number=false, summary=false)
    println(String(take!(io)))
    return summ
end

"Compute and return pairwise Mann-Whitney-U test on final median branch coverage"
function significance(data::TargetData, conf::Real)::DataFrame
    fuzzers = ["aflnet", "aflnet-no-state", "aflnwe", "aflpp",
               "nyx", "nyx-newspec", "nyx-balanced", "nyx-aggressive"]
    tab = DataFrame("target" => String[],
                    "vs" => String[],
                    "aflnet" => Union{String, Missing}[],
                    "aflnet-no-state" => Union{String, Missing}[],
                    "aflnwe" => Union{String, Missing}[],
                    "aflpp" => Union{String, Missing}[],
                    "nyx" => Union{String, Missing}[],
                    "nyx-newspec" => Union{String, Missing}[],
                    "nyx-balanced" => Union{String, Missing}[],
                    "nyx-aggressive" => Union{String, Missing}[])
    for fuzz_i in fuzzers
        d = Dict{String, Union{String, Missing}}("vs" => fuzz_i, "target" => data.target)
        for f in fuzzers
            d[f] = missing
        end
        for fuzz_j in fuzzers
            (fuzz_i == fuzz_j) && continue
            runs_i = @view data.runslastcov[data.runslastcov.fuzzer .== fuzz_i, :cov]
            runs_j = @view data.runslastcov[data.runslastcov.fuzzer .== fuzz_j, :cov]
            (length(runs_i) == 0 || length(runs_j) == 0) && continue
            test = MannWhitneyUTest(runs_i, runs_j)
            ρ = pvalue(test)
            d[fuzz_j] = @sprintf("%8.1f %c", test.median, ρ < conf ? "✓" : "x")
        end
        push!(tab, d)
    end
    return tab
end

function loadall(dir::String; fixaflnwe=false)
    options, choices = targets(dir, false)
    length(choices) > 0 || return
    selected = options[collect(choices)]
    df = DataFrame()
    for targetfile in selected
        runs = getruns(targetfile, UInt(1440))
        if runs != nothing
            insertcols!(runs.df, 1, :target => runs.target)
            append!(df, runs.df)
        end
    end
    select!(df, :target, :fuzzer, :run, :time, :b_abs => :cov)
    !fixaflnwe && return df
    df_cp = DataFrame()
    old_val = 0
    for r in eachrow(df)
        if r.fuzzer == "aflnwe" && r.target == "forked-daapd"
            if r.cov < old_val
                r.cov = old_val
            else
                old_val = r.cov
            end
        end
        push!(df_cp, r)
    end
    return df_cp
end

function mktable(df::DataFrame; noseeds=false)
    if noseeds
        baseline_fuzz = "aflnet-no-state"
        other_fuzzs = ["nyx-aggressive"]
        table = DataFrame("target"=>[],
                          baseline_fuzz=>[],
                          # "nyx-aggressive Δ"=>[],
                          "nyx-aggressive %"=>[])
    else
        baseline_fuzz = "aflnet"
        other_fuzzs = ["aflnet-no-state", "aflnwe", "aflpp", "nyx", "nyx-balanced", "nyx-aggressive"]
        table = DataFrame("target"=>[],
                          baseline_fuzz=>[],
                          # "aflnet-no-state Δ"=>[],
                          "aflnet-no-state %"=>[],
                          # "aflnwe Δ"=>[],
                          "aflnwe %"=>[],
                          # "aflpp Δ"=>[],
                          "aflpp %"=>[],
                          # "nyx Δ"=>[],
                          "nyx %"=>[],
                          # "nyx-balanced Δ"=>[],
                          "nyx-balanced %"=>[],
                          # "nyx-aggressive Δ"=>[],
                          "nyx-aggressive %"=>[])
    end
    for gd in groupby(df, :target)
        baseline = @view gd[gd.fuzzer .== baseline_fuzz, :]
        baseline_last = combine(groupby(baseline, :run), :cov => last => :last_cov)
        row = Dict()
        row["target"] = gd.target[1]
        baseline_med = median(baseline_last.last_cov)
        @show row[baseline_fuzz] = "\$$baseline_med\$"
        for fuzz in other_fuzzs
            fuzz == baseline_fuzz && continue
            if !any(gd.fuzzer .== fuzz)
                # row["$fuzz Δ"] = "n/a"
                row["$fuzz %"] = "n/a"
                continue
            end
            fuzz_data = @view gd[gd.fuzzer .== fuzz, :]
            fuzz_last = combine(groupby(fuzz_data, :run), :cov => last => :last_cov)
            test = MannWhitneyUTest(fuzz_last.last_cov, baseline_last.last_cov)
            perc = (median(fuzz_last.last_cov) - baseline_med) / (baseline_med / 100)
            if pvalue(test) < 0.05
                # row["$fuzz Δ"] = @sprintf("\$\\mathbf{%+.1f}\$", test.median)
                row["$fuzz %"] = @sprintf("\$\\mathbf{%+.1f\\%%}\$", perc)
            else
                # row["$fuzz Δ"] = @sprintf("\$%+.1f\$", test.median)
                row["$fuzz %"] = @sprintf("\$%+.1f\\%%\$", perc)
            end
        end
        push!(table, row, cols=:subset)
    end
    sort!(table, :target)
    for row in eachrow(table)
        println(join(Tuple(row), " & "), "\\\\")
    end
    return table
end

function timetocov(df::DataFrame)
    baseline_fuzz = "aflnet"
    # other_fuzzs = ["aflnet-no-state", "aflnwe", "aflpp", "nyx", "nyx-balanced", "nyx-aggressive"]
    other_fuzzs = ["nyx", "nyx-balanced", "nyx-aggressive"]
    table = DataFrame("target"=>[], "nyx"=>[], "nyx-balanced"=>[], "nyx-aggressive"=>[])
    for gd in groupby(df, :target)
        baseline = @view gd[gd.fuzzer .== baseline_fuzz, :]
        baseline_meds = combine(groupby(baseline, :time), :cov => median => :med_cov)
        baseline_med = last(baseline_meds.med_cov)
        baseline_med_time = first(baseline_meds[baseline_meds.med_cov .>= baseline_med, :time])
        row = Dict{String, Any}("target" => gd.target[1])
        for fuzz in other_fuzzs
            # for each run, find time to baseline median last cov
            fuzz_data = @view gd[gd.fuzzer .== fuzz, :]
            fuzz_meds = combine(groupby(fuzz_data, :time), :cov => median => :med_cov)
            ttcov = fuzz_meds[fuzz_meds.med_cov .>= baseline_med, :time]
            if length(ttcov) > 0
                ttcov = ttcov[1]
                # perc = (ttcov - baseline_med_time) / (baseline_med_time / 100)
                # perc = (baseline_med_time - ttcov) / (baseline_med_time / 100)
                # row[fuzz] = @sprintf("%.2f%%", perc)
                row[fuzz] = "$ttcov $baseline_med_time"
            else
                row[fuzz] = "-"
            end
        end
        push!(table, row, cols=:union)
    end
    sort!(table, "target")
    return table
end

getfuzzname(f) =
    if f == "nyx"
        "nyxnet-none"
    elseif f == "nyx-aggressive"
        "nyxnet-aggressive"
    elseif f == "nyx-balanced"
        "nyxnet-balanced"
    else
        f
    end

LINE_TYPES = Dict(
                  "aflnet" => :dot,
                  "nyx" => :dash,
                  "nyx-balanced" => :dashdot,
                  "nyx-aggressive" => :solid,
                  "aflnet-no-state" => :dash,
                  "aflnwe" => :dot,
                  "aflpp" => :dashdot,
                 )

function mkplotpaper(df::DataFrame, extra_target::String, first_target::String="kamailio";
        alltargets=false, allfuzz=false, noseeds=false, fixaflnwe=false)
    @assert extra_target != first_target
    selected_fuzzers = allfuzz ?
        ["aflnet", "aflnet-no-state", "aflnwe", "aflpp", "nyx", "nyx-balanced", "nyx-aggressive"] :
        ["aflnet", "nyx", "nyx-balanced", "nyx-aggressive"]
    ps = []
    timeformatter(x) = @sprintf("%2.0fh", x ÷ 60)
    sort!(df, :target)
    df[!, :time] = df.time .+ 1
    agg = combine(groupby(df, [:target, :fuzzer, :time]), :cov => median => :med_cov)
    if fixaflnwe
        agg_cp = DataFrame()
        old_val = 0
        for r in eachrow(agg)
            if r.fuzzer == "aflnwe" && r.target == "forked-daapd"
                if r.med_cov < old_val
                    r.med_cov = old_val
                else
                    old_val = r.med_cov
                end
            end
            push!(agg_cp, r)
        end
        agg = agg_cp
    end
    extra_plot = nothing
    extra_plot_2 = nothing
    first_p = nothing
    pic_size = (400, 400) .* 0.8
    idx_multiplot = 1
    for gd in groupby(agg, :target)
        target = gd.target[1]
        gd = filter(:fuzzer => f -> f in selected_fuzzers, gd; view=false)
        fuzzers = unique(gd.fuzzer)
        cs = [COLORMAP[f] for f in fuzzers]
        label_fuzzers = permutedims([getfuzzname(f) for f in fuzzers])
        line_types = permutedims([LINE_TYPES[f] for f in fuzzers])
        if target == extra_target
            mkextra(leg) = @df gd plot(:time, :med_cov, group=:fuzzer, title=target, color_palette=cs,
                                    line=line_types,
                                    legend=leg ? :bottomright : false,
                                    label=label_fuzzers,
                                    yguide="Branches",
                                    xformatter=timeformatter,
                                    xticks=0:240:1440,
                                    linewidth=alltargets ? 2 : 1,
                                    size=pic_size,
                                   )
            extra_plot = mkextra(true)
            extra_plot_2 = mkextra(false)
        else
            yguide = target == first_target ? "Branches" : ""
            legend = (!alltargets && idx_multiplot == 12) ? :bottomright : false
            p = @df gd plot(:time, :med_cov, group=:fuzzer, title=target, color_palette=cs,
                            line=line_types,
                            legend=legend,
                            label=label_fuzzers,
                            yguide=yguide,
                            xticks=0:240:1440,
                            xformatter=timeformatter,
                            linewidth=2,
                           )
            if target == first_target
                first_p = p
            else
                push!(ps, p)
            end
            idx_multiplot += 1
        end
    end
    pic_size_scaled = pic_size .* 0.8
    if noseeds
        grid_l = [2, 6]
        ps = [first_p ps... extra_plot]
    else
        grid_l = alltargets ? [2, 7] : [2, 6]
        ps = alltargets ? [extra_plot first_p ps... extra_plot_2] : [first_p ps...]
    end
    ps = plot(
              ps...,
              layout=Tuple(grid_l),
              size=pic_size_scaled.*reverse(grid_l),
             )
    return ps, extra_plot
end

end # module

max_stars_repo_name: cyruscyliu/nyx-net-profuzzbench

max_issues_repo_name: cyruscyliu/nyx-net-profuzzbench

max_forks_repo_name: cyruscyliu/nyx-net-profuzzbench


text:
# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/NodeNumbering.jl/blob/master/LICENSE

using NodeNumbering

@testset "Calculate bandwidth of adjacency graph" begin

    G = Dict(
        1 => [3, 8, 9],
        2 => [3, 8, 7],
        3 => [1, 2],
        4 => [8, 9],
        5 => [7, 8],
        6 => [2, 7],
        7 => [5, 2, 6],
        8 => [1, 2, 4, 5],
        9 => [1, 4])

    bw = NodeNumbering.calculate_bandwidth(G)

    @test bw == 17

end


text:
using Clang

# HSA_HEADERS are those headers to be wrapped.
const HSA_INCLUDE = joinpath(@__DIR__, "include") |> normpath

hsa_headers_base = joinpath(@__DIR__, "include", "hsa")
const HSA_HEADERS = String[]
push!(HSA_HEADERS, joinpath(hsa_headers_base, "hsa.h"))
push!(HSA_HEADERS, joinpath(hsa_headers_base, "hsa_ext_amd.h"))
push!(HSA_HEADERS, joinpath(hsa_headers_base, "hsa_ext_finalize.h"))
push!(HSA_HEADERS, joinpath(hsa_headers_base, "hsa_ext_image.h"))

wc = init(; headers = HSA_HEADERS,
            output_file = joinpath(@__DIR__, "hsa_interface.jl"),
            common_file = joinpath(@__DIR__, "hsa_types.jl"),
            clang_includes = vcat(HSA_INCLUDE, CLANG_INCLUDE),
            #clang_args = ["-I", joinpath(HSA_INCLUDE, "..")],
            header_wrapped = (root, current)->root == current,
            header_library = x->"libhsa-runtime64",
            clang_diagnostics = true,
            )

run(wc)

# Replace stuff
for (src,dst) in [("libhsa-runtime64","\"libhsa-runtime64\"")]
  for file in ("hsa_interface.jl", "hsa_types.jl")
    run(Cmd(["sed", "-i", "s/$src/$dst/g", file]))
  end
end
# Remove useless HSA_API macros
#run(Cmd(["sed", "-i", "/^.*HSA_API.*\$/d", "hsa_types.jl"]))


text:
using CliOptions

# A utility which searches for files of which name matches a given pattern and optionally
# invoke a command line for each of them

spec = CliOptionSpec(
    HelpOption(),
    Option("-x", "--exec"; default = nothing, until = ";",
           help = "Execute command for each found file."),
    Positional("starting-point"; default = ".",
               help = "Root of directory tree to execute recursive file search."),
)
options = parse_args(spec)

# Recursively search for matching files
for (rootpath, dirs, files) in walkdir(options.starting_point)
    for fn in files
        path = joinpath(rootpath, fn)
        if options.exec === nothing
            println(path)
        else
            commandline = copy(options.exec)
            push!(commandline, path)
            run(Cmd(commandline))
        end
    end
end


text:
### ============== ### ============== ### ============== ###
### OUTPUT FOLDER STRUCTURE
### ============== ### ============== ### ============== ###

function set_output_data_structure(path, N, P, γ)

    parent_folder_path = "$(homedir())/SIM_DATA/$(path)"
    folder_path        = parent_folder_path * "/DATA/data_N_$(N)"
    reps_path          = folder_path * "/data_N_$(N)_p_$(P)_g_$(γ)"
    # reps_path          = folder_path * "/data_N_$(N)_k_$(κ)_g_$(γ)"

    try
        mkdir("$(homedir())/SIM_DATA")
    catch error
        println("Main data folder already exists")
    end

    try
        mkdir(parent_folder_path)
    catch error
        println("Parent folder already exists")
    end

    try
        mkdir(parent_folder_path * "/DATA")
    catch error
        println("Data folder already exists")
    end

    try
        mkdir(folder_path)
    catch error
        println("Folder already exists")
    end

    try
        mkdir(reps_path)
    catch error
        println("Parameter folder already exists")
    end

    return reps_path
end

### ============== ### ============== ###
###   BUILD DIRECTED RANDOM NETWORK   ###
### ============== ### ============== ###

function set_directed_random_network(N, degs)

    neigh = Vector{Vector{Int}}(N)
    Nij   = Vector{Int64}()
    poski = Vector{Int64}()

    neigh[1] = sample(filter(x-> x != 1, collect(1:N)), degs[1], replace=false, ordered = true)
    # println(1, ":", degs[1], " |", neigh[1])

    push!(poski, 1)
    push!(Nij, degs[1])
    for j in neigh[1]
        push!(Nij, j)
    end

    for i in 2:N
    	neigh[i] = sample(filter(x-> x != i, collect(1:N)), degs[i], replace=false, ordered = true)
        k_last = poski[endof(poski)]
        # println(i, ":", degs[i], " |", neigh[i], " |", k_last)
        if degs[i] > 0
            push!(poski, k_last + degs[i-1] + 1)
            push!(Nij, degs[i])
            for j in neigh[i]
                push!(Nij, j)
            end
        else
            push!(Nij, 0)
            push!(poski, k_last + degs[i-1] + 1)
        end
    end

    # println(poski)
    # println(Nij)

    return poski, Nij
end

### ============== ### ============== ###
###     COMPUTE NETWORK INTERACTIONS
### ============== ### ============== ###

function compute_network_interactions_2D(ang::SharedArray, ang_n::SharedArray, Nij::SharedArray, poski::SharedArray)

    num_phi = 0.0
    den_phi = 0.0

    # for i in first(localindexes(ang)):last(localindexes(ang))
    for i in localindexes(ang)

        ang_n[i] = 0.0

        num_phi = 0.0
        den_phi = 0.0

        ki   = Nij[poski[i]]
        init = poski[i]

        for j in 1:ki
            num_phi += cos( ang[ Nij[ init + j] ])
            den_phi += sin( ang[ Nij[ init + j] ])
        end

        ang_n[i] = atan2(den_phi, num_phi)
    end
end

### ============== ### ============== ### ============== ###
### UPDATE PARTICLE'S POSITIONS AND VELOCITIES
### ============== ### ============== ### ============== ###

function update_particles_2D(pos::SharedArray, ang::SharedArray, ang_n::SharedArray, dt::Float64, v0::Float64, γ::Float64, σ::Float64, ξ_dist)

    γ_dt  = γ*dt
    v0_dt = v0*dt
    new_angle = 0.0

    # for i in first(localindexes(ang)):last(localindexes(ang))
    for i in localindexes(ang)

        new_angle = ang[i] + γ_dt * sin(ang_n[i] - ang[i]) + σ * rand(ξ_dist)

        n_y = pos[2i] + v0_dt * sin(new_angle)
        n_x = pos[2i-1] + v0_dt * cos(new_angle)

        ang[i] = new_angle

        pos[2i]   = n_y
        pos[2i-1] = n_x
    end
end

### ============== ### ============== ### ============== ###
### SYSTEM UPDATE (METRIC SHORT-RANGE INTERACTIONS)
### ============== ### ============== ### ============== ###

function evolve_system_2D(pos::SharedArray, ang::SharedArray, ang_n::SharedArray, poski::SharedArray, Nij::SharedArray, dt::Float64, v0::Float64, γ::Float64, σ::Float64, ξ_dist)

    @sync begin
        for p in workers()
            @async remotecall_wait(compute_network_interactions_2D, p, ang, ang_n, Nij, poski)
        end
    end

    @sync begin
        for p in workers()
            @async remotecall_wait(update_particles_2D, p, pos, ang, ang_n, dt, v0, γ, σ, ξ_dist)
        end
    end
end
### ============== ### ============== ### ============== ###


text:
## reader

function Base.parse(::Type{Module}, data::Vector{T}) where T<:Union{UInt8,Int8}
    membuf = MemoryBuffer(data, "", false)
    out_ref = Ref{API.LLVMModuleRef}()

    status = convert(Core.Bool, API.LLVMParseBitcode2(ref(membuf), out_ref))
    @assert !status # caught by diagnostics handler

    Module(out_ref[])
end

function Base.parse(::Type{Module}, data::Vector{T}, ctx::Context) where T<:Union{UInt8,Int8}
    membuf = MemoryBuffer(data, "", false)
    out_ref = Ref{API.LLVMModuleRef}()

    status = convert(Core.Bool, API.LLVMParseBitcodeInContext2(ref(ctx), ref(membuf), out_ref))
    @assert !status # caught by diagnostics handler

    Module(out_ref[])
end

## writer

Base.write(io::IOStream, mod::Module) =
    API.LLVMWriteBitcodeToFD(ref(mod), Cint(fd(io)), convert(Bool, false), convert(Bool, true))

Base.convert(::Type{MemoryBuffer}, mod::Module) = MemoryBuffer(
    API.LLVMWriteBitcodeToMemoryBuffer(ref(mod)))

Base.convert(::Type{Vector{T}}, mod::Module) where {T<:Union{UInt8,Int8}} =
    convert(Vector{T}, convert(MemoryBuffer, mod))


text:
using Todict
using Base.Test

@test 123 |> todict(:asd) == Dict(:asd => 123)
@test todict(123, :asd) == Dict(:asd => 123)
@test todict(123, :a, :b=>x->x+1) == Dict(:a => 123, :b => 124)

max_stars_repo_name: closescreen/Todict

max_issues_repo_name: closescreen/Todict

max_forks_repo_name: closescreen/Todict


text:
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENSE in the project root.
# ------------------------------------------------------------------

"""
    ∠(A, B, C)

Angle ∠ABC between rays BA and BC.
See https://en.wikipedia.org/wiki/Angle.

Uses the two-argument form of `atan`.
See https://en.wikipedia.org/wiki/Atan2.

## Example

```julia
∠(Point(1,0), Point(0,0), Point(0,1)) == π/2
```
"""
function ∠(A::P, B::P, C::P) where {P<:Point{2}}
  BA = A - B
  BC = C - B
  atan(BA × BC, BA ⋅ BC)
end


text:
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK
# Copyright (C) 2019 Samuel Powell

# examples/imagedata.jl: example to extract image data to AbstractArray
using Spinnaker

camlist = CameraList()
cam = camlist[0]
gammenset = gammaenable!(cam, false)
@assert gammenset == false
adcbits!(cam, "Bit12")
adcbits(cam)
pixelformat(cam)
pixelformat!(cam, "Mono16")
@assert pixelformat(cam) == "Mono16"
triggersource!(cam, "Software")
triggermode!(cam, "On")
acquisitionmode!(cam, "Continuous")
gain!(cam, 12.0)
exposure!(cam, 1e6)
start!(cam)
trigger!(cam)
image = getimage(cam)
stop!(cam)
arr = CameraImage(image, Float64)