text:
typealias NULL C_NULL
# begin enum GMT_enum_api
const GMT_USAGE = 0
const GMT_SYNOPSIS = 1
const GMT_STR16 = 16
# end enum GMT_enum_api
const GMT_SESSION_NORMAL   = 0   # Typical mode to GMT_Create_Session
const GMT_SESSION_NOEXIT   = 1   # Call return and not exit when error
const GMT_SESSION_EXTERNAL = 2   # Called by an external API (e.g., Matlab, Julia, Python).
const GMT_SESSION_COLMAJOR = 4   # External API uses column-major formats (e.g., Julai, MATLAB, Fortran). [Row-major format]
# begin enum GMT_enum_type
const GMT_CHAR = 0
const GMT_UCHAR = 1
const GMT_SHORT = 2
const GMT_USHORT = 3
const GMT_INT = 4
const GMT_UINT = 5
const GMT_LONG = 6
const GMT_ULONG = 7
const GMT_FLOAT = 8
const GMT_DOUBLE = 9
const GMT_TEXT = 10
const GMT_DATETIME = 11
const GMT_N_TYPES = 12
# end enum GMT_enum_type
# begin enum GMT_enum_opt
const GMT_OPT_USAGE = 63
const GMT_OPT_SYNOPSIS = 94
const GMT_OPT_PARAMETER = 45
const GMT_OPT_INFILE = 60
const GMT_OPT_OUTFILE = 62
# end enum GMT_enum_opt
immutable GMT_OPTION			# Structure for a single GMT command option
	option::UInt8				# 1-char command line -<option> (e.g. D in -D) identifying the option (* if file)
	arg::Ptr{UInt8}				# If not NULL, contains the argument for this option
	next::Ptr{GMT_OPTION}
	previous::Ptr{GMT_OPTION}
end
# begin enum GMT_enum_method
const GMT_IS_FILE = 0
const GMT_IS_STREAM = 1
const GMT_IS_FDESC = 2
const GMT_IS_DUPLICATE = 3
const GMT_IS_REFERENCE = 4
# end enum GMT_enum_method
# begin enum GMT_enum_via
const GMT_VIA_NONE = 0
const GMT_VIA_OUTPUT = 2048
# end enum GMT_enum_via
# begin enum GMT_enum_family
const GMT_IS_DATASET = 0
const GMT_IS_GRID = 1
const GMT_IS_IMAGE = 2
const GMT_IS_CPT = 3				# To be removed whem >= GMT5.3 only
const GMT_IS_PALETTE = 3
const GMT_IS_POSTSCRIPT = 4
const GMT_IS_TEXTSET = 5
const GMT_IS_MATRIX = 6
const GMT_IS_VECTOR = 7
const GMT_IS_COORD = 8
const GMT_N_FAMILIES = 9
# end enum GMT_enum_family
const GMT_PS_EMPTY = 0
const GMT_PS_HEADER = 1
const GMT_PS_TRAILER = 2
const GMT_PS_COMPLETE = 3
# begin enum GMT_enum_comment
const GMT_COMMENT_IS_TEXT = 0
const GMT_COMMENT_IS_OPTION = 1
const GMT_COMMENT_IS_COMMAND = 2
const GMT_COMMENT_IS_REMARK = 4
const GMT_COMMENT_IS_TITLE = 8
const GMT_COMMENT_IS_NAME_X = 16
const GMT_COMMENT_IS_NAME_Y = 32
const GMT_COMMENT_IS_NAME_Z = 64
const GMT_COMMENT_IS_COLNAMES = 128
const GMT_COMMENT_IS_RESET = 256
# end enum GMT_enum_comment
# begin enum GMT_api_err_enum
const GMT_NOTSET = -1
const GMT_NOERROR = 0
# end enum GMT_api_err_enum
# begin enum GMT_module_enum
const GMT_MODULE_USAGE	  = -6
const GMT_MODULE_SYNOPSIS = -5
const GMT_MODULE_LIST     = -4
const GMT_MODULE_EXIST    = -3
const GMT_MODULE_PURPOSE  = -2
const GMT_MODULE_OPT      = -1
const GMT_MODULE_CMD      = 0
# end enum GMT_module_enum
# begin enum GMT_io_enum
const GMT_IN = 0
const GMT_OUT = 1
const GMT_ERR = 2
# end enum GMT_io_enum
# begin enum GMT_enum_dimensions
const GMT_X = 0
const GMT_Y = 1
const GMT_Z = 2
# end enum GMT_enum_dimensions
# begin enum GMT_enum_freg
const GMT_ADD_FILES_IF_NONE = 1
const GMT_ADD_FILES_ALWAYS = 2
const GMT_ADD_STDIO_IF_NONE = 4
const GMT_ADD_STDIO_ALWAYS = 8
const GMT_ADD_EXISTING = 16
const GMT_ADD_DEFAULT = 6
# end enum GMT_enum_freg
# begin enum GMT_enum_ioset
const GMT_IO_DONE = 0
const GMT_IO_ASCII = 512
const GMT_IO_RESET = 32768
const GMT_IO_UNREG = 16384
# end enum GMT_enum_ioset
# begin enum GMT_enum_read
const GMT_READ_DOUBLE = 0
const GMT_READ_NORMAL = 0
const GMT_READ_TEXT = 1
const GMT_READ_MIXED = 2
const GMT_FILE_BREAK = 4
# end enum GMT_enum_read

const GMT_ALLOC_EXTERNALLY = 0    # Allocated outside of GMT: We cannot reallocate or free this memory
const GMT_ALLOC_INTERNALLY = 1    # Allocated by GMT: We may reallocate as needed and free when no longer needed
const GMT_ALLOC_NORMAL = 0        # Normal allocation of new dataset based on shape of input dataset
const GMT_ALLOC_VERTICAL = 4      # Allocate a single table for data set to hold all input tables by vertical concatenation */
const GMT_ALLOC_HORIZONTAL = 8
# begin enum GMT_enum_write
const GMT_WRITE_DOUBLE = 0
const GMT_WRITE_TEXT = 1
const GMT_WRITE_SEGMENT_HEADER = 2
const GMT_WRITE_TABLE_HEADER = 3
const GMT_WRITE_TABLE_START = 4
const GMT_WRITE_NOLF = 16
const GMT_STRICT_CONVERSION = 1024
const GMT_LAX_CONVERSION = 2048
# end enum GMT_enum_write
# begin enum GMT_enum_header
const GMT_HEADER_OFF = 0
const GMT_HEADER_ON = 1
# end enum GMT_enum_header
# begin enum GMT_enum_dest
const GMT_WRITE_SET = 0
const GMT_WRITE_OGR = 1
const GMT_WRITE_TABLE = 2
const GMT_WRITE_SEGMENT = 3
const GMT_WRITE_TABLE_SEGMENT = 4
# end enum GMT_enum_dest
# begin enum GMT_enum_alloc
const GMT_ALLOCATED_EXTERNALLY = 0
const GMT_ALLOCATED_BY_GMT = 1
# end enum GMT_enum_alloc
# begin enum GMT_enum_duplicate
const GMT_DUPLICATE_NONE = 0
const GMT_DUPLICATE_ALLOC = 1
const GMT_DUPLICATE_DATA = 2
# end enum GMT_enum_duplicate
# begin enum GMT_enum_shape
const GMT_ALLOC_NORMAL = 0
const GMT_ALLOC_VERTICAL = 4
const GMT_ALLOC_HORIZONTAL = 8
# end enum GMT_enum_shape
# begin enum GMT_enum_out
const GMT_WRITE_NORMAL = 0
const GMT_WRITE_HEADER = 1
const GMT_WRITE_SKIP = 2
# end enum GMT_enum_out
# begin enum GMT_FFT_mode
const GMT_FFT_FWD = 0
const GMT_FFT_INV = 1
const GMT_FFT_REAL = 0
const GMT_FFT_COMPLEX = 1
# end enum GMT_FFT_mode
# begin enum GMT_time_mode
const GMT_TIME_NONE = 0
const GMT_TIME_CLOCK = 1
const GMT_TIME_ELAPSED = 2
const GMT_TIME_RESET = 4
# end enum GMT_time_mode
# begin enum GMT_enum_verbose
const GMT_MSG_QUIET = 0
const GMT_MSG_NORMAL = 1
const GMT_MSG_TICTOC = 2
const GMT_MSG_COMPAT = 3
const GMT_MSG_VERBOSE = 4
const GMT_MSG_LONG_VERBOSE = 5
const GMT_MSG_DEBUG = 6
# end enum GMT_enum_verbose
# begin enum GMT_enum_reg
const GMT_GRID_NODE_REG = 0
const GMT_GRID_PIXEL_REG = 1
const GMT_GRID_DEFAULT_REG = 1024
# end enum GMT_enum_reg
# begin enum GMT_enum_gridindex
const GMT_XLO = 0
const GMT_XHI = 1
const GMT_YLO = 2
const GMT_YHI = 3
const GMT_ZLO = 4
const GMT_ZHI = 5
# end enum GMT_enum_gridindex
# begin enum GMT_enum_dimindex
const GMT_TBL = 0
const GMT_SEG = 1
const GMT_ROW = 2
const GMT_COL = 3
# end enum GMT_enum_dimindex
# begin enum GMT_enum_gridio
const GMT_GRID_IS_REAL = 0
const GMT_GRID_ALL = 0
const GMT_GRID_HEADER_ONLY = 1
const GMT_GRID_DATA_ONLY = 2
const GMT_GRID_IS_COMPLEX_REAL = 4
const GMT_GRID_IS_COMPLEX_IMAG = 8
const GMT_GRID_IS_COMPLEX_MASK = 12
const GMT_GRID_NO_HEADER = 16
const GMT_GRID_ROW_BY_ROW = 32
const GMT_GRID_ROW_BY_ROW_MANUAL = 64
# end enum GMT_enum_gridio
# begin enum GMT_enum_grdlen
const GMT_GRID_UNIT_LEN80 = 80
const GMT_GRID_TITLE_LEN80 = 80
const GMT_GRID_VARNAME_LEN80 = 80
const GMT_GRID_COMMAND_LEN320 = 320
const GMT_GRID_REMARK_LEN160 = 160
const GMT_GRID_NAME_LEN256 = 256
const GMT_GRID_HEADER_SIZE = 892
# end enum GMT_enum_grdlen

typealias Gmt_api_error_code UInt32
const GMT_OK = 0
const GMT_WRONG_MATRIX_SHAPE = 1
const GMT_ACCESS_NOT_ENABLED = 2
const GMT_ARGV_LIST_NULL = 3
const GMT_ARG_IS_NULL = 4
const GMT_COUNTER_IS_NEGATIVE = 5
const GMT_BAD_GEOMETRY = 6
const GMT_BAD_PERMISSION = 7
const GMT_CPT_READ_ERROR = 8
const GMT_DATA_READ_ERROR = 9
const GMT_DATA_WRITE_ERROR = 10
const GMT_DIM_TOO_LARGE = 11
const GMT_DIM_TOO_SMALL = 12
const GMT_ERROR_ON_FCLOSE = 13
const GMT_ERROR_ON_FDOPEN = 14
const GMT_ERROR_ON_FOPEN = 15
const GMT_FILE_NOT_FOUND = 16
const GMT_GRID_BC_ERROR = 17
const GMT_GRID_READ_ERROR = 18
const GMT_GRID_WRITE_ERROR = 19
const GMT_ID_TOO_LARGE = 20
const GMT_IMAGE_BC_ERROR = 21
const GMT_IMAGE_READ_ERROR = 22
const GMT_MEMORY_ERROR = 23
const GMT_FREE_EXTERNAL_NOT_ALLOWED = 24
const GMT_FREE_WRONG_LEVEL = 25
const GMT_NOT_A_SESSION = 26
const GMT_NOT_A_VALID_ARG = 27
const GMT_NOT_A_VALID_DIRECTION = 28
const GMT_NOT_A_VALID_FAMILY = 29
const GMT_NOT_A_VALID_ID = 30
const GMT_NOT_A_VALID_IO_ACCESS = 31
const GMT_NOT_A_VALID_IO_MODE = 32
const GMT_NOT_A_VALID_IO_SESSION = 33
const GMT_NOT_A_VALID_METHOD = 34
const GMT_NOT_A_VALID_MODE = 35
const GMT_NOT_A_VALID_MODULE = 36
const GMT_NOT_A_VALID_PARAMETER = 37
const GMT_NOT_A_VALID_TYPE = 38
const GMT_NOT_INPUT_OBJECT = 39
const GMT_NOT_OUTPUT_OBJECT = 40
const GMT_NO_GRDHEADER = 41
const GMT_NO_INPUT = 42
const GMT_NO_OUTPUT = 43
const GMT_NO_PARAMETERS = 44
const GMT_NO_RESOURCES = 45
const GMT_N_COLS_NOT_SET = 46
const GMT_N_COLS_VARY = 47
const GMT_N_ROWS_NOT_SET = 48
const GMT_OBJECT_NOT_FOUND = 49
const GMT_OGR_ONE_TABLE_ONLY = 50
const GMT_ONLY_ONE_ALLOWED = 51
const GMT_OPTION_EXIST = 52
const GMT_OPTION_HISTORY_ERROR = 53
const GMT_OPTION_IS_NULL = 54
const GMT_OPTION_LIST_NULL = 55
const GMT_OPTION_NOT_FOUND = 56
const GMT_OPTION_SORT_ERROR = 57
const GMT_OUTPUT_NOT_SET = 58
const GMT_PADDING_NOT_ALLOWED = 59
const GMT_PARSE_ERROR = 60
const GMT_PROG_NOT_FOUND = 61
const GMT_PTR_IS_NULL = 62
const GMT_PTR_NOT_NULL = 63
const GMT_PTR_NOT_UNIQUE = 64
const GMT_READ_ONCE = 65
const GMT_RUNTIME_ERROR = 66
const GMT_SIZE_IS_ZERO = 67
const GMT_STREAM_NOT_ALLOWED = 68
const GMT_SUBSET_NOT_ALLOWED = 69
const GMT_VALUE_NOT_SET = 70
const GMT_WRITTEN_ONCE = 71
# end enum Gmt_api_error_code

const DOUBLE_CLASS = 1
const SINGLE_CLASS = 2
const INT64_CLASS  = 3
const UINT64_CLASS = 4
const INT32_CLASS  = 5
const UINT32_CLASS = 6
const INT16_CLASS  = 7
const UINT16_CLASS = 8
const INT8_CLASS   = 9
const UINT8_CLASS  = 10

type GMT_GRID_HEADER
	n_columns::UInt32
	n_rows::UInt32
	registration::UInt32
	wesn::NTuple{4, Cdouble}
	z_min::Cdouble
	z_max::Cdouble
	inc::NTuple{2, Cdouble}
	z_scale_factor::Cdouble
	z_add_offset::Cdouble
	x_unit::NTuple{80, UInt8}
	y_unit::NTuple{80, UInt8}
	z_unit::NTuple{80, UInt8}
	title::NTuple{80, UInt8}
	command::NTuple{320, UInt8}
	remark::NTuple{160, UInt8}
	# Variables "hidden" from the API. This section is flexible and considered private
	_type::UInt32
	bits::UInt32
	complex_mode::UInt32
	mx::UInt32 				# Actual dimensions of the grid in memory, allowing for the padding
	my::UInt32
	nm::Csize_t 			# Number of data items in this grid (n_columns * n_rows) [padding is excluded]
	size::Csize_t 			# Actual number of items required to hold this grid (= mx * my)
	n_alloc::Csize_t
	trendmode::UInt32
	arrangement::UInt32
	n_bands::UInt32
	pad::NTuple{4, UInt32}
	BC::NTuple{4, UInt32}
	grdtype::UInt32
	reset_pad::UInt32
	name::NTuple{256, UInt8}
	varname::NTuple{80, UInt8}
	ProjRefPROJ4::Ptr{UInt8}
	ProjRefWKT::Ptr{UInt8}
	row_order::Cint
	z_id::Cint
	ncid::Cint
	xy_dim::NTuple{2, Cint}
	t_index::NTuple{3, Csize_t}
	data_offset::Csize_t
	stride::UInt32
	nan_value::Cfloat
	xy_off::Cdouble
	r_inc::NTuple{2, Cdouble}
	flags::NTuple{4, UInt8}
	pocket::Ptr{UInt8}
	mem_layout::NTuple{4, UInt8}
	bcr_threshold::Cdouble
	has_NaNs::UInt32
	bcr_interpolant::UInt32
	bcr_n::UInt32
	nxp::UInt32
	nyp::UInt32
	no_BC::UInt32
	gn::UInt32
	gs::UInt32
	is_netcdf4::UInt32
	z_chunksize::NTuple{2, Csize_t}
	z_shuffle::UInt32
	z_deflate_level::UInt32
	z_scale_autoadust::UInt32
	z_offset_autoadust::UInt32
	xy_adjust::NTuple{2, UInt32}
	xy_mode::NTuple{2, UInt32}
	xy_unit::NTuple{2, UInt32}
	xy_unit_to_meter::NTuple{2, Cdouble}
	index_function::Ptr{Void}
end

type GMT_GRID
	header::Ptr{GMT_GRID_HEADER}
	data::Ptr{Cfloat}
	id::UInt32
	alloc_level::UInt32
	alloc_mode::UInt32
	x::Ptr{Cdouble}
	y::Ptr{Cdouble}
	extra::Ptr{Void}
end

# begin enum GMT_enum_geometry
typealias GMT_enum_geometry UInt32
const GMT_IS_POINT = 1
const GMT_IS_LINE = 2
const GMT_IS_POLY = 4
const GMT_IS_PLP = 7
const GMT_IS_SURFACE = 8
const GMT_IS_NONE = 16
# end enum GMT_enum_geometry
# begin enum GMT_enum_pol
typealias GMT_enum_pol UInt32
const GMT_IS_PERIMETER = 0
const GMT_IS_HOLE = 1
# end enum GMT_enum_pol
# begin enum GMT_enum_ascii_input_return
typealias GMT_enum_ascii_input_return UInt32
const GMT_IO_DATA_RECORD = 0
const GMT_IO_TABLE_HEADER = 1
const GMT_IO_SEGMENT_HEADER = 2
const GMT_IO_ANY_HEADER = 3
const GMT_IO_MISMATCH = 4
const GMT_IO_EOF = 8
const GMT_IO_NAN = 16
const GMT_IO_NEW_SEGMENT = 18
const GMT_IO_GAP = 32
const GMT_IO_LINE_BREAK = 58
const GMT_IO_NEXT_FILE = 64
# end enum GMT_enum_ascii_input_return
immutable GMT_OGR
	geometry::UInt32
	n_aspatial::UInt32
	region::Ptr{UInt8}
	proj::NTuple{4, Ptr{UInt8}}
	_type::Ptr{UInt32}
	name::Ptr{Ptr{UInt8}}
	pol_mode::GMT_enum_pol
	tvalue::Ptr{Ptr{UInt8}}
	dvalue::Ptr{Cdouble}
end
immutable GMT_OGR_SEG
	pol_mode::GMT_enum_pol
	n_aspatial::UInt32
	tvalue::Ptr{Ptr{UInt8}}
	dvalue::Ptr{Cdouble}
end
type GMT_DATASEGMENT
	n_rows::UInt64
	n_columns::UInt64
	min::Ptr{Cdouble}
	max::Ptr{Cdouble}
	data::Ptr{Ptr{Cdouble}}
	label::Ptr{UInt8}
	header::Ptr{UInt8}
	text::Ptr{Ptr{UInt8}}
	mode::UInt32
	pol_mode::UInt32
	id::UInt64
	n_alloc::Cint
	range::Cint
	pole::Cint
	dist::Cdouble
	lat_limit::Cdouble
	ogr::Ptr{GMT_OGR_SEG}
	next::Ptr{GMT_DATASEGMENT}
	alloc_mode::UInt32
	file::NTuple{2, Ptr{UInt8}}
end
type GMT_DATATABLE
	n_headers::UInt32
	n_columns::UInt64
	n_segments::UInt64
	n_records::UInt64
	min::Ptr{Cdouble}
	max::Ptr{Cdouble}
	header::Ptr{Ptr{UInt8}}
	segment::Ptr{Ptr{GMT_DATASEGMENT}}
	id::UInt64
	n_alloc::Cint
	mode::UInt32
	ogr::Ptr{GMT_OGR}
	file::NTuple{2, Ptr{UInt8}}
end
type GMT_DATASET
	n_tables::UInt64
	n_columns::UInt64
	n_segments::UInt64
	n_records::UInt64
	min::Ptr{Cdouble}
	max::Ptr{Cdouble}
	table::Ptr{Ptr{GMT_DATATABLE}}
	id::UInt64
	n_alloc::Cint
	dim::NTuple{4, UInt64}
	geometry::UInt32
	alloc_level::UInt32
	io_mode::UInt32
	alloc_mode::UInt32
	file::NTuple{2, Ptr{UInt8}}
end
type GMT_TEXTSEGMENT
	n_rows::UInt64
	data::Ptr{Ptr{UInt8}}
	label::Ptr{UInt8}
	header::Ptr{UInt8}
	id::UInt64
	mode::UInt32
	n_alloc::Cint
	file::NTuple{2, Ptr{UInt8}}
	tvalue::Ptr{Ptr{UInt8}}
end
type GMT_TEXTTABLE
	n_headers::UInt32
	n_segments::UInt64
	n_records::UInt64
	header::Ptr{Ptr{UInt8}}
	segment::Ptr{Ptr{GMT_TEXTSEGMENT}}
	id::UInt64
	n_alloc::Cint
	mode::UInt32
	file::NTuple{2, Ptr{UInt8}}
end
type GMT_TEXTSET
	n_tables::UInt64
	n_segments::UInt64
	n_records::UInt64
	table::Ptr{Ptr{GMT_TEXTTABLE}}
	id::UInt64
	n_alloc::Csize_t
	geometry::UInt32
	alloc_level::UInt32
	io_mode::UInt32
	alloc_mode::UInt32
	file::NTuple{2, Ptr{UInt8}}
end
# begin enum GMT_enum_color
typealias GMT_enum_color UInt32
const GMT_RGB = 0
const GMT_CMYK = 1
const GMT_HSV = 2
const GMT_COLORINT = 4
const GMT_NO_COLORNAMES = 8
# end enum GMT_enum_color
# begin enum GMT_enum_bfn
typealias GMT_enum_bfn UInt32
const GMT_BGD = 0
const GMT_FGD = 1
const GMT_NAN = 2
# end enum GMT_enum_bfn
# begin enum GMT_enum_cpt
typealias GMT_enum_cpt UInt32
const GMT_CPT_REQUIRED = 0
const GMT_CPT_OPTIONAL = 1
# end enum GMT_enum_cpt
# begin enum GMT_enum_cptflags
typealias GMT_enum_cptflags UInt32
const GMT_CPT_NO_BNF = 1
const GMT_CPT_EXTEND_BNF = 2
# end enum GMT_enum_cptflags
immutable GMT_FILL
	rgb::NTuple{4, Cdouble}
	f_rgb::NTuple{4, Cdouble}
	b_rgb::NTuple{4, Cdouble}
	use_pattern::Bool
	pattern_no::Int32
	dpi::UInt32
	pattern::NTuple{256, UInt8}		# was char pattern[GMT_BUFSIZ];
end
immutable GMT_LUT
	z_low::Cdouble
	z_high::Cdouble
	i_dz::Cdouble
	rgb_low::NTuple{4, Cdouble}
	rgb_high::NTuple{4, Cdouble}
	rgb_diff::NTuple{4, Cdouble}
	hsv_low::NTuple{4, Cdouble}
	hsv_high::NTuple{4, Cdouble}
	hsv_diff::NTuple{4, Cdouble}
	annot::UInt32
	skip::UInt32
	fill::Ptr{GMT_FILL}
	label::Ptr{UInt8}
end
immutable GMT_BFN
	rgb::NTuple{4, Cdouble}
	hsv::NTuple{4, Cdouble}
	skip::UInt32
	fill::Ptr{GMT_FILL}
end
type GMT_PALETTE
	n_headers::UInt32
	n_colors::UInt32
	mode::UInt32
	data::Ptr{GMT_LUT}
	bfn::NTuple{3, GMT_BFN}
	header::Ptr{Ptr{UInt8}}
	id::UInt64
	alloc_mode::UInt32
	alloc_level::UInt32
	auto_scale::UInt32
	model::UInt32
	is_gray::UInt32
	is_bw::UInt32
	is_continuous::UInt32
	has_pattern::UInt32
	has_hinge::UInt32
	skip::UInt32
	categorical::UInt32
	z_adjust::NTuple{2, UInt32}
	z_mode::NTuple{2, UInt32}
	z_unit::NTuple{2, UInt32}
	z_unit_to_meter::NTuple{2, Cdouble}
	minmax::NTuple{2, Cdouble}
	hinge::Cdouble
end
type GMT_IMAGE
	_type::UInt32
	colormap::Ptr{Cint}
	n_indexed_colors::Cint
	header::Ptr{GMT_GRID_HEADER}
	data::Ptr{Cuchar}
	alpha::Ptr{Cuchar}
	id::UInt64
	alloc_level::UInt32
	alloc_mode::UInt32
	color_interp::Ptr{UInt8}
	x::Ptr{Cdouble}
	y::Ptr{Cdouble}
end
type GMT_POSTSCRIPT
	n_alloc::Csize_t
	n_bytes::Csize_t
	mode::UInt32
	n_headers::UInt32
	data::Ptr{UInt8}
	header::Ptr{Ptr{UInt8}}
	id::UInt64
	alloc_level::UInt32
	alloc_mode::UInt32
end
immutable GMT_UNIVECTOR
	uc1::Ptr{UInt8}
	sc1::Ptr{Int8}
	ui2::Ptr{UInt16}
	si2::Ptr{Int16}
	ui4::Ptr{UInt32}
	si4::Ptr{Int32}
	ui8::Ptr{UInt64}
	si8::Ptr{Int64}
	f4::Ptr{Float32}
	f8::Ptr{Float64}
end

immutable GMT_VECTOR
	n_columns::UInt64
	n_rows::UInt64
	registration::UInt32
	_type::Ptr{UInt32}
	#data::Ptr{GMT_UNIVECTOR}
	data::Ptr{Ptr{Void}}
	range::NTuple{2, Cdouble}
	command::NTuple{320, UInt8}
	remark::NTuple{160, UInt8}
	id::UInt64
	alloc_level::UInt32
	alloc_mode::UInt32
end
# begin enum GMT_enum_fmt
typealias GMT_enum_fmt UInt32
const GMT_IS_ROW_FORMAT = 0
const GMT_IS_COL_FORMAT = 1
# end enum GMT_enum_fmt

type GMT_MATRIX
	n_rows::UInt64
	n_columns::UInt64
	n_layers::UInt64
	shape::UInt32
	registration::UInt32
	dim::Csize_t
	size::Csize_t
	_type::UInt32
	range::NTuple{6, Cdouble}
#	data::GMT_UNIVECTOR
#	data::Union(Ptr{UInt8},Ptr{Int8},Ptr{UInt16},Ptr{Int16},Ptr{UInt32},Ptr{Int32},
#		Ptr{UInt64},Ptr{Int64},Ptr{Float32},Ptr{Float64})
	data::Ptr{Void}
	command::NTuple{320, UInt8}
	remark::NTuple{160, UInt8}
	id::UInt64
	alloc_level::UInt32
	alloc_mode::UInt32
end

type GMT_RESOURCE
	family::UInt32          # GMT data family, i.e., GMT_IS_DATASET, GMT_IS_GRID, etc.
	geometry::UInt32        # One of the recognized GMT geometries
	direction::UInt32       # Either GMT_IN or GMT_OUT
	option::Ptr{GMT_OPTION} # Pointer to the corresponding module option
	name::NTuple{16, UInt8} # Object ID returned by GMT_Register_IO
	pos::Cint               # Corresponding index into external object in|out arrays
	mode::Cint              # Either primary (0) or secondary (1) resource
	object::Ptr{Void}       # Pointer to the actual GMT object
end

immutable GMTAPI_DATA_OBJECT
	# Information for each input or output data entity, including information
	# needed while reading/writing from a table (file or array)
	rec::UInt64                 # Current rec to read [GMT_DATASET and GMT_TEXTSET to/from MATRIX/VECTOR only]
	n_rows::UInt64              # Number or rows in this array [GMT_DATASET and GMT_TEXTSET to/from MATRIX/VETOR only]
	n_columns::UInt64			# Number of columns to process in this dataset [GMT_DATASET only]
	n_expected_fields::UInt64	# Number of expected columns for this dataset [GMT_DATASET only]
	n_alloc::Csize_t			# Number of items allocated so far if writing to memory
	ID::UInt32					# Unique identifier which is >= 0
	alloc_level::UInt32			# Nested module level when object was allocated
	status::UInt32				# 0 when first registered, 1 after reading/writing has started, 2 when finished
	selected::Cint				# true if requested by current module, false otherwise
	close_file::Cint			# true if we opened source as a file and thus need to close it when done
	region::Cint				# true if wesn was passed, false otherwise
	no_longer_owner::Cint		# true if the data pointed to by the object was passed on to another object
	messenger::Cint				# true for output objects passed from the outside to receive data from GMT. If true we destroy data pointer before writing
	alloc_mode::UInt32			# GMT_ALLOCATED_{BY_GMT|EXTERNALLY}
	direction::UInt32			# GMT_IN or GMT_OUT
	family::UInt32				# One of GMT_IS_{DATASET|TEXTSET|CPT|IMAGE|GRID|MATRIX|VECTOR|COORD}
	actual_family::UInt32		# May be GMT_IS_MATRIX|VECTOR when one of the others are created via those
	method::UInt32              # One of GMT_IS_{FILE,STREAM,FDESC,DUPLICATE,REFERENCE} or sum with enum GMT_enum_via (GMT_VIA_{NONE,VECTOR,MATRIX,OUTPUT}); using unsigned type because sum exceeds enum GMT_enum_method
	geometry::GMT_enum_geometry	# One of GMT_IS_{POINT|LINE|POLY|PLP|SURFACE|NONE}
	wesn::NTuple{4, Cdouble}	# Grid domain limits
	resource::Ptr{Void}			# Points to registered filename, memory location, etc., where data can be obtained from with GMT_Get_Data.
	data::Ptr{Void}				# Points to GMT object that was read from a resource
	#FILE *fp;					# Pointer to source/destination stream [For rec-by-rec procession, NULL if memory location]
	fp::Ptr{Void}				# Pointer to source/destination stream [For rec-by-rec procession, NULL if memory location]
	filename::Ptr{UInt8}		# Filename, stream, of file handle (otherwise NULL)
	#void *(*import) (struct GMT_CTRL *, FILE *, uint64_t *, int *);	# Pointer to input function (for DATASET/TEXTSET only)
	ifun::Ptr{Void} 			# Pointer to input function (for DATASET/TEXTSET only)
	# Start of temporary variables for API debug - They are only set when building GMT with /DEBUG
	G::Ptr{Void}				# struct GMT_GRID *G;
	D::Ptr{Void}				# struct GMT_DATASET *D;
	T::Ptr{Void}				# struct GMT_TEXTSET *T;
	C::Ptr{Void}				# struct GMT_PALETTE *C;
	M::Ptr{Void}				# struct GMT_MATRIX *M;
	V::Ptr{Void}				# struct GMT_VECTOR *V;
	I::Ptr{Void}				# struct GMT_IMAGE *I;
end

immutable Gmt_libinfo
	name::Ptr{UInt8}	# Library tag name [without leading "lib" and extension], e.g. "gmt", "gmtsuppl" */
	path::Ptr{UInt8}	# Full path to library as given in GMT_CUSTOM_LIBS */
	skip::Ptr{Bool}		# true if we tried to open it and it was not available the first time */
	handle::Ptr{Void}	# Handle to the shared library, returned by dlopen or dlopen_special */
end

type GMTAPI_CTRL
	# Master controller which holds all GMT API related information at run-time for a single session.
	# Users can run several GMT sessions concurrently; each session requires its own structure.
	# Use GMTAPI_Create_Session to initialize a new session and GMTAPI_Destroy_Session to end it.

	current_rec::NTuple{2, UInt64}	# Current record number >= 0 in the combined virtual dataset (in and out)
	n_objects::UInt32			# Number of currently active input and output data objects
	unique_ID::UInt32			# Used to create unique IDs for duration of session
	session_ID::UInt32			# ID of this session
	unique_var_ID::UInt32		# Used to create unique object IDs (grid,dataset, etc) for duration of session
	current_item::NTuple{2, UInt32}	# Array number of current dataset being processed (in and out)
	pad::UInt32					# Session default for number of rows/cols padding for grids [2]
	mode::UInt32				# 1 if called via external API (Matlab, Python) [0]
	leave_grid_scaled::UInt32	# 1 if we dont want to unpack a grid after we packed it for writing [0]
	registered::NTuple{2, Cint}	# true if at least one source/destination has been registered (in and out)
	io_enabled::NTuple{2, Cint}	# true if access has been allowed (in and out)
	n_objects_alloc::Csize_t	# Allocation counter for data objects
	error::Int32				# Error code from latest API call [GMT_OK]
	last_error::Int32			# Error code from previous API call [GMT_OK]
	shelf::Int32				# Place to pass hidden values within API
	io_mode::NTuple{2, UInt32}	# 1 if access as set, 0 if record-by-record
	#GMT::Ptr{GMT_CTRL}			# Key structure with low-level GMT internal parameters
	GMT::Ptr{Void}				# Maybe one day. Till than just keep it as void
	object::Ptr{Ptr{GMTAPI_DATA_OBJECT}}	# List of registered data objects
	session_tag::Ptr{UInt8}		# Name tag for this session (or NULL)
	internal::Bool				# true if session was initiated by gmt.c
	deep_debug::Bool			# temporary for debugging
	#int (*print_func) (FILE *, const char *);	# Pointer to fprintf function (may be reset by external APIs like MEX)
	pf::Ptr{Void}				# Don't know what to put here, so ley it be *void
	do_not_exit::UInt32			# 0 by default, mieaning it is OK to call exit  (may be reset by external APIs like MEX to call return instead)
	lib::Ptr{Gmt_libinfo}		# List of shared libs to consider
	n_shared_libs::UInt32		# How many in lib
end

#=
immutable GMT_CTRL
	# Master structure for a GMT invokation.  All internal settings for GMT is accessed here
	session::GMT_SESSION     # Structure with all values that do not change throughout a session
	init::GMT_INIT           # Structure with all values that do not change in a GMT_func call
	common::GMT_COMMON       # Structure with all the common GMT command settings (-R -J ..)
	current::GMT_CURRENT     # Structure with all the GMT items that can change during execution, such as defaults settings (pens, colors, fonts.. )
	hidden::GMT_INTERNAL     # Internal global variables that are not to be changed directly by users
	PSL::Ptr{PSL_CTRL}       # Pointer to the PSL structure [or NULL]
	parent::Ptr{GMTAPI_CTRL} # Owner of this structure [or NULL]; gives access to the API from functions being passed *GMT only
end

struct GMT_SESSION {
	# These are parameters that is set once at the start of a GMT session and
	# are essentially read-only constants for the duration of the session */
	FILE *std[3];			/* Pointers for standard input, output, and error */
	void *(*input_ascii) (struct GMT_CTRL *, FILE *, uint64_t *, int *);	/* Pointer to function reading ascii tables only */
	int (*output_ascii) (struct GMT_CTRL *, FILE *, uint64_t, double *);	/* Pointer to function writing ascii tables only */
	n_fonts::UInt32				# Total number of fonts returned by GMT_init_fonts */
	n_user_media::UInt32		# Total number of user media returned by gmt_load_user_media */
	min_meminc::Csize_t			# with -DMEMDEBUG, sets min/max memory increments */
	max_meminc::Csize_t
	f_NaN::Float32				# Holds the IEEE NaN for floats */
	d_NaN::Float64				# Holds the IEEE NaN for doubles */
	no_rgb::NTuple{4, Cdouble}	# To hold {-1, -1, -1, 0} when needed */
	double u2u[4][4];		/* u2u is the 4x4 conversion matrix for cm, inch, m, pt */
	char unit_name[4][8];		/* Full name of the 4 units cm, inch, m, pt */
	struct GMT_HASH rgb_hashnode[GMT_N_COLOR_NAMES];/* Used to translate colornames to r/g/b */
	rgb_hashnode_init::Bool		# true once the rgb_hashnode array has been loaded; false otherwise */
	n_shorthands::UInt32		# Length of arrray with shorthand information */
	char *grdformat[GMT_N_GRD_FORMATS];	/* Type and description of grid format */
	int (*readinfo[GMT_N_GRD_FORMATS]) (struct GMT_CTRL *, struct GMT_GRID_HEADER *);	/* Pointers to grid read header functions */
	int (*updateinfo[GMT_N_GRD_FORMATS]) (struct GMT_CTRL *, struct GMT_GRID_HEADER *);	/* Pointers to grid update header functions */
	int (*writeinfo[GMT_N_GRD_FORMATS]) (struct GMT_CTRL *, struct GMT_GRID_HEADER *);	/* Pointers to grid write header functions */
	int (*readgrd[GMT_N_GRD_FORMATS]) (struct GMT_CTRL *, struct GMT_GRID_HEADER *, float *, double *, unsigned int *, unsigned int);	/* Pointers to grid read functions */
	int (*writegrd[GMT_N_GRD_FORMATS]) (struct GMT_CTRL *, struct GMT_GRID_HEADER *, float *, double *, unsigned int *, unsigned int);	/* Pointers to grid read functions */
	int (*fft1d[k_n_fft_algorithms]) (struct GMT_CTRL *, float *, unsigned int, int, unsigned int);	/* Pointers to available 1-D FFT functions (or NULL if not configured) */
	int (*fft2d[k_n_fft_algorithms]) (struct GMT_CTRL *, float *, unsigned int, unsigned int, int, unsigned int);	/* Pointers to available 2-D FFT functions (or NULL if not configured) */
	# This part contains pointers that may point to additional memory outside this struct
	DCWDIR::Ptr{UInt8}				# Path to the DCW directory
	GSHHGDIR::Ptr{UInt8}			# Path to the GSHHG directory
	SHAREDIR::Ptr{UInt8}			# Path to the GMT share directory
	HOMEDIR::Ptr{UInt8}				# Path to the user's home directory
	USERDIR::Ptr{UInt8}				# Path to the user's GMT settings directory
	DATADIR::Ptr{UInt8}				# Path to one or more directories with data sets
	TMPDIR::Ptr{UInt8}				# Path to the directory directory for isolation mode
	CUSTOM_LIBS::Ptr{UInt8}			# Names of one or more comma-separated GMT-compatible shared libraries
	user_media_name::Ptr{Ptr{UInt8}}		# Length of array with custom media dimensions
	font::Ptr{GMT_FONTSPEC}			# Array with font names and height specification
	user_media::Ptr{GMT_MEDIA}		# Array with custom media dimensions
	shorthand::Ptr{GMT_SHORTHAND}	# Array with info about shorthand file extension magic
};

struct GMT_COMMON {
	# Structure with all information given via the common GMT command-line options -R -J ..
	struct synopsis {	# \0 (zero) or ^ */
		bool active;
		bool extended;	# + to also show non-common options */
	} synopsis;
	struct B {	# -B<params> */
		bool active[2];	# 0 = primary annotation, 1 = secondary annotations */
		int mode;	# 5 = GMT 5 syntax, 4 = GMT 4 syntax, 1 = Either, -1 = mix (error), 0 = not set yet */
		char string[2][GMT_LEN256];
	} B;
	struct API_I {	# -I<xinc>[/<yinc>] grids only, and for API use only */
		bool active;
		double inc[2];
	} API_I;
	struct J {	# -J<params>
		bool active, zactive;
		unsigned int id;
		double par[6];
		char string[GMT_LEN256];
	} J;
	struct K {	# -K
		bool active;
	} K;
	struct O {	# -O
		bool active;
	} O;
	struct P {	# -P
		bool active;
	} P;
	struct R {	# -Rw/e/s/n[/z_min/z_max][r] */
		bool active;
		bool oblique;	# true when -R...r was given (oblique map, probably), else false (map borders are meridians/parallels) */
		double wesn[6];		# Boundaries of west, east, south, north, low-z and hi-z */
		char string[GMT_LEN256];
	} R;
	struct U {	# -U */
		bool active;
		unsigned int just;
		double x, y;
		char *label;		# Content not counted by sizeof (struct)
	} U;
	struct V {	# -V */
		bool active;
	} V;
	struct X {	# -X */
		bool active;
		double off;
		char mode;	# r, a, or c */
	} X;
	struct Y {	# -Y */
		bool active;
		double off;
		char mode;	# r, a, or c */
	} Y;
	struct a {	# -a<col>=<name>[:<type>][,col>=<name>[:<type>], etc][+g<geometry>] */
		bool active;
		unsigned int geometry;
		unsigned int n_aspatial;
		bool clip;		# true if we wish to clip lines/polygons at Dateline [false] */
		bool output;		# true when we wish to build OGR output */
		int col[MAX_ASPATIAL];	# Col id, include negative items such as GMT_IS_T (-5) */
		int ogr[MAX_ASPATIAL];	# Column order, or -1 if not set */
		unsigned int type[MAX_ASPATIAL];
		char *name[MAX_ASPATIAL];
	} a;
	struct b {	# -b[i][o][s|S][d|D][#cols][cvar1/var2/...] */
		bool active[2];		# true if current input/output is in native binary format */
		bool o_delay;		# true if we dont know number of output columns until we have read at least one input record */
		enum GMT_swap_direction swab[2];	# k_swap_in or k_swap_out if current binary input/output must be byte-swapped, else k_swap_none */
		uint64_t ncol[2];		# Number of expected columns of input/output 0 means it will be determined by program
		char type[2];			# Default column type, if set [d for double] */
		char varnames[GMT_BUFSIZ];	# List of variable names to be input/output in netCDF mode [GMT4 COMPATIBILITY ONLY] */
	} b;
	struct c {	# -c */
		bool active;
		unsigned int copies;
	} c;
	struct f {	# -f[i|o]<col>|<colrange>[t|T|g],..
		bool active[2];	# For GMT_IN|OUT
	} f;
	struct g {	# -g[+]x|x|y|Y|d|Y<gap>[unit]
		bool active;
		unsigned int n_methods;			# How many different criteria to apply
		uint64_t n_col;				# Largest column-number needed to be read */
		bool match_all;			# If true then all specified criteria must be met to be a gap [default is any of them] */
		enum GMT_enum_gaps method[GMT_N_GAP_METHODS];	# How distances are computed for each criteria */
		uint64_t col[GMT_N_GAP_METHODS];	# Which column to use (-1 for x,y distance) */
		double gap[GMT_N_GAP_METHODS];		# The critical distances for each criteria */
		double (*get_dist[GMT_N_GAP_METHODS]) (struct GMT_CTRL *GMT, uint64_t);	# Pointers to functions that compute those distances */
	} g;
	struct h {	# -h[i|o][<nrecs>][+d][+c][+r<remark>][+t<title>] */
		bool active;
		bool add_colnames;
		unsigned int mode;
		unsigned int n_recs;
		char *title;
		char *remark;
		char *colnames;	# Not set by -h but maintained here */
	} h;
	struct i {	# -i<col>|<colrange>,.. */
		bool active;
		uint64_t n_cols;
	} i;
	struct n {	# -n[b|c|l|n][+a][+b<BC>][+c][+t<threshold>] */
		bool active;
		bool antialias;	# Defaults to true, if supported */
		bool truncate;	# Defaults to false */
		unsigned int interpolant;	# Defaults to BCR_BICUBIC */
		bool bc_set;	# true if +b was parsed */
		char BC[4];		# For BC settings via +bg|n[x|y]|p[x|y] */
		double threshold;	# Defaults to 0.5 */
	} n;
	struct o {	# -o<col>|<colrange>,.. */
		bool active;
		uint64_t n_cols;
	} o;
	struct p {	# -p<az>/<el>[+wlon0/lat0[/z0]][+vx0[cip]/y0[cip]] */
		bool active;
	} p;
	struct r {	# -r */
		bool active;
		unsigned int registration;
	} r;
	struct s {	# -s[r] */
		bool active;
	} s;
	struct t {	# -t<transparency> */
		bool active;
		double value;
	} t;
	struct x {	# -x+a|[-]n */
		bool active;
		int n_threads;
	} x;
	struct colon {	# -:[i|o] */
		bool active;
		bool toggle[2];
	} colon;
};

struct GMT_INIT 	# Holds misc run-time parameters */
	n_custom_symbols::UInt32
	module_name::Ptr{UInt8}			# Name of current module or NULL if not set */
	module_lib::Ptr{UInt8}			# Name of current shared library or NULL if not set */
	# The rest of the struct contains pointers that may point to memory not included by this struct */
	runtime_bindir::Ptr{UInt8}		# Directory that contains the main exe at run-time */
	runtime_libdir::Ptr{UInt8}		# Directory that contains the main shared lib at run-time */
	char *history[GMT_N_UNIQUE];	# The internal gmt.history information */
	struct GMT_CUSTOM_SYMBOL **custom_symbol; # For custom symbol plotting in psxy[z]. */
end

struct GMT_CURRENT {
	# These are internal parameters that need to be passed around between
	# many GMT functions.  These values may change by user interaction.
	struct GMT_DEFAULTS setting;	# Holds all GMT defaults parameters
	struct GMT_IO io;		# Holds all i/o-related parameters
	struct GMT_PROJ proj;		# Holds all projection-related parameters
	struct GMT_MAP map;		# Holds all projection-related parameters
	struct GMT_PLOT plot;		# Holds all plotting-related parameters
	struct GMT_TIME_CONV time;	# Holds all time-related parameters
	struct GMT_POSTSCRIPT ps;		# Hold parameters related to PS setup
	struct GMT_OPTION *options;	# Pointer to current program's options
	struct GMT_FFT_HIDDEN fft;	# Structure with info that must survive between FFT calls
#ifdef HAVE_GDAL
	struct GMT_GDALREAD_IN_CTRL  gdal_read_in;  # Hold parameters related to options transmitted to gdalread */
	struct GMT_GDALREAD_OUT_CTRL gdal_read_out; # Hold parameters related to options transmitted from gdalread */
	struct GMT_GDALWRITE_CTRL    gdal_write;    # Hold parameters related to options transmitted to gdalwrite */
#endif
};

struct GMT_INTERNAL {
	# These are internal parameters that need to be passed around between
	# many GMT functions.  These may change during execution but are not
	# modified directly by user interaction.
	func_level::UInt32		# Keeps track of what level in a nested GMT_func calling GMT_func etc we are.  0 is top function
	mem_cols::Csize_t		# Current number of allocated columns for temp memory
	mem_rows::Csize_t		# Current number of allocated rows for temp memory
	mem_coord::Ptr{Ptr{Float64}}		# Columns of temp memory
	struct MEMORY_TRACKER *mem_keeper;
};

immutable GMT_CTRL
	# Master structure for a GMT invokation. All internal settings for GMT is accessed here
	session::GMT_SESSION	# Structure with all values that do not change throughout a session */
	init::GMT_INIT			# Structure with all values that do not change in a GMT_func call */
	common::GMT_COMMON		# Structure with all the common GMT command settings (-R -J ..) */
	current::GMT_CURRENT	# Structure with all the GMT items that can change during execution, such as defaults settings (pens, colors, fonts.. ) */
	hidden::GMT_INTERNAL	# Internal global variables that are not to be changed directly by users */
	PSL::Ptr{PSL_CTRL}		# Pointer to the PSL structure [or NULL] */
	parent::Ptr{GMTAPI_CTRL}	# Owner of this structure [or NULL]; gives access to the API from functions being passed *GMT only */
end
=#


text:
using BinaryBuilder

name = "pprof"

# PProf doesn't have proper versions yet
# so we use Go's pseudo version
# `TZ=UTC git show --quiet --date='format-local:%Y%m%d%H%M%S' --format="%cd" $hash`

hash = "f9b734f9ee64d0f5b63636a45cc77ed2744997ab"
timestamp = "20191205061153"
version = Base.VersionNumber("0.0.0-$timestamp")

# Collection of sources required to build pprof
sources = [
    "https://github.com/google/pprof.git" =>
    hash,
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/pprof/
mkdir -p ${bindir}
go build -o ${bindir}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    ExecutableProduct("pprof", :pprof),
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; compilers=[:c, :go])

ext: jl


text:
using BinaryProvider

# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))
products = [
    LibraryProduct(prefix, ["libCoinUtils"], :libCoinUtils),
]

# Download binaries from hosted location
bin_prefix = "https://github.com/JuliaBinaryWrappers/CoinUtils_jll.jl/releases/download/CoinUtils-v2.11.3+2"

# Listing of files generated by BinaryBuilder:
download_info = Dict(
    Linux(:aarch64, libc=:glibc, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.aarch64-linux-gnu-cxx03.tar.gz", "bdf03e9d0151b2a36774f50b2ed062809f6c04eb213baeed988a34c3ac86dcdb"),
    Linux(:aarch64, libc=:glibc, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.aarch64-linux-gnu-cxx11.tar.gz", "281d406c299fe4921f526b112bf5c2143740ad622e479d770c61f49dbcd9aa14"),
    Linux(:aarch64, libc=:musl, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.aarch64-linux-musl-cxx03.tar.gz", "b397be857cffa42b1e0d68a24a4d388e82c68bf88943f5e162d74b350924842f"),
    Linux(:aarch64, libc=:musl, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.aarch64-linux-musl-cxx11.tar.gz", "d2c5bda683a28994c570bb95709e25144b5249aac0b6a38c1d99033dc7f58858"),
    Linux(:armv7l, libc=:glibc, call_abi=:eabihf, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.armv7l-linux-gnueabihf-cxx03.tar.gz", "1a72e3f85586fe6547c94f1d11eb8ccef7cceeec105ea7c9680ed3106bb45ba1"),
    Linux(:armv7l, libc=:glibc, call_abi=:eabihf, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.armv7l-linux-gnueabihf-cxx11.tar.gz", "c99df716b6e04dc9cd0014d7f868f878a6522200dfd13d8599faf41f72f2d5f7"),
    Linux(:armv7l, libc=:musl, call_abi=:eabihf, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.armv7l-linux-musleabihf-cxx03.tar.gz", "df024a1162a1881b1e1ba5bef8b668edb218a19afe3b4e7666555b47608f4e0d"),
    Linux(:armv7l, libc=:musl, call_abi=:eabihf, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.armv7l-linux-musleabihf-cxx11.tar.gz", "476beb1b75ce5fbbe64bdcfd68b62db113c189a1e66fd2fa5b7d8d85198da018"),
    Linux(:i686, libc=:glibc, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.i686-linux-gnu-cxx03.tar.gz", "6ce3f033a2d25c15313640df017bc0cf9eed1b66905a52b5e651ad05bf5970ad"),
    Linux(:i686, libc=:glibc, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.i686-linux-gnu-cxx11.tar.gz", "191ca3d57d2cb16bc350bfffc3ab40768921e76c3784ed05ad4c10e194e0d49f"),
    Linux(:i686, libc=:musl, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.i686-linux-musl-cxx03.tar.gz", "83f94924658e648dd0f320eccffc645d7cba32ced25b7b40eaaca671c22dfbc9"),
    Linux(:i686, libc=:musl, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.i686-linux-musl-cxx11.tar.gz", "b180fa8261f9a911fce6210d0cc7caeb7a3937fc754cac6409511cee89c9568d"),
    Windows(:i686, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.i686-w64-mingw32-cxx03.tar.gz", "3a6f3accc91ea61bc06a6eeab172ca56ac696fe2bb2b5b7bb57bdbc529d0bea3"),
    Windows(:i686, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.i686-w64-mingw32-cxx11.tar.gz", "b645610f3fc9238eb36acd90a1ab9fe6a1b430dd52f762903b976ae04982e140"),
    MacOS(:x86_64, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-apple-darwin14-cxx03.tar.gz", "5834f659c246273dea641134febb958f53e76c4fe1f39957dea4f857d5dac60f"),
    MacOS(:x86_64, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-apple-darwin14-cxx11.tar.gz", "429f5c6fc1ab0e2fc5c764e9e3dc2888b2f50d0341bd1c89b6978bfc268bf5af"),
    Linux(:x86_64, libc=:glibc, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-linux-gnu-cxx03.tar.gz", "b8b9d837d41744e4e246ca0a693feae562eb5b9c0f216f555d0d555a40dbe485"),
    Linux(:x86_64, libc=:glibc, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-linux-gnu-cxx11.tar.gz", "084895866f69ef916828a87aba824adbd74b1b2b12b1e510d8449efef990391e"),
    Linux(:x86_64, libc=:musl, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-linux-musl-cxx03.tar.gz", "cd26b305bb509f2195e53fb808b138e4582058fd073efbccc8a64f459ac15433"),
    Linux(:x86_64, libc=:musl, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-linux-musl-cxx11.tar.gz", "cd10e052e2426c228af4d3cb76f30fd3de97c0c0c6596b5aec0603f98f716b63"),
    Windows(:x86_64, compiler_abi=CompilerABI(:gcc_any, :cxx03)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-w64-mingw32-cxx03.tar.gz", "8c61b7844d4e3cab25195aba244aed4a0f6b13d62fba50607ee71174deb89172"),
    Windows(:x86_64, compiler_abi=CompilerABI(:gcc_any, :cxx11)) => ("$bin_prefix/CoinUtils.v2.11.3.x86_64-w64-mingw32-cxx11.tar.gz", "a56ea6bab489bd40e9ff13bf61714b34c18c2b739710ffdb74cfe97ebf16a866"),
)

# Install unsatisfied or updated dependencies:
# We added `, isolate=true` as otherwise, it would segfault when closing `OpenBLAS32`,
# probably because it is conflicting with Julia openblas.
unsatisfied = any(!satisfied(p; verbose=verbose, isolate=true) for p in products)
dl_info = choose_download(download_info, platform_key_abi())
if dl_info === nothing && unsatisfied
    # If we don't have a compatible .tar.gz to download, complain.
    # Alternatively, you could attempt to install from a separate provider,
    # build from source or something even more ambitious here.
    error("Your platform (\"$(Sys.MACHINE)\", parsed as \"$(triplet(platform_key_abi()))\") is not supported by this package!")
end

# If we have a download, and we are unsatisfied (or the version we're
# trying to install is not itself installed) then load it up!
if unsatisfied || !isinstalled(dl_info...; prefix=prefix)
    # Download and install binaries
    install(dl_info...; prefix=prefix, force=true, verbose=verbose)
end


text:
using Test
using LogicCircuits
using ProbabilisticCircuits
using LightGraphs
using MetaGraphs
using DataFrames
using Suppressor

@testset "learn chow-liu tree tests" begin
    EPS = 1e-6

    function test_chow_liu_tree(t, train_x)
        @test t isa CLT
        @test t isa MetaDiGraph
        @test is_directed(t)
        @test !has_self_loops(t)
        @test ne(t) == num_features(train_x) - 1
        @test nv(t) == num_features(train_x)
        @test_nowarn @suppress_out print_tree(t)
        for v in 1 : num_features(train_x)
            @test has_vertex(t, v)
            p = get_prop(t, v, :parent)
            @test p == 0 || has_edge(t, p, v)
            cpt = get_prop(t, v, :cpt)
            if p == 0
                @test cpt[1] ≈ sum(train_x[:,v]) / num_examples(train_x) atol=EPS
                @test cpt[1] + cpt[0] ≈ 1.0 atol=EPS
            else
                @test cpt[(1,1)] ≈ sum(train_x[:,p] .& train_x[:,v]) / sum(train_x[:,p]) atol=EPS
                @test cpt[(1,0)] ≈ sum(.!train_x[:,p] .& train_x[:,v]) / (num_examples(train_x) - sum(train_x[:,p])) atol=EPS
                @test cpt[(1,1)] + cpt[(0, 1)] ≈ 1.0 atol=EPS
                @test cpt[(1,0)] + cpt[(0, 0)] ≈ 1.0 atol=EPS
            end
        end
        for (e1, e2) in [(1, 3), (1, 4), (1, 7), (1, 9),
                        (2, 8), (2, 10), (3, 2), (3, 5), (4, 6)]
            @test has_edge(t, e1, e2) || has_edge(t, e2, e1)
        end

    end

    train_x = DataFrame(BitArray([1 0 1 0 1 0 1 0 1 0;
                                1 1 1 1 1 1 1 1 1 1;
                                0 0 0 0 0 0 0 0 0 0;
                                0 1 1 0 1 0 0 1 0 1]), :auto)
    @test_throws Exception learn_chow_liu_tree(train_x; α = 0.0, clt_root="")
    t1 = learn_chow_liu_tree(train_x; α=0.0, clt_root="graph_center")
    test_chow_liu_tree(t1, train_x)
    t2 = learn_chow_liu_tree(train_x; α=0.0, clt_root="rand")
    test_chow_liu_tree(t2, train_x)
end


text:
using Base.Test

using Clp

include("../src/BendersBridge.jl")

@testset "farmer" begin
    include("../examples/farmer.jl")
    status, objval, soln = DLP(m, ClpSolver())
    @test status == :Optimal
    @test objval == -108390
    @test soln == [170, 80, 250]
end


text:
mutable struct MultiClassLikelihood{L} <: AbstractLikelihood
    invlink::L
    n_class::Int # Number of classes
    class_mapping::Vector{Any} # Classes labels mapping
    ind_mapping::Dict{Any,Int} # Mapping from label to index
    function MultiClassLikelihood(invlink::L, n_class::Int) where {L}
        return new{L}(invlink, n_class)
    end
    function MultiClassLikelihood(invlink::L, n_class, class_mapping, ind_mapping) where {L}
        return new{L}(invlink, n_class, class_mapping, ind_mapping)
    end
end

function MultiClassLikelihood(invlink::AbstractLink, ylabels::AbstractVector)
    return MultiClassLikelihood(
        invlink,
        length(ylabels),
        ylabels,
        Dict(value => key for (key, value) in enumerate(ylabels)),
    )
end

n_latent(l::MultiClassLikelihood) = n_class(l)

n_class(l::MultiClassLikelihood) = l.n_class

function (l::MultiClassLikelihood)(f::AbstractVector)
    return l.invlink(f)
end

function (l::MultiClassLikelihood)(y::Integer, f::AbstractVector)
    return l.invlink(f)[y]
end

function Base.show(io::IO, l::MultiClassLikelihood)
    return print(io, "Multiclass Likelihood (", n_class(l), " classes, $(l.invlink) )")
end

## Return the labels in a vector of vectors for multiple outputs ##
function treat_labels!(y::AbstractArray{T,N}, likelihood::MultiClassLikelihood) where {T,N}
    N <= 1 || error("Target should be a vector of labels")
    init_multiclass_likelihood!(likelihood, y) # Initialize a mapping if not existing
    return create_one_hot(likelihood, y)
end

function init_multiclass_likelihood!(l::MultiClassLikelihood, y::AbstractVector)
    if !isdefined(l, :ind_mapping)
        create_mapping!(l, y)
    end
end

view_y(::MultiClassLikelihood, y::BitMatrix, i::AbstractVector) = view(y, i, :)

onehot_to_ind(y::AbstractVector) = findfirst(y .== 1)

function Distributions.loglikelihood(
    l::MultiClassLikelihood, y::AbstractVector, f::AbstractVector
)
    return loglikelihood(l, onehot_to_ind(y), f)
end

function create_mapping!(l::MultiClassLikelihood, y::AbstractVector)
    num_latent = n_latent(l)
    if !isdefined(l, :class_mapping)
        l.class_mapping = unique(y)
        if length(l.class_mapping) <= num_latent &&
           issubset(l.class_mapping, collect(1:num_latent))
            l.class_mapping = collect(1:num_latent)
        elseif length(l.class_mapping) > num_latent
            throw(
                ErrorException(
                    "The number of unique labels in the data : $(l.class_mapping) is not of the same size then the predefined class number ; $num_latent",
                ),
            )
        end
    end
    return l.ind_mapping = Dict(value => key for (key, value) in enumerate(l.class_mapping))
end

# Given the labels, return one hot encoding, and the mapping of each class
function create_one_hot(l::MultiClassLikelihood, y)
    issubset(unique(y), l.class_mapping) ||
        error("Some labels of y are not part of the expect labels")
    Y = falses(length(y), n_class(l))
    for i in 1:length(y)
        for j in 1:n_class(l)
            if y[i] == l.class_mapping[j]
                Y[i, j] = true
                break # Once we found the right one, we get out
            end
        end
    end
    return Y
end

function compute_proba(
    l::MultiClassLikelihood,
    μ::Tuple{Vararg{<:AbstractVector{T}}},
    σ²::Tuple{Vararg{<:AbstractVector{T}}},
    nSamples::Integer=200,
) where {T<:Real}
    K = n_class(l) # Number of classes
    n = length(μ[1]) # Number of test points
    μ = hcat(μ...) # Concatenate means together
    μ = [μ[i, :] for i in 1:n] # Create one vector per sample
    σ² = hcat(σ²...) # Concatenate variances together
    σ² = [σ²[i, :] for i in 1:n] # Create one vector per sample
    pred = zeros(T, n, K) # Empty container for the predictions
    for i in 1:n
        # p = MvNormal(μ[i],sqrt.(abs.(σ²[i])))
        # p = MvNormal(μ[i],sqrt.(max.(eps(T),σ²[i]))) #WARNING DO NOT USE VARIANCE
        pred[i, :] .= l(μ[i])
        # for _ in 1:nSamples
        # end
    end
    return NamedTuple{Tuple(Symbol.(l.class_mapping))}(eachcol(pred))
end

function expec_loglike(
    model::AbstractGPModel{T,<:MultiClassLikelihood,<:NumericalVI}
) where {T}
    return compute_log_expectations(model)
end

function Distributions.loglikelihood(l::MultiClassLikelihood, y::AbstractVector, fs)
    return loglikelihood.(l, y, [getindex.(fs, i) for i in 1:length(y)])
end

function ∇loglikehood(l::MultiClassLikelihood, y::AbstractVector, fs)
    return ∇loglikelihood.(l, y, [getindex.(fs, i) for i in 1:length(y)])
end

include("softmax.jl")
include("logisticsoftmax.jl")


text:
#Demo 2: Symbol test
#-------------------------------------------------------------------------------

using CMDimData
using CMDimData.EasyPlot
using CMDimData.MDDatasets

#==Attributes
===============================================================================#
infoaxes = cons(:attribute_list,
	xyaxes = set(xscale=:lin, yscale=:lin),
	labels = set(xaxis="X-Axis Label", yaxis="Y-Axis Label")
)
dfltwattr = cons(:attribute_list, #Default waveform attributes
	line = set(style=:solid, color=:red),
	glyph = set(shape=:square, size=3),
)

#==Input data
===============================================================================#
x = collect(0:1:10)
x = DataF1(x, 1*x)

#==Generate EasyPlot
===============================================================================#
plot = cons(:plot, infoaxes, title = "Symbol Test")
let xoffset=0, yoffset=0
for sz in [1, 3, 5]; for w in [1, 2, 3]
	overw = cons(:a, line=set(color=:blue, width=w), glyph=set(size=sz))
	push!(plot, cons(:wfrm, xshift(x+yoffset, xoffset), dfltwattr, overw, label="sz=$sz, w=$w"))
	xoffset += .5; yoffset += 10
end; end

#Coarse width test
xoffset=0; #yoffset=0
for sz in [1, 2]; for w in [1, 5, 10]
	overw = cons(:a, line=set(width=w), glyph=set(size=sz))
	push!(plot, cons(:wfrm, xshift(x+yoffset, xoffset), dfltwattr, overw, label="sz=$sz, w=$w"))
	xoffset += .5; yoffset += 10
end; end
end

pcoll = push!(cons(:plot_collection, title="Sample Plot"), plot)

#==Return pcoll to user (call evalfile(...))
===============================================================================#
pcoll


text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:3] <= 1)

                     @variable(m, -2.888482713819031 <= q <= 4.953638237128964)

                     add_NL_constraint(m, :(swish(0.8288775426207136 + -0.6672424360859748*$(x[1]) + 0.028347984312300234*$(x[2]) + 0.11850756042164479*$(x[3])) + swish(-0.7336296978706387 + 0.2644686964706797*$(x[1]) + 0.2908846438936661*$(x[2]) + -0.6031271331048136*$(x[3])) + swish(0.9373299169048916 + -0.6697043956054385*$(x[1]) + 0.9604003039018942*$(x[2]) + 0.3183773216775858*$(x[3])) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
#! /usr/bin/julia

# Rosetta Code, Truncatable primes

function isltruncprime{T<:Integer}(n::T, base::T=10)
    isprime(n) || return false
    p = n
    f = prevpow(base, p)
    while 1 < f
        (d, p) = divrem(p, f)
        isprime(p) || return false
        d != 0 || return false
        f = div(f, base)
    end
    return true
end

function isrtruncprime{T<:Integer}(n::T, base::T=10)
    isprime(n) || return false
    p = n
    while base < p
        p = div(p, base)
        isprime(p) || return false
    end
    return true
end

hi = 10^6

for i in reverse(primes(hi))
    isltruncprime(i) || continue
    println("The largest  left truncatable prime ≤ ", hi, " is ", i, ".")
    break
end

for i in reverse(primes(hi))
    isrtruncprime(i) || continue
    println("The largest right truncatable prime ≤ ", hi, " is ", i, ".")
    break
end

max_stars_repo_name: MichaeLeroy/rosetta-code

max_issues_repo_name: MichaeLeroy/rosetta-code

max_forks_repo_name: MichaeLeroy/rosetta-code


text:
using JuMP, Ipopt

#EV = Model(with_optimizer(Ipopt.Optimizer, print_level=2))
#@variable(EV, 0 <= Z[1:3] )
#EV[:Z]

#o_tmp = :(0)

#o1 = :( (Y)^2 )
#for i=1:3
#    global Y = Z[i]
#    println(Y)
#
#    #o1 = :($(Z[i])^2 * $(prob[i]))
#    bla = eval(o1)
#    #println(bla)
#    o_tmp = add_expr(o_tmp, bla)
#    println(o_tmp)
#end

#eval(o_tmp)

#add_NL_constraint(EV, :($(o_tmp) <= 2))


text:
using JuMP
using Mayday
using Base.Test
using SCS

function test_spotopt_van_der_pol(basis_generator=Mayday.monomial)
	# Replicates the test from https://github.com/spot-toolbox/spotless/blob/master/spotopt/tests/example_vanDerPol.m
	# which maximizes the verified Region of Attraction of a linear controller
	# for the van der Pol oscillator about the origin.

	x, y = generators(:x, :y)

	# System dynamics:
	f = -[y; (1 - x^2) * y - x]

	# Construct a Lyapunov function
	J = jacobian(f, :x, :y)
	A = evaluate(J, 0.0, 0.0)
	P = lyap(A', eye(2,2))
	V = Mayday.quad([x; y], P)
	Vdot = sum(grad(V, :x, :y) .* f)

	# Solve for the maximum RoA, parameterized by rho
	model = Model(solver=SCSSolver())
	@variable(model, rho)
	lambda = defPolynomial(model, [:x, :y], 4, basis_generator)
	d = Int(floor(deg(lambda * Vdot) / 2 - 1))
	addSoSConstraint(model, lambda * Vdot + (V - rho) * (x^2 + y^2)^d, basis_generator)
	@objective(model, Max, rho)
	solve(model)

	result = getvalue(rho)
	@show result

	# Verify rho against the answer we get from spotless
	@test abs(result - 2.3045) < 1e-3
end

test_spotopt_van_der_pol()


text:
#=
  Cantor distribution
  from Foundations of Probabilistic Programming,
  page 5
  """
  Finally, the program in Fig. 1.4 generates a real number between [0, 1] whose
  expansion in base 3 does not contain any 1’s. This program is not like the others
  in that it does not halt (nor is it meant to). The program generates a sample from
  a curious and in many respects counterintuitive distribution called the Cantor
  distribution. It cannot be described using discrete probability distributions (i.e.
  finite or countable weighted sums of point masses), although the program only
  uses a discrete fair coin as a source. The Cantor distribution is also an example of
  continuous probability distribution, which assigns probability zero to every element
  of the state space. It is also an example of a so-called singular distribution, since
  it can be shown that the set of all its possible outcomes—that is to say the set of
  all real numbers whose base-3 expansion contains no 1’s—has measure 0 in the
  Lebesgue measure on [0, 1]
  """
=#

using Turing, StatsPlots, DataFrames
include("../jl_utils.jl")

# Plain simulation
function cantor_plain()
     x = 0
     d = 1
     i = 0
     while i < 10  # true
         d = d / 3
         x = x + 2*rand(DiscreteUniform(0,1))*d
         println("d:$d x:$x")
         i+=1
     end
end

# cantor_plain()

# Using Turing
@model cantor() = begin
    x ~ Uniform(0,1)
    d ~ Uniform(0,1)
    d = 1
    i = 0
    while i < 100  # true
        d /= 3
        t ~ DiscreteUniform(0,1)
        x += 2*t*d
        # println("d:$d x:$x")
        i += 1
    end
    dfinal ~ Uniform(0,1)
    dfinal = d
end

model = cantor()

num_chains = 4
# chains = sample(model, MH(), MCMCThreads(), 1000, num_chains)
chains = sample(model, MH(), 100)

display(chains)
show_var_dist_pct(chains, :d,20)
show_var_dist_pct(chains, :dfinal,20)
# show_var_dist_pct(chains, :y)
# show_var_dist_pct(chains, :u,20)
# show_var_dist_pct(chains, :v,20)

max_stars_repo_name: Wikunia/hakank

max_issues_repo_name: Wikunia/hakank

max_forks_repo_name: Wikunia/hakank


text:
#CircuitAnalysis show functions
#-------------------------------------------------------------------------------

#==Generate friendly show functions
===============================================================================#

_showcompact(io::IO, t::Type{<:TImpedance}) = print(io, "TImpedance")
_showcompact(io::IO, t::Type{<:TAdmittance}) = print(io, "TAdmittance")
_showcompact(io::IO, t::Type{<:TInductance}) = print(io, "TInductance")
_showcompact(io::IO, t::Type{<:TCapacitance}) = print(io, "TCapacitance")

Base.show(io::IO, t::Type{TImpedance{T}}) where T = print(io, "TImpedance{$T}")
Base.show(io::IO, t::Type{TAdmittance{T}}) where T = print(io, "TAdmittance{$T}")
Base.show(io::IO, t::Type{TInductance{T}}) where T = print(io, "TInductance{$T}")
Base.show(io::IO, t::Type{TCapacitance{T}}) where T = print(io, "TCapacitance{$T}")

function Base.show(io::IO, x::DataTag{ID,T}) where {ID,T}
	_showcompact(io, DataTag{ID,T})
	print(io, "(", x.v, ")")
end

#Last line


text:
function testplaneconnect()
  sp = SegmentParameters(w=0.5,h=0.2,sigma=62.1e6*1e-3)
  n1 = Node(1,0,0)
  n2 = Node(2,0,0)
  n3 = Node(3,0,0)
  n11 = Node(1,0,-1)
  n12 = Node(2,0,-1)
  n13 = Node(3,0,-1)
  n4 = Node(10,0,0)
  hsegs = connectnodes([n1,n2,n3,n4],sp)
  vsegs = [Segment(n1,n11,sp), Segment(n2,n12,sp), Segment(n3,n13,sp)]
  g1 = Group([n1;n2;n3;n4;n11;n12;n13;hsegs;vsegs], Dict(:a=>n4,:b=>[n11,n12,n13]))
  n5 = Node(20,20,-1)
  (planenodes,equivgroup) = planeconnect([n5,n11,n12,n13])
  u1 = UniformPlane(
  x1=0,  y1=0,  z1=-1,
  x2=0,  y2=20, z2=-1,
  x3=20, y3=20, z3=-1,
  thick = .5,
  seg1=100, seg2=100,
  nodes = planenodes)
  g2 = Group([n5,u1,equivgroup])
  title = Comment("term with node array")
  u = Units("mm")
  pre = Group([title,u])
  ex = External(n1,n5)
  f = Freq(min=1e-1, max=1e9, ndec=0.05)
  e = End()
  post = Group([ex,f,e])
  Group([pre;g1;g2;post])
end
testplaneconnect()

# test transform with rectangulararray
function test_rectangulararray_transform()
  g1 = transform(Node(1,1,1), rectangulararray(0,0,[1,2,3]))
  via = viagroup(radius=5, height=3, h=1, n=8)
  g2 = transform(via,  rectangulararray([20,40,60],[40,80],[100,200]))
end
test_rectangulararray_transform()

function testparsefasthenrymat()
  pfhmr_example3 = parsefasthenrymat("example3_Zc.mat")
  pfhmr_eightloops = parsefasthenrymat("eightloopsZc.mat")
end
testparsefasthenrymat()


text:
using Test
using Unitful

@testset "Test thermodynamic functions" begin
#Test NASA
@testset "Test thermodyamics from NASA polynomial" begin
nasap1 = NASApolynomial(coefs=[4.03055,-0.00214171,4.90611e-05,-5.99027e-08,2.38945e-11,-11257.6,3.5613],Tmin=300.0,Tmax=650.73)
nasap2 = NASApolynomial(coefs=[-0.307954,0.0245269,-1.2413e-05,3.07724e-09,-3.01467e-13,-10693,22.628],Tmin=650.73,Tmax=3000.0)
nasa = NASA(polys=[nasap1,nasap2])
Tlist= 400.0:200:2000.0

#test Cp
@testset "Test get heat capacity function" begin
Cpexplist = [7.80157, 10.5653, 12.8213, 14.5817, 15.9420, 16.9861, 17.78645, 18.4041, 18.8883] * R
Cps = [getHeatCapacity(nasa,T) for T in Tlist]
@test Cps ≈ Cpexplist rtol=1e-3
end;

#test S
@testset "Test get entropy function" begin
Sexplist = [29.6534, 33.3516, 36.7131, 39.7715, 42.5557, 45.0952, 47.4179, 49.5501, 51.5152]*R
Ss = [getEntropy(nasa,T) for T in Tlist]
@test Ss ≈ Sexplist rtol=1e-3
end;

#test H
@testset "Test get enthalpy function" begin
Hexplist = [-22.7613, -12.1027, -6.14236, -2.16615, 0.743456, 2.99256, 4.79397, 6.27334, 7.51156].*Tlist*R
Hs = [getEnthalpy(nasa,T) for T in Tlist]
@test Hs ≈ Hexplist rtol=1e-3
end;
end;

#test Wilhoit
@testset "Test thermodynamics from Wilhoit" begin
w = Wilhoit(Cp0=4.0*R,Cpinf=21.5*R,coefs=[0.0977518,-16.3067,26.2524,-12.6785],B=1068.68,H0=-94088.0*R,S0=-118.46*R)
Tlist = 200.0:200:2000.0

#test Cp
@testset "Test get heat capacity function" begin
Cpexplist = [5.12003, 7.80327, 10.5528, 12.8323, 14.6013, 15.9511, 16.9842, 17.7837, 18.4114, 18.9117]*R
Cps = [getHeatCapacity(w,T) for T in Tlist]
@test Cps ≈ Cpexplist rtol=1e-3
end;

#test S
@testset "Test get entropy function" begin
Sexplist = [25.3095, 29.6445, 33.3398, 36.7006, 39.7629, 42.5499, 45.0898, 47.4122, 49.5445, 51.5112]*R
Ss = [getEntropy(w,T) for T in Tlist]
@test Ss ≈ Sexplist rtol=1e-3
end;

#test H
@testset "Test get enthalpy function" begin
Hexplist = [-51.9303, -22.7609, -12.1050, -6.14444, -2.16433, 0.747500, 2.99646, 4.79698, 6.27618, 7.51564].*Tlist*R
Hs = [getEnthalpy(w,T) for T in Tlist]
@test Hs ≈ Hexplist rtol=1e-3
end;
end;
end;


text:
# this is mostly copy-pasta from Parsers.jl main xparse function
@inline function xparse(::Type{T}, source::Union{AbstractVector{UInt8}, IO}, pos, len, options::Options{ignorerepeated, Q, debug, S, D, DF}) where {T <: AbstractString, ignorerepeated, Q, debug, S, D, DF}
    startpos = vstartpos = vpos = pos
    sentinelpos = 0
    code = SUCCESS
    sentinel = options.sentinel
    quoted = false
    if debug
        println("parsing $T, pos=$pos, len=$len")
    end
    if eof(source, pos, len)
        code = (sentinel === missing ? SENTINEL : OK) | EOF
        @goto donedone
    end
    b = peekbyte(source, pos)
    if debug
        println("string 1) parsed: '$(escape_string(string(Char(b))))'")
    end
    # strip leading whitespace
    while b == options.wh1 || b == options.wh2
        if debug
            println("stripping leading whitespace")
        end
        pos += 1
        incr!(source)
        if eof(source, pos, len)
            code |= EOF
            @goto donedone
        end
        b = peekbyte(source, pos)
        if debug
            println("string 2) parsed: '$(escape_string(string(Char(b))))'")
        end
    end
    # check for start of quoted field
    if Q
        quoted = b == options.oq
        if quoted
            if debug
                println("detected open quote character")
            end
            code = QUOTED
            pos += 1
            vstartpos = pos
            incr!(source)
            if eof(source, pos, len)
                code |= INVALID_QUOTED_FIELD
                @goto donedone
            end
            b = peekbyte(source, pos)
            if debug
                println("string 3) parsed: '$(escape_string(string(Char(b))))'")
            end
            # ignore whitespace within quoted field
            while b == options.wh1 || b == options.wh2
                if debug
                    println("stripping whitespace within quoted field")
                end
                pos += 1
                incr!(source)
                if eof(source, pos, len)
                    code |= INVALID_QUOTED_FIELD | EOF
                    @goto donedone
                end
                b = peekbyte(source, pos)
                if debug
                    println("string 4) parsed: '$(escape_string(string(Char(b))))'")
                end
            end
        end
    end
    # check for sentinel values if applicable
    if sentinel !== nothing && sentinel !== missing
        if debug
            println("checking for sentinel value")
        end
        sentstart = pos
        sentinelpos = checksentinel(source, pos, len, sentinel, debug)
    end
    vpos = pos
    if Q
        # for quoted fields, find the closing quote character
        # we should be positioned at the correct place to find the closing quote character if everything is as it should be
        # if we don't find the quote character immediately, something's wrong, so mark INVALID
        if quoted
            if debug
                println("looking for close quote character")
            end
            same = options.cq == options.e
            while true
                vpos = pos
                pos += 1
                incr!(source)
                if same && b == options.e
                    if eof(source, pos, len)
                        code |= EOF
                        @goto donedone
                    elseif peekbyte(source, pos) != options.cq
                        break
                    end
                    code |= ESCAPED_STRING
                    pos += 1
                    incr!(source)
                elseif b == options.e
                    if eof(source, pos, len)
                        code |= INVALID_QUOTED_FIELD | EOF
                        @goto donedone
                    end
                    code |= ESCAPED_STRING
                    pos += 1
                    incr!(source)
                elseif b == options.cq
                    if eof(source, pos, len)
                        code |= EOF
                        @goto donedone
                    end
                    break
                end
                if eof(source, pos, len)
                    code |= INVALID_QUOTED_FIELD | EOF
                    @goto donedone
                end
                b = peekbyte(source, pos)
                if debug
                    println("string 9) parsed: '$(escape_string(string(Char(b))))'")
                end
            end
            b = peekbyte(source, pos)
            if debug
                println("string 10) parsed: '$(escape_string(string(Char(b))))'")
            end
            # ignore whitespace after quoted field
            while b == options.wh1 || b == options.wh2
                if debug
                    println("stripping trailing whitespace after close quote character")
                end
                pos += 1
                incr!(source)
                if eof(source, pos, len)
                    code |= EOF
                    @goto donedone
                end
                b = peekbyte(source, pos)
                if debug
                    println("string 11) parsed: '$(escape_string(string(Char(b))))'")
                end
            end
        end
    end
    if options.delim !== nothing
        delim = options.delim
        quo = Int(!quoted)
        # now we check for a delimiter; if we don't find it, keep parsing until we do
        if debug
            println("checking for delimiter: pos=$pos")
        end
        while true
            if !ignorerepeated
                if delim isa UInt8
                    if b == delim
                        pos += 1
                        incr!(source)
                        code |= DELIMITED
                        @goto donedone
                    end
                else
                    predelimpos = pos
                    pos = checkdelim(source, pos, len, delim)
                    if pos > predelimpos
                        # found the delimiter we were looking for
                        code |= DELIMITED
                        @goto donedone
                    end
                end
            else
                if delim isa UInt8
                    matched = false
                    while b == delim
                        matched = true
                        pos += 1
                        incr!(source)
                        if eof(source, pos, len)
                            code |= DELIMITED
                            @goto donedone
                        end
                        b = peekbyte(source, pos)
                        if debug
                            println("string 14) parsed: '$(escape_string(string(Char(b))))'")
                        end
                    end
                    if matched
                        code |= DELIMITED
                        @goto donedone
                    end
                else
                    matched = false
                    predelimpos = pos
                    pos = checkdelim(source, pos, len, delim)
                    while pos > predelimpos
                        matched = true
                        if eof(source, pos, len)
                            code |= DELIMITED
                            @goto donedone
                        end
                        predelimpos = pos
                        pos = checkdelim(source, pos, len, delim)
                    end
                    if matched
                        code |= DELIMITED
                        @goto donedone
                    end
                end
            end
            # didn't find delimiter, but let's check for a newline character
            if b == UInt8('\n')
                pos += 1
                incr!(source)
                code |= NEWLINE | ifelse(eof(source, pos, len), EOF, SUCCESS)
                @goto donedone
            elseif b == UInt8('\r')
                pos += 1
                incr!(source)
                if !eof(source, pos, len) && peekbyte(source, pos) == UInt8('\n')
                    pos += 1
                    incr!(source)
                end
                code |= NEWLINE | ifelse(eof(source, pos, len), EOF, SUCCESS)
                @goto donedone
            end
            # didn't find delimiter nor newline, so increment and check the next byte
            pos += 1
            vpos += quo
            incr!(source)
            if eof(source, pos, len)
                code |= EOF
                @goto donedone
            end
            b = peekbyte(source, pos)
        end
    end

@label donedone
    if sentinel !== nothing && sentinel !== missing && sentstart == vstartpos && sentinelpos == vpos
        # if we matched a sentinel value that was as long or longer than our type value
        code |= SENTINEL
    elseif sentinel === missing && vstartpos == vpos
        code |= SENTINEL
    else
        code |= OK
    end
    if debug
        println("finished parsing: $(codes(code))")
    end
    return code, code, Int64(vstartpos), Int64(vpos - vstartpos), Int64(pos - startpos)
end


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

const MAX_GROUPING_SIZE = 24

struct DicEntry
    original::Vector{UInt8}
    lc_attr::UInt16
    rc_attr::UInt16
    posid::UInt16
    wcost::Int16
    feature::Vector{UInt8}
    skip::Bool
end

#------------------------------------------------------------------------------

struct CharProperty
    mmap::Vector{UInt32}
    category_names:: Vector{Vector{UInt8}}
end

struct CharInfo
    default_type::UInt32
    type::UInt32
    count::UInt32
    group::UInt32
    invoke::UInt32
end

function utf8_to_ucs2(s::Vector{UInt8}, index::Int64)::Tuple{UInt16, Int64}
    # utf8 to ucs2(16bit) code and it's array size
    ln::Int64 = 0

    if (s[index] & 0b10000000) == 0b00000000
        ln = 1
    elseif (s[index] & 0b11100000) == 0b11000000
        ln = 2
    elseif (s[index] & 0b11110000) == 0b11100000
        ln = 3
    elseif (s[index] & 0b11111000) == 0b11110000
        ln = 4
    else
        throw("invalid utf8 string array: $(s)")
    end

    if ln == 1
        ch32 = UInt32(s[index+0])
    elseif ln == 2
        ch32 = UInt32(s[index+0] & 0x1F) << 6
        ch32 |= s[index+1] & 0x3F
    elseif ln == 3
        ch32 = UInt32(s[index+0] & 0x0F) << 12
        ch32 |= UInt32(s[index+1] & 0x3F) << 6
        ch32 |= s[index+2] & 0x3F
    elseif ln == 4
        ch32 = UInt32(s[index+0] & 0x07) << 18
        ch32 |= UInt32(s[index+1] & 0x3F) << 12
        ch32 |= UInt32(s[index+2] & 0x3F) << 6
        ch32 |= s[index+3] & 0x03F
    end

    # ucs4 to ucs2
    if ch32 < 0x10000
        ch16 = UInt16(ch32)
    else
        ch16 = UInt16((((ch32-0x10000) // 0x400 + 0xD800) << 8) + ((ch32-0x10000) % 0x400 + 0xDC00))
    end
    (ch16, ln)
end

function get_char_propery(path::AbstractString)::CharProperty
    category_names = []
    f = open(path)
    num_categories = read(f, UInt32)
    for _ in 1:num_categories
        raw_data = zeros(UInt8, 32)
        readbytes!(f, raw_data, 32)
        push!(category_names, view(raw_data, 1:findfirst(x -> x==0, raw_data)-1))
    end
    mmap = Mmap.mmap(f, Vector{UInt32}, 0xFFFF)
    close(f)
    CharProperty(mmap, category_names)
end

function get_char_info(cp::CharProperty, code_point::UInt16)::CharInfo
    v = cp.mmap[code_point+1]
    CharInfo(
        (v >> 18) & 0b11111111,
        v & 0b111111111111111111,
        (v >> 26) & 0b1111,
        (v >> 30) & 0b1,
        (v >> 31) & 0b1
    )
end

function get_group_length(cp::CharProperty, s::Vector{UInt8}, default_type::UInt32)::Int64
    i = 1
    char_count = 0
    while i <= length(s)
        ch16, ln = utf8_to_ucs2(s, i)
        char_info = get_char_info(cp, ch16)
        if ((1 << default_type) & char_info.type) != 0
            i += ln
            char_count += 1
            if char_count > MAX_GROUPING_SIZE
                return -1
            end
        else
            break
        end
    end
    i - 1
end

function get_count_length(cp::CharProperty, s::Vector{UInt8}, default_type::UInt32, count::Int64)::Int64
    i = 1
    j = 1
    while j <= count
        if i > length(s)
            return -1
        end
        ch16, ln = utf8_to_ucs2(s, i)
        char_info = get_char_info(cp, ch16)
        if ((1 << default_type) & char_info.type) == 0
            return -1
        end
        i += ln
        j += 1
    end
    i - 1
end

function get_unknown_lengths(cp::CharProperty, s::Vector{UInt8})::Tuple{UInt32, Vector{UInt32}, Bool}
    ln_list::Vector{UInt32} = []
    ch16, first_ln = utf8_to_ucs2(s, 1)
    char_info = get_char_info(cp, ch16)
    if char_info.group != 0
        ln = get_group_length(cp, s, char_info.default_type)
        if ln > 0
            push!(ln_list, ln)
        end
    end
    if char_info.count != 0
        n = 1
        while n <= char_info.count
            ln = get_count_length(cp, s, char_info.default_type, n)
            if ln < 0
                break
            end
            push!(ln_list, ln)
            n += 1
        end
    end
    if length(ln_list) == 0
        push!(ln_list, fist_ln)
    end
    (char_info.default_type, ln_list, char_info.invoke == 1)
end

#------------------------------------------------------------------------------

struct MecabDic
    mmap::Vector{UInt8}
    dic_size::UInt32
    lsize::UInt32
    rsize::UInt32
    da_offset::UInt32
    token_offset::UInt32
    feature_offset::UInt32
end

function get_mecabdic(path::AbstractString)::MecabDic
    f = open(path)
    dic_size = read(f, UInt32) ^ 0xef718f77
    version = read(f, UInt32)
    dictype = read(f, UInt32)
    lexsize = read(f, UInt32)
    lsize = read(f, UInt32)
    rsize = read(f, UInt32)
    dsize = read(f, UInt32)
    tsize = read(f, UInt32)
    fsize = read(f, UInt32)
    read(f, UInt32)     # 0:dummy
    raw_data = zeros(UInt8, 32)
    readbytes!(f, raw_data, 32)
    charset = String(raw_data[1:findfirst(x -> x==0, raw_data)-1])
    da_offset = 1
    token_offset = 1 + dsize
    feature_offset = token_offset + tsize
    mmap = Mmap.mmap(f, Vector{UInt8}, filesize(path)-72)
    close(f)
    MecabDic(
        mmap, dic_size, lsize, rsize,
        da_offset, token_offset, feature_offset
    )
end

function base_check(dic::MecabDic, idx::UInt32)::Tuple{Int32, UInt32}
    i = dic.da_offset + idx * 8
    (reinterpret(Int32, view(dic.mmap, i:i+3))[1], reinterpret(UInt32, view(dic.mmap, i+4:i+7))[1])
end

function exact_match_search(dic::MecabDic, s::Vector{UInt8})::Int32
    v::Int32 = -1
    b, _ = base_check(dic, UInt32(0))
    for item in s
        p = UInt32(b + Int32(item) + 1)
        base, check = base_check(dic, p)
        if b == Int32(check)
            b = base
        else
            return v
        end
    end

    p = UInt32(b)
    n, check = base_check(dic, p)
    if b == Int32(check) && n < 0
        v = Int32(-n-1)
    end

    v
end

function common_prefix_search(dic::MecabDic, s::Vector{UInt8})::Vector{Tuple{Int32, Int64}}
    results::Vector{Tuple{Int32, Int64}} = []
    b, _ = base_check(dic, UInt32(0))
    for i in 1:length(s)
        item = s[i]
        p = UInt32(b)
        n, check = base_check(dic, p)
        if b == Int32(check) && n < 0
            push!(results, (-n-1, Int64(i)-1))
        end
        p = UInt32(b + Int32(item) + 1)
        base, check = base_check(dic, p)
        if b == Int32(check)
            b = base
        else
            return results
        end
    end
    p = UInt32(b)
    n, check = base_check(dic, p)
    if b == Int32(check) && n < 0
        push!(results, (-n-1, length(s)))
    end

    results
end

function get_entries_by_index(dic::MecabDic, idx::UInt32, count::UInt32, s::Vector{UInt8}, skip::Bool)::Vector{DicEntry}
    results::Vector{DicEntry} = []
    for i in 1:count
        offset = dic.token_offset + (idx + i-1) * 16
        lc_attr = reinterpret(UInt16, view(dic.mmap, offset:offset+1))[1]
        rc_attr = reinterpret(UInt16, view(dic.mmap, offset+2:offset+3))[1]
        posid = reinterpret(UInt16, view(dic.mmap, offset+4:offset+5))[1]
        wcost = reinterpret(Int16, view(dic.mmap, offset+6:offset+7))[1]
        feature = reinterpret(UInt32, view(dic.mmap, offset+8:offset+11))[1]
        j = dic.feature_offset + feature
        k = j
        while dic.mmap[k] != 0
            k += 1
        end
        feature = dic.mmap[j:k-1]
        push!(results, DicEntry(s, lc_attr, rc_attr, posid, wcost, feature, skip))
    end

    results
end

function get_entries(dic::MecabDic, result::UInt32, s::Vector{UInt8}, skip::Bool)::Vector{DicEntry}
    idx = result >> 8
    count = result & 0xFF
    get_entries_by_index(dic, idx, count, s, skip)
end

function lookup(dic::MecabDic, s::Vector{UInt8})::Vector{DicEntry}
    results::Vector{DicEntry} = []
    for (result, ln) in common_prefix_search(dic, s)
        idx = UInt32(result >> 8)
        count = UInt32(result & 0xFF)
        results = vcat(results, get_entries_by_index(dic, idx, count, s[1:ln], false))
    end

    results
end

function lookup_unknowns(dic::MecabDic, s::Vector{UInt8}, cp::CharProperty)::Tuple{Vector{DicEntry}, Bool}
    default_type, ln_vec, invoke = get_unknown_lengths(cp, s)
    category_name = cp.category_names[default_type]
    result = exact_match_search(dic, category_name)
    results::Vector{DicEntry} = []
    for i in ln_vec
        new_results = get_entries(dic, UInt32(result), s[1:i], category_name == b"SPACE")
        results = vcat(results, new_results)
    end

    (results, invoke)
end

#------------------------------------------------------------------------------

struct Matrix
    mmap::Vector{Int16}
    lsize::UInt32
    rsize::UInt32
end

function get_matrix(path::AbstractString)::Matrix
    f = open(path)
    lsize = UInt32(read(f, UInt16))
    rsize = UInt32(read(f, UInt16))
    mmap = Mmap.mmap(f, Vector{Int16}, lsize * rsize)
    close(f)
    Matrix(mmap, lsize, rsize)
end

function get_trans_cost(m::Matrix, id1::UInt16, id2::UInt16)::Int32
    Int32(m.mmap[UInt32(id2) * m.lsize + UInt32(id1) + 1])
end


text:
module Slacker
using HTTP, JSON

include("slackbot.jl")

export SlackConfig, addConfig, loadConfig, sendMessage, removeConfigFile, readConfigFile
export hasConfig, removeConfig

end # module


text:
using NetflixPrize
using Base.Test

realdata = joinpath(Pkg.dir("NetflixPrize"), "data", "download", "training_set")
testdata = joinpath(Pkg.dir("NetflixPrize"), "test", "testdata", "mv_1.txt")

#Copy test data over if real data doesn't exist
if !isdir(realdata)
    dir = joinpath(Pkg.dir("NetflixPrize"), "data")
    isdir(dir) || mkdir(dir)
    dir = joinpath(dir, "download")
    isdir(dir) || mkdir(dir)
    isdir(realdata) || mkdir(realdata)

    cp(testdata, joinpath(realdata, "mv_1.txt"))
end

NetflixPrize.training_set()


text:
@doc """
	ExactState <: QState
# Structure
- `site::ITensor`: An order N tensor for a N-qubit system.
""" ->
ExactState

@doc """
	ExactState(N::Int, init::Vector{T}) where T<:Number
Construct a N-qubit Exact state with all qubit initialized to given initial value.
""" ->
ExactState(N::Int, init::Vector{T} where T<:Number)

@doc """
	ExactState(N::Int)
Construct an ExactState with N qubits all initialized to |0>.
""" ->
ExactState(N::Int)

@doc """
	copy(state::ExactState)
Make a copy of given state.
""" ->
copy(state::ExactState)

@doc """
	isapprox(state1::ExactState, state2::ExactState)
Do an approximate comparison between two states.
""" ->
isapprox(state1::ExactState, state2::ExactState)

@doc """
	numQubits(state::ExactState)
Return number of qubits in given state.
""" ->
numQubits(state::ExactState)

@doc """
	toMPSState(state::ExactState; kwargs...)
Turn given ExactState into a MPSState.
# Keyword Arguments
* The same as keywords taken by `svd`. See also **svd**.
""" ->
toMPSState(state::ExactState; kwargs...)

@doc """
	ρ(state::ExactState, config::Vector{Int})
Return probability density of given configuration.
""" ->
ρ(state::ExactState, config::Vector{Int})


text:
using Distributions
using LinearAlgebra
using Random

# Define the DGP
function simulate_sample(N0, N1)
    X0 = [ones(N0) rand([0, 1], N0, 4) rand(N0)]
    X1 = kron([ones(2, 4) [1, 0] [0, 0]], ones(N1))
    α = 4
    δ = α / √(1 + α^2)
    ω = 1
    ξ = - ω * δ * √(2 / π)
    ϵ = √(1 - δ^2) .* randn(N0) + δ .* abs.(randn(N0)) .+ ξ
    y0 = 1.0 .+ 0.5 * X0[:, end - 1] .+ 0.5 * X0[:, end] .+ ϵ
    y1 = LinRange(-3, 3, N1) |> collect |> x -> repeat(x, 2)
    return y0, X0, y1, X1, ϵ
end

# # Not run
# Random.seed!(1);
# N0, N1 = 500, 0;
# y0, X0, y1, X1, ϵ = simulate_sample(N0, N1);
# mean(ϵ)


text:
"""
    smoothspec(z, nas)

Smoothen field `z(ns,ns)` with a spectral method at scale `ns/nas`
Takes into account missing values.
"""
function smoothspec(zi, nas)

    iinan = findall(isnan.(zi))
    iinotnan = findall(.~isnan.(zi))
    zi[iinan] = 0.

    nss = size(zi)
    ns = nss[1]
    sdim = div(ns, nas) # the smoothing radius is one large scale pixel wide (setting the diameter to 1 pixel is wrong)

    kx = [collect(0:ns/2)' collect(-ns/2+1:-1)']'
    kx = kx*ones(1,ns)
    kx = kx.^2+permutedims(kx, [2 1]).^2

    zif = fft(zi)
    zif[kx[:].>(nas/2).^2] = 0.0
    zif[kx[:].==(nas/2).^2] = real(zif[kx[:].==(nas/2).^2]*2.0)
    zif = real(ifft(zif))

    return zif
end


text:
using Base: Float64
using Pkg
current_env = Base.load_path()[1]
Pkg.activate(@__DIR__)

using RadialBasisFunctionModels
using Test
import ForwardDiff

#%%
@testset "Gaussian" begin
	φ = Gaussian()
	@test φ(0) == 1
	@test φ(0) isa Float64	# stanard precision of `exp`
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = Gaussian( rand(Float16) )
	@test RadialBasisFunctionModels.cpd_order(φ) == 0
	@test φ(0) == 1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = Gaussian( rand(Float32) )
	@test φ(0) == 1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float32

	φ = Gaussian( rand(Float64) )
	@test φ(0) == 1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float64
	@test φ(Float16(0)) isa Float64

	φ = Gaussian()

	@test RadialBasisFunctionModels.df( φ, 0 ) == 0
	x = rand()
	@test RadialBasisFunctionModels.df( φ, x ) ≈ ForwardDiff.derivative( φ, x)
end

#%%
@testset "Multiquadric" begin
	φ = Multiquadric()
	@test RadialBasisFunctionModels.cpd_order(φ) == 1
	@test φ(0) == -1
	@test φ(0) isa Float64	# stanard precision of `sqrt`
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = Multiquadric(; α = one(Float16) )
	@test φ(0) == -1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = Multiquadric(; α = one(Float32) )
	@test φ(0) == -1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float32

	φ = Multiquadric(; α = one(Float64) )
	@test φ(0) == -1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float64
	@test φ(Float16(0)) isa Float64

	φ = Multiquadric()
	x = rand()
	@test RadialBasisFunctionModels.df( φ, x ) ≈ ForwardDiff.derivative( φ, x)
end

#%%
@testset "InverseMultiquadric" begin
	φ = InverseMultiquadric()
	@test RadialBasisFunctionModels.cpd_order(φ) == 0
	@test φ(0) == 1
	@test φ(0) isa Float64	# stanard precision of `sqrt`
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = InverseMultiquadric(; α = one(Float16) )
	@test φ(0) == 1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = InverseMultiquadric(; α = one(Float32) )
	@test φ(0) == 1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float32

	φ = InverseMultiquadric(; α = one(Float64) )
	@test φ(0) == 1
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float64
	@test φ(Float16(0)) isa Float64

	φ = InverseMultiquadric()
	x = rand()
	@test RadialBasisFunctionModels.df( φ, x ) ≈ ForwardDiff.derivative( φ, x)
end

#%%
@testset "Cubic" begin
	φ = Cubic()
	@test RadialBasisFunctionModels.cpd_order(φ) == 2
	@test φ(0) == 0
	@test φ(1) == 1
	@test φ(0) isa Int
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	φ = Cubic( Float64(3) )
	@test φ.β isa Int

	φ = Cubic()

	@test RadialBasisFunctionModels.df( φ, 0 ) == 0
	x = rand()
	@test RadialBasisFunctionModels.df( φ, x ) ≈ ForwardDiff.derivative( φ, x)
end

#%%
@testset "ThinPlateSpline" begin
	φ = ThinPlateSpline()
	@test RadialBasisFunctionModels.cpd_order(φ) == 3
	@test φ(0) == 0
	@test φ(0.0) isa Float64
	@test φ(0f0) isa Float32
	@test φ(Float16(0)) isa Float16

	@test RadialBasisFunctionModels.df( φ, 0 ) == 0
	x = rand()
	@test RadialBasisFunctionModels.df( φ, x ) ≈ ForwardDiff.derivative( φ, x)
end

#%%
Pkg.activate(current_env)