text:
#
# C API
#

"Indicates that the element will be appended to the list on `blpapi_Element_set` functions (`blpapi_defs.h`)."
const BLPAPI_ELEMENT_INDEX_END = 0xffffffff

function blpapi_getVersionInfo(majorVersion::Ref{Cint}, minorVersion::Ref{Cint}, patchVersion::Ref{Cint}, buildVersion::Ref{Cint})
    ccall((:blpapi_getVersionInfo, libblpapi3), Cvoid, (Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}), majorVersion, minorVersion, patchVersion, buildVersion)
end

# const char* blpapi_getLastErrorDescription(int resultCode);
function blpapi_getLastErrorDescription(resultCode::Cint) :: String
    unsafe_string(ccall((:blpapi_getLastErrorDescription, libblpapi3), Cstring, (Cint,), resultCode))
end

#
# blpapi_sessionoptions.h
#

#blpapi_SessionOptions_t *blpapi_SessionOptions_create(void);
function blpapi_SessionOptions_create()
    ccall((:blpapi_SessionOptions_create, libblpapi3), Ptr{Cvoid}, ())
end

#void blpapi_SessionOptions_destroy(blpapi_SessionOptions_t *parameters);
function blpapi_SessionOptions_destroy(options_handle::Ptr{Cvoid})
    ccall((:blpapi_SessionOptions_destroy, libblpapi3), Cvoid, (Ptr{Cvoid},), options_handle)
end

#const char *blpapi_SessionOptions_serverHost(
#                                          blpapi_SessionOptions_t *parameters);
function blpapi_SessionOptions_serverHost(opt_handle::Ptr{Cvoid})
    ccall((:blpapi_SessionOptions_serverHost, libblpapi3), Ptr{UInt8}, (Ptr{Cvoid},), opt_handle)
end

#unsigned int blpapi_SessionOptions_serverPort(
#                                          blpapi_SessionOptions_t *parameters);
function blpapi_SessionOptions_serverPort(options_handle::Ptr{Cvoid})
    ccall((:blpapi_SessionOptions_serverPort, libblpapi3), UInt32, (Ptr{Cvoid},), options_handle)
end

#int blpapi_SessionOptions_setServerHost(blpapi_SessionOptions_t *parameters,
#                                        const char              *serverHost);
function blpapi_SessionOptions_setServerHost(options_handle::Ptr{Cvoid}, server_host::AbstractString)
    ccall((:blpapi_SessionOptions_setServerHost, libblpapi3), Cint, (Ptr{Cvoid}, Cstring), options_handle, server_host)
end

#void blpapi_SessionOptions_setClientMode(blpapi_SessionOptions_t *parameters,
#                                         int                      clientMode);
function blpapi_SessionOptions_setClientMode(options_handle::Ptr{Cvoid}, client_mode::Integer)
    ccall((:blpapi_SessionOptions_setClientMode, libblpapi3), Cvoid, (Ptr{Cvoid}, Cint), options_handle, client_mode)
end

#int blpapi_SessionOptions_clientMode(
#                                          blpapi_SessionOptions_t *parameters);
function blpapi_SessionOptions_clientMode(options_handle::Ptr{Cvoid})
    ccall((:blpapi_SessionOptions_clientMode, libblpapi3), Cint, (Ptr{Cvoid},), options_handle)
end

#int blpapi_SessionOptions_setServerPort(blpapi_SessionOptions_t *parameters,
#                                        unsigned short           serverPort);
function blpapi_SessionOptions_setServerPort(options_handle::Ptr{Cvoid}, server_port::UInt16)
    ccall((:blpapi_SessionOptions_setServerPort, libblpapi3), Cint, (Ptr{Cvoid}, UInt16), options_handle, server_port)
end

#int blpapi_SessionOptions_setServiceCheckTimeout(
#                                        blpapi_SessionOptions_t *paramaters,
#                                        int                      timeoutMsecs);
function blpapi_SessionOptions_setServiceCheckTimeout(options_handle::Ptr{Cvoid}, timeout_msecs::Integer)
    ccall((:blpapi_SessionOptions_setServiceCheckTimeout, libblpapi3), Cint, (Ptr{Cvoid}, Cint), options_handle, timeout_msecs)
end

#int blpapi_SessionOptions_setServiceDownloadTimeout(
#                                        blpapi_SessionOptions_t *paramaters,
#                                        int                      timeoutMsecs);
function blpapi_SessionOptions_setServiceDownloadTimeout(options_handle::Ptr{Cvoid}, timeout_msecs::Integer)
    ccall((:blpapi_SessionOptions_setServiceDownloadTimeout, libblpapi3), Cint, (Ptr{Cvoid}, Cint), options_handle, timeout_msecs)
end

#
# blpapi_session.h
#

#blpapi_Session_t* blpapi_Session_create(
#        blpapi_SessionOptions_t *parameters,
#        blpapi_EventHandler_t handler,
#        blpapi_EventDispatcher_t* dispatcher,
#        void *userData);
function blpapi_Session_create(options_handle::Ptr{Cvoid}, event_handler_handle::Ptr{Cvoid}, dispatcher_handler::Ptr{Cvoid}, user_data_handle::Ptr{Cvoid})
    ccall((:blpapi_Session_create, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}), options_handle, event_handler_handle, dispatcher_handler, user_data_handle)
end

#void blpapi_Session_destroy(
#        blpapi_Session_t *session);
function blpapi_Session_destroy(session_handle::Ptr{Cvoid})
    ccall((:blpapi_Session_destroy, libblpapi3), Cvoid, (Ptr{Cvoid},), session_handle)
end

#int blpapi_Session_start(
#        blpapi_Session_t *session);
function blpapi_Session_start(session_handle::Ptr{Cvoid})
    ccall((:blpapi_Session_start, libblpapi3), Cint, (Ptr{Cvoid},), session_handle)
end

#int blpapi_Session_stop(
#        blpapi_Session_t* session);
function blpapi_Session_stop(session_handle::Ptr{Cvoid})
    ccall((:blpapi_Session_stop, libblpapi3), Cint, (Ptr{Cvoid},), session_handle)
end

#int blpapi_Session_openService(
#        blpapi_Session_t *session,
#        const char* serviceName);
function blpapi_Session_openService(session_handle::Ptr{Cvoid}, service_name::AbstractString)
    ccall((:blpapi_Session_openService, libblpapi3), Cint, (Ptr{Cvoid}, Cstring), session_handle, service_name)
end

#int blpapi_Session_getService(
#        blpapi_Session_t *session,
#        blpapi_Service_t **service,
#        const char* serviceName);
function blpapi_Session_getService(session_handle::Ptr{Cvoid}, service_handle_ref::Ref{Ptr{Cvoid}}, service_name::AbstractString)
    ccall((:blpapi_Session_getService, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Cstring), session_handle, service_handle_ref, service_name)
end

#int blpapi_Session_sendRequest(
#        blpapi_Session_t *session,
#        const blpapi_Request_t *request,
#        blpapi_CorrelationId_t *correlationId,
#        blpapi_Identity_t *identity,
#        blpapi_EventQueue_t *eventQueue,
#        const char *requestLabel,
#        int requestLabelLen);
function blpapi_Session_sendRequest(session_handle::Ptr{Cvoid}, request_handle::Ptr{Cvoid}, correlation_ref::Ref{CorrelationId}, queue_handle::Ptr{Cvoid})
    ccall((:blpapi_Session_sendRequest, libblpapi3), Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Ref{CorrelationId}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Cint), session_handle, request_handle, correlation_ref, C_NULL, queue_handle, C_NULL, 0)
end

#int blpapi_Session_nextEvent(
#        blpapi_Session_t* session,
#        blpapi_Event_t **eventPointer,
#        unsigned int timeoutInMilliseconds);
function blpapi_Session_nextEvent(session_handle::Ptr{Cvoid}, event_handle_ref::Ref{Ptr{Cvoid}}, timeout::Integer)
    ccall((:blpapi_Session_nextEvent, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, UInt32), session_handle, event_handle_ref, timeout)
end

#int blpapi_Session_tryNextEvent(
#        blpapi_Session_t* session,
#        blpapi_Event_t **eventPointer);
function blpapi_Session_tryNextEvent(session_handle::Ptr{Cvoid}, event_handle_ref::Ref{Ptr{Cvoid}})
    ccall((:blpapi_Session_tryNextEvent, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}), session_handle, event_handle_ref)
end

#int blpapi_Session_subscribe(
#        blpapi_Session_t *session,
#        const blpapi_SubscriptionList_t *subscriptionList,
#        const blpapi_Identity_t* handle,
#        const char *requestLabel,
#        int requestLabelLen);
function blpapi_Session_subscribe(session_handle::Ptr{Cvoid}, sublist_handle::Ptr{Cvoid}, identity_handle::Ptr{Cvoid}, request_label::Ptr{UInt8}, request_label_len::Integer)
    ccall((:blpapi_Session_subscribe, libblpapi3), Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{UInt8}, Cint), session_handle, sublist_handle, identity_handle, request_label, request_label_len)
end

#int blpapi_Session_unsubscribe(
#        blpapi_Session_t *session,
#        const blpapi_SubscriptionList_t *unsubscriptionList,
#        const char *requestLabel,
#        int requestLabelLen);
function blpapi_Session_unsubscribe(session_handle::Ptr{Cvoid}, sublist_handle::Ptr{Cvoid}, request_label::Ptr{UInt8}, request_label_len::Integer)
    ccall((:blpapi_Session_unsubscribe, libblpapi3), Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Ptr{UInt8}, Cint), session_handle, sublist_handle, request_label, request_label_len)
end

#int blpapi_Session_cancel(
#        blpapi_Session_t *session,
#        const blpapi_CorrelationId_t *correlationIds,
#        size_t numCorrelationIds,
#        const char *requestLabel,
#        int requestLabelLen);
function blpapi_Session_cancel(session_handle::Ptr{Cvoid}, correlation_ids_array::Ptr{Cvoid}, num_correlation_ids::Integer, request_label::Ptr{UInt8}, request_label_len::Integer)
    ccall((:blpapi_Session_cancel, libblpapi3), Cint, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{UInt8}, Cint), session_handle, correlation_ids_array, num_correlation_ids, request_label, request_label_len)
end

#
# blpapi_service.h
#

# const char* blpapi_Service_name(blpapi_Service_t *service);
function blpapi_Service_name(service_handle::Ptr{Cvoid})
    ccall((:blpapi_Service_name, libblpapi3), Cstring, (Ptr{Cvoid},), service_handle)
end

# int blpapi_Service_numOperations(blpapi_Service_t *service);
function blpapi_Service_numOperations(service_handle::Ptr{Cvoid})
    ccall((:blpapi_Service_numOperations, libblpapi3), Cint, (Ptr{Cvoid},), service_handle)
end

# int blpapi_Service_getOperationAt(
#        blpapi_Service_t *service,
#        blpapi_Operation_t **operation,
#        size_t index);
function blpapi_Service_getOperationAt(service_handle::Ptr{Cvoid}, operation_handle_ref::Ref{Ptr{Cvoid}}, index::Integer)
    ccall((:blpapi_Service_getOperationAt, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Csize_t), service_handle, operation_handle_ref, index)
end

# int blpapi_Service_getOperation(
#        blpapi_Service_t *service,
#        blpapi_Operation_t **operation,
#        const char* nameString,
#        const blpapi_Name_t *name);
function blpapi_Service_getOperation(service_handle::Ptr{Cvoid}, operation_handle_ref::Ref{Ptr{Cvoid}}, name::AbstractString, blpapiname::Ptr{Cvoid})
    ccall((:blpapi_Service_getOperation, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Cstring, Ptr{Cvoid}), service_handle, operation_handle_ref, name, blpapiname)
end

#int blpapi_Service_createRequest(
#        blpapi_Service_t* service,
#        blpapi_Request_t** request,
#        const char *operation);
function blpapi_Service_createRequest(service_handle::Ptr{Cvoid}, request_handle_ref::Ref{Ptr{Cvoid}}, operation_name::AbstractString)
    ccall((:blpapi_Service_createRequest, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Cstring), service_handle, request_handle_ref, operation_name)
end

# const char* blpapi_Operation_name(blpapi_Operation_t *service);
function blpapi_Operation_name(operation_handle::Ptr{Cvoid})
    ccall((:blpapi_Operation_name, libblpapi3), Cstring, (Ptr{Cvoid},), operation_handle)
end

#int blpapi_Operation_requestDefinition(
#        blpapi_Operation_t *service,
#        blpapi_SchemaElementDefinition_t **requestDefinition);
function blpapi_Operation_requestDefinition(operation_handle::Ptr{Cvoid}, element_definition_handle_ref::Ref{Ptr{Cvoid}})
    ccall((:blpapi_Operation_requestDefinition, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}), operation_handle, element_definition_handle_ref)
end

#int blpapi_Operation_numResponseDefinitions(
#        blpapi_Operation_t *service);
function blpapi_Operation_numResponseDefinitions(operation_handle::Ptr{Cvoid})
    ccall((:blpapi_Operation_numResponseDefinitions, libblpapi3), Cint, (Ptr{Cvoid},), operation_handle)
end

#int blpapi_Operation_responseDefinition(
#        blpapi_Operation_t *service,
#        blpapi_SchemaElementDefinition_t **responseDefinition,
#        size_t index);
function blpapi_Operation_responseDefinition(operation_handle::Ptr{Cvoid}, element_definition_handle_ref::Ref{Ptr{Cvoid}}, index::Integer)
    ccall((:blpapi_Operation_responseDefinition, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Csize_t), operation_handle, element_definition_handle_ref, index)
end

#
# blpapi_schema.h
#

#blpapi_Name_t *blpapi_SchemaElementDefinition_name(
#        const blpapi_SchemaElementDefinition_t *field);
function blpapi_SchemaElementDefinition_name(schema_element_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaElementDefinition_name, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), schema_element_handle)
end

#int blpapi_SchemaElementDefinition_status(
#        const blpapi_SchemaElementDefinition_t *field);
function blpapi_SchemaElementDefinition_status(schema_element_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaElementDefinition_status, libblpapi3), Cint, (Ptr{Cvoid},), schema_element_handle)
end

#size_t blpapi_SchemaElementDefinition_numAlternateNames(
#        const blpapi_SchemaElementDefinition_t *field);
function blpapi_SchemaElementDefinition_numAlternateNames(schema_element_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaElementDefinition_numAlternateNames, libblpapi3), Csize_t, (Ptr{Cvoid},), schema_element_handle)
end

#blpapi_Name_t *blpapi_SchemaElementDefinition_getAlternateName(
#        const blpapi_SchemaElementDefinition_t *field,
#        size_t index);
function blpapi_SchemaElementDefinition_getAlternateName(schema_element_handle::Ptr{Cvoid}, index::Integer)
    ccall((:blpapi_SchemaElementDefinition_getAlternateName, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t), schema_element_handle, index)
end

#size_t blpapi_SchemaElementDefinition_minValues(
#        const blpapi_SchemaElementDefinition_t *field);
function blpapi_SchemaElementDefinition_minValues(schema_element_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaElementDefinition_minValues, libblpapi3), Csize_t, (Ptr{Cvoid},), schema_element_handle)
end

#size_t blpapi_SchemaElementDefinition_maxValues(
#        const blpapi_SchemaElementDefinition_t *field);
function blpapi_SchemaElementDefinition_maxValues(schema_element_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaElementDefinition_maxValues, libblpapi3), Csize_t, (Ptr{Cvoid},), schema_element_handle)
end

#blpapi_SchemaTypeDefinition_t *blpapi_SchemaElementDefinition_type(
#        const blpapi_SchemaElementDefinition_t *field);
function blpapi_SchemaElementDefinition_type(schema_element_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaElementDefinition_type, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), schema_element_handle)
end

#blpapi_Name_t *blpapi_SchemaTypeDefinition_name(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_name(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_name, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), schema_type_handle)
end

#const char *blpapi_SchemaTypeDefinition_description(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_description(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_description, libblpapi3), Cstring, (Ptr{Cvoid},), schema_type_handle)
end

#int blpapi_SchemaTypeDefinition_status(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_status(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_status, libblpapi3), Cint, (Ptr{Cvoid},), schema_type_handle)
end

#int blpapi_SchemaTypeDefinition_datatype(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_datatype(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_datatype, libblpapi3), Cint, (Ptr{Cvoid},), schema_type_handle)
end

#int blpapi_SchemaTypeDefinition_isComplex(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_isComplex(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_isComplex, libblpapi3), Cint, (Ptr{Cvoid},), schema_type_handle)
end

#int blpapi_SchemaTypeDefinition_isSimple(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_isSimple(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_isSimple, libblpapi3), Cint, (Ptr{Cvoid},), schema_type_handle)
end

#int blpapi_SchemaTypeDefinition_isEnumeration(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_isEnumeration(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_isEnumeration, libblpapi3), Cint, (Ptr{Cvoid},), schema_type_handle)
end

#size_t blpapi_SchemaTypeDefinition_numElementDefinitions(
#        const blpapi_SchemaTypeDefinition_t *type);
function blpapi_SchemaTypeDefinition_numElementDefinitions(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_numElementDefinitions, libblpapi3), Csize_t, (Ptr{Cvoid},), schema_type_handle)
end

#blpapi_SchemaElementDefinition_t*
#blpapi_SchemaTypeDefinition_getElementDefinitionAt(
#        const blpapi_SchemaTypeDefinition_t *type,
#        size_t index);
function blpapi_SchemaTypeDefinition_getElementDefinitionAt(schema_type_handle::Ptr{Cvoid}, index::Integer)
    ccall((:blpapi_SchemaTypeDefinition_getElementDefinitionAt, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t), schema_type_handle, index)
end

#blpapi_ConstantList_t*
#blpapi_SchemaTypeDefinition_enumeration(
#        const blpapi_SchemaTypeDefinition_t *element);
function blpapi_SchemaTypeDefinition_enumeration(schema_type_handle::Ptr{Cvoid})
    ccall((:blpapi_SchemaTypeDefinition_enumeration, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), schema_type_handle)
end

#
# blpapi_name.h
#

#void blpapi_Name_destroy(
#        blpapi_Name_t *name);
function blpapi_Name_destroy(name_handle::Ptr{Cvoid})
    ccall((:blpapi_Name_destroy, libblpapi3), Cvoid, (Ptr{Cvoid},), name_handle)
end

#const char* blpapi_Name_string(
#        const blpapi_Name_t *name);
function blpapi_Name_string(name_handle::Ptr{Cvoid})
    ccall((:blpapi_Name_string, libblpapi3), Cstring, (Ptr{Cvoid},), name_handle)
end

#blpapi_Name_t* blpapi_Name_findName(
#        const char* nameString);
function blpapi_Name_findName(name::AbstractString)
    ccall((:blpapi_Name_findName, libblpapi3), Ptr{Cvoid}, (Cstring,), name)
end

#blpapi_Name_t* blpapi_Name_create(
#        const char* nameString);
function blpapi_Name_create(name::AbstractString)
    ccall((:blpapi_Name_create, libblpapi3), Ptr{Cvoid}, (Cstring,), name)
end

#
# blpapi_constant.h
#

#blpapi_Name_t* blpapi_Constant_name(
#        const blpapi_Constant_t *constant);
function blpapi_Constant_name(const_handle::Ptr{Cvoid})
    ccall((:blpapi_Constant_name, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), const_handle)
end

#const char* blpapi_Constant_description(
#        const blpapi_Constant_t *constant);
function blpapi_Constant_description(const_handle::Ptr{Cvoid})
    ccall((:blpapi_Constant_description, libblpapi3), Cstring, (Ptr{Cvoid},), const_handle)
end

#int blpapi_Constant_status(
#        const blpapi_Constant_t *constant);
function blpapi_Constant_status(const_handle::Ptr{Cvoid})
    ccall((:blpapi_Constant_status, libblpapi3), Cint, (Ptr{Cvoid},), const_handle)
end

#int blpapi_Constant_datatype(
#        const blpapi_Constant_t *constant);
function blpapi_Constant_datatype(const_handle::Ptr{Cvoid})
    ccall((:blpapi_Constant_datatype, libblpapi3), Cint, (Ptr{Cvoid},), const_handle)
end

#int blpapi_Constant_getValueAsChar(
#    const blpapi_Constant_t *constant,
#    blpapi_Char_t *buffer);
function blpapi_Constant_getValueAsChar(const_handle::Ptr{Cvoid}, buffer::Ref{Cchar})
    ccall((:blpapi_Constant_getValueAsChar, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Cchar}), const_handle, buffer)
end

#int blpapi_Constant_getValueAsInt32(
#    const blpapi_Constant_t *constant,
#    blpapi_Int32_t *buffer);
function blpapi_Constant_getValueAsInt32(const_handle::Ptr{Cvoid}, buffer::Ref{Cint})
    ccall((:blpapi_Constant_getValueAsInt32, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Cint}), const_handle, buffer)
end

#int blpapi_Constant_getValueAsInt64(
#    const blpapi_Constant_t *constant,
#    blpapi_Int64_t *buffer);
function blpapi_Constant_getValueAsInt64(const_handle::Ptr{Cvoid}, buffer::Ref{Int64})
    ccall((:blpapi_Constant_getValueAsInt64, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Int64}), const_handle, buffer)
end

#int blpapi_Constant_getValueAsFloat32(
#    const blpapi_Constant_t *constant,
#    blpapi_Float32_t *buffer);
function blpapi_Constant_getValueAsFloat32(const_handle::Ptr{Cvoid}, buffer::Ref{Float32})
    ccall((:blpapi_Constant_getValueAsFloat32, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Float32}), const_handle, buffer)
end

#int blpapi_Constant_getValueAsFloat64(
#    const blpapi_Constant_t *constant,
#    blpapi_Float64_t *buffer);
function blpapi_Constant_getValueAsFloat64(const_handle::Ptr{Cvoid}, buffer::Ref{Float64})
    ccall((:blpapi_Constant_getValueAsFloat64, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Float64}), const_handle, buffer)
end

#int blpapi_Constant_getValueAsDatetime(
#    const blpapi_Constant_t *constant,
#    blpapi_Datetime_t *buffer);
function blpapi_Constant_getValueAsDatetime(const_handle::Ptr{Cvoid}, buffer::Ref{BLPDateTime})
    ccall((:blpapi_Constant_getValueAsDatetime, libblpapi3), Cint, (Ptr{Cvoid}, Ref{BLPDateTime}), const_handle, buffer)
end

#int blpapi_Constant_getValueAsString(
#    const blpapi_Constant_t *constant,
#    const char **buffer);
function blpapi_Constant_getValueAsString(const_handle::Ptr{Cvoid}, buffer::Ref{Cstring})
    ccall((:blpapi_Constant_getValueAsString, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Cstring}), const_handle, buffer)
end

#blpapi_Name_t* blpapi_ConstantList_name(
#        const blpapi_ConstantList_t *list);
function blpapi_ConstantList_name(list_handle::Ptr{Cvoid})
    ccall((:blpapi_ConstantList_name, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), list_handle)
end

#const char* blpapi_ConstantList_description(
#        const blpapi_ConstantList_t *list);
function blpapi_ConstantList_description(list_handle::Ptr{Cvoid})
    ccall((:blpapi_ConstantList_description, libblpapi3), Cstring, (Ptr{Cvoid},), list_handle)
end

#int blpapi_ConstantList_numConstants(
#        const blpapi_ConstantList_t *list);
function blpapi_ConstantList_numConstants(list_handle::Ptr{Cvoid})
    ccall((:blpapi_ConstantList_numConstants, libblpapi3), Cint, (Ptr{Cvoid},), list_handle)
end

#int blpapi_ConstantList_datatype(
#        const blpapi_ConstantList_t *constant);
function blpapi_ConstantList_datatype(list_handle::Ptr{Cvoid})
    ccall((:blpapi_ConstantList_datatype, libblpapi3), Cint, (Ptr{Cvoid},), list_handle)
end

#int blpapi_ConstantList_status(
#        const blpapi_ConstantList_t *list);
function blpapi_ConstantList_status(list_handle::Ptr{Cvoid})
    ccall((:blpapi_ConstantList_status, libblpapi3), Cint, (Ptr{Cvoid},), list_handle)
end

#blpapi_Constant_t* blpapi_ConstantList_getConstantAt(
#        const blpapi_ConstantList_t *constant,
#        size_t index);
function blpapi_ConstantList_getConstantAt(list_handle::Ptr{Cvoid}, index::Integer)
    ccall((:blpapi_ConstantList_getConstantAt, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t), list_handle, index)
end

#
# blpapi_request.h
#

#void blpapi_Request_destroy(
#        blpapi_Request_t *request);
function blpapi_Request_destroy(request_handle::Ptr{Cvoid})
    ccall((:blpapi_Request_destroy, libblpapi3), Cvoid, (Ptr{Cvoid},), request_handle)
end

#blpapi_Element_t* blpapi_Request_elements(
#        blpapi_Request_t *request);
function blpapi_Request_elements(request_handle::Ptr{Cvoid})
    ccall((:blpapi_Request_elements, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), request_handle)
end

#
# blpapi_element.h
#

#blpapi_Name_t* blpapi_Element_name(const blpapi_Element_t *element);
function blpapi_Element_name(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_name, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), element_handle)
end

#blpapi_SchemaElementDefinition_t* blpapi_Element_definition(const blpapi_Element_t* element);
function blpapi_Element_definition(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_definition, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), element_handle)
end

#int blpapi_Element_datatype (
#        const blpapi_Element_t* element);
function blpapi_Element_datatype(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_datatype, libblpapi3), Cint, (Ptr{Cvoid},), element_handle)
end

#int blpapi_Element_getElement(
#        const blpapi_Element_t *element,
#        blpapi_Element_t **result,
#        const char* nameString,
#        const blpapi_Name_t *name);
function blpapi_Element_getElement(element_handle::Ptr{Cvoid}, result_element_handle_ref::Ref{Ptr{Cvoid}}, element_name_string::Ptr{UInt8}, element_blp_name::Ptr{Cvoid})
    ccall((:blpapi_Element_getElement, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Ptr{UInt8}, Ptr{Cvoid}), element_handle, result_element_handle_ref, element_name_string, element_blp_name)
end

#int blpapi_Element_getElementAt(
#        const blpapi_Element_t* element,
#        blpapi_Element_t **result,
#        size_t position);
function blpapi_Element_getElementAt(element_handle::Ptr{Cvoid}, result_element_handle_ref::Ref{Ptr{Cvoid}}, index::Csize_t)
    ccall((:blpapi_Element_getElementAt, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Csize_t), element_handle, result_element_handle_ref, index)
end

#int blpapi_Element_getChoice(
#        const blpapi_Element_t *element,
#        blpapi_Element_t **result);
function blpapi_Element_getChoice(element_handle::Ptr{Cvoid}, result_element_handle_ref::Ref{Ptr{Cvoid}})
    ccall((:blpapi_Element_getChoice, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}), element_handle, result_element_handle_ref)
end

#int blpapi_Element_hasElement(
#        const blpapi_Element_t *element,
#        const char* nameString,
#        const blpapi_Name_t *name);
function blpapi_Element_hasElement(element_handle::Ptr{Cvoid}, element_name_string::Ptr{UInt8}, element_blp_name::Ptr{Cvoid})
    ccall((:blpapi_Element_hasElement, libblpapi3), Cint, (Ptr{Cvoid}, Ptr{UInt8}, Ptr{Cvoid}), element_handle, element_name_string, element_blp_name)
end

#int blpapi_Element_isArray(
#        const blpapi_Element_t* element);
function blpapi_Element_isArray(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_isArray, libblpapi3), Cint, (Ptr{Cvoid},), element_handle)
end

#int blpapi_Element_setValueString(
#        blpapi_Element_t *element,
#        const char *value,
#        size_t index);
function blpapi_Element_setValueString(element_handle::Ptr{Cvoid}, value::AbstractString, index::Integer)
    ccall((:blpapi_Element_setValueString, libblpapi3), Cint, (Ptr{Cvoid}, Cstring, Csize_t), element_handle, value, index)
end

#int blpapi_Element_setValueChar(
#        blpapi_Element_t *element,
#        blpapi_Char_t value,
#        size_t index);
function blpapi_Element_setValueChar(element_handle::Ptr{Cvoid}, value::Char, index::Integer)
    ccall((:blpapi_Element_setValueChar, libblpapi3), Cint, (Ptr{Cvoid}, Cchar, Csize_t), element_handle, value, index)
end

#int blpapi_Element_setValueBool(
#        blpapi_Element_t *element,
#        blpapi_Bool_t value,
#        size_t index);
function blpapi_Element_setValueBool(element_handle::Ptr{Cvoid}, value::Bool, index::Integer)
    ccall((:blpapi_Element_setValueBool, libblpapi3), Cint, (Ptr{Cvoid}, Cint, Csize_t), element_handle, value, index)
end

#int blpapi_Element_setValueDatetime(
#        blpapi_Element_t *element,
#        const blpapi_Datetime_t *value,
#        size_t index);
function blpapi_Element_setValueDatetime(element_handle::Ptr{Cvoid}, value::BLPDateTime, index::Integer)
    ccall((:blpapi_Element_setValueDatetime, libblpapi3), Cint, (Ptr{Cvoid}, Ref{BLPDateTime}, Csize_t), element_handle, Ref(value), index)
end

#int blpapi_Element_setValueInt32(
#        blpapi_Element_t *element,
#        blpapi_Int32_t value,
#        size_t index);
function blpapi_Element_setValueInt32(element_handle::Ptr{Cvoid}, value::Int32, index::Integer)
    ccall((:blpapi_Element_setValueInt32, libblpapi3), Cint, (Ptr{Cvoid}, Int32, Csize_t), element_handle, value, index)
end

#int blpapi_Element_setValueInt64(
#        blpapi_Element_t *element,
#        blpapi_Int64_t value,
#        size_t index);
function blpapi_Element_setValueInt64(element_handle::Ptr{Cvoid}, value::Int64, index::Integer)
    ccall((:blpapi_Element_setValueInt64, libblpapi3), Cint, (Ptr{Cvoid}, Int64, Csize_t), element_handle, value, index)
end

#int blpapi_Element_setValueFloat32(
#        blpapi_Element_t *element,
#        blpapi_Float32_t value,
#        size_t index);
function blpapi_Element_setValueFloat32(element_handle::Ptr{Cvoid}, value::Float32, index::Integer)
    ccall((:blpapi_Element_setValueFloat32, libblpapi3), Cint, (Ptr{Cvoid}, Float32, Csize_t), element_handle, value, index)
end

#int blpapi_Element_setValueFloat64(
#        blpapi_Element_t *element,
#        blpapi_Float64_t value,
#        size_t index);
function blpapi_Element_setValueFloat64(element_handle::Ptr{Cvoid}, value::Float64, index::Integer)
    ccall((:blpapi_Element_setValueFloat64, libblpapi3), Cint, (Ptr{Cvoid}, Float64, Csize_t), element_handle, value, index)
end

#size_t blpapi_Element_numElements(
#        const blpapi_Element_t* element);
function blpapi_Element_numElements(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_numElements, libblpapi3), Csize_t, (Ptr{Cvoid},), element_handle)
end

#size_t blpapi_Element_numValues(
#        const blpapi_Element_t* element);
function blpapi_Element_numValues(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_numValues, libblpapi3), Csize_t, (Ptr{Cvoid},), element_handle)
end

#int blpapi_Element_isNullValue(
#        const blpapi_Element_t* element,
#        size_t position);
function blpapi_Element_isNullValue(element_handle::Ptr{Cvoid}, index::Integer)
    ccall((:blpapi_Element_isNullValue, libblpapi3), Cint, (Ptr{Cvoid}, Csize_t), element_handle, index)
end

#int blpapi_Element_isNull(
#        const blpapi_Element_t* element);
function blpapi_Element_isNull(element_handle::Ptr{Cvoid})
    ccall((:blpapi_Element_isNull, libblpapi3), Cint, (Ptr{Cvoid},), element_handle)
end

#int blpapi_Element_getValueAsBool(
#        const blpapi_Element_t *element,
#        blpapi_Bool_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsBool(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Cint}, index::Integer)
    ccall((:blpapi_Element_getValueAsBool, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Cint}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsChar(
#        const blpapi_Element_t *element,
#        blpapi_Char_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsChar(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Cchar}, index::Integer)
    ccall((:blpapi_Element_getValueAsChar, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Cchar}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsInt32(
#        const blpapi_Element_t *element,
#        blpapi_Int32_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsInt32(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Int32}, index::Integer)
    ccall((:blpapi_Element_getValueAsInt32, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Int32}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsInt64(
#        const blpapi_Element_t *element,
#        blpapi_Int64_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsInt64(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Int64}, index::Integer)
    ccall((:blpapi_Element_getValueAsInt64, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Int64}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsFloat32(
#        const blpapi_Element_t *element,
#        blpapi_Float32_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsFloat32(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Float32}, index::Integer)
    ccall((:blpapi_Element_getValueAsFloat32, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Float32}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsFloat64(
#        const blpapi_Element_t *element,
#        blpapi_Float64_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsFloat64(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Float64}, index::Integer)
    ccall((:blpapi_Element_getValueAsFloat64, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Float64}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsString(
#        const blpapi_Element_t *element,
#        const char **buffer,
#        size_t index);
function blpapi_Element_getValueAsString(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Cstring}, index::Integer)
    ccall((:blpapi_Element_getValueAsString, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Cstring}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsDatetime(
#        const blpapi_Element_t *element,
#        blpapi_Datetime_t *buffer,
#        size_t index);
function blpapi_Element_getValueAsDatetime(element_handle::Ptr{Cvoid}, buffer_ref::Ref{BLPDateTime}, index::Integer)
    ccall((:blpapi_Element_getValueAsDatetime, libblpapi3), Cint, (Ptr{Cvoid}, Ref{BLPDateTime}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsHighPrecisionDatetime(
#        const blpapi_Element_t *element,
#        blpapi_HighPrecisionDatetime_t *buffer,
#        size_t index);

#int blpapi_Element_getValueAsElement(
#        const blpapi_Element_t *element,
#        blpapi_Element_t **buffer,
#        size_t index);
function blpapi_Element_getValueAsElement(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Ptr{Cvoid}}, index::Integer)
    ccall((:blpapi_Element_getValueAsElement, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Csize_t), element_handle, buffer_ref, index)
end

#int blpapi_Element_getValueAsName(
#        const blpapi_Element_t *element,
#        blpapi_Name_t **buffer,
#        size_t index);
function blpapi_Element_getValueAsName(element_handle::Ptr{Cvoid}, buffer_ref::Ref{Ptr{Cvoid}}, index::Integer)
    ccall((:blpapi_Element_getValueAsName, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}, Csize_t), element_handle, buffer_ref, index)
end

#
# blpapi_event.h
#

#int blpapi_Event_eventType(
#        const blpapi_Event_t *event);
function blpapi_Event_eventType(event_handle::Ptr{Cvoid})
    ccall((:blpapi_Event_eventType, libblpapi3), Cint, (Ptr{Cvoid},), event_handle)
end

#int blpapi_Event_release(
#        const blpapi_Event_t *event);
function blpapi_Event_release(event_handle::Ptr{Cvoid})
    ccall((:blpapi_Event_release, libblpapi3), Cint, (Ptr{Cvoid},), event_handle)
end

#blpapi_EventQueue_t* blpapi_EventQueue_create(void);
function blpapi_EventQueue_create()
    ccall((:blpapi_EventQueue_create, libblpapi3), Ptr{Cvoid}, ())
end

#int blpapi_EventQueue_destroy(blpapi_EventQueue_t* eventQueue);
function blpapi_EventQueue_destroy(queue_handle::Ptr{Cvoid})
    ccall((:blpapi_EventQueue_destroy, libblpapi3), Cint, (Ptr{Cvoid},), queue_handle)
end

#blpapi_Event_t* blpapi_EventQueue_nextEvent(
#        blpapi_EventQueue_t *eventQueue,
#        int timeout);
function blpapi_EventQueue_nextEvent(queue_handle::Ptr{Cvoid}, timeout::Integer)
    @threadcall((:blpapi_EventQueue_nextEvent, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid}, Cint), queue_handle, timeout)
end

#int blpapi_EventQueue_purge(blpapi_EventQueue_t *eventQueue);
function blpapi_EventQueue_purge(queue_handle::Ptr{Cvoid})
    ccall((:blpapi_EventQueue_purge, libblpapi3), Cint, (Ptr{Cvoid},), queue_handle)
end

#int blpapi_EventQueue_tryNextEvent(
#        blpapi_EventQueue_t *eventQueue,
#        blpapi_Event_t **eventPointer);
function blpapi_EventQueue_tryNextEvent(queue_handle::Ptr{Cvoid}, event_handle_ref::Ref{Ptr{Cvoid}})
    ccall((:blpapi_EventQueue_tryNextEvent, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}), queue_handle, event_handle_ref)
end

#void blpapi_MessageIterator_destroy(
#        blpapi_MessageIterator_t* iterator);
function blpapi_MessageIterator_destroy(msg_iterator_handle::Ptr{Cvoid})
    ccall((:blpapi_MessageIterator_destroy, libblpapi3), Cvoid, (Ptr{Cvoid},), msg_iterator_handle)
end

#blpapi_MessageIterator_t* blpapi_MessageIterator_create(
#        const blpapi_Event_t *event);
function blpapi_MessageIterator_create(event_handle::Ptr{Cvoid})
    ccall((:blpapi_MessageIterator_create, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), event_handle)
end

#int blpapi_MessageIterator_next(
#        blpapi_MessageIterator_t* iterator,
#        blpapi_Message_t** result);
function blpapi_MessageIterator_next(msg_iter_handle::Ptr{Cvoid}, result_msg_handle_ref::Ref{Ptr{Cvoid}})
    ccall((:blpapi_MessageIterator_next, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{Cvoid}}), msg_iter_handle, result_msg_handle_ref)
end

#
# blpapi_message.h
#

#blpapi_Element_t* blpapi_Message_elements(
#        const blpapi_Message_t *message);
function blpapi_Message_elements(message_handle::Ptr{Cvoid})
    ccall((:blpapi_Message_elements, libblpapi3), Ptr{Cvoid}, (Ptr{Cvoid},), message_handle)
end

#int blpapi_Message_numCorrelationIds(
#        const blpapi_Message_t *message);
function blpapi_Message_numCorrelationIds(message_handle::Ptr{Cvoid})
    ccall((:blpapi_Message_numCorrelationIds, libblpapi3), Cint, (Ptr{Cvoid},), message_handle)
end

#blpapi_CorrelationId_t blpapi_Message_correlationId(
#        const blpapi_Message_t *message,
#        size_t index);
function blpapi_Message_correlationId(message_handle::Ptr{Cvoid}, index::Integer)
    ccall((:blpapi_Message_correlationId, libblpapi3), CorrelationId, (Ptr{Cvoid}, Csize_t), message_handle, index)
end

#
# blpapi_subscriptionlist.h
#

#blpapi_SubscriptionList_t *blpapi_SubscriptionList_create(void);
function blpapi_SubscriptionList_create()
    ccall((:blpapi_SubscriptionList_create, libblpapi3), Ptr{Cvoid}, ())
end

#void blpapi_SubscriptionList_destroy(blpapi_SubscriptionList_t *list);
function blpapi_SubscriptionList_destroy(sublist_handle::Ptr{Cvoid})
    ccall((:blpapi_SubscriptionList_destroy, libblpapi3), Cvoid, (Ptr{Cvoid},), sublist_handle)
end

#int blpapi_SubscriptionList_add(
#                             blpapi_SubscriptionList_t     *list,
#                             const char                    *subscriptionString,
#                             const blpapi_CorrelationId_t  *correlationId,
#                             const char                   **fields,
#                             const char                   **options,
#                             size_t                         numfields,
#                             size_t                         numOptions);

#int blpapi_SubscriptionList_addResolved(
#                              blpapi_SubscriptionList_t    *list,
#                              const char                   *subscriptionString,
#                              const blpapi_CorrelationId_t *correlationId);
function blpapi_SubscriptionList_addResolved(sublist_handle::Ptr{Cvoid}, subcription_string::AbstractString, correlation_ref::Ref{CorrelationId})
    ccall((:blpapi_SubscriptionList_addResolved, libblpapi3), Cint, (Ptr{Cvoid}, Cstring, Ref{CorrelationId}), sublist_handle, subcription_string, correlation_ref)
end

#int blpapi_SubscriptionList_clear(blpapi_SubscriptionList_t *list);
function blpapi_SubscriptionList_clear(sublist_handle::Ptr{Cvoid})
    ccall((:blpapi_SubscriptionList_clear, libblpapi3), Cint, (Ptr{Cvoid},), sublist_handle)
end

#int blpapi_SubscriptionList_append(blpapi_SubscriptionList_t       *dest,
#                                   const blpapi_SubscriptionList_t *src);

#int blpapi_SubscriptionList_size(const blpapi_SubscriptionList_t *list);
function blpapi_SubscriptionList_size(sublist_handle::Ptr{Cvoid})
    ccall((:blpapi_SubscriptionList_size, libblpapi3), Cint, (Ptr{Cvoid},), sublist_handle)
end

#int blpapi_SubscriptionList_correlationIdAt(
#                                       const blpapi_SubscriptionList_t *list,
#                                       blpapi_CorrelationId_t          *result,
#                                       size_t                           index);
function blpapi_SubscriptionList_correlationIdAt(sublist_handle::Ptr{Cvoid}, correlation_ref::Ref{CorrelationId}, index::Integer)
    ccall((:blpapi_SubscriptionList_correlationIdAt, libblpapi3), Cint, (Ptr{Cvoid}, Ref{CorrelationId}, Csize_t), sublist_handle, correlation_ref, index)
end

#int blpapi_SubscriptionList_topicStringAt(blpapi_SubscriptionList_t  *list,
#                                          const char                **result,
#                                          size_t                      index);
function blpapi_SubscriptionList_topicStringAt(sublist_handle::Ptr{Cvoid}, result::Ref{Ptr{UInt8}}, index::Integer)
    ccall((:blpapi_SubscriptionList_topicStringAt, libblpapi3), Cint, (Ptr{Cvoid}, Ref{Ptr{UInt8}}, Csize_t), sublist_handle, result, index)
end

#int blpapi_SubscriptionList_isResolvedAt(blpapi_SubscriptionList_t *list,
#                                         int                       *result,
#                                         size_t                     index);

max_stars_repo_licenses: OpenSSL MIT

max_issues_repo_licenses: OpenSSL MIT

max_forks_repo_licenses: OpenSSL MIT


text:
using DocStringExtensions
"""
Computes the temperature at different elevations

$(SIGNATURES)

The Temperature should be an array of different days of measurements. The height of the station where temperature was measured should be given (Measured_Temp_Elevation)
as well as the min and maximum elevation using the Elevation struct.
"""
function gettemperatureatelevation(Elevations::Elevations, Temperature::Array{Float64,1})
    Nr_Elevationbands = Int((Elevations.Max_elevation - Elevations.Min_elevation) / Elevations.Thickness_Band)
    # make an array with number of rows equal to number of days, and columns equal to number of elevations
    Temp_Elevation = zeros(length(Temperature), Nr_Elevationbands)
    Elevation = Float64[]
    for i in 1 : Nr_Elevationbands
        Current_Elevation = (Elevations.Min_elevation + Elevations.Thickness_Band/2) + Elevations.Thickness_Band * (i - 1)
        for j in 1: length(Temperature)
            Temp_Elevation[j,i] = Temperature[j] - 0.006 * (Current_Elevation - Elevations.Measured_Temp_Elevation)
        end
        push!(Elevation, Current_Elevation)
    end
    return Elevation::Array{Float64, 1}, Temp_Elevation::Array{Float64,2}, Nr_Elevationbands::Int64
end
"""
Computes the precipitation at different elevations assuming a precipitation gradient with altitude

$(SIGNATURES)

The precipitation should be an array of different days of measurements. The height of the station where percipitation was measured should be given (Elevations.Measured_Prec_Elevation)
as well as the min and maximum elevation using the Elevation struct.
"""
function getprecipitationatelevation(Elevations::Elevations, Prec_Gradient::Float64, Precipitation)
    Nr_Elevationbands = Int((Elevations.Max_elevation - Elevations.Min_elevation) / Elevations.Thickness_Band)
    # make an array with number of rows equal to number of days, and columns equal to number of elevations
    Precipitation_Elevation = zeros(length(Precipitation),Nr_Elevationbands)
    Elevation = Float64[]
    for i in 1 : Nr_Elevationbands
        Current_Elevation = (Elevations.Min_elevation + Elevations.Thickness_Band/2) + Elevations.Thickness_Band * (i - 1)
        for j in 1: length(Precipitation)
            Precipitation_Elevation[j,i] = max((Precipitation[j] + Prec_Gradient * (Current_Elevation - Elevations.Measured_Prec_Elevation)),0)
        end
        push!(Elevation, Current_Elevation)
    end
    return Elevation::Array{Float64, 1}, Precipitation_Elevation::Array{Float64, 2}, Nr_Elevationbands::Int64
end

"""
Computes the elevations for a given HRU

$(SIGNATURES)

Returns the elevations of each HRU and the corresponding percentage of area.
"""
function getelevationsperHRU(Areal_Percentage::Array{Float64,1}, Elevation_Catchment, Elevation_Zone)
        Elevation_HRU = Float64[]
        Area = Float64[]
        j = 1
        for (i, elevation) in enumerate(Elevation_Catchment)
                if j <= length(Elevation_Zone) && elevation == Elevation_Zone[j]
                        if Areal_Percentage[i] != 0
                                push!(Area, Areal_Percentage[i])
                                push!(Elevation_HRU, j)
                        end
                        j+= 1
                end
        end
        return Area, Elevation_HRU
end

"""
Computes the daily mean temperature

$(SIGNATURES)

x has to be given as an array of Dates and Temperature Measurements.
Compute the mean daily temperature, assuming that the times of measurement are representatively distributed over the day

"""
function daily_mean(Temperature_Array)
        Temperature_Daily::Array{Float64, 1} = Array{Float64, 1}[]
        Date_Daily::Array{Date,1} = Array{Date, 1}[]
        # to make it correct when a value is missing the mean should not just be taken from the other values (Different times of day)
        # skips days with missing values
        measurement_count::Int16 = 0
        temperature_day_total = 0
        lastvalue = length(Temperature_Array[:,1])
        #Temperature_Array_Iterator = skipmissing(Temperature_Array)
        for i in 1:length(Temperature_Array[:,1])
        # sum up all measurements for a day and count the measurements
                if (i > 1 && Temperature_Array[i, 1] != Temperature_Array[i-1, 1])
                        mean_Temp = temperature_day_total / measurement_count
                        measurement_count = 0
                        temperature_day_total = 0

                        push!(Date_Daily, Temperature_Array[i - 1, 1])
                        push!(Temperature_Daily, mean_Temp)
                elseif i == lastvalue
                        if ismissing(Temperature_Array[i,2]) != true
                                temperature_day_total += Temperature_Array[i, 2]
                                measurement_count += 1
                        end
                        mean_Temp = temperature_day_total / measurement_count
                        push!(Date_Daily, Temperature_Array[i, 1])
                        push!(Temperature_Daily, mean_Temp)
                end

                if ismissing(Temperature_Array[i,2]) != true
                        temperature_day_total += Temperature_Array[i, 2]
                        measurement_count += 1
                end
        end

        return Date_Daily, Temperature_Daily
end

ext: jl

max_stars_repo_name: sarah-hanus/hbv-mountain

max_issues_repo_name: sarah-hanus/hbv-mountain

max_forks_repo_name: sarah-hanus/hbv-mountain


text:
module Knockout

using WebIO, Observables, JSExpr, JSON, RelocatableFolders, Memoize
import Observables: off, observe, AbstractObservable, ObservablePair

export knockout

folder_dir = @path joinpath(@__DIR__, "..")
@memoize knockout_js() = joinpath(folder_dir, "assets", "knockout.js")
@memoize knockout_punches_js() = joinpath(folder_dir, "assets", "knockout_punches.js")

"""
`knockout(template, data=Dict(), extra_js = js""; computed = [], methods = [])`

Create a Knockout scope, with HTML structure provided by `template` and filled with `data`.
# Arguments
- `template` the `Node` that acts as the template. See [Knockout syntax](http://knockoutjs.com/documentation/value-binding.html)
- `data` is either a dictionary or an array of `propertyName => value` pairs.
If a property's value is an observable, this function automatically sets up Julia -> JS communication.
To set up JS to Julia communication set up an event handler on `scope[propertyName]` (by calling `on(f, scope[propertyName])`)
_before_ rendering the scope.
You can specify that you want some knockout observable to be computed as a function of other observables,
e.g `knockout(...; computed = Dict(:fullName => @js function(){this.firstName() + ' ' + this.lastName()}))`.
You can pass functions that you want available in the Knockout scope as keyword arguments to
`knockout` E.g. `knockout(...; methods=Dict(:sayhello=>@js function(){ alert("hello!") }))`
"""
function knockout(template, data=Dict(), extra_js = js""; computed = [], methods = [])
    widget = Scope(imports=[
        "knockout" => knockout_js(),
        "knockout_punches" => knockout_punches_js(),
    ])
    widget(template)
    ko_data = Dict()
    watches = Dict()
    for (k, v) in data
        skey = string(k)
        (v isa ObservablePair) && (v = v.second)
        if isa(v, AbstractObservable)
            # associate the observable with the widget
            setobservable!(widget, skey, v)

            # forward updates from Julia to Knockoutjs
            onjs(v, @js function (val)
                if val != this.model[$skey]()
                    this.valueFromJulia[$skey] = true
                    this.model[$skey](val)
                end
            end)

            # forward updates from Knockoutjs to Julia
            watches[skey] = @js this[$skey].subscribe( function(val)
                if !this.valueFromJulia[$skey]
                    $v[] = val
                end
                this.valueFromJulia[$skey] = false
            end, self)
            ko_data[skey] = @js $v[]
        else
            ko_data[skey] = v
        end
    end

    methods_dict = Dict()
    for (k, f) in methods
        skey = string(k)
        methods_dict[skey] = @js this[$skey] = $f
    end

    computed_dict = Dict()
    for (k, f) in computed
        skey = string(k)
        computed_dict[skey] = @js this[$skey] = ko.computed($f, this)
    end

    on_import = js"""
    function (ko, koPunches) {
        ko.punches.enableAll();
        ko.bindingHandlers.numericValue = {
            init: function(element, valueAccessor, allBindings, data, context) {
                var stringified = ko.observable(ko.unwrap(valueAccessor()));
                stringified.subscribe(function(value) {
                    var val = parseFloat(value);
                    if (!isNaN(val)) {
                        valueAccessor()(val);
                    }
                });
                valueAccessor().subscribe(function(value) {
                    var str = JSON.stringify(value);
                    if ((str == "0") && (["-0", "-0."].indexOf(stringified()) >= 0))
                         return;
                     if (["null", ""].indexOf(str) >= 0)
                         return;
                    stringified(str);
                });
                ko.applyBindingsToNode(
                    element,
                    {
                        value: stringified,
                        valueUpdate: allBindings.get('valueUpdate'),
                    },
                    context,
                );
            }
        };
        var json_data = $ko_data;
        var self = this;
        function AppViewModel() {
            for (var key in json_data) {
                var el = json_data[key];
                this[key] = Array.isArray(el) ? ko.observableArray(el) : ko.observable(el);
            }
            $(dict2js(methods_dict))
            $(dict2js(computed_dict))
            $(dict2js(watches))
            $extra_js
        }
        self.model = new AppViewModel();
        self.valueFromJulia = {};
        for (var key in json_data) {
            self.valueFromJulia[key] = false;
        }
        ko.applyBindings(self.model, self.dom);
    }
    """
    onimport(widget, on_import)
    widget
end

function dict2js(d::AbstractDict)
    isempty(d) ? js"" : js"$(values(d)...,)"
end

isnumeric(x) = false
isnumeric(x::Number) = true
isnumeric(x::Bool) = false
isnumeric(x::AbstractObservable) = isnumeric(x[])

js_lambda(s::String) = "function (){$s}"

end # module


text:
@coeff function K_BS(reactor::Reactor)
  K_b * K_n * K_T / (K_I^2)
end


text:
# fit.jl

fit_nlopt!(lmm::MetidaModel; kwargs...)  = error("MetidaNLopt not found. \n - Run `using MetidaNLopt` before.")

"""
    fit!(lmm::LMM{T}; kwargs...
    ) where T

Fit LMM model.

# Keywords:

* `solver` - :default / :nlopt for using with MetidaNLopt.jl/ :cuda for using with MetidaCu.jl
* `verbose` - :auto / 1 / 2 / 3
* `varlinkf` - :exp / :sq / :identity [ref](./details/#Variance-parameters-link-function)
* `rholinkf` - :sigm / :atan / :sqsigm / :psigm
* `aifirst` - first iteration with AI-like method - :default / :ai / :score
* `g_tol` - absolute tolerance in the gradient
* `x_tol` - absolute tolerance of theta vector
* `f_tol` - absolute tolerance in changes of the REML
* `hes` - calculate REML Hessian
* `init` - initial theta values
* `refitinit` - true/false - if true - use last values for initial condition
* `optmethod` - Optimization method. Look at Optim.jl documentation. (Newton by default)
* `io` - output IO
"""
function fit!(lmm::LMM{T}; kwargs...) where T

    kwkeys = keys(kwargs)

    :solver ∈ kwkeys ? solver = kwargs[:solver] : solver = :default
    :verbose ∈ kwkeys ? verbose = kwargs[:verbose] : verbose = :auto
    :varlinkf ∈ kwkeys ? varlinkf = kwargs[:varlinkf] : varlinkf = :exp
    :rholinkf ∈ kwkeys ? rholinkf = kwargs[:rholinkf] : rholinkf = :sigm
    :aifirst ∈ kwkeys ? aifirst = kwargs[:aifirst] : aifirst = :default
    :g_tol ∈ kwkeys ? g_tol = kwargs[:g_tol] : g_tol = 1e-10
    :x_tol ∈ kwkeys ? x_tol = kwargs[:x_tol] : x_tol = :1e-10
    :f_tol ∈ kwkeys ? f_tol = kwargs[:f_tol] : f_tol = :1e-10
    :hes ∈ kwkeys ? hes = kwargs[:hes] : hes = true
    :init ∈ kwkeys ? init = kwargs[:init] : init = :nothing
    :io ∈ kwkeys ? io = kwargs[:io] : io = stdout
    :time_limit ∈ kwkeys ? time_limit = kwargs[:time_limit] : time_limit = 120
    :iterations ∈ kwkeys ? iterations = kwargs[:iterations] : iterations = 300
    :refitinit ∈ kwkeys ? refitinit = kwargs[:refitinit] : refitinit = false
    :optmethod ∈ kwkeys ? optmethod = kwargs[:optmethod] : optmethod = :default

    # If model was fitted, previous results can be used if `refitinit` == true
    # Before fitting clear log
    if lmm.result.fit
        if length(lmm.log) > 0 deleteat!(lmm.log, 1:length(lmm.log)) end
        lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Refit model..."))
        if refitinit
            lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Using previous initial parameters."))
            init = lmm.result.theta
        end
    end
    lmm.result.fit = false
    # Use default solver (Optim.jl with Newton)
    solver == :default || return fit_nlopt!(lmm; kwargs...)
    # Set verbose mode
    if verbose == :auto
        verbose = 1
    end
    # Optimization method
    if optmethod == :default
        optmethod  = NEWTON_OM
    end

    # Optimization function
    optfunc = reml_sweep_β
    # Make data views
    data = LMMDataViews(lmm)
    #Optim options
    optoptions = Optim.Options(g_tol = g_tol, x_tol = x_tol, f_abstol = f_tol,
        iterations = iterations,
        time_limit = time_limit,
        store_trace = true,
        show_trace = false,
        allow_f_increases = true,
        extended_trace = true,
        callback = optim_callback)
    ############################################################################
    # Initial variance
    θ  = zeros(T, lmm.covstr.tl)
    if isa(init, Vector{T})
        if length(θ) == length(init)
            copyto!(θ, init)
            lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Using provided θ: "*string(θ)))
        else
            error("init length $(length(init)) != θ length $(length(θ))")
        end
    else
        initθ = sqrt(initvar(lmm.data.yv, lmm.mm.m)[1])/(length(lmm.covstr.random)+1)
        #θ                      .= initθ
        for i = 1:length(θ)
            if lmm.covstr.ct[i] == :var
                θ[i] = initθ
            elseif lmm.covstr.ct[i] == :rho
                θ[i] = 1e-4
            end
        end
        lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Initial θ: "*string(θ)))
    end
    # Initial step with modified Newton method
    chunk  = ForwardDiff.Chunk{1}()
    if isa(aifirst, Bool)
        if aifirst aifirst == :ai else aifirst == :default end
    end
    ############################################################################
    if aifirst == :ai || aifirst == :score
        optstep!(lmm, data, θ; method = aifirst, maxopt = 10)
        lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "First step with AI-like method ($aifirst), θ: "*string(θ)))
    end
    varlinkrvecapply!(θ, lmm.covstr.ct; varlinkf = varlinkf, rholinkf = rholinkf)

    # Twice differentiable object
    vloptf(x) = optfunc(lmm, data, varlinkvecapply(x, lmm.covstr.ct; varlinkf = varlinkf, rholinkf = rholinkf))[1]
    gcfg   = ForwardDiff.GradientConfig(vloptf, θ, chunk)
    hcfg   = ForwardDiff.HessianConfig(vloptf, θ, chunk)
    gfunc!(g, x) = ForwardDiff.gradient!(g, vloptf, x, gcfg, Val{false}())
    hfunc!(h, x) = begin
        ForwardDiff.hessian!(h, vloptf, x, hcfg, Val{false}())
    end
    td = TwiceDifferentiable(vloptf, gfunc!, hfunc!, θ)
    # Optimization object
    try
        lmm.result.optim  = Optim.optimize(td, θ, optmethod, optoptions)
    catch e
        lmmlog!(lmm, LMMLogMsg(:ERROR, "Newton method failed, try LBFGS. Error: $e"))
        optmethod  = LBFGS_OM
        lmm.result.optim  = Optim.optimize(td, θ, optmethod, optoptions)
    end
        # Theta (θ) vector
    lmm.result.theta  = varlinkvecapply!(deepcopy(Optim.minimizer(lmm.result.optim)), lmm.covstr.ct; varlinkf = varlinkf, rholinkf = rholinkf)
    lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Resulting θ: "*string(lmm.result.theta)*"; $(Optim.iterations(lmm.result.optim)) iterations."))

        # -2 LogREML, β, iC
    lmm.result.reml, lmm.result.beta, iC, θ₃, noerrors = optfunc(lmm, data, lmm.result.theta)
        # If errors in last evaluetion - log it.
    if !noerrors LMMLogMsg(:ERROR, "The last optimization step wasn't accurate. Results can be wrong!") end
        # Fit true
    if !isnan(lmm.result.reml) && !isinf(lmm.result.reml) && noerrors
        # Variance-vovariance matrix of β
        lmm.result.c            = inv(Matrix(iC))
        # SE
        if  !any(x-> x < 0.0, diag(lmm.result.c))
            lmm.result.se           = sqrt.(diag(lmm.result.c))
            if any(x-> x < 1e-8, lmm.result.se) && minimum(lmm.result.se)/maximum(lmm.result.se) < 1e-8 lmmlog!(io, lmm, verbose, LMMLogMsg(:WARN, "Some of the SE parameters is suspicious.")) end
            lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Model fitted."))
            lmm.result.fit      = true
        end
    end
    # Check G
    if lmm.covstr.random[1].covtype.s != :ZERO
        for i = 1:length(lmm.covstr.random)
            dg = det(gmatrix(lmm, i))
            if dg < 1e-8 lmmlog!(io, lmm, verbose, LMMLogMsg(:WARN, "det(G) of random effect $(i) is less 1e-08.")) end
        end
    end
    # Check Hessian
    if hes && lmm.result.fit
            # Hessian
        lmm.result.h      = hessian(lmm, lmm.result.theta)
            # H positive definite check
        if !isposdef(Symmetric(lmm.result.h))
            lmmlog!(io, lmm, verbose, LMMLogMsg(:WARN, "Hessian is not positive definite."))
        end
        qrd = qr(lmm.result.h, Val(true))
        for i = 1:length(lmm.result.theta)
            if abs(qrd.R[i,i]) < 1E-8
                if lmm.covstr.ct[qrd.jpvt[i]] == :var
                    lmmlog!(io, lmm, verbose, LMMLogMsg(:WARN, "Hessian parameter (variation) QR.R diagonal value ($(qrd.jpvt[i])) is less than 1e-8."))
                elseif lmm.covstr.ct[qrd.jpvt[i]] == :rho
                    lmmlog!(io, lmm, verbose, LMMLogMsg(:WARN, "Hessian parameter (rho) QR.R diagonal value ($(qrd.jpvt[i])) is less than 1e-8."))
                end
            end
        end
    end
    #
    if !lmm.result.fit
        lmmlog!(io, lmm, verbose, LMMLogMsg(:INFO, "Model NOT fitted."))
    end
    # return
    lmm
end

function optstep!(lmm, data, θ; method::Symbol = :ai, maxopt::Int=10)
    if method == :ai ai_func = sweep_ai else ai_func = sweep_score end
    reml, beta, θs₂, θ₃, rt = reml_sweep_β(lmm, data, θ)
    rt || error("Wrong initial conditions.")
    chunk  = ForwardDiff.Chunk{1}()
    aif(x) = ai_func(lmm, data, x, beta)
    grf(x) = reml_sweep_β(lmm, data, x, beta)[1]
    aihcfg = ForwardDiff.HessianConfig(aif, θ, chunk)
    aigcfg = ForwardDiff.GradientConfig(grf, θ, chunk)
    ai = ForwardDiff.hessian(aif, θ, aihcfg, Val{false}())
    gr = ForwardDiff.gradient(grf, θ, aigcfg, Val{false}())
    θt = similar(θ)
    try
        mul!(θt, inv(ai), gr)
    catch
        mul!(θt, pinv(ai), gr)
    end
    for i = 1:length(θ)
        if lmm.covstr.ct[i] == :rho
            if θ[i] - θt[i] > 1.0 - eps() θt[i] = θ[i] - 1.0 + eps() elseif θ[i] - θt[i] < -1.0 + eps() θt[i] = θ[i] + 1.0 - eps() end
        else
            if θ[i] - θt[i] < eps() θt[i] = θ[i] / 2.0 end
        end
    end
    local maxopti = maxopt
    local remlc
    while maxopti > 0
        θr = θ - θt
        remlc, beta, θs₂, θ₃, rt = reml_sweep_β(lmm, data, θr)
        maxopti -= 1
        if rt && remlc < reml return copyto!(θ, θr), remlc, maxopt-maxopti, true else θt ./= 2.0 end
    end
    return θ, remlc, maxopt-maxopti, false
end


text:
# By default, Julia/LLVM does not use fused multiply-add operations (FMAs).
# Since these FMAs can increase the performance of many numerical algorithms,
# we need to opt-in explicitly.
# See https://ranocha.de/blog/Optimizing_EC_Trixi for further details.
@muladd begin

# Initialize data structures in element container
function init_elements!(elements, mesh::StructuredMesh{2}, basis::LobattoLegendreBasis)
  @unpack node_coordinates, left_neighbors,
          jacobian_matrix, contravariant_vectors, inverse_jacobian = elements

  linear_indices = LinearIndices(size(mesh))

  # Calculate node coordinates, Jacobian matrix, and inverse Jacobian determinant
  for cell_y in 1:size(mesh, 2), cell_x in 1:size(mesh, 1)
    element = linear_indices[cell_x, cell_y]

    calc_node_coordinates!(node_coordinates, element, cell_x, cell_y, mesh.mapping, mesh, basis)

    calc_jacobian_matrix!(jacobian_matrix, element, node_coordinates, basis)

    calc_contravariant_vectors!(contravariant_vectors, element, jacobian_matrix)

    calc_inverse_jacobian!(inverse_jacobian, element, jacobian_matrix)
  end

  initialize_left_neighbor_connectivity!(left_neighbors, mesh, linear_indices)

  return nothing
end

# Calculate physical coordinates to which every node of the reference element is mapped
# `mesh.mapping` is passed as an additional argument for type stability (function barrier)
function calc_node_coordinates!(node_coordinates, element,
                                cell_x, cell_y, mapping,
                                mesh::StructuredMesh{2},
                                basis::LobattoLegendreBasis)
  @unpack nodes = basis

  # Get cell length in reference mesh
  dx = 2 / size(mesh, 1)
  dy = 2 / size(mesh, 2)

  # Calculate node coordinates of reference mesh
  cell_x_offset = -1 + (cell_x-1) * dx + dx/2
  cell_y_offset = -1 + (cell_y-1) * dy + dy/2

  for j in eachnode(basis), i in eachnode(basis)
    # node_coordinates are the mapped reference node_coordinates
    node_coordinates[:, i, j, element] .= mapping(cell_x_offset + dx/2 * nodes[i],
                                                  cell_y_offset + dy/2 * nodes[j])
  end
end

# Calculate Jacobian matrix of the mapping from the reference element to the element in the physical domain
function calc_jacobian_matrix!(jacobian_matrix, element, node_coordinates::AbstractArray{<:Any, 4}, basis::LobattoLegendreBasis)
  @unpack derivative_matrix = basis

  # The code below is equivalent to the following matrix multiplications, which
  # seem to end up calling generic linear algebra code from Julia. Thus, the
  # optimized code below using `@turbo` is much faster.
  # jacobian_matrix[1, 1, :, :, element] = derivative_matrix * node_coordinates[1, :, :, element]  # x_ξ
  # jacobian_matrix[2, 1, :, :, element] = derivative_matrix * node_coordinates[2, :, :, element]  # y_ξ
  # jacobian_matrix[1, 2, :, :, element] = node_coordinates[1, :, :, element] * derivative_matrix' # x_η
  # jacobian_matrix[2, 2, :, :, element] = node_coordinates[2, :, :, element] * derivative_matrix' # y_η

  # x_ξ, y_ξ
  @turbo for xy in indices((jacobian_matrix, node_coordinates), (1, 1))
    for j in indices((jacobian_matrix, node_coordinates), (4, 3)), i in indices((jacobian_matrix, derivative_matrix), (3, 1))
      result = zero(eltype(jacobian_matrix))
      for ii in indices((node_coordinates, derivative_matrix), (2, 2))
        result += derivative_matrix[i, ii] * node_coordinates[xy, ii, j, element]
      end
      jacobian_matrix[xy, 1, i, j, element] = result
    end
  end

  # x_η, y_η
  @turbo for xy in indices((jacobian_matrix, node_coordinates), (1, 1))
    for j in indices((jacobian_matrix, derivative_matrix), (4, 1)), i in indices((jacobian_matrix, node_coordinates), (3, 2))
      result = zero(eltype(jacobian_matrix))
      for jj in indices((node_coordinates, derivative_matrix), (3, 2))
        result += derivative_matrix[j, jj] * node_coordinates[xy, i, jj, element]
      end
      jacobian_matrix[xy, 2, i, j, element] = result
    end
  end

  return jacobian_matrix
end

# Calculate contravarant vectors, multiplied by the Jacobian determinant J of the transformation mapping.
# Those are called Ja^i in Kopriva's blue book.
function calc_contravariant_vectors!(contravariant_vectors::AbstractArray{<:Any,5}, element, jacobian_matrix)
  # The code below is equivalent to the following using broadcasting but much faster.
  # # First contravariant vector Ja^1
  # contravariant_vectors[1, 1, :, :, element] =  jacobian_matrix[2, 2, :, :, element]
  # contravariant_vectors[2, 1, :, :, element] = -jacobian_matrix[1, 2, :, :, element]
  # # Second contravariant vector Ja^2
  # contravariant_vectors[1, 2, :, :, element] = -jacobian_matrix[2, 1, :, :, element]
  # contravariant_vectors[2, 2, :, :, element] =  jacobian_matrix[1, 1, :, :, element]

  @turbo for j in indices((contravariant_vectors, jacobian_matrix), (4, 4)),
             i in indices((contravariant_vectors, jacobian_matrix), (3, 3))
    # First contravariant vector Ja^1
    contravariant_vectors[1, 1, i, j, element] =  jacobian_matrix[2, 2, i, j, element]
    contravariant_vectors[2, 1, i, j, element] = -jacobian_matrix[1, 2, i, j, element]

    # Second contravariant vector Ja^2
    contravariant_vectors[1, 2, i, j, element] = -jacobian_matrix[2, 1, i, j, element]
    contravariant_vectors[2, 2, i, j, element] =  jacobian_matrix[1, 1, i, j, element]
  end

  return contravariant_vectors
end

# Calculate inverse Jacobian (determinant of Jacobian matrix of the mapping) in each node
function calc_inverse_jacobian!(inverse_jacobian::AbstractArray{<:Any,3}, element, jacobian_matrix)
  # The code below is equivalent to the following high-level code but much faster.
  # inverse_jacobian[i, j, element] = inv(det(jacobian_matrix[:, :, i, j, element])

  @turbo for j in indices((inverse_jacobian, jacobian_matrix), (2, 4)),
             i in indices((inverse_jacobian, jacobian_matrix), (1, 3))
    inverse_jacobian[i, j, element] = inv(jacobian_matrix[1, 1, i, j, element] * jacobian_matrix[2, 2, i, j, element] -
                                          jacobian_matrix[1, 2, i, j, element] * jacobian_matrix[2, 1, i, j, element])
  end

  return inverse_jacobian
end

# Save id of left neighbor of every element
function initialize_left_neighbor_connectivity!(left_neighbors, mesh::StructuredMesh{2}, linear_indices)
  # Neighbors in x-direction
  for cell_y in 1:size(mesh, 2)
    # Inner elements
    for cell_x in 2:size(mesh, 1)
      element = linear_indices[cell_x, cell_y]
      left_neighbors[1, element] = linear_indices[cell_x - 1, cell_y]
    end

    if isperiodic(mesh, 1)
      # Periodic boundary
      left_neighbors[1, linear_indices[1, cell_y]] = linear_indices[end, cell_y]
    else
      # Use boundary conditions
      left_neighbors[1, linear_indices[1, cell_y]] = 0
    end
  end

  # Neighbors in y-direction
  for cell_x in 1:size(mesh, 1)
    # Inner elements
    for cell_y in 2:size(mesh, 2)
      element = linear_indices[cell_x, cell_y]
      left_neighbors[2, element] = linear_indices[cell_x, cell_y - 1]
    end

    if isperiodic(mesh, 2)
      # Periodic boundary
      left_neighbors[2, linear_indices[cell_x, 1]] = linear_indices[cell_x, end]
    else
      # Use boundary conditions
      left_neighbors[2, linear_indices[cell_x, 1]] = 0
    end
  end

  return left_neighbors
end

end # @muladd


text:
# [Julia package for function approximation](https://github.com/JuliaApproximation/ApproxFun.jl)

using ApproxFun

x = Fun(identity, 0..100)

g = sqrt(x)

g2 = g(2)

x = Fun(identity, 0.1 .. 1.)

w = Fun(identity,0.1 .. 1.)

T = Fun(identity,0.1 .. 1.)

ν = Fun(identity,0.1 .. 1.)

#kern = ν^4 * besselj(1, 2π*√(x*x+w*w/4) )^2

kern = Fun( x -> (ν^4 * besselj(1, 2π*√(x*x+w*w/4) )^2 / (x^2 + w^2/4) - T)^2 )

max_stars_repo_name: alsam/julia-samples

max_issues_repo_name: alsam/julia-samples

max_forks_repo_name: alsam/julia-samples


text:
julia> Pkg.add("Primes")
julia> factor(8796093022207)
[9719=>1,431=>1,2099863=>1]

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
# This file is a part of NeighborhoodApproximationIndex.jl

import SimilaritySearch: search, getpools, index!
using InvertedFiles, Intersections, KCenters, StatsBase, Parameters, LinearAlgebra
export KnrIndex, search, KnrOrderingStrategies, DistanceOrdering, InternalDistanceOrdering, DistanceOnTopKOrdering

mutable struct KnrOpt
    ksearch::Int32
end

abstract type KnrOrderingStrategy end

"""
    struct DistanceOrdering <: KnrOrderingStrategy end

Used as `ordering` parameter of `KnrIndex` specifies that each object `u` found by the inverted index will be evaluated against a given query.
This is the default ordering strategy.
"""
struct DistanceOrdering <: KnrOrderingStrategy end

"""
    struct InternalDistanceOrdering <: KnrOrderingStrategy end

Used as `ordering` parameter of `KnrIndex` specifies that the internal distance of the underlying inverted index will be used to ordering the `k` nearest neighbors.
Useful when the internal distance is quite representative of the real distance metric or whenever speed is the major objective.
"""
struct InternalDistanceOrdering <: KnrOrderingStrategy end

"""
    struct DistanceOnTopKOrdering <: KnrOrderingStrategy
        top::Int
    end

Used as `ordering` parameter of `KnrIndex` specifies that only the `top` elements are evaluated against the distance metric. Useful for very costly distance functions. If you are in doubt please use `DistanceOrdering` instead.
"""
mutable struct DistanceOnTopKOrdering <: KnrOrderingStrategy
    top::Int
end

"""
    struct KnrIndex <: AbstractSearchContext

The K nearest references inverted index

# Parameters

- `dist`: the distance function of the index
- `db`: the database of indexed objects
- `centers`: a search index for a set of references
- `invfile`: an inverted file data structure
- `kbuild`: the number of references to be computed and stored by each indexed object
- `ordering`: specifies how the index performs final `k` nn selection
- `opt`: the parameters to be optimized by `optimize!`
"""
struct KnrIndex{
            DistType<:SemiMetric,
            DataType<:AbstractDatabase,
            CentersIndex<:AbstractSearchContext,
            InvIndexType<:AbstractInvertedFile,
            OrderingType<:KnrOrderingStrategy
        } <: AbstractSearchContext
    dist::DistType
    db::DataType
    centers::CentersIndex
    invfile::InvIndexType
    kbuild::Int32
    ordering::OrderingType
    opt::KnrOpt
end

@inline Base.length(idx::KnrIndex) = length(idx.invfile)
Base.show(io::IO, idx::KnrIndex) = print(io, "{$(typeof(idx)) centers=$(typeof(idx.centers)), n=$(length(idx)), ordering=$(idx.ordering)}")

"""
    struct KnrCaches
        enc
    end

Caches used for `KnrIndex` (one per thread)

# Properties
- `enc`: `KnnResult` for encoding purposes
"""
struct KnrCaches
    enc::KnnResult
end

const GlobalKnrCachesPool = Vector{KnrCaches}(undef, 0)

function __init__()
    n = Threads.nthreads()

    while length(GlobalKnrCachesPool) < n
        push!(GlobalKnrCachesPool, KnrCaches(KnnResult(10)))
    end
end

getpools(idx::KnrIndex) = GlobalKnrCachesPool

function getencodeknnresult(k::Integer, pools::Vector{KnrCaches})
    reuse!(pools[Threads.threadid()].enc, k)
end

"""
    push!(idx::KnrIndex, obj; pools=getpools(idx), encpools=getpools(idx.centers))

Inserts `obj` into the indexed
"""
function Base.push!(idx::KnrIndex, obj; pools=getpools(idx), encpools=getpools(idx.centers))
    res = getencodeknnresult(idx.kbuild, pools)
    search(idx.centers, obj, res; pools=encpools)
    push!(idx.invfile, res)
    idx
end

"""
    get_parallel_block(n)

An heuristic to compute the `parallel_block` with respect with the number of elements to insert
"""
get_parallel_block(n) = min(n, 8 * Threads.nthreads())

"""
    append!(idx::KnrIndex, db; <kwargs>)

Appends all items in the database `db` into the index

# Arguments
- `idx`: the index structure
- `db`: the objects to be appended

# Keyword arguments
- `parallel_block`: the number of elements to be inserted in parallel
- `pools`: unused argument
- `verbose`: controls the verbosity of the procedure
"""
function Base.append!(idx::KnrIndex, db;
        parallel_block=get_parallel_block(length(db)),
        pools=getpools(idx),
        verbose=true
    )

    append!(idx.db, db)
    index!(idx; parallel_block, pools, verbose)
end

"""
    index!(idx::KnrIndex; parallel_block=get_parallel_block(length(idx.db)), pools=nothing, verbose=true)

Indexes all non indexed items in the database

# Arguments

- `idx`: the index structure

# Keyword arguments
- `parallel_block`: the number of elements to be inserted in parallel
- `pools`: unused parameter
- `verbose`: controls verbosity of the procedure

"""
function index!(idx::KnrIndex; parallel_block=get_parallel_block(length(idx.db)), pools=nothing, verbose=true)
    sp = length(idx) + 1
    n = length(idx.db)
    E = [KnnResult(idx.kbuild) for _ in 1:parallel_block]
    while sp < n
        ep = min(n, sp + parallel_block - 1)
        verbose && println(stderr, "$(typeof(idx)) appending chunk ", (sp=sp, ep=ep, n=n), " ", Dates.now())

        Threads.@threads for i in sp:ep
            begin
                res = reuse!(E[i - sp + 1], idx.kbuild)
                search(idx.centers, idx[i], res)
            end
        end

        append!(idx.invfile, VectorDatabase(E), ep-sp+1; parallel_block)
        sp = ep + 1
    end
end

"""
    KnrIndex(
        dist::SemiMetric,
        db::AbstractDatabase;
        invfiletype=BinaryInvertedFile,
        invfiledist=JaccardDistance(),
        initial=:dnet,
        maxiters=0,
        refs=references(dist, db; initial),
        centers=nothing,
        kbuild=3,
        ksearch=1,
        centersrecall::AbstractFloat=length(db) > 10^3 ? 0.95 : 1.0,
        ordering=DistanceOrdering(),
        pools=nothing,
        parallel_block=get_parallel_block(length(db)),
        verbose=false
    )

A convenient function to create a `KnrIndex`, it uses several default arguments. After the construction, use [`optimize!`](@ref) to adjust the index to some performance.

# Arguments
- `dist`: Distance object (a `SemiMetric` object, see `Distances.jl`)
- `db`: The database of objects to be indexed.

# Keyword arguments
- `invfiletype`: the type of the underlying inverted file (`BinaryInvertedFile` or `WeightedInvertedFile`)
- `invfiledist`: the distance of the underlying inverted file (see [`InvertedFiles.jl`](https://github.com/sadit/InvertedFiles.jl) package)
- `centers`: The index used for centers/references, if `centers === nothing` then a sample of `db` will be used.
- `initial`: indicates how references are selected, only used if `refs` will be computed; see [`references`](@ref) for more detail.
- `maxiters`: how many iterations of the Lloyd algorithm are applied to initial references, only used if `refs` will be computed; see [`references`](@ref) for more detail.
- `refs`: the set of reference, only used if `centers === nothing`
- `centersrecall`: used when `centers === nothing`; if `centersrecall == 1` then it will create an exact index on `refs` or an approximate if `0 < centersrecall < 1`
- `kbuild`: the number of references to compute and store on construction
- `ksearch`: the number of references to compute on searching
- `ordering`: the ordering strategy
- `pools`: an object with preallocated caches specific for `KnrIndex`, if `pools=nothing` it will use default caches.
- `parallel_block` Parallel construction works on batches, this is the size of these blocks
- `verbose` true if you want to see messages
"""
function KnrIndex(
        dist::SemiMetric,
        db::AbstractDatabase;
        invfiletype=BinaryInvertedFile,
        invfiledist=JaccardDistance(),
        initial=:dnet,
        maxiters=0,
        refs=references(dist, db; initial, maxiters),
        centers=nothing,
        kbuild::Integer=3,
        ksearch::Integer=1,
        centersrecall::AbstractFloat=length(db) > 10^3 ? 0.95 : 1.0,
        ordering::KnrOrderingStrategy=DistanceOrdering(),
        pools=nothing,
        parallel_block::Integer=get_parallel_block(length(db)),
        verbose=false
    )
    kbuild = convert(Int32, kbuild)
    ksearch = convert(Int32, ksearch)

    if centers === nothing
        if centersrecall == 1.0
            centers = ExhaustiveSearch(; db=refs, dist)
        else
            0 < centersrecall < 1 || throw(ArgumentError("the expected recall for centers index should be 0 < centersrecall < 0"))
            centers = SearchGraph(; db=refs, dist, verbose)
            index!(centers; parallel_block)
            optimize!(centers, OptimizeParameters(kind=MinRecall(centersrecall)))
        end
    end

    invfile = invfiletype(length(centers), invfiledist)
    idx = KnrIndex(dist, db, centers, invfile, kbuild, ordering, KnrOpt(ksearch))
    pools = pools === nothing ? getpools(idx) : pools
    index!(idx; parallel_block, pools, verbose)
    idx
end

max_stars_repo_name: sadit/NeighborhoodApproximationIndex

max_issues_repo_name: sadit/NeighborhoodApproximationIndex

max_forks_repo_name: sadit/NeighborhoodApproximationIndex


text:
import Base
using JSON, Gtk, HTTP # Requests

export FetchPage
# ======================================================================================
# Generate the DOM by recursively reading the dict conatining all structural and
# stylistic data.
# ======================================================================================
function CreateDomTree(document::Page, parent::Element)
    DOM = parent.DOM
    if isa(DOM["nodes"], Array)
        for DOM_node in DOM["nodes"]
            push!(parent.children, Element(DOM_node))
            node = parent.children[end]
            if haskey(DOM_node, "nodes") # Instantiate Children
                CreateDomTree(document, node)
            end
        end
    end
end
# ======================================================================================
#
# ======================================================================================
# function newPage(document, name)
#         node = document.children[1]
#         parent = document.parent
#
# end
# ======================================================================================
# win::Gtk.GtkWindowLeafGtk.GtkCanvas
# ======================================================================================
# function FetchPage(win, URL::String, canvas::Gtk.GtkCanvas, wide)
function FetchPage(document, URL::String)

    node = document.children[1]
       # .......................................................................
       # get the file...
       uri = HTTP.parse(HTTP.URI, URL)
              if uri.scheme == "file"
                 File = pwd() * uri.path
                       Page_text = open(f->read(f, String), File)
              elseif uri.scheme == "http" || uri.scheme == "https"
                  got = HTTP.request("GET", URL; verbose=3).body
                  Page_text = readall(got)
              end

        pageContent = readSml(Page_text)
        # ......................................................................
        document.styles = Dict("charset"=>"utf-8")
        document.head = Dict("charset"=>"utf-8","author"=>"Travis Deane Ashworth","links"=>Dict("url"=>"http://travis.net16.net/test.sml"),"keywords"=>"web tech,browser concept,sml Pages,fragmented web tech","title"=>"MyPage")

                push!(node.DOM["nodes"], tabControls)
                push!(node.DOM["nodes"], navigation)

                tab["nodes"][2]["text"] = document.head["title"]
                plus = pop!(tabControls["nodes"][1]["nodes"]) # Take button off end.
                push!(tabControls["nodes"][1]["nodes"], tab)  # Add new tab.
                push!(tabControls["nodes"][1]["nodes"], plus) # put button back on.
                # Page content
                newPage["nodes"] = [pageContent]
                push!(node.DOM["nodes"], newPage)
        # ......................................................................
        CreateDomTree(document, node)
end
# ======================================================================================


text:
function move(instructions, dir = Complex(1, 0), way = Complex(10, 1), pos = Complex(0, 0))
    pos1 = pos2 = pos
    directions = Dict([("N", Complex(0, 1)), ("S", Complex(0, -1)), ("E", Complex(1, 0)), ("W", Complex(-1, 0))])
    for instruction in instructions
        (cmd, num) = match(r"([NSEWLRF])([0-9]+)", instruction).captures
        val = parse(Int, num)
        if cmd == "F"
            pos1, pos2 = map(x -> x[1] += x[2] * val, [[pos1, dir], [pos2, way]])
        elseif cmd == "L"
            dir, way = map(x -> x *= Complex(0, 1)^div(val, 90), [dir, way])
        elseif cmd == "R"
            dir, way = map(x -> x *= Complex(0, -1)^div(val, 90), [dir, way])
        else
            pos1, way = map(x -> x += val * get(directions, cmd, nothing), [pos1, way])
        end
    end
    return map(x -> abs(real(x)) + abs(imag(x)), [pos1, pos2])
end

instructions = readlines("d12.in")
(pos1, pos2) = move(instructions)
println("P1: ", pos1)
println("P2: ", pos2)

max_stars_repo_name: eduellery/adventofcode

max_issues_repo_name: eduellery/adventofcode

max_forks_repo_name: eduellery/adventofcode


text:
module RecurrentNN
import Base.tanh

export Model, RNN, LSTM, GRU, GFLSTM, GFGRU
export NNMatrix, randNNMat, forwardprop, softmax
export Solver, step!, AdamSolver, RMSPropSolver
export SolverParams, AdamSolverParams, RMSPropSolverParams
export Graph, backprop!, rowpluck!

include("recurrent.jl")
include("graph.jl")
include("solver.jl")
include("rmspropsolver.jl")
include("adamsolver.jl")
include("rnn.jl")
include("lstm.jl")
include("gru.jl")
include("gflstm.jl")
include("gfgru.jl")

end # module

max_forks_repo_name: haroldsoh/RecurrentNN


text:
############################################################################################
# Models to be used in construction
objectives = [
    Objective(ModelWrapper(MyBaseModel(), myparameter1, FlattenDefault()), data_uv),
    Objective(ModelWrapper(MyBaseModel(), myparameter1, FlattenDefault(; output = Float32)), data_uv)
]
generated = [UpdateFalse(), UpdateTrue()]
#=
iter=1
=#

############################################################################################
## Make model for several parameter types
for iter in eachindex(objectives)
    _obj = objectives[iter]
    _flattentype = _obj.model.info.reconstruct.default.output
    @testset "Kernel construction and propagation, ASMC with MCMC" begin
        ## MCMC
        mcmc = MCMC(NUTS,(:μ, :σ,); stepsize = ConfigStepsize(;stepsizeadaption = UpdateFalse()))
        kerneldefault  = SMCDefault(Ntuning = 5, jittermin = 1, jittermax = 5)
        samplingdefault = SampleDefault(chains = 4)
        smc_c = SMCConstructor(mcmc, SMCDefault(;generated = generated[iter]))
        smc_c(_rng, _obj.model, _obj.data, _obj.temperature, samplingdefault)
        SMC(_rng, mcmc, _obj, kerneldefault, samplingdefault)
        @test BaytesCore.get_sym(mcmc) == BaytesSMC.get_sym(smc_c)
        ## Propose new parameter
        smc = SMC(_rng, mcmc, _obj, SMCDefault(;generated = generated[iter]))
        vals, diagnostics = propose!(_rng, smc, _obj.model, _obj.data)
        @test eltype(diagnostics.ρ) == _flattentype
        vals, diagnostics = propose!(_rng, smc, _obj.model, _obj.data, _obj.temperature, UpdateFalse())
        @test eltype(diagnostics.ρ) == _flattentype
        ## Postprocessing
        generate_showvalues(diagnostics)()
        diagtype = infer(_rng, AbstractDiagnostics, smc, _obj.model, _obj.data)
        @test diagnostics isa diagtype
        TGenerated = BaytesSMC.infer_generated(_rng, smc, _obj.model, _obj.data)
        @test diagnostics.generated isa TGenerated
        diags = Vector{diagtype}(undef, 100)
        for iter in eachindex(diags)
            _, diags[iter] = propose!(_rng, smc, _obj.model, _obj.data)
        end
        results(diags, smc, 2, [.1, .2, .5, .8, .9])
    end
end

@testset "Kernel construction and propagation, ASMC with PMCMC" begin
    ## MCMC
    pfdefault_pmcmc = ParticleFilterDefault(referencing = Ancestral(),)
    mcmcdefault = MCMCDefault(; stepsize = ConfigStepsize(;stepsizeadaption = UpdateFalse()))
    pmcmc = ParticleGibbs(
        ParticleFilterConstructor(keys(myobjective_pf.tagged.parameter), pfdefault_pmcmc),
        MCMCConstructor(NUTS, keys(myobjective_mcmc.tagged.parameter), mcmcdefault)
    )
    ## Propose new parameter
    @test length(myobjective_mcmc.model.val.latent) == length(myobjective_mcmc.data)
    smc = SMC(_rng, pmcmc, myobjective_mcmc)
    vals, diagnostics = propose!(
        _rng,
        smc,
        myobjective_mcmc.model,
        myobjective_mcmc.data,
        myobjective_mcmc.temperature,
        UpdateTrue()
    )

    ## Postprocessing
    diagtype = infer(_rng, AbstractDiagnostics, smc, myobjective_mcmc.model, myobjective_mcmc.data)
    @test diagnostics isa diagtype
    smc = SMC(_rng, pmcmc, myobjective_mcmc)
    diags = Vector{diagtype}(undef, 100)
    for iter in eachindex(diags)
        _, diags[iter] = propose!(
            _rng,
            smc,
            myobjective_mcmc.model,
            myobjective_mcmc.data,
            myobjective_mcmc.temperature,
            UpdateTrue()
        )
    end
    results(diags, smc, 2, [.1, .2, .5, .8, .9])
end

############################################################################################
## Check IBIS
for iter in eachindex(objectives)
    _obj = objectives[iter]
    _flattentype = _obj.model.info.reconstruct.default.output
    @testset "Kernel construction and propagation, IBIS" begin
        ## Assign smc kernel ~ use PMCMC to check both MCMC and Particle Filter
        ## MCMC
        mcmc = MCMC(NUTS,(:μ, :σ,); stepsize = ConfigStepsize(;stepsizeadaption = UpdateFalse()))
        kerneldefault  = SMCDefault(Ntuning = 5, jittermin = 1, jittermax = 5)
        samplingdefault = SampleDefault(chains = 4)
        smc_c = SMCConstructor(mcmc, SMCDefault())

        #Create new objective with small amount of data
        _obj2 = Objective(_obj.model, _obj.data[1:50])
        SMC(_rng, mcmc, _obj2, kerneldefault, samplingdefault)
        @test BaytesCore.get_sym(mcmc) == BaytesSMC.get_sym(smc_c)
        ## Propose new parameter
        smc = SMC(_rng, mcmc, _obj2)
        vals, diagnostics = propose!(_rng, smc, _obj2.model, _obj2.data)
        @test eltype(diagnostics.ρ) == _flattentype
        ## Postprocessing
        smc = SMC(_rng, mcmc, _obj2)
        diagtype = infer(_rng, AbstractDiagnostics, smc, _obj.model, _obj.data)
        @test diagnostics isa diagtype
        datadiff = length(_obj.data) - length(_obj2.data) - 1
        diags = Vector{diagtype}(undef, datadiff)
        for iter in eachindex(diags)
            data_temp = _obj.data[1:(length(_obj2.data) + iter)]
            _, diags[iter] = propose!(_rng, smc, _obj.model, data_temp)
        end
        results(diags, smc, 2, [.1, .2, .5, .8, .9])
    end
end

############################################################################################
## Check SMC2
@testset "Kernel construction and propagation, SMC2" begin
    ## MCMC
    pfdefault_propagate = ParticleFilterDefault(referencing = Marginal(),)
    pfdefault_pmcmc = ParticleFilterDefault(referencing = Ancestral(),)
    mcmcdefault = MCMCDefault(; stepsize = ConfigStepsize(;stepsizeadaption = UpdateFalse()))

    pmcmc = ParticleGibbs(
        ParticleFilterConstructor(keys(myobjective_pf.tagged.parameter), pfdefault_pmcmc),
        MCMCConstructor(NUTS, keys(myobjective_mcmc.tagged.parameter), mcmcdefault)
    )
    pf = ParticleFilterConstructor(keys(myobjective_pf.tagged.parameter), pfdefault_propagate)
    smc2 = SMC2Constructor(pf, pmcmc)
    SMC2(pf, pmcmc)
    @test keys(myobjective_mcmc.model.val) == BaytesSMC.get_sym(smc2)

    ## Propose new parameter and exten tagged propagation parameter
    _obj = Objective(deepcopy(mymodel), data_init)
    @test length(_obj.model.val.latent) == length(_obj.data)  == N_SMC2
    smc = SMC(_rng, smc2, _obj)
    vals, diagnostics = propose!(
        _rng,
        smc,
        _obj.model,
        data[1:N_SMC2+1],
        1.0,
        UpdateTrue()
    )
    @test length(mymodel.val.latent) == N_SMC2
    @test length(_obj.model.val.latent) == N_SMC2 + 1
    ## Postprocessing
    diagtype = infer(_rng, AbstractDiagnostics, smc, _obj.model, _obj.data)
    @test diagnostics isa diagtype

    _obj = Objective(deepcopy(mymodel), data_init)
    smc = SMC(_rng, smc2, _obj)
    diags = Vector{diagtype}(undef, 100)
    for iter in eachindex(diags)
        data_temp = data[1:N_SMC2+iter]
        _, diags[iter] = propose!(
            _rng,
            smc,
            _obj.model,
            data_temp,
            1.0,
            UpdateTrue()
        )
    end
    results(diags, smc, 2, [.1, .2, .5, .8, .9])
end


text:
export read_line_by_line, xor_tensor

"""read a file to data type T line by line, and convert to a vector."""
function read_line_by_line(::Type{T}, filename::String) where T
    map.(s -> parse(T, s), split.(eachline(filename), '\t'))
end

function control3(::Type{T}; inverse::Bool=false) where {T}
    tensor = zeros(T, 2,2,2)
    a, b = [1,0], [0,1]
    tensor[1,1,:] .= inverse ? b : a
    tensor[2,2,:] .= inverse ? a : b
    return tensor
end

function control4(::Type{T}; inverse::Bool=false) where {T}
    tensor = zeros(T, 2,2,2,2)
    a, b = [1,0], [0,1]
    tensor[1,1,1,:] .= a
    tensor[2,2,1,:] .= a
    tensor[1,1,2,:] .= inverse ? b : a
    tensor[2,2,2,:] .= inverse ? a : b
    return tensor
end

function xor_tensor(::Type{T}) where {T}
    tensor = zeros(T, 2,2,2)
    tensor[:,:,1] .= [1 0; 0 1]
    tensor[:,:,2] .= [0 1; 1 0]
    return tensor
end


text:
using Base.Test

include("bob.jl")

questions = (
        "Does this cryogenic chamber make me look fat?",
        "You are, what, like 15?",
        "fffbbcbeab?",
        "4?", ":) ?",
        "Wait! Hang on. Are you going to be OK?",
        "Okay if like my  spacebar  quite a bit?   ",
)

yells = (
        "WATCH OUT!",
        "FCECDFCAAB",
        "WHAT THE HELL WERE YOU THINKING?",
        "1, 2, 3 GO!",
        "ZOMG THE %^*@#\$(*^ ZOMBIES ARE COMING!!11!!1!",
        "I HATE YOU",
)

silences = (
        "",
        "          ",
        "\t\t\t\t\t\t\t\t\t\t",
        "\n\r \t",
)

miscs = (
        "Tom-ay-to, tom-aaaah-to.",
        "Let's go make out behind the gym!",
        "It's OK if you don't want to go to the DMV.",
        "1, 2, 3",
        "Ending with ? means a question.",
        "\nDoes this cryogenic chamber make me look fat?\nno",
        "         hmmmmmmm...",
        "This is a statement ending with whitespace      ",
)

response = Dict(
        :question => "Sure.",
        :yelling => "Whoa, chill out!",
        :silence => "Fine. Be that way!",
        :misc => "Whatever."
)

@testset "questions" begin
    @testset "$question" for question in questions
        @test bob(question) == response[:question]
    end
end

@testset "yelling" begin
    @testset "$yell" for yell in yells
        @test bob(yell) == response[:yelling]
    end
end

@testset "silence" begin
    @testset "$silence" for silence in silences
        @test bob(silence) == response[:silence]
    end
end

@testset "misc" begin
    @testset "$misc" for misc in miscs
        @test bob(misc) == response[:misc]
    end
end


text:
### Null curve ###

struct NullIRCurve <: AbstractIRCurve{NullMethod} end

ERF(curve::NullIRCurve, maturity::Date) = 1.0
ERF(curve::NullIRCurve, maturity::YearFraction) = 1.0
ER(curve::NullIRCurve, maturity::Date) = 0.0
ER(curve::NullIRCurve, maturity::YearFraction) = 0.0
discountfactor(curve::NullIRCurve, maturity::Date) = 1.0
discountfactor(curve::NullIRCurve, maturity::YearFraction) = 1.0
curve_get_name(::NullIRCurve) = "NullCurve"
curve_get_date(::NullIRCurve) = error("Date for NullCurve is not defined.")
isnullcurve(curve::NullIRCurve) = true
isnullcurve(curve::AbstractIRCurve) = false
forward_rate(curve::NullIRCurve, forward_date::Date, maturity::Date) = 0.0
forward_rate(curve::NullIRCurve, forward_date::Date, maturity::YearFraction) = 0.0
zero_rate(curve::NullIRCurve, maturity::Date) = 0.0
zero_rate(curve::NullIRCurve, maturity::YearFraction) = 0.0
zero_rate(curve::NullIRCurve, maturity_vec::Vector{Date}) = zeros(length(maturity_vec))


text:
#
# Adding separators to SCIP.Optimizer.
#

"""
    include_sepa(
        o::Optimizer,
        sepa::SEPA;
        name::String,
        description::String,
        priority::Int,
        freq::Int,
        maxbounddist::Float,
        usesubscip::Bool,
        delay::Bool
    )

Include a user defined separator `sepa` to the SCIP optimizer instance `o`.

All parameters have default values, that can be set as keyword arguments.
"""
function include_sepa(o::Optimizer, sepa::SEPA;
                      name="", description="", priority=0, freq=1,
                      maxbounddist=0.0, usessubscip=false,
                      delay=false) where {SEPA <: AbstractSeparator}
    include_sepa(o.inner.scip[], o.inner.sepas, sepa, name=name, description=description,
                 priority=priority, freq=freq, maxbounddist=maxbounddist,
                 usessubscip=usessubscip, delay=delay)
end

#
# Separator for cutcallbacks.
#

mutable struct CutCbSeparator <: AbstractSeparator
    scipd::SCIPData
    cutcallback::Function
end

# If no cut callback is given, the cut callback does nothing.
CutCbSeparator(scipd::SCIPData) = CutCbSeparator(scipd, cb_data -> nothing)

"""
Used for an argument to the cut callback, which in turn uses that argument to
obtain the LP-solution via `MOI.get` and to add cuts via `MOI.submit`.
"""
mutable struct CutCbData
    sepa::CutCbSeparator
    "Did the cut callback call submit?"
    submit_called::Bool
end

function exec_lp(sepa::CutCbSeparator)
    cb_data = CutCbData(sepa, false)
    sepa.cutcallback(cb_data)
    return cb_data.submit_called ? SCIP_SEPARATED : SCIP_DIDNOTFIND
end

#
# MOI Interface for cutcallbacks
#

function MOI.get(o::Optimizer, ::MOI.CallbackVariablePrimal{CutCbData}, vi)
    return SCIPgetSolVal(o, C_NULL, var(o, vi))
end

function MOI.set(o::Optimizer, ::MOI.UserCutCallback, cb::Function)
    if o.moi_separator === nothing
        o.moi_separator = CutCbSeparator(o.inner, cb)
        include_sepa(o, o.moi_separator)
    else
        o.moi_separator.cutcallback = cb;
    end
end
MOI.supports(::Optimizer, ::MOI.UserCutCallback) = true

function MOI.submit(o::Optimizer, cb_data::MOI.UserCut{CutCbData},
                    func::SAF, set::S) where {S <: BOUNDS}
    varrefs = [VarRef(t.variable.value) for t in func.terms]
    coefs = [t.coefficient for t in func.terms]

    lhs, rhs = bounds(set)
    lhs = lhs === nothing ? -SCIPinfinity(o) : lhs
    rhs = rhs === nothing ?  SCIPinfinity(o) : rhs

    add_cut_sepa(o.inner.scip[], o.inner.vars, o.inner.sepas, cb_data.callback_data.sepa, varrefs, coefs, lhs, rhs)
    cb_data.callback_data.submit_called = true
end
MOI.supports(::Optimizer, ::MOI.UserCut{CutCbData}) = true