text:
# Store specific byte patterns in these variables for the fuzzer. These
# values are taken verbatim from the C++ function FuzzTest1.
const overflowingInt32Val = read(IOBuffer(UInt8[0x83, 0x33, 0x33, 0x33]), Int32)
const overflowingInt64Val = read(IOBuffer(UInt8[0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44]), Int64)

# CheckByteLayout verifies the bytes of a Builder in various scenarios.
function CheckByteLayout()
	check = want-> begin
	got = b.bytes[b.head+1:end]
	@test want == got
	return
end

# test 1: numbers

b = FlatBuffers.Builder()
check(UInt8[])
FlatBuffers.prepend!(b, true)
check(UInt8[1])
FlatBuffers.prepend!(b, Int8(-127))
check(UInt8[129, 1])
FlatBuffers.prepend!(b, UInt8(255))
check(UInt8[255, 129, 1])
FlatBuffers.prepend!(b, Int16(-32222))
check(UInt8[0x22, 0x82, 0, 255, 129, 1]) # first pad
FlatBuffers.prepend!(b, UInt16(0xFEEE))
check(UInt8[0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]) # no pad this time
FlatBuffers.prepend!(b, Int32(-53687092))
check(UInt8[204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1])
FlatBuffers.prepend!(b, UInt32(0x98765432))
check(UInt8[0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1])

# test 1b: numbers 2

b = FlatBuffers.Builder()
prepend!(b, 0x1122334455667788)
check(UInt8[0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11])

# test 2: 1xbyte vector

b = FlatBuffers.Builder()
check(UInt8[])
FlatBuffers.startvector(b, sizeof(Bool), 1, 1)
check(UInt8[0, 0, 0]) # align to 4bytes
FlatBuffers.prepend!(b, UInt8(1))
check(UInt8[1, 0, 0, 0])
FlatBuffers.endvector(b, 1)
check(UInt8[1, 0, 0, 0, 1, 0, 0, 0]) # padding

# test 3: 2xbyte vector

b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(UInt8), 2, 1)
check(UInt8[0, 0]) # align to 4bytes
FlatBuffers.prepend!(b, UInt8(1))
check(UInt8[1, 0, 0])
FlatBuffers.prepend!(b, UInt8(2))
check(UInt8[2, 1, 0, 0])
FlatBuffers.endvector(b, 2)
check(UInt8[2, 0, 0, 0, 2, 1, 0, 0]) # padding

# test 3b: 11xbyte vector matches builder size

b = FlatBuffers.Builder(Any, 12)
FlatBuffers.startvector(b, sizeof(UInt8), 8, 1)
start = UInt8[]
check(start)
for i = 1:11
	FlatBuffers.prepend!(b, UInt8(i))
	start = append!(UInt8[i], start)
	check(start)
end
FlatBuffers.endvector(b, 8)
check(append!(UInt8[8, 0, 0, 0], start))

# test 4: 1xuint16 vector

b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(UInt16), 1, 1)
check(UInt8[0, 0]) # align to 4bytes
FlatBuffers.prepend!(b, UInt16(1))
check(UInt8[1, 0, 0, 0])
FlatBuffers.endvector(b, 1)
check(UInt8[1, 0, 0, 0, 1, 0, 0, 0]) # padding

# test 5: 2xuint16 vector

b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(UInt16), 2, 1)
check(UInt8[]) # align to 4bytes
FlatBuffers.prepend!(b, UInt16(0xABCD))
check(UInt8[0xCD, 0xAB])
FlatBuffers.prepend!(b, UInt16(0xDCBA))
check(UInt8[0xBA, 0xDC, 0xCD, 0xAB])
FlatBuffers.endvector(b, 2)
check(UInt8[2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB])

# test 6: CreateString

b = FlatBuffers.Builder()
FlatBuffers.createstring(b, "foo")
check(UInt8[3, 0, 0, 0, 'f', 'o', 'o', 0]) # 0-terminated, no pad
FlatBuffers.createstring(b, "moop")
check(UInt8[4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, # 0-terminated, 3-byte pad
	3, 0, 0, 0, 'f', 'o', 'o', 0])

# test 6b: CreateString unicode

b = FlatBuffers.Builder()
# These characters are chinese from blog.golang.org/strings
# We use escape codes here so that editors without unicode support
# aren't bothered:
uni_str = "\u65e5\u672c\u8a9e"
FlatBuffers.createstring(b, uni_str)
check(UInt8[9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, #  null-terminated, 2-byte pad
	0, 0])

# test 6c: CreateUInt8String

b = FlatBuffers.Builder()
FlatBuffers.createstring(b, "foo")
check(UInt8[3, 0, 0, 0, 'f', 'o', 'o', 0]) # 0-terminated, no pad
FlatBuffers.createstring(b, "moop")
check(UInt8[4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, # 0-terminated, 3-byte pad
	3, 0, 0, 0, 'f', 'o', 'o', 0])

# test 7: empty vtable
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 0)
check(UInt8[])
FlatBuffers.endobject(b)
check(UInt8[4, 0, 4, 0, 4, 0, 0, 0])

# test 8: vtable with one true bool
b = FlatBuffers.Builder()
check(UInt8[])
FlatBuffers.startobject(b, 1)
check(UInt8[])
FlatBuffers.prependslot!(b, 1, true, false)
FlatBuffers.endobject(b)
check(UInt8[
	6, 0, # vtable bytes
	8, 0, # length of object including vtable offset
	7, 0, # start of bool value
	6, 0, 0, 0, # offset for start of vtable (int32)
	0, 0, 0, # padded to 4 bytes
	1, # bool value
	])

# test 9: vtable with one default bool
b = FlatBuffers.Builder()
check(UInt8[])
FlatBuffers.startobject(b, 1)
check(UInt8[])
FlatBuffers.prependslot!(b, 1, false, false)
FlatBuffers.endobject(b)
check(UInt8[
	6, 0, # vtable bytes
	4, 0, # end of object from here
	0, 0, # entry 1 is zero
	6, 0, 0, 0, # offset for start of vtable (int32)
	])

# test 10: vtable with one int16
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 1)
FlatBuffers.prependslot!(b, 1, Int16(0x789A), Int16(0))
FlatBuffers.endobject(b)
check(UInt8[
	6, 0, # vtable bytes
	8, 0, # end of object from here
	6, 0, # offset to value
	6, 0, 0, 0, # offset for start of vtable (int32)
	0, 0, # padding to 4 bytes
	0x9A, 0x78,
	])

# test 11: vtable with two int16
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 2)
FlatBuffers.prependslot!(b, 1, Int16(0x3456), Int16(0))
FlatBuffers.prependslot!(b, 2, Int16(0x789A), Int16(0))
FlatBuffers.endobject(b)
check(UInt8[
	8, 0, # vtable bytes
	8, 0, # end of object from here
	6, 0, # offset to value 0
	4, 0, # offset to value 1
	8, 0, 0, 0, # offset for start of vtable (int32)
	0x9A, 0x78, # value 1
	0x56, 0x34, # value 0
	])

# test 12: vtable with int16 and bool
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 2)
FlatBuffers.prependslot!(b, 1, Int16(0x3456), Int16(0))
FlatBuffers.prependslot!(b, 2, true, false)
FlatBuffers.endobject(b)
check(UInt8[
	8, 0, # vtable bytes
	8, 0, # end of object from here
	6, 0, # offset to value 0
	5, 0, # offset to value 1
	8, 0, 0, 0, # offset for start of vtable (int32)
	0,          # padding
	1,          # value 1
	0x56, 0x34, # value 0
	])

# test 12: vtable with empty vector
b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(UInt8), 0, 1)
vecend = FlatBuffers.endvector(b, 0)
FlatBuffers.startobject(b, 1)
FlatBuffers.prependoffsetslot!(b, 1, UInt32(vecend), UInt32(0))
FlatBuffers.endobject(b)
check(UInt8[
	6, 0, # vtable bytes
	8, 0,
	4, 0, # offset to vector offset
	6, 0, 0, 0, # offset for start of vtable (int32)
	4, 0, 0, 0,
	0, 0, 0, 0, # length of vector (not in struct)
	])

# test 12b: vtable with empty vector of byte and some scalars
b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(UInt8), 0, 1)
vecend = FlatBuffers.endvector(b, 0)
FlatBuffers.startobject(b, 2)
FlatBuffers.prependslot!(b, 1, Int16(55), Int16(0))
FlatBuffers.prependoffsetslot!(b, 2, UInt32(vecend), UInt32(0))
FlatBuffers.endobject(b)
check(UInt8[
	8, 0, # vtable bytes
	12, 0,
	10, 0, # offset to value 0
	4, 0, # offset to vector offset
	8, 0, 0, 0, # vtable loc
	8, 0, 0, 0, # value 1
	0, 0, 55, 0, # value 0

	0, 0, 0, 0, # length of vector (not in struct)
	])

# test 13: vtable with 1 int16 and 2-vector of int16
b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(Int16), 2, 1)
FlatBuffers.prepend!(b, Int16(0x1234))
FlatBuffers.prepend!(b, Int16(0x5678))
vecend = FlatBuffers.endvector(b, 2)
FlatBuffers.startobject(b, 2)
FlatBuffers.prependoffsetslot!(b, 2, UInt32(vecend), UInt32(0))
FlatBuffers.prependslot!(b, 1, Int16(55), Int16(0))
FlatBuffers.endobject(b)
check(UInt8[
	8, 0, # vtable bytes
	12, 0, # length of object
	6, 0, # start of value 0 from end of vtable
	8, 0, # start of value 1 from end of buffer
	8, 0, 0, 0, # offset for start of vtable (int32)
	0, 0, # padding
	55, 0, # value 0
	4, 0, 0, 0, # vector position from here
	2, 0, 0, 0, # length of vector (uint32)
	0x78, 0x56, # vector value 1
	0x34, 0x12, # vector value 0
	])

# test 14: vtable with 1 struct of 1 int8, 1 int16, 1 int32
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 1)
FlatBuffers.prep!(b, 4+4+4, 0)
FlatBuffers.prepend!(b, Int8(55))
FlatBuffers.pad!(b, 3)
FlatBuffers.prepend!(b, Int16(0x1234))
FlatBuffers.pad!(b, 2)
FlatBuffers.prepend!(b, Int32(0x12345678))
structStart = FlatBuffers.offset(b)
FlatBuffers.prependstructslot!(b, 1, structStart, 0)
FlatBuffers.endobject(b)
check(UInt8[
	6, 0, # vtable bytes
	16, 0, # end of object from here
	4, 0, # start of struct from here
	6, 0, 0, 0, # offset for start of vtable (int32)
	0x78, 0x56, 0x34, 0x12, # value 2
	0, 0, # padding
	0x34, 0x12, # value 1
	0, 0, 0, # padding
	55, # value 0
	])

# test 15: vtable with 1 vector of 2 struct of 2 int8
b = FlatBuffers.Builder()
FlatBuffers.startvector(b, sizeof(Int8)*2, 2, 1)
FlatBuffers.prepend!(b, Int8(33))
FlatBuffers.prepend!(b, Int8(44))
FlatBuffers.prepend!(b, Int8(55))
FlatBuffers.prepend!(b, Int8(66))
vecend = FlatBuffers.endvector(b, 2)
FlatBuffers.startobject(b, 1)
FlatBuffers.prependoffsetslot!(b, 1, UInt32(vecend), UInt32(0))
FlatBuffers.endobject(b)
check(UInt8[
	6, 0, # vtable bytes
	8, 0,
	4, 0, # offset of vector offset
	6, 0, 0, 0, # offset for start of vtable (int32)
	4, 0, 0, 0, # vector start offset

	2, 0, 0, 0, # vector length
	66, # vector value 1,1
	55, # vector value 1,0
	44, # vector value 0,1
	33, # vector value 0,0
	])

# test 16: table with some elements
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 2)
FlatBuffers.prependslot!(b, 1, Int8(33), Int8(0))
FlatBuffers.prependslot!(b, 2, Int16(66), Int16(0))
off = FlatBuffers.endobject(b)
FlatBuffers.finish!(b, off) #TODO

check(UInt8[
	12, 0, 0, 0, # root of table: points to vtable offset

	8, 0, # vtable bytes
	8, 0, # end of object from here
	7, 0, # start of value 0
	4, 0, # start of value 1

	8, 0, 0, 0, # offset for start of vtable (int32)

	66, 0, # value 1
	0,  # padding
	33, # value 0
	])

# test 17: one unfinished table and one finished table
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 2)
FlatBuffers.prependslot!(b, 1, Int8(33), Int8(0))
FlatBuffers.prependslot!(b, 2, Int8(44), Int8(0))
off = FlatBuffers.endobject(b)
FlatBuffers.finish!(b, off)

FlatBuffers.startobject(b, 3)
FlatBuffers.prependslot!(b, 1, Int8(55), Int8(0))
FlatBuffers.prependslot!(b, 2, Int8(66), Int8(0))
FlatBuffers.prependslot!(b, 3, Int8(77), Int8(0))
off = FlatBuffers.endobject(b)
FlatBuffers.finish!(b, off)

check(UInt8[
	16, 0, 0, 0, # root of table: points to object
	0, 0, # padding

	10, 0, # vtable bytes
	8, 0, # size of object
	7, 0, # start of value 0
	6, 0, # start of value 1
	5, 0, # start of value 2
	10, 0, 0, 0, # offset for start of vtable (int32)
	0,  # padding
	77, # value 2
	66, # value 1
	55, # value 0

	12, 0, 0, 0, # root of table: points to object

	8, 0, # vtable bytes
	8, 0, # size of object
	7, 0, # start of value 0
	6, 0, # start of value 1
	8, 0, 0, 0, # offset for start of vtable (int32)
	0, 0, # padding
	44, # value 1
	33, # value 0
	])

# test 18: a bunch of bools
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 8)
FlatBuffers.prependslot!(b, 1, true, false)
FlatBuffers.prependslot!(b, 2, true, false)
FlatBuffers.prependslot!(b, 3, true, false)
FlatBuffers.prependslot!(b, 4, true, false)
FlatBuffers.prependslot!(b, 5, true, false)
FlatBuffers.prependslot!(b, 6, true, false)
FlatBuffers.prependslot!(b, 7, true, false)
FlatBuffers.prependslot!(b, 8, true, false)
off = FlatBuffers.endobject(b)
FlatBuffers.finish!(b, off)

check(UInt8[
	24, 0, 0, 0, # root of table: points to vtable offset

	20, 0, # vtable bytes
	12, 0, # size of object
	11, 0, # start of value 0
	10, 0, # start of value 1
	9, 0, # start of value 2
	8, 0, # start of value 3
	7, 0, # start of value 4
	6, 0, # start of value 5
	5, 0, # start of value 6
	4, 0, # start of value 7
	20, 0, 0, 0, # vtable offset

	1, # value 7
	1, # value 6
	1, # value 5
	1, # value 4
	1, # value 3
	1, # value 2
	1, # value 1
	1, # value 0
	])

# test 19: three bools
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 3)
FlatBuffers.prependslot!(b, 1, true, false)
FlatBuffers.prependslot!(b, 2, true, false)
FlatBuffers.prependslot!(b, 3, true, false)
off = FlatBuffers.endobject(b)
FlatBuffers.finish!(b, off)

check(UInt8[
	16, 0, 0, 0, # root of table: points to vtable offset

	0, 0, # padding

	10, 0, # vtable bytes
	8, 0, # size of object
	7, 0, # start of value 0
	6, 0, # start of value 1
	5, 0, # start of value 2
	10, 0, 0, 0, # vtable offset from here

	0, # padding
	1, # value 2
	1, # value 1
	1, # value 0
	])

# test 20: some floats
b = FlatBuffers.Builder()
FlatBuffers.startobject(b, 1)
FlatBuffers.prependslot!(b, 1, Float32(1.0), Float32(0.0))
off = FlatBuffers.endobject(b)

check(UInt8[
	6, 0, # vtable bytes
	8, 0, # size of object
	4, 0, # start of value 0
	6, 0, 0, 0, # vtable offset

	0, 0, 128, 63, # value 0
	])
end

# CheckManualBuild builds a Monster manually.
function CheckManualBuild()
	b = FlatBuffers.Builder()
	str = FlatBuffers.createstring(b, "MyMonster")

	FlatBuffers.startvector(b, 1, 5, 1)
	FlatBuffers.prepend!(b, UInt8(4))
	FlatBuffers.prepend!(b, UInt8(3))
	FlatBuffers.prepend!(b, UInt8(2))
	FlatBuffers.prepend!(b, UInt8(1))
	FlatBuffers.prepend!(b, UInt8(0))
	inv = FlatBuffers.endvector(b, 5)

	FlatBuffers.startobject(b, 13)
	FlatBuffers.prependslot!(b, 2, Int16(20), Int16(100))
	mon2 = FlatBuffers.endobject(b)

	# Test4Vector
	FlatBuffers.startvector(b, 4, 2, 1)

	# Test 0
	FlatBuffers.prep!(b, 2, 4)
	FlatBuffers.pad!(b, 1)
	FlatBuffers.place!(b, Int8(20))
	FlatBuffers.place!(b, Int16(10))

	# Test 1
	FlatBuffers.prep!(b, 2, 4)
	FlatBuffers.pad!(b, 1)
	FlatBuffers.place!(b, Int8(40))
	FlatBuffers.place!(b, Int16(30))

	# end testvector
	test4 = FlatBuffers.endvector(b, 2)

	FlatBuffers.startobject(b, 13)

	# a vec3
	FlatBuffers.prep!(b, 16, 32)
	FlatBuffers.pad!(b, 2)
	FlatBuffers.prep!(b, 2, 4)
	FlatBuffers.pad!(b, 1)
	FlatBuffers.place!(b, UInt8(6))
	FlatBuffers.place!(b, Int16(5))
	FlatBuffers.pad!(b, 1)
	FlatBuffers.place!(b, UInt8(4))
	FlatBuffers.place!(b, Float64(3.0))
	FlatBuffers.pad!(b, 4)
	FlatBuffers.place!(b, Float32(3.0))
	FlatBuffers.place!(b, Float32(2.0))
	FlatBuffers.place!(b, Float32(1.0))
	vec3Loc = FlatBuffers.offset(b)
	# end vec3

	FlatBuffers.prependstructslot!(b, 1, vec3Loc, 0) # vec3. noop
	FlatBuffers.prependslot!(b, 3, Int16(80), Int16(100))     # hp
	FlatBuffers.prependoffsetslot!(b, 4, Int32(str), Int32(0))
	FlatBuffers.prependoffsetslot!(b, 6, Int32(inv), Int32(0)) # inventory
	FlatBuffers.prependslot!(b, 8, UInt8(1), UInt8(0))
	FlatBuffers.prependoffsetslot!(b, 9, Int32(mon2), Int32(0))
	FlatBuffers.prependoffsetslot!(b, 10, Int32(test4), Int32(0))
	mon = FlatBuffers.endobject(b)

	FlatBuffers.finish!(b, mon)

	return b.bytes, b.head
end

# CheckVtableDeduplication verifies that vtables are deduplicated.
function CheckVtableDeduplication()
	b = FlatBuffers.Builder()

	FlatBuffers.startobject(b, 4)
	FlatBuffers.prependslot!(b, 1, UInt8(0), UInt8(0))
	FlatBuffers.prependslot!(b, 2, UInt8(11), UInt8(0))
	FlatBuffers.prependslot!(b, 3, UInt8(22), UInt8(0))
	FlatBuffers.prependslot!(b, 4, Int16(33), Int16(0))
	obj0 = FlatBuffers.endobject(b)

	FlatBuffers.startobject(b, 4)
	FlatBuffers.prependslot!(b, 1, UInt8(0), UInt8(0))
	FlatBuffers.prependslot!(b, 2, UInt8(44), UInt8(0))
	FlatBuffers.prependslot!(b, 3, UInt8(55), UInt8(0))
	FlatBuffers.prependslot!(b, 4, Int16(66), Int16(0))
	obj1 = FlatBuffers.endobject(b)

	FlatBuffers.startobject(b, 4)
	FlatBuffers.prependslot!(b, 1, UInt8(0), UInt8(0))
	FlatBuffers.prependslot!(b, 2, UInt8(77), UInt8(0))
	FlatBuffers.prependslot!(b, 3, UInt8(88), UInt8(0))
	FlatBuffers.prependslot!(b, 4, Int16(99), Int16(0))
	obj2 = FlatBuffers.endobject(b)

	got = b.bytes[b.head+1:end]

	want = UInt8[
	240, 255, 255, 255, # == -12. offset to dedupped vtable.
	99, 0,
	88,
	77,
	248, 255, 255, 255, # == -8. offset to dedupped vtable.
	66, 0,
	55,
	44,
	12, 0, # start of vtable
	8, 0,
	0, 0,
	7, 0,
	6, 0,
	4, 0,
	12, 0, 0, 0, # table0
	33, 0,
	22,
	11
	]

	@test got == want

	table0 = FlatBuffers.Table{Any}(b.bytes, length(b.bytes) - obj0)
	table1 = FlatBuffers.Table{Any}(b.bytes, length(b.bytes) - obj1)
	table2 = FlatBuffers.Table{Any}(b.bytes, length(b.bytes) - obj2)

	function testTable(tab, a, b, c, d)
		# vtable size
		got = FlatBuffers.getoffsetslot(tab, 0, Int16(0))
		@test 12 == got
		# object size
		got = FlatBuffers.getoffsetslot(tab, 2, Int16(0))
		@test 8 == got
		# default value
		got = FlatBuffers.getoffsetslot(tab, 4, Int16(0))
		@test a == got
		got = FlatBuffers.getslot(tab, 6, UInt8(0))
		@test b == got
		val = FlatBuffers.getslot(tab, 8, UInt8(0))
		c != val && throw(ArgumentError("failed 8, 0: $got"))
		got = FlatBuffers.getslot(tab, 10, UInt8(0))
		@test d == got
		return
	end

	testTable(table0, UInt16(0), UInt8(11), UInt8(22), UInt8(33))
	testTable(table1, UInt16(0), UInt8(44), UInt8(55), UInt8(66))
	testTable(table2, UInt16(0), UInt8(77), UInt8(88), UInt8(99))
end

# CheckNotInObjectError verifies that `endobject` fails if not inside an
# object.
function CheckNotInObjectError()
	b = FlatBuffers.Builder()

	@test_throws ArgumentError FlatBuffers.endobject(b)
end

# CheckStringIsNestedError verifies that a string can not be created inside
# another object.
function CheckStringIsNestedError()
	b = FlatBuffers.Builder()
	FlatBuffers.startobject(b, 0)
	@test_throws ArgumentError FlatBuffers.createstring(b, "foo")
end

# CheckByteStringIsNestedError verifies that a bytestring can not be created
# inside another object.
function CheckByteStringIsNestedError()
	b = FlatBuffers.Builder()
	FlatBuffers.startobject(b, 0)
	@test_throws ArgumentError FlatBuffers.createstring(b, "foo")
end

# CheckStructIsNotInlineError verifies that writing a struct in a location
# away from where it is used will cause a panic.
function CheckStructIsNotInlineError()
	b = FlatBuffers.Builder()
	FlatBuffers.startobject(b, 0)
	@test_throws ArgumentError FlatBuffers.prependstructslot!(b, 0, 1, 0)
end

# CheckFinishedBytesError verifies that `FinishedBytes` panics if the table
# is not finished.
function CheckFinishedBytesError()
	b = FlatBuffers.Builder()

	@test_throws ArgumentError FlatBuffers.finishedbytes(b)
end

function CheckCreateByteVector()
	raw = UInt8(0):UInt8(29)

	for size = 1:30
		b1 = FlatBuffers.Builder()
		b2 = FlatBuffers.Builder()
		FlatBuffers.startvector(b1, 1, size, 1)
		for i = size:-1:1
			FlatBuffers.prepend!(b1, raw[i])
		end
		FlatBuffers.endvector(b1, size)
		FlatBuffers.createbytevector(b2, raw[1:size])
		@test b1.bytes == b2.bytes
	end
end

const InitialLCGSeed = 48271
mutable struct LCG
	val::UInt32
	LCG() = new(UInt32(InitialLCGSeed))
end
reset!(lcg::LCG) = lcg.val = UInt32(InitialLCGSeed)
function next(lcg::LCG)
	n = UInt32((UInt64(lcg.val) * UInt64(279470273)) % UInt64(4294967291))
	lcg.val = n
	return n
end

# Low level stress/fuzz test: serialize/deserialize a variety of
# different kinds of data in different combinations
function checkFuzz(fuzzFields, fuzzObjects, verbose=true)

	# Values we're testing against: chosen to ensure no bits get chopped
	# off anywhere, and also be different from eachother.
	boolVal = true
	int8Val = Int8(-127) # 0x81
	uint8Val = UInt8(0xFF)
	int16Val = Int16(-32222) # 0x8222
	uint16Val = UInt16(0xFEEE)
	int32Val = Int32(overflowingInt32Val)
	uint32Val = UInt32(0xFDDDDDDD)
	int64Val = Int64(overflowingInt64Val)
	uint64Val = UInt64(0xFCCCCCCCCCCCCCCC)
	float32Val = Float32(3.14159)
	float64Val = Float64(3.14159265359)

	testValuesMax = 11 # hardcoded to the number of scalar types

	b = FlatBuffers.Builder()
	l = LCG()

	objects = fill(0, fuzzObjects)

	# Generate fuzzObjects random objects each consisting of
	# fuzzFields fields, each of a random type.
	for i = 1:fuzzObjects
		FlatBuffers.startobject(b, fuzzFields)

		for f = 1:fuzzFields
			choice = next(l) % UInt32(testValuesMax)
			if choice ==  0
				FlatBuffers.prependslot!(b, f, boolVal, false)
			elseif choice ==  1
				FlatBuffers.prependslot!(b, f, int8Val, Int8(0))
			elseif choice ==  2
				FlatBuffers.prependslot!(b, f, uint8Val, UInt8(0))
			elseif choice ==  3
				FlatBuffers.prependslot!(b, f, int16Val, Int16(0))
			elseif choice ==  4
				FlatBuffers.prependslot!(b, f, uint16Val, UInt16(0))
			elseif choice ==  5
				FlatBuffers.prependslot!(b, f, int32Val, Int32(0))
			elseif choice ==  6
				FlatBuffers.prependslot!(b, f, uint32Val, UInt32(0))
			elseif choice ==  7
				FlatBuffers.prependslot!(b, f, int64Val, Int64(0))
			elseif choice ==  8
				FlatBuffers.prependslot!(b, f, uint64Val, UInt64(0))
			elseif choice ==  9
				FlatBuffers.prependslot!(b, f, float32Val, Float32(0))
			elseif choice ==  10
				FlatBuffers.prependslot!(b, f, float64Val, Float64(0))
			end
		end

		off = FlatBuffers.endobject(b)

		# store the offset from the end of the builder buffer,
		# since it will keep growing:
		objects[i] = off
	end

	# Do some bookkeeping to generate stats on fuzzes:
	stats = Dict{String,Int}()
	function check(desc, want, got)
		v = get!(stats, desc, 0)
		stats[desc] = v + 1
		@test want == got
	end

	l = LCG() # Reset.

	# Test that all objects we generated are readable and return the
	# expected values. We generate random objects in the same order
	# so this is deterministic.
	for i = 1:fuzzObjects

		table = FlatBuffers.Table{Any}(b.bytes, length(b.bytes) - objects[i])

		for j = 0:(fuzzFields - 1)
			f = (FlatBuffers.VtableMetadataFields + j) * sizeof(Int16)
			choice = next(l) % UInt32(testValuesMax)

			if choice == 0
				check("bool", boolVal, FlatBuffers.getslot(table, f, false))
			elseif choice == 1
				check("int8", int8Val, FlatBuffers.getslot(table, f, Int8(0)))
			elseif choice == 2
				check("uint8", uint8Val, FlatBuffers.getslot(table, f, UInt8(0)))
			elseif choice == 3
				check("int16", int16Val, FlatBuffers.getslot(table, f, Int16(0)))
			elseif choice == 4
				check("uint16", uint16Val, FlatBuffers.getslot(table, f, UInt16(0)))
			elseif choice == 5
				check("int32", int32Val, FlatBuffers.getslot(table, f, Int32(0)))
			elseif choice == 6
				check("uint32", uint32Val, FlatBuffers.getslot(table, f, UInt32(0)))
			elseif choice == 7
				check("int64", int64Val, FlatBuffers.getslot(table, f, Int64(0)))
			elseif choice == 8
				check("uint64", uint64Val, FlatBuffers.getslot(table, f, UInt64(0)))
			elseif choice == 9
				check("float32", float32Val, FlatBuffers.getslot(table, f, Float32(0)))
			elseif choice == 10
				check("float64", float64Val, FlatBuffers.getslot(table, f, Float64(0)))
			end
		end
	end

	# If enough checks were made, verify that all scalar types were used:
	if fuzzFields*fuzzObjects >= testValuesMax
		if length(stats) != testValuesMax
			throw(ArgumentError("fuzzing failed to test all scalar types"))
		end
	end

	# Print some counts, if needed:
	if verbose
		if fuzzFields == 0 || fuzzObjects == 0
			println("fuzz\tfields: $fuzzFields \tobjects: $fuzzObjects \t[none]\t 0")
		else
			ks = sort!(collect(keys(stats)))
			for k in ks
				println("fuzz\tfields: $fuzzFields \tobjects: $fuzzObjects \t$(k): $(stats[k])")
			end
		end
	end
	return
end


text:
# ---
# title: "`tophat`"
# id: op_tophat
# cover: assets/tophat.png
# ---

# The (white) tophat operator is defined as `img - opening(img)`. Intuitively, this filter
# can be used to extract small white elements and details from an image.

using ImageMorphology
using TestImages
using ImageBase
using ImageShow

#-

img = restrict(testimage_dip3e("fig1005")) # wirebond mask

out1 = tophat(img) # default: all spatial dimensions, r=1, a box-shape SE
out2 = tophat(img; dims=(2,)) # only apply to the second dimension
out3 = tophat(img; r=5) # half-size r=5
out4 = tophat(img, strel_diamond((5, 5))) # generic SE -- this version doesn't accept `r` and `dims`

mosaic(img, out1, out2, out3, out4; nrow=1)

# ## See also

# To extract black small details, use [`bothat`](@ref op_bothat).

bothat(img) == tophat(complement.(img))

# For a comprehensive and more accurate documentation, please check the [`tophat`](@ref)
# reference page.

# save cover image #src
using FileIO #src
mkpath("assets") #src
img = Gray.(restrict(testimage("blobs"))) #src
save("assets/tophat.png", tophat(img; r=2)) #src

ext: jl


text:
using CausalInference
using LightGraphs
using Test
using Random
using LinearAlgebra
using Statistics

function skeleton2(n::V, I, par...) where {V}
    g = CompleteGraph(n)
    S = Dict{edgetype(g),Vector{V}}()
    d = 0 # depth
    while true
        isdone = true
        for e in collect(edges(g)) # cannot remove edges while iterating
            n = copy(neighbors(g, src(e)))::Vector{V}
            append!(n, neighbors(g, dst(e)))
            sort!(n)
            if length(n) > d  # i.e. |n\{dst(e)}| >= d
                removesorted!(n, dst(e))
                removesorted!(n, src(e))

                isdone = false
                for s in combinations(n, d)

                    if I(src(e), dst(e), s, par...)
                        rem_edge!(g, e)
                        if !(e in keys(S))
                            S[e] = s
                        end
                        break
                    end
                end
            end
        end
        d = d + 1
        if isdone
            return g, S
        end
    end
end

qu(x) = x*x'

@testset "d10" begin
    d = 10 # 40 disconnected
    n = 10000
    alpha = 0.3
    Random.seed!(5)
    E = LowerTriangular([i > j ? 1*(rand() < alpha) : 0 for i in 1:d, j in 1:d])
    L = E .* rand(d,d)
    println("\nVertices: $d, Edges: ", sum(E))

    X = (I - L)\randn(d, n)
    Σ = cov(X, dims=2)
    Σtrue = inv(qu((I-L)'))

    @test norm(Σ -  Σtrue)  < .25*d*d/sqrt(n)
    di = sqrt.(diag(Σtrue));
    Ctrue = (Σtrue)./(di*di');
    C = cor(X, dims=2)

    gd = DiGraph(E)
    g = Graph(Symmetric(E+E'))

    @time h, s = skeleton(d, dseporacle, gd)
    @test g == h

    println("Using true correlation")
    @time h, s = skeleton(d, gausscitest, (Ctrue, n*n), 0.05)
    O = Matrix(adjacency_matrix(g))
    a = O +  2*Matrix(adjacency_matrix(h))
    println("num edges found ", div(sum(a .== 3),2), " of ", ne(g), ", false edges ", div(sum(a .== 2),2) )

    @test div(sum(a .== 3),2)/ne(g) >= 0.9
    @test  div(sum(a .== 2),2)/ne(g) <= 0.1

    println("Using data (n = $n)")
    @time h, s = skeleton(d, gausscitest, (C,n), 2.5)

    a = O +  2*Matrix(adjacency_matrix(h))
    println("num edges found ", div(sum(a .== 3),2), " of ", ne(g), ", false edges ", div(sum(a .== 2),2) )

    @test div(sum(a .== 3),2)/ne(g) >= 0.9
    @test div(sum(a .== 2),2)/ne(g) <= 0.1
end

@testset "d23" begin
    d = 23 # 40 disconnected
    n = 100000
    alpha = 0.2
    Random.seed!(5)
    E = LowerTriangular([i > j ? 1*(rand() < alpha) : 0 for i in 1:d, j in 1:d])
    L = E .* rand(d,d)
    println("\nVertices: $d, Edges: ", sum(E))

    X = (I - L)\randn(d, n)
    Σ = cov(X, dims=2)
    Σtrue = inv(qu((I-L)'))

    @test norm(Σ -  Σtrue)  < .2*d*d/sqrt(n)
    di = sqrt.(diag(Σtrue));
    Ctrue = (Σtrue)./(di*di');
    C = cor(X, dims=2)
    g = Graph(Symmetric(E+E'))
    gd = DiGraph(E)

    @time h, s = skeleton(d, dseporacle, gd)
    @test g == h

    println("Using true correlation")
    @time h, s = skeleton(d, gausscitest, (Ctrue, n*n), 0.05)
    O = Matrix(adjacency_matrix(g))
    a = O +  2*Matrix(adjacency_matrix(h))
    println("num edges found ", div(sum(a .== 3),2), " of ", ne(g), ", false edges ", div(sum(a .== 2),2) )

    @test div(sum(a .== 3),2)/ne(g) >= 0.9
    @test div(sum(a .== 2),2)/ne(g) <= 0.1

    println("Using data (n = $n)")
    @time h, s = skeleton(d, gausscitest, (C,n), 1.96)

    a = O +  2*Matrix(adjacency_matrix(h))
    println("num edges found ", div(sum(a .== 3),2), " of ", ne(g), ", false edges ", div(sum(a .== 2),2) )

    @test div(sum(a .== 3),2)/ne(g) >= 0.85
    @test div(sum(a .== 2),2)/ne(g) <= 0.15
end

@testset "d5" begin
     g = DiGraph(5)
    d = nv(g)
    for (i,j) in [(1,2), (2,3), (2,4),(4,5), (3,5)]
        add_edge!(g,i,j)
    end

    h, s = skeleton(d, dseporacle, g)
    @test Graph(g) == h
    h, s = skeleton(d, CausalInference.truetest)
    @test ne(h) == 0

end

@testset "truefalse" begin
    d = 15
    @time h, s = skeleton(d, CausalInference.falsetest)
    @test ne(h) == div(d*(d-1),2)
     d = 100
    @time h, s = skeleton(d, CausalInference.truetest)
    @test ne(h) == 0
end


text:
module MyExample

# Write your package code here.
include("extra.jl")

end

max_stars_repo_name: zhaotianjing/MyExample

max_issues_repo_name: zhaotianjing/MyExample

max_forks_repo_name: zhaotianjing/MyExample


text:
using TSx
using Documenter

DocMeta.setdocmeta!(TSx, :DocTestSetup, :(using TSx, DataFrames, Dates, Statistics); recursive=true)

makedocs(;
    modules=[TSx],
    authors="xKDR Forum",
    repo="https://github.com/xKDR/TSx.jl/blob/{commit}{path}#{line}",
    sitename="TSx.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://xKDR.github.io/TSx.jl",
        assets=String[],
    ),
    pages=[
        "Introduction" => "index.md",
        "Basic demo of TSx" => "demo_finance.md",
        "User guide" => "user_guide.md",
        "API reference" => "api.md",
    ],
    doctest=false,               # TODO: switch to true in the version after v0.1.0
    strict=false,                # TODO: switch to true in the version after v0.1.0
)

deploydocs(;
    repo="github.com/xKDR/TSx.jl",
    devbranch="main",
    target = "build",
)


text:
abstract type Branch <: Device end

include("./branches/lines.jl")
include("./branches/transformers.jl")
include("./branches/dc_lines.jl")
include("../utils/ybus_calculations.jl")
include("../utils/ptdf_calculations.jl")


text:
module DecompositionDB

using Mongoc
using Dates
using UUIDs
using Random
import Base.setindex!
using Combinatorics
using LightGraphs, MetaGraphs

include("../utils/graph.jl")
include("../utils/constructgraph.jl")
include("getqueries.jl")
include("setqueries.jl")
include("processing.jl")

end # module

max_stars_repo_name: charlyalizadeh/OPFdecgen

max_issues_repo_name: charlyalizadeh/OPFdecgen

max_forks_repo_name: charlyalizadeh/OPFdecgen


text:
function poset(adj, root)
#function [depth] = poset(adj, root)
#% POSET		Identify a partial ordering among the nodes of a graph
#%
#%  [DEPTH] = POSET(ADJ,ROOT)
#%
#% Inputs :
#%    ADJ : Adjacency Matrix
#%    ROOT : Node to start with
#%
#% Outputs :
#%    DEPTH : Depth of the Node
#%
#% Usage Example : [depth] = poset(adj,12);
#%
#%
#% Note     : All Nodes must be connected
#% See also #
#
#% Uses :
#
#% Change History :
#% Date		Time		Prog	Note
#% 17-Jun-1998	12:01 PM	ATC	Created under MATLAB 5.1.0.421

#% ATC = Ali Taylan Cemgil,
#% SNN - University of Nijmegen, Department of Medical Physics and Biophysics
#% e-mail : cemgil@mbfys.kun.nl

adj = adj+adj'

N = size(adj,1)
depth = zeros(N,1)
    depth[root] = 1
    queue=[]
    queue = vec(vcat(queue,root))

while true
  if isempty(queue)
    if all(depth.>0)
        break
    else
      root = find(depth.==0)
      root = root[1]
      depth[root] = 1
        queue=[]
        queue = vec(vcat(queue,root))
    end
  end
    r = queue[1]
    queue=vec(queue)
    shift!(queue)
  idx = find(adj[r,:])
  idx2 = find(depth[idx].==1);
  idx = idx[idx2]
  queue = vec(vcat(queue, idx))
  depth[idx] = depth[r]+1
end
    return depth
end


text:
using InlineStrings

export InlineString, InlineStringType
export String1, String3, String7, String15, String31, String63, String127, String255
export InlineString1, InlineString3, InlineString7, InlineString15, InlineString31, InlineString63, InlineString127, InlineString255


text:
using LinearAlgebra
using Test

using ProximalOperators
using ProximalAlgorithms

@testset "Lasso small (strongly convex, $T)" for T in [Float32, Float64]
    dim = 5
    μf = T(1)
    Lf = T(10)

    x_star = T[0.8466800540711814, 0.17674262101590932, -0.4987234606672925, 0.5531315167924573, -0.14739365562631113]

    lam = (μf + Lf) / 2

    w = T[0.15823052457732423, 0.6874613398393697, 0.9357764685973888, 0.05863707298785681, 0.49087050154723844]
    D = Diagonal(sqrt(μf) .+ (sqrt(Lf) - sqrt(μf)) * w)
    D[1] = sqrt(μf)
    D[end] = sqrt(Lf)

    B = T[
        0.6997086717991196 0.37124544422925876 0.31840520080247225 0.20097960566711592 0.038329117953706526;
        0.1134636504826555 0.8273912343075426 0.8997522727456534 0.9821118072706589 0.9100659142463259;
        0.9701886480567284 0.42825250593295605 0.6952640061565183 0.9699979632534245 0.6106722979088736;
        0.4442755181780246 0.4641748710746476 0.9716060376558348 0.5951146731055232 0.5699044913634803;
        0.6681510415197733 0.35423403325449887 0.28461925562068024 0.15941152427241456 0.6499046326711716
    ]
    Q = qr(B).Q
    A = Q * D * Q'
    b = A * x_star + lam * inv(A') * sign.(x_star)

    f = LeastSquares(A, b)
    h = NormL1(lam)

    TOL = T(1e-4)

    x0 = A \ b
    x0_backup = copy(x0)

    @testset "SFISTA" begin
        solver = ProximalAlgorithms.SFISTA(tol = TOL)
        y, it = solver(x0, f = f, h = h, Lf = Lf, μf = μf)
        @test eltype(y) == T
        @test norm(y - x_star) <= TOL
        @test it < 40
        @test x0 == x0_backup
    end

    @testset "ForwardBackward" begin
        solver = ProximalAlgorithms.ForwardBackward(tol = TOL)
        y, it = solver(x0, f = f, g = h, Lf = Lf)
        @test eltype(y) == T
        @test norm(y - x_star, Inf) <= TOL
        @test it < 110
        @test x0 == x0_backup
    end

    @testset "FastForwardBackward" begin
        solver = ProximalAlgorithms.FastForwardBackward(tol = TOL)
        y, it = solver(x0, f = f, g = h, Lf = Lf, mf = μf)
        @test eltype(y) == T
        @test norm(y - x_star, Inf) <= TOL
        @test it < 35
        @test x0 == x0_backup
    end

    @testset "FastForwardBackward (custom extrapolation)" begin
        solver = ProximalAlgorithms.FastForwardBackward(tol = TOL)
        y, it = solver(x0, f = f, g = h, gamma = 1/Lf, mf = μf, extrapolation_sequence=ProximalAlgorithms.ConstantNesterovSequence(μf, 1/Lf))
        @test eltype(y) == T
        @test norm(y - x_star, Inf) <= TOL
        @test it < 35
        @test x0 == x0_backup
    end

    @testset "DRLS" begin
        solver = ProximalAlgorithms.DRLS(tol = TOL)
        u, v, it = solver(x0, f = f, g = h, muf = μf)
        @test eltype(u) == T
        @test eltype(v) == T
        @test norm(v - x_star, Inf) <= TOL
        @test it < 14
        @test x0 == x0_backup
    end

    @testset "PANOC" begin
        solver = ProximalAlgorithms.PANOC(tol = TOL)
        y, it = solver(x0, f = f, g = h, Lf = Lf)
        @test eltype(y) == T
        @test norm(y - x_star, Inf) <= TOL
        @test it < 45
        @test x0 == x0_backup
    end

    @testset "PANOCplus" begin
        solver = ProximalAlgorithms.PANOCplus(tol = TOL)
        y, it = solver(x0, f = f, g = h, Lf = Lf)
        @test eltype(y) == T
        @test norm(y - x_star, Inf) <= TOL
        @test it < 45
        @test x0 == x0_backup
    end

end


text:
using CrystalNets, PeriodicGraphs, TextWrap, ArgParse, LinearAlgebra, SparseArrays,
      StaticArrays, Chemfiles, Logging, Tokenize

const __bodyfunction__ = Dict{Method,Any}()

# Find keyword "body functions" (the function that contains the body
# as written by the developer, called after all missing keyword-arguments
# have been assigned values), in a manner that doesn't depend on
# gensymmed names.
# `mnokw` is the method that gets called when you invoke it without
# supplying any keywords.
function __lookup_kwbody__(mnokw::Method)
    function getsym(arg)
        isa(arg, Symbol) && return arg
        @assert isa(arg, GlobalRef)
        return arg.name
    end

    f = get(__bodyfunction__, mnokw, nothing)
    if f === nothing
        fmod = mnokw.module
        # The lowered code for `mnokw` should look like
        #   %1 = mkw(kwvalues..., #self#, args...)
        #        return %1
        # where `mkw` is the name of the "active" keyword body-function.
        ast = Base.uncompressed_ast(mnokw)
        if isa(ast, Core.CodeInfo) && length(ast.code) >= 2
            callexpr = ast.code[end-1]
            if isa(callexpr, Expr) && callexpr.head == :call
                fsym = callexpr.args[1]
                if isa(fsym, Symbol)
                    f = getfield(fmod, fsym)
                elseif isa(fsym, GlobalRef)
                    if fsym.mod === Core && fsym.name === :_apply
                        f = getfield(mnokw.module, getsym(callexpr.args[2]))
                    elseif fsym.mod === Core && fsym.name === :_apply_iterate
                        f = getfield(mnokw.module, getsym(callexpr.args[3]))
                    else
                        f = getfield(fsym.mod, fsym.name)
                    end
                else
                    f = missing
                end
            else
                f = missing
            end
        else
            f = missing
        end
        __bodyfunction__[mnokw] = f
    end
    return f
end

function _precompile_()
    ccall(:jl_generating_output, Cint, ()) == 1 || return nothing

    # Tokenize
    Base.precompile(Tuple{typeof(Base._collect),UnitRange{Int},Tokenize.Lexers.Lexer{IOBuffer, Tokenize.Tokens.Token},Base.HasEltype,Base.SizeUnknown})

    # LightGraphs
    Base.precompile(Tuple{typeof(LightGraphs.floyd_warshall_shortest_paths),LightGraphs.SimpleGraph{Int},LightGraphs.DefaultDistance})
    Base.precompile(Tuple{Type{LightGraphs.SimpleGraph},Vector{LightGraphs.SimpleGraphs.SimpleEdge{Int}}})

    # PeriodicGraphs
    Base.precompile(Tuple{Type{Dict{PeriodicEdge3D, Nothing}}})
    Base.precompile(Tuple{Type{Dict{PeriodicVertex3D, Nothing}}})
    Base.precompile(Tuple{typeof(Base._unique!),typeof(identity),Vector{PeriodicEdge3D},Set{PeriodicEdge3D},Int,Int})
    Base.precompile(Tuple{typeof(Base.ht_keyindex),Dict{PeriodicVertex3D, Nothing},PeriodicVertex3D})
    Base.precompile(Tuple{typeof(copyto!),Vector{PeriodicEdge3D},PeriodicGraphs.PeriodicEdgeIter{3}})
    Base.precompile(Tuple{typeof(deleteat!),Vector{PeriodicVertex3D},BitVector})
    Base.precompile(Tuple{typeof(has_edge),PeriodicGraph3D,PeriodicEdge3D})
    Base.precompile(Tuple{typeof(offset_representatives!),PeriodicGraph3D,Vector{SVector{3,Int}}})
    Base.precompile(Tuple{typeof(searchsortedfirst),Vector{PeriodicVertex3D},PeriodicVertex3D,Int,Int,Base.Order.ForwardOrdering})
    Base.precompile(Tuple{typeof(setindex!),Dict{PeriodicEdge3D, Nothing},Nothing,PeriodicEdge3D})
    Base.precompile(Tuple{typeof(sort!),Vector{PeriodicEdge3D},Int,Int,Base.Sort.MergeSortAlg,Base.Order.ForwardOrdering,Vector{PeriodicEdge3D}})
    Base.precompile(Tuple{typeof(sort!),Vector{PeriodicVertex3D},Int,Int,Base.Sort.MergeSortAlg,Base.Order.ForwardOrdering,Vector{PeriodicVertex3D}})
    Base.precompile(Tuple{typeof(union!),Set{PeriodicVertex3D},Vector{PeriodicVertex3D}})
    Base.precompile(Tuple{typeof(Base.setindex!),Dict{PeriodicEdge3D, Nothing},Nothing,PeriodicEdge3D})
    Base.precompile(Tuple{typeof(Base.union!),Set{PeriodicVertex3D},Vector{PeriodicVertex3D}})

    # SparseArrays
    Base.precompile(Tuple{typeof(*),SparseArrays.SparseMatrixCSC{Int, Int},Matrix{Rational{BigInt}}})
    Base.precompile(Tuple{typeof(Base.copyto_unaliased!),IndexCartesian,SubArray{Int, 1, SparseArrays.SparseMatrixCSC{Int, Int}, Tuple{Int, Base.Slice{Base.OneTo{Int}}}, false},IndexLinear,Vector{Int}})
    Base.precompile(Tuple{typeof(Base.mightalias),SubArray{Int, 1, SparseArrays.SparseMatrixCSC{Int, Int}, Tuple{Int, Base.Slice{Base.OneTo{Int}}}, false},Vector{Int}})
    Base.precompile(Tuple{typeof(LinearAlgebra.mul!),Matrix{BigInt},SparseArrays.SparseMatrixCSC{Int, Int},Matrix{BigInt},Bool,Bool})
    Base.precompile(Tuple{typeof(SparseArrays.dimlub),Vector{Int}})
    Base.precompile(Tuple{typeof(SparseArrays.findnz),SparseArrays.SparseMatrixCSC{Int, Int}})
    Base.precompile(Tuple{typeof(SparseArrays.sparse_check_length),String,Vector{Int},Int,Type})
    Base.precompile(Tuple{typeof(SparseArrays.spzeros),Type{Int},Type{Int},Int,Int})
    Base.precompile(Tuple{typeof(getindex),SparseArrays.SparseMatrixCSC{Int, Int},UnitRange{Int},UnitRange{Int}})

    # Logging
    Base.precompile(Tuple{typeof(Base.CoreLogging.handle_message),Logging.ConsoleLogger,Any,Any,Any,Any,Any,Any,Any})
    Base.precompile(Tuple{typeof(Base.CoreLogging.shouldlog),Logging.ConsoleLogger,Base.CoreLogging.LogLevel,Module,Symbol,Symbol})
    Base.precompile(Tuple{typeof(Logging.default_metafmt),Base.CoreLogging.LogLevel,Any,Any,Any,Any,Any})
    Base.precompile(Tuple{typeof(Logging.termlength),SubString{String}})
    let fbody = try __lookup_kwbody__(which(Base.CoreLogging.handle_message, (Logging.ConsoleLogger,Any,Any,Any,Any,Any,Any,Any,))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Any,typeof(Base.CoreLogging.handle_message),Logging.ConsoleLogger,Any,Any,Any,Any,Any,Any,Any,))
        end
    end

    # TextWrap
    Base.precompile(Tuple{Core.kwftype(typeof(TextWrap.wrap)),NamedTuple{(:break_long_words, :break_on_hyphens), Tuple{Bool, Bool}},typeof(TextWrap.wrap),SubString{String}})
    Base.precompile(Tuple{Core.kwftype(typeof(TextWrap.wrap)),NamedTuple{(:break_long_words, :break_on_hyphens, :initial_indent, :subsequent_indent), Tuple{Bool, Bool, String, String}},typeof(TextWrap.wrap),String})

    # ArgParse
    Base.precompile(Tuple{Core.kwftype(typeof(ArgParse.Type)),Any,Type{ArgParse.ArgParseSettings}})
    Base.precompile(Tuple{Core.kwftype(typeof(ArgParse.add_arg_field!)),Any,typeof(ArgParse.add_arg_field!),ArgParse.ArgParseSettings,Vector{T} where T<:AbstractString})
    Base.precompile(Tuple{typeof(ArgParse.parse1_optarg!),ArgParse.ParserState,ArgParse.ArgParseSettings,ArgParse.ArgParseField,Any,AbstractString})
    Base.precompile(Tuple{typeof(ArgParse.preparse!),Channel,ArgParse.ParserState,ArgParse.ArgParseSettings})
    Base.precompile(Tuple{typeof(ArgParse.print_group),IO,Vector{T} where T,AbstractString,Int,Int,AbstractString,AbstractString,AbstractString})
    let fbody = try __lookup_kwbody__(which(ArgParse.show_help, (ArgParse.ArgParseSettings,))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Any,typeof(ArgParse.show_help),ArgParse.ArgParseSettings,))
        end
    end
    let fbody = try __lookup_kwbody__(which(any, (Function,Vector{ArgParse.ArgParseGroup},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Function,typeof(any),Function,Vector{ArgParse.ArgParseGroup},))
        end
    end

    # LinearAlgebra
    Base.precompile(Tuple{Type{Matrix{Float64}},LinearAlgebra.UniformScaling{Bool},Tuple{Int, Int}})
    Base.precompile(Tuple{typeof(LinearAlgebra.norm),Vector{Float64},Int})
    Base.precompile(Tuple{typeof(eltype),LinearAlgebra.Adjoint{Rational{Int}, Matrix{Rational{Int}}}})
    Base.precompile(Tuple{typeof(isone),Matrix{Int32}})
    Base.precompile(Tuple{typeof(hcat),Vector{Rational{Int}},LinearAlgebra.Adjoint{Rational{Int}, Matrix{Rational{Int}}}})
    let fbody = try __lookup_kwbody__(which(LinearAlgebra.rank, (Matrix{Int},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Float64,Float64,typeof(LinearAlgebra.rank),Matrix{Int},))
        end
    end

    # Base
    Base.precompile(Tuple{Core.kwftype(typeof(Base.with_output_color)),NamedTuple{(:bold,), Tuple{Bool}},typeof(Base.with_output_color),Function,Symbol,IOContext{Base.TTY},String,Vararg{Any, N} where N})
    Base.precompile(Tuple{Type{Base.IteratorSize},Base.Iterators.ProductIterator{Tuple{UnitRange{Int}, UnitRange{Int}}}})
    Base.precompile(Tuple{Type{Dict{Symbol, Any}},Base.Iterators.Pairs{Symbol, Any, Tuple{Symbol, Symbol, Symbol}, NamedTuple{(:help, :metavar, :required), Tuple{String, String, Bool}}}})
    Base.precompile(Tuple{Type{Dict{Symbol, Any}},Base.Iterators.Pairs{Symbol, Any, Tuple{Symbol, Symbol}, NamedTuple{(:help, :action), Tuple{String, Symbol}}}})
    Base.precompile(Tuple{Type{Dict{Symbol, Any}},Base.Iterators.Pairs{Symbol, String, Tuple{Symbol, Symbol}, NamedTuple{(:help, :metavar), Tuple{String, String}}}})
    Base.precompile(Tuple{Type{Tuple{Tuple{Vector{Tuple{Int, Int}}, Vector{Tuple{Int, Int}}}, Tuple{Vector{Tuple{Int, Int}}, Vector{Tuple{Int, Int}}}, Tuple{Vector{Tuple{Int, Int}}, Vector{Tuple{Int, Int}}}}},Vector{Tuple{Vector{Any}, Vector{Any}}}})
    for T in (Int8, Int16, Int32, Int64, Int128)
       Base.precompile(Tuple{Type{SubArray},IndexLinear,Matrix{Rational{T}},Tuple{Base.Slice{Base.OneTo{Int}}, Int},Tuple{Bool}})
       Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{2}, Nothing, Type{Rational{T}}, Tuple{Matrix{Rational{Int}}}}})
    end
    Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{2}, Nothing, typeof(big), Tuple{Matrix{Rational{Int}}}}})
    Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{2}, Nothing, typeof(denominator), Tuple{Matrix{Rational{Int}}}}})
    Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{2}, Nothing, typeof(numerator), Tuple{Matrix{Rational{Int}}}}})
    Base.precompile(Tuple{typeof(Base.deepcopy_internal),NTuple{9, BigFloat},IdDict{Any, Any}})
    Base.precompile(Tuple{typeof(Base.display_error),Base.TTY,ErrorException,Vector{Union{Ptr{Nothing}, Base.InterpreterIP}}})
    Base.precompile(Tuple{typeof(Base.grow_to!),Dict{Symbol, Any},Tuple{Pair{Symbol, String}, Pair{Symbol, Bool}, Pair{Symbol, String}},Int})
    Base.precompile(Tuple{typeof(Base.grow_to!),Dict{Symbol, Any},Tuple{Pair{Symbol, String}, Pair{Symbol, Symbol}},Int})
    Base.precompile(Tuple{typeof(Base.print_to_string),Int128,Vararg{Any, N} where N})
    Base.precompile(Tuple{typeof(Base.reducedim_init),Function,typeof(min),Matrix{Float64},Int})
    Base.precompile(Tuple{typeof(Base.setindex_widen_up_to),Vector{Int},Expr,Int})
    Base.precompile(Tuple{typeof(Base.setindex_widen_up_to),Vector{Tuple{Any}},Tuple{},Int})
    Base.precompile(Tuple{typeof(Base.setindex_widen_up_to),Vector{Tuple{Int}},Tuple{},Int})
    Base.precompile(Tuple{typeof(Base.setindex_widen_up_to),Vector{Tuple{}},Tuple{Int},Int})
    Base.precompile(Tuple{typeof(Base.typed_hvcat),Type{BigFloat},Tuple{Int, Int, Int},BigFloat,Vararg{Number, N} where N})
    Base.precompile(Tuple{typeof(Base.typed_hvcat),Type{Float64},Tuple{Int, Int, Int},Int,Vararg{Number, N} where N})
    Base.precompile(Tuple{typeof(copy),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{2}, Tuple{Base.OneTo{Int}, Base.OneTo{Int}}, Type{Int}, Tuple{Matrix{Rational{BigInt}}}}})
    Base.precompile(Tuple{typeof(maximum),Matrix{Int}})
    Base.precompile(Tuple{typeof(minimum),Matrix{Int}})
    Base.precompile(Tuple{typeof(push!),Vector{String},String,String,String})
    Base.precompile(Tuple{typeof(setindex!),Dict{String, Tuple{Exception, Vector{Union{Ptr{Nothing}, Base.InterpreterIP}}}},Tuple{ArgumentError, Vector{Union{Ptr{Nothing}, Base.InterpreterIP}}},String})
    Base.precompile(Tuple{typeof(string),Int128,String,Vararg{Any, N} where N})
    Base.precompile(Tuple{typeof(vcat),Vector{Expr},Vector{Expr}})
    @static if VERSION >= v"1.6-"
        let fbody = try __lookup_kwbody__(which(Base.print_within_stacktrace, (IOContext{Base.TTY},String,Vararg{Any, N} where N,))) catch missing end
            if !ismissing(fbody)
                precompile(fbody, (Symbol,Bool,typeof(Base.print_within_stacktrace),IOContext{Base.TTY},String,Vararg{Any, N} where N,))
            end
        end
    end
    let fbody = try __lookup_kwbody__(which(all, (Function,Vector{String},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Function,typeof(all),Function,Vector{String},))
        end
    end
    let fbody = try __lookup_kwbody__(which(any, (Function,Vector{AbstractString},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Function,typeof(any),Function,Vector{AbstractString},))
        end
    end
    let fbody = try __lookup_kwbody__(which(sort!, (Vector{Int},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sort!),Vector{Int},))
        end
    end
    let fbody = try __lookup_kwbody__(which(sortperm, (Vector{Symbol},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{Symbol},))
        end
    end
    let fbody = try __lookup_kwbody__(which(sortperm, (Vector{Tuple{Int, Vector{Int}}},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{Tuple{Int, Vector{Int}}},))
        end
    end
    let fbody = try __lookup_kwbody__(which(sortperm, (Vector{Vector{Int}},))) catch missing end
        if !ismissing(fbody)
            precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{Vector{Int}},))
        end
    end

    # StaticArrays
    Base.precompile(Tuple{Type{Vector{SVector{3, Float64}}},Vector{SubArray{Float64, 1, Matrix{Float64}, Tuple{Base.Slice{Base.OneTo{Int}}, Int}, true}}})
    Base.precompile(Tuple{Type{Vector{SVector{3, Int}}},Vector{Any}})
    Base.precompile(Tuple{Type{Base.Broadcast.BroadcastStyle},Base.Broadcast.DefaultArrayStyle{0},StaticArrays.StaticArrayStyle{2}})
    Base.precompile(Tuple{Type{Base.Broadcast.BroadcastStyle},Base.Broadcast.DefaultArrayStyle{1},StaticArrays.StaticArrayStyle{1}})
    Base.precompile(Tuple{Type{Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Axes, F, Args} where Args<:Tuple where F where Axes},typeof(+),Tuple{SVector{3, Int}, SVector{3, Int}}})
    Base.precompile(Tuple{Type{Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Axes, F, Args} where Args<:Tuple where F where Axes},typeof(-),Tuple{SVector{3, Rational{Int}}, SVector{3, Int}}})
    Base.precompile(Tuple{Type{Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Axes, F, Args} where Args<:Tuple where F where Axes},typeof(floor),Tuple{Base.RefValue{Type{Int}}, SVector{3, Rational{Int}}}})
    Base.precompile(Tuple{Type{Dict{Int, SVector{3, Int}}}})
    Base.precompile(Tuple{Type{Dict{SVector{3, Int}, Nothing}}})
    Base.precompile(Tuple{Type{SMatrix{3, 3, BigFloat, 9}},NTuple{9, Float64}})
    Base.precompile(Tuple{typeof(==),Vector{Tuple{Int, Int, SVector{3, Rational{Int}}}},Vector{Tuple{Int, Int, SVector{3, Rational{Int}}}}})
    Base.precompile(Tuple{typeof(>),SVector{3, Int},SizedVector{3, Int, 1}})
    Base.precompile(Tuple{typeof(>),SizedVector{3, Int, 1},SVector{3, Int}})
    Base.precompile(Tuple{typeof(Base.Broadcast.broadcasted),Function,SVector{3, Rational{Int}},SVector{3, Int}})
    Base.precompile(Tuple{typeof(StaticArrays.arithmetic_closure),Type{BigFloat}})
    Base.precompile(Tuple{typeof(LinearAlgebra.generic_norm2),SubArray{BigFloat, 1, SMatrix{3, 3, BigFloat, 9}, Tuple{Base.Slice{SOneTo{3}}, Int}, true}})
    Base.precompile(Tuple{typeof(StaticArrays._axes),Size{(3, 3)}})
    Base.precompile(Tuple{typeof(StaticArrays._axes),Size{(3,)}})

    Base.precompile(Tuple{Type{Size},Type{SubArray{Int, 1, Matrix{Int}, Tuple{Int, Base.Slice{Base.OneTo{Int}}}, true}}})
    Base.precompile(Tuple{typeof(<),SVector{3, Int},SizedVector{3, Int, 1}})
    for T in (Int8, Int16, Int32, Int64, Int128)
        Base.precompile(Tuple{Type{Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}},Vector{Any}})
        Base.precompile(Tuple{Type{SVector{3, Int}},Tuple{Rational{T}, Rational{T}, Rational{T}}})
        Base.precompile(Tuple{Type{Dict{Int, Vector{SMatrix{3, 3, Rational{T}, 9}}}}})
        Base.precompile(Tuple{Type{Dict{SVector{9, Rational{T}}, Nothing}}})
        Base.precompile(Tuple{Type{Base.Broadcast.Broadcasted{Base.Broadcast.Style{Tuple}, Axes, F, Args} where Args<:Tuple where F where Axes},typeof(isempty),Tuple{Tuple{Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}, Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}, Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}}}})
        Base.precompile(Tuple{typeof(<),SVector{3, Rational{T}},SVector{3, Rational{Int}}})
        Base.precompile(Tuple{typeof(<),SVector{3, Rational{Int}},SVector{3, Rational{T}}})
        Base.precompile(Tuple{typeof(==),SVector{3, Rational{Int}},SVector{3, Rational{T}}})
        Base.precompile(Tuple{typeof(==),SMatrix{3, 3, T, 9},LinearAlgebra.UniformScaling{Bool}})
        Base.precompile(Tuple{typeof(LinearAlgebra.generic_matmatmul!),Matrix{Rational{widen(T)}},Char,Char,SizedMatrix{3, 3, Rational{widen(T)}, 2},Matrix{Rational{T}},LinearAlgebra.MulAddMul{true, true, Bool, Bool}})
        Base.precompile(Tuple{typeof(LinearAlgebra.dot),SubArray{BigFloat, 1, SMatrix{3, 3, BigFloat, 9}, Tuple{Base.Slice{SOneTo{3}}, T}, true},SubArray{BigFloat, 1, SMatrix{3, 3, BigFloat, 9}, Tuple{Base.Slice{SOneTo{3}}, T}, true}})
        Base.precompile(Tuple{typeof(Base.Broadcast.broadcasted),Base.Broadcast.Style{Tuple},Function,Tuple{Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}, Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}, Vector{Tuple{Int, Int, SVector{3, Rational{T}}}}}})
        Base.precompile(Tuple{typeof(Base.Broadcast.materialize!),Base.Broadcast.DefaultArrayStyle{1},SubArray{Rational{CrystalNets.soft_widen(T)}, 1, Matrix{Rational{CrystalNets.soft_widen(T)}}, Tuple{Base.Slice{Base.OneTo{Int}}, Int}, true},Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(-), Tuple{Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(+), Tuple{SVector{3, Rational{T}}, SVector{3, Int}}}, SVector{3, Rational{T}}}}})
        Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(-), Tuple{SVector{3, Rational{T}}, SVector{3, Int}}}})
        Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(floor), Tuple{Base.RefValue{Type{Int}}, SVector{3, Rational{T}}}}})
        Base.precompile(Tuple{typeof(allunique),Vector{SVector{3, Rational{T}}}})
        Base.precompile(Tuple{typeof(append!),Vector{SMatrix{3, 3, Rational{T}, 9}},Vector{SMatrix{3, 3, Rational{T}, 9}}})
        Base.precompile(Tuple{typeof(append!),Vector{SMatrix{3, 3, Rational{T}, 9}},Vector{SMatrix{3, 3, Rational{widen(T)}, 9}}})
        let fbody = try __lookup_kwbody__(which(sortperm, (Vector{SVector{3, Rational{T}}},))) catch missing end
            if !ismissing(fbody)
                precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{SVector{3, Rational{T}}},))
            end
        end
        let fbody = try __lookup_kwbody__(which(sortperm, (Vector{SVector{3, Rational{Int128}}},))) catch missing end
            if !ismissing(fbody)
                precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{SVector{3, Rational{T}}},))
            end
        end
        Base.precompile(Tuple{typeof(sort!),Vector{Int},Base.Sort.QuickSortAlg,Base.Order.Perm{Base.Order.ForwardOrdering, Vector{SVector{3, Rational{T}}}}})
     end
     Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(//), Tuple{Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(round), Tuple{Base.RefValue{Type{Int128}}, Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(*), Tuple{Int128, SVector{3, Float64}}}}}, Int128}}})
     Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(//), Tuple{Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(round), Tuple{Base.RefValue{Type{BigInt}}, Base.Broadcast.Broadcasted{StaticArrays.StaticArrayStyle{1}, Nothing, typeof(*), Tuple{BigInt, SVector{3, Float64}}}}}, BigInt}}})
     Base.precompile(Tuple{typeof(Base._foldl_impl),Base.BottomRF{typeof(hcat)},Base.ReshapedArray{Int, 2, SVector{3, Int}, Tuple{}},Set{SVector{3, Int}}})
     Base.precompile(Tuple{typeof(Base.setindex_widen_up_to),Vector{Tuple{StaticArrays.Dynamic}},Tuple{Int},Int})
     Base.precompile(Tuple{typeof(StaticArrays._axes),Size{(9,)}})
     Base.precompile(Tuple{typeof(setindex!),Dict{Int, SVector{3, Int}},SVector{3, Int},Int})
     Base.precompile(Tuple{typeof(setindex!),Dict{SVector{3, Int}, Nothing},Nothing,SVector{3, Int}})
     Base.precompile(Tuple{typeof(which(StaticArrays._getindex,(AbstractArray,Tuple{Vararg{Size, N} where N},Any,)).generator.gen),Any,Any,Any,Any})
     Base.precompile(Tuple{typeof(which(StaticArrays._map,(Any,Vararg{AbstractArray, N} where N,)).generator.gen),Any,Any,Any})
     Base.precompile(Tuple{typeof(which(StaticArrays.combine_sizes,(Tuple{Vararg{Size, N} where N},)).generator.gen),Any,Any})
     let fbody = try __lookup_kwbody__(which(LinearAlgebra.rank, (Base.ReshapedArray{Int, 2, SVector{3, Int}, Tuple{}},))) catch missing end
         if !ismissing(fbody)
             precompile(fbody, (Float64,Float64,typeof(LinearAlgebra.rank),Base.ReshapedArray{Int, 2, SVector{3, Int}, Tuple{}},))
         end
     end
     let fbody = try __lookup_kwbody__(which(sortperm, (Vector{SVector{3, Float64}},))) catch missing end
         if !ismissing(fbody)
             precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{SVector{3, Float64}},))
         end
     end
     let fbody = try __lookup_kwbody__(which(sortperm, (Vector{SVector{3, Rational{BigInt}}},))) catch missing end
         if !ismissing(fbody)
             precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{SVector{3, Rational{BigInt}}},))
         end
     end
     let fbody = try __lookup_kwbody__(which(sortperm, (Vector{SVector{3, Rational{Bool}}},))) catch missing end
         if !ismissing(fbody)
             precompile(fbody, (Base.Sort.QuickSortAlg,Function,Function,Nothing,Base.Order.ForwardOrdering,typeof(sortperm),Vector{SVector{3, Rational{Bool}}},))
         end
     end
     let fbody = try __lookup_kwbody__(which(sprint, (Function,SVector{3, Int},Vararg{Any, N} where N,))) catch missing end
         if !ismissing(fbody)
             precompile(fbody, (Nothing,Int,typeof(sprint),Function,SVector{3, Int},Vararg{Any, N} where N,))
         end
     end
     Base.precompile(Tuple{typeof(sort!),Vector{Int},Base.Sort.QuickSortAlg,Base.Order.Perm{Base.Order.ForwardOrdering, Vector{SVector{3, Float64}}}})

    # Chemfiles
    Base.precompile(Tuple{Type{Chemfiles.Atom},Chemfiles.Frame,Int})
    Base.precompile(Tuple{Type{Chemfiles.Atom},String})
    Base.precompile(Tuple{Type{Chemfiles.Frame}})
    Base.precompile(Tuple{Type{Chemfiles.Topology},Chemfiles.Frame})
    Base.precompile(Tuple{Type{Chemfiles.UnitCell},BigFloat,BigFloat,BigFloat,BigFloat,BigFloat,BigFloat})
    Base.precompile(Tuple{Type{Chemfiles.UnitCell},Chemfiles.Frame})
    Base.precompile(Tuple{typeof(Chemfiles.__free),Chemfiles.CxxPointer{Chemfiles.lib.CHFL_ATOM}})
    Base.precompile(Tuple{typeof(Chemfiles.__free),Chemfiles.CxxPointer{Chemfiles.lib.CHFL_CELL}})
    Base.precompile(Tuple{typeof(Chemfiles.__free),Chemfiles.CxxPointer{Chemfiles.lib.CHFL_TOPOLOGY}})
    Base.precompile(Tuple{typeof(Chemfiles.__strip_null),String})
    Base.precompile(Tuple{typeof(Chemfiles.add_atom!),Chemfiles.Frame,Chemfiles.Atom,Vector{Float64},Vector{Float64}})
    Base.precompile(Tuple{typeof(Chemfiles.bonds),Chemfiles.Topology})
    Base.precompile(Tuple{typeof(Chemfiles.matrix),Chemfiles.UnitCell})
    Base.precompile(Tuple{typeof(Chemfiles.positions),Chemfiles.Frame})
    Base.precompile(Tuple{typeof(Chemfiles.set_type!),Chemfiles.Atom,String})

    # CrystalNets
    Base.precompile(Tuple{Core.kwftype(typeof(CrystalNets.reckognize_topologies)),NamedTuple{(:ignore_atoms,), Tuple{Tuple{Symbol}}},typeof(CrystalNets.reckognize_topologies),String})
    # Base.precompile(Tuple{CrystalNets.var"#730#threadsfor_fun#121"{Tuple{Symbol}, String, Dict{String, String}, Dict{String, Tuple{Exception, Vector{Union{Ptr{Nothing}, Base.InterpreterIP}}}}, Dict{String, String}, Vector{String}}})
    for T in (Bool, Int8, Int16, Int32, Int64, Int128, BigInt)
       # Base.precompile(Tuple{CrystalNets.var"#670#threadsfor_fun#114"{CrystalNet{Rational{T}}, Vector{Int}, Base.Threads.SpinLock, Vector{Pair{Int, Tuple{Matrix{Rational{CrystalNets.soft_widen(T)}}, Vector{Int}}}}, Int, DataType, Vector{Int}}})
       # Base.precompile(Tuple{CrystalNets.var"#685#threadsfor_fun#116"{Rational{T}, Dict{Int, Vector{SMatrix{3, 3, Rational{CrystalNets.soft_widen(T)}, 9}}}, Base.Threads.SpinLock, DataType, Vector{Pair{Int, Tuple{Matrix{Rational{CrystalNets.soft_widen(T)}}, Vector{Int}}}}}})

       Base.precompile(Tuple{Type{CrystalNet{Rational{T}}},CrystalNets.Cell,Vector{Symbol},PeriodicGraph3D,Matrix{Rational{T}}})
       Base.precompile(Tuple{typeof(CrystalNets.isrank3),Matrix{Rational{T}}})
       Base.precompile(Tuple{typeof(CrystalNets.minimize),CrystalNet{Rational{T}}})
       Base.precompile(Tuple{typeof(CrystalNets.topological_key),CrystalNet{Rational{T}}})
       Base.precompile(Tuple{typeof(topological_genome),CrystalNet{Rational{T}}})

    end
    Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(CrystalNets.parsestrip), Tuple{Vector{String}}}})
    Base.precompile(Tuple{typeof(CrystalNets.invalid_input_error),String,ErrorException,Vector{Union{Ptr{Nothing}, Base.InterpreterIP}}})
    Base.precompile(Tuple{typeof(CrystalNets.julia_main)})
    Base.precompile(Tuple{typeof(SparseArrays.sparse),Vector{Int},Vector{Int},Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}},Int,Int,Function})
    Base.precompile(Tuple{typeof(SparseArrays.sparse),Vector{Int},Vector{Int},Vector{CrystalNets.Modulos.Modulo{2147483629, Int32}},Int,Int,Function})
    Base.precompile(Tuple{typeof(CrystalNets.parse_chemfile),String})
    Base.precompile(Tuple{typeof(CrystalNets.parse_chemfile),String,Bool})
    Base.precompile(Tuple{Core.kwftype(typeof(CrystalNets.parse_chemfile)),NamedTuple{(:ignore_atoms,), Tuple{Tuple{Symbol}}},typeof(CrystalNets.reckognize_topologies),String})
    Base.precompile(Tuple{Core.kwftype(typeof(CrystalNets.parse_chemfile)),NamedTuple{(:ignore_atoms,), Tuple{Tuple{Symbol}}},typeof(CrystalNets.reckognize_topologies),String,Bool})
    Base.precompile(Tuple{Type{Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Axes, F, Args} where Args<:Tuple where F where Axes},typeof(CrystalNets.parsestrip),Tuple{Vector{String}}})
    Base.precompile(Tuple{typeof(-),CrystalNets.Modulos.Modulo{2147483647, Int32},CrystalNets.Modulos.Modulo{2147483647, Int32}})
    Base.precompile(Tuple{typeof(/),Int,CrystalNets.Modulos.Modulo{2147483647, Int32}})
    Base.precompile(Tuple{typeof(==),Matrix{CrystalNets.Modulos.Modulo{2147483647, Int32}},Matrix{Int}})
    Base.precompile(Tuple{typeof(Base.Broadcast.materialize),Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(CrystalNets.parsestrip), Tuple{Vector{String}}}})
    Base.precompile(Tuple{typeof(Base._unsafe_copyto!),Matrix{CrystalNets.Modulos.Modulo{2147483647, Int32}},Int,Matrix{Int},Int,Int})
    Base.precompile(Tuple{typeof(Base._unsafe_getindex),IndexLinear,Matrix{CrystalNets.Modulos.Modulo{2147483647, Int32}},Int,Base.Slice{Base.OneTo{Int}}})
    Base.precompile(Tuple{typeof(Base.copyto_unaliased!),IndexLinear,SubArray{CrystalNets.Modulos.Modulo{2147483647, Int32}, 1, Matrix{CrystalNets.Modulos.Modulo{2147483647, Int32}}, Tuple{Int, Base.Slice{Base.OneTo{Int}}}, true},IndexLinear,Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}}})
    Base.precompile(Tuple{typeof(Base.deepcopy_internal),Vector{CrystalNets.EquivalentPosition},IdDict{Any, Any}})
    Base.precompile(Tuple{typeof(CrystalNets.isrank3),Matrix{Rational{Int32}}})
    Base.precompile(Tuple{typeof(LinearAlgebra.mul!),Matrix{CrystalNets.Modulos.Modulo{2147483647, Int32}},SparseArrays.SparseMatrixCSC{Int, Int},Matrix{CrystalNets.Modulos.Modulo{2147483647, Int32}},Bool,Bool})
    Base.precompile(Tuple{typeof(SparseArrays._setindex_scalar!),SparseArrays.SparseMatrixCSC{CrystalNets.Modulos.Modulo{2147483647, Int32}, Int},Int,Int,Int})
    Base.precompile(Tuple{typeof(SparseArrays.sparse!),Vector{Int},Vector{Int},Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}},Int,Int,typeof(+),Vector{Int},Vector{Int},Vector{Int},Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}},Vector{Int},Vector{Int},Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}}})
    Base.precompile(Tuple{typeof(SparseArrays.sparse),Vector{Int},Vector{Int},Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}},Int,Int,Function})
    Base.precompile(Tuple{typeof(SparseArrays.sparse_check_length),String,Vector{CrystalNets.Modulos.Modulo{2147483647, Int32}},Int,Type})
    Base.precompile(Tuple{typeof(getindex),SparseArrays.SparseMatrixCSC{CrystalNets.Modulos.Modulo{2147483647, Int32}, Int},UnitRange{Int},UnitRange{Int}})
    Base.precompile(Tuple{typeof(parse_chemfile),String})
    Base.precompile(Tuple{typeof(reckognize_topology),PeriodicGraph3D})
    for T in (Nothing, CrystalNets.Clusters)
        Base.precompile(Tuple{typeof(CrystalNets.ifexport), CrystalNets.Crystal{T}})
        Base.precompile(Tuple{typeof(CrystalNets.ifexport), CrystalNets.Crystal{T}, Nothing})
        Base.precompile(Tuple{typeof(CrystalNets.ifexport), CrystalNets.Crystal{T}, String})
        Base.precompile(Tuple{typeof(CrystalNets.ifexport), CrystalNets.Crystal{T}, Nothing, String})
        Base.precompile(Tuple{typeof(CrystalNets.ifexport), CrystalNets.Crystal{T}, String, String})
    end
end

_precompile_()


text:
function fastparse(str::ASCIIString)
    dy = 0
    for i = 1:4
        c = str[i]
        dy = 10*dy + (c - '0')
    end

    dm = 0
    for i = 6:7
        c = str[i]
        dm = 10*dm + (c - '0')
    end

    dd = 0
    for i = 9:10
        c = str[i]
        dd = 10*dd + (c - '0')
    end

    th = 0
    for i = 12:13
        c = str[i]
        th = 10*th + (c - '0')
    end

    tm = 0
    for i = 15:16
        c = str[i]
        tm = 10*tm + (c - '0')
    end

    ts = 0
    for i = 18:19
        c = str[i]
        ts = 10*ts + (c - '0')
    end

    tms = 0
    for i = 21:23
        if i <= length(str)
            c = str[i]
        else
            c = '0'
        end
        tms = 10*tms + (c - '0')
    end
    DateTime(dy,dm,dd,th,tm,ts,tms)
end

function fastparse{S<:AbstractString}(ads::Vector{S})
    l = length(ads)
    a = Array(DateTime, l)
    for i in 1:l
        a[i] = fastparse(ads[i])
    end
    a
end


text:
module DataStructures

    using Compat

    import Base: <, <=, length, isempty, start, next, done,
                 show, dump, empty!, getindex, setindex!, get, get!,
                 in, haskey, keys, merge, copy, cat,
                 push!, pop!, shift!, unshift!, insert!,
                 union!, delete!, similar, sizehint,
                 isequal, hash,
                 map, reverse,
                 first, last, eltype, getkey, values,
                 merge!, lt, Ordering, ForwardOrdering, Forward,
                 ReverseOrdering, Reverse, Lt,
                 isless,
                 union, intersect, symdiff, setdiff, issubset,
                 find, searchsortedfirst, searchsortedlast, endof

    export Deque, Stack, Queue
    export deque, enqueue!, dequeue!, update!
    export capacity, num_blocks, front, back, top, sizehint

    export Accumulator, counter
    export ClassifiedCollections
    export classified_lists, classified_sets, classified_counters

    export IntDisjointSets, DisjointSets, num_groups, find_root, in_same_set
    export push!

    export AbstractHeap, compare, extract_all!
    export BinaryHeap, binary_minheap, binary_maxheap, nlargest, nsmallest
    export MutableBinaryHeap, mutable_binary_minheap, mutable_binary_maxheap

    export OrderedDict, OrderedSet
    export DefaultDict, DefaultOrderedDict
    export Trie, subtrie, keys_with_prefix, path

    export LinkedList, Nil, Cons, nil, cons, head, tail, list, filter, cat,
           reverse
    export SortedDict, SortedMultiDict, SortedSet
    export SDToken, SDSemiToken, SMDToken, SMDSemiToken
    export SetToken, SetSemiToken
    export startof
    export pastendsemitoken, beforestartsemitoken
    export searchsortedafter, searchequalrange
    export packcopy, packdeepcopy
    export exclusive, inclusive, semitokens
    export orderobject, Lt, compare

    if VERSION < v"0.4.0-dev"
        using Docile
    end

    include("delegate.jl")

    include("deque.jl")
    include("stack.jl")
    include("queue.jl")
    include("accumulator.jl")
    include("classifiedcollections.jl")
    include("disjoint_set.jl")
    include("heaps.jl")

    include("hashdict.jl")
    include("ordereddict.jl")
    include("orderedset.jl")
    include("defaultdict.jl")
    include("trie.jl")

    include("list.jl")
    include("balancedTree.jl")
    include("tokens.jl")

    import .Tokens: IntSemiToken

    include("sortedDict.jl")
    include("sortedMultiDict.jl")
    include("sortedSet.jl")
    include("tokens2.jl")
    include("containerloops.jl")

    export status
    export deref_key, deref_value, deref, advance, regress

    @deprecate stack Stack
    @deprecate queue Queue
    @deprecate add! push!

    @deprecate HashDict{K,V}(ks::AbstractArray{K}, vs::AbstractArray{V}) HashDict{K,V,Unordered}(ks,vs)
    @deprecate HashDict(ks, vs) HashDict{Any,Any,Unordered}(ks, vs)

    @deprecate OrderedDict(ks, vs) OrderedDict(zip(ks,vs))
    @deprecate OrderedDict{K,V}(ks::AbstractArray{K}, vs::AbstractArray{V}) OrderedDict{K,V}(zip(ks,vs))
    @deprecate OrderedDict{K,V}(::Type{K},::Type{V}) OrderedDict{K,V}()

    @deprecate OrderedSet(a, b...) OrderedSet(Any[a, b...])
    @deprecate OrderedSet{T<:Number}(xs::T...)  OrderedSet{T}(xs)      # (almost) mimic Set deprecation in Base
end


text:
using Random, LinearAlgebra, Zygote
using Stheno: ColVecs, BlockData

@timedtestset "abstract_data_set" begin
    rng, N, D = MersenneTwister(123456), 10, 2
    x, X = randn(rng, N), randn(rng, D, N)

    # Test Matrix data sets.
    @timedtestset "ColVecs" begin
        DX = ColVecs(X)
        @test DX == DX
        @test size(DX) == (N,)
        @test length(DX) == N
        @test getindex(DX, 5) isa Vector
        @test getindex(DX, 5) == X[:, 5]
        @test getindex(DX, 1:2:6) isa ColVecs
        @test getindex(DX, 1:2:6) == ColVecs(X[:, 1:2:6])
        @test view(DX, 4) isa AbstractVector
        @test view(DX, 4) == view(X, :, 4)
        @test view(DX, 1:2:4) isa ColVecs
        @test view(DX, 1:2:4) == ColVecs(view(X, :, 1:2:4))
        @test eltype(DX) == Vector{Float64}
        @test eachindex(DX) == 1:N

        let
            @test Zygote.forward(ColVecs, X)[1] == DX
            DX, back = Zygote.forward(ColVecs, X)
            @test back((X=ones(size(X)),))[1] == ones(size(X))

            @test Zygote.forward(DX->DX.X, DX)[1] == X
            X_, back = Zygote.forward(DX->DX.X, DX)
            @test back(ones(size(X)))[1].X == ones(size(X))
        end
    end

    # Test BlockDataSet.
    @timedtestset "BlockData" begin
        DX = ColVecs(X)
        DxX = BlockData([x, DX])
        @test size(DxX) == (2N,)
        @test length(DxX) == 2N
        @test DxX == DxX
        @test DxX == BlockData([x, DX])
        @test length([x for x in DxX]) == 2N
        @test getindex(DxX, 1) === x[1]
        @test getindex(DxX, 2) === x[2]
        @test getindex(DxX, N) === x[N]
        @test getindex(DxX, N + 1) == DX[1]
        @test view(DxX, 2, 1) == view(DX, 1)
        @test view(DxX, 2, N) == view(DX, N)
        @test eachindex(DxX) isa BlockVector
        @test eachindex(DxX) == _BlockArray([1:N, N+1:2N], [N, N])

        # Test iteration.
        @test [x for x in DxX][1] == x[1]
        @test [x for x in DxX][N] == x[end]
        @test [x for x in DxX][N + 1] == DX[1]
        @test [x for x in DxX][end] == DX[end]

        # Test that identically typed arrays yield the appropriate element type.
        @test eltype(BlockData([randn(5), randn(4)])) == Float64
        @test eltype(DxX) == Any
        @test eltype(BlockData([DX, DX])) == Vector{Float64}
        @test eltype(BlockData([eachindex(DX), eachindex(DX)])) == Int
    end
end


text:
"""
`calibForce(POSES, F, m0=0.3; offset=true)`
If result is bad, check if you send data in correct form;
`POSES` ∈ ℜ(4,4,N) is always the position of the tool frame from the robot FK,
4x4 transformation matrices
`F` ∈ ℜ(N,3) vector of forces (accepts ℜ(Nx6) matrix with torques also)
usage `Rf*force[i,1:3] + forceoffs = POSES[1:3,1:3,i]'*[0, 0, mf*-9.82]`. This implementation assumes that the gravity vector is [0,0,-g], or in words, that the gravity is acting along the negative z axis.

[Bagge Carlson, F.](https://www.control.lth.se/staff/fredrik-bagge-carlson/), ["Machine Learning and System Identification for Estimation in Physical Systems"](https://lup.lub.lu.se/search/publication/ffb8dc85-ce12-4f75-8f2b-0881e492f6c0) (PhD Thesis 2018).
"""
function calibForce(POSES,F,m0::Real=0.3; kwargs...)
    g0 = [0,0,-m0*9.82]
    calibForce(POSES,F,g0; kwargs...)
end
function calibForce(POSES,F,g::AbstractVector; offset=true, verbose=true)

    N = size(POSES,3)

    local forceoffs
    I = Robotlib.I3
    A  = Array{eltype(F)}(undef, 3N, offset ? 12 : 9)
    B  = Array{eltype(F)}(undef, 3N)
    A2 = Array{eltype(F)}(undef, 3N, offset ? 4 : 1)
    B2 = Array{eltype(F)}(undef, 3N)
    At = offset ? (F,i) -> [F[i,1]*I   F[i,2]*I    F[i,3]*I   -I] : (F,i) -> [F[i,1]*I   F[i,2]*I    F[i,3]*I]

    for i = 1:N
        RA               = POSES[1:3,1:3,i]'
        b                = RA*g
        A[3(i-1)+1:3i,:] = At(F,i)
        B[3(i-1)+1:3i]   = b
    end
    verbose && @info("Condition number of Gram matrix: ", cond(A'A))
    w  = tls(A,B)
    Rf = reshape(w[1:9],3,3)
    verbose && @info("Determinant of Rf before orthonormalization: ", det(Rf), opnorm(Rf))
    if det(Rf) < 0
        verbose && @warn("det(Rf) < 0, left handed coordinate system? Trying to solve the problem with reversed gravity (-g)")
        return calibForce(POSES,F,-g; offset=offset, verbose=verbose)
    end
    toOrthoNormal!(Rf)
    At = offset ? RA -> [RA*g/norm(g) -I] : RA -> RA*g/norm(g)

    for i = 1:N
        RA                = POSES[1:3,1:3,i]'
        b                 = Rf*F[i,1:3]
        A2[3(i-1)+1:3i,:] = At(RA)
        B2[3(i-1)+1:3i]   = b
    end
    w         = A2\B2
    m         = w[1]/9.82
    offset && (forceoffs = w[2:4])

    m < 0 && @error("Estimated mass is negative, left handed coordinate system for sensor?")
    if offset
        return Rf,m,forceoffs
    else
        return Rf, m
    end
end

import Robotlib: skew

"""
    This function uses Cayley transform to solve for R. It requires a known mass so it is recommended to use `calibForce` instead.
"""
function calibForce2(POSES,F,m)
    N  = size(POSES,3)
    g  = -9.82
    mg = m*g

    I  = Robotlib.I3
    A  = Array{eltype(F)}(undef, 3N, 3)
    B  = Array{eltype(F)}(undef, 3N)

    for i = 1:N
        RA               = POSES[3,1:3,i]
        A[3(i-1)+1:3i,:] = skew(F[i,1:3][:] + RA*mg)
        B[3(i-1)+1:3i]   = RA*mg - F[i,1:3]
    end
    @info("Condition number of Gram matrix: ", cond(A'A))
    w  = tls(A,B)
    S  = skew(w)
    Rf = (I+S)\(I-S)
end


text:
# Pressurized cylinder with no supports
module pressurized_cylinder_free_examples

using LinearAlgebra
using FinEtools
using FinEtoolsDeforLinear
using FinEtoolsFlexStructures.FESetShellT3Module: FESetShellT3
using FinEtoolsFlexStructures.FEMMShellT3FFModule
using FinEtoolsFlexStructures.RotUtilModule: initial_Rfield, update_rotation_field!
using VisualStructures: plot_nodes, plot_midline, render, plot_space_box, plot_midsurface, space_aspectratio, save_to_json
using FinEtools.MeshExportModule.VTKWrite: vtkwrite

function cylindrical!(csmatout::FFltMat, XYZ::FFltMat, tangents::FFltMat, fe_label::FInt)
    n = cross(tangents[:, 1], tangents[:, 2])
    n = n/norm(n)
    # r = vec(XYZ); r[2] = 0.0
    csmatout[:, 3] .= n
    csmatout[:, 2] .= (0.0, 1.0, 0.0)
    cross3!(view(csmatout, :, 1), view(csmatout, :, 2), view(csmatout, :, 3))
    return csmatout
end

function _execute_dsg_model(formul, n = 8, visualize = true)
    # analytical solution for the vertical deflection and the midpoint of the
    # free edge
    analyt_sol=-0.3024;
    # Parameters:
    E=4.32e8;
    nu=0.0;
    thickness = 0.25; # geometrical dimensions are in feet
    pressure = 100.0;
    R = 25.0;
    L = 50.0;

    tolerance = R/n/1000
    fens, fes = T3block(90/360*2*pi,L/2,n,n);
    fens.xyz = xyz3(fens)
    for i in 1:count(fens)
        a=fens.xyz[i, 1]; y=fens.xyz[i, 2];
        fens.xyz[i, :] .= (R*sin(a), y, R*cos(a))
    end

    mater = MatDeforElastIso(DeforModelRed3D, E, nu)

    sfes = FESetShellT3()
    accepttodelegate(fes, sfes)
    femm = formul.make(IntegDomain(fes, TriRule(1), thickness), mater)
    stiffness = formul.stiffness
    associategeometry! = formul.associategeometry!

    # Construct the requisite fields, geometry and displacement
    # Initialize configuration variables
    geom0 = NodalField(fens.xyz)
    u0 = NodalField(zeros(size(fens.xyz,1), 3))
    Rfield0 = initial_Rfield(fens)
    dchi = NodalField(zeros(size(fens.xyz,1), 6))

    # Apply EBC's
    # plane of symmetry perpendicular to Z
    l1 = selectnode(fens; box = Float64[-Inf Inf -Inf Inf 0 0], inflate = tolerance)
    for i in [3,4,5]
        setebc!(dchi, l1, true, i)
    end
    # plane of symmetry perpendicular to Y
    l1 = selectnode(fens; box = Float64[-Inf Inf 0 0 -Inf Inf], inflate = tolerance)
    for i in [2,4,6]
        setebc!(dchi, l1, true, i)
    end
    # plane of symmetry perpendicular to X
    l1 = selectnode(fens; box = Float64[0 0 -Inf Inf -Inf Inf], inflate = tolerance)
    for i in [1,5,6]
        setebc!(dchi, l1, true, i)
    end
    applyebc!(dchi)
    numberdofs!(dchi);

    # Assemble the system matrix
    associategeometry!(femm, geom0)
    K = stiffness(femm, geom0, u0, Rfield0, dchi);

    # Midpoint of the free edge
    # nl = selectnode(fens; box = Float64[R R L/2 L/2 -Inf Inf], inflate = tolerance)
    lfemm = FEMMBase(IntegDomain(fes, TriRule(3)))
    function computeforce!(forceout::FFltVec, XYZ::FFltMat, tangents::FFltMat, fe_label::FInt)
        n = cross(tangents[:, 1], tangents[:, 2])
        n = n/norm(n)
        # r = vec(XYZ); r[2] = 0.0
        # r .= vec(r)/norm(vec(r))
        forceout[1:3] = n*pressure
        forceout[4:6] .= 0.0
        # @show dot(n, forceout[1:3])
        return forceout
    end
    fi = ForceIntensity(FFlt, 6, computeforce!);
    F = distribloads(lfemm, geom0, dchi, fi, 2);

    # Solve
    U = K\F
    scattersysvec!(dchi, U[:])
    # resultpercent =   dchi.values[nl, 3][1]/analyt_sol*100
    # @info "Solution: $(round(resultpercent, digits = 4))%"

    # Generate a graphical display of resultants
    ocsys = CSys(3, 3, cylindrical!)
    scalars = []
    for nc in 1:3
        fld = fieldfromintegpoints(femm, geom0, dchi, :moment, nc, outputcsys = ocsys)
            # fld = elemfieldfromintegpoints(femm, geom0, dchi, :moment, nc)
        push!(scalars, ("m$nc", fld.values))
    end
    vtkwrite("pressurized_cylinder_free-m.vtu", fens, fes; scalars = scalars, vectors = [("u", dchi.values[:, 1:3])])
    scalars = []
    for nc in 1:3
        fld = fieldfromintegpoints(femm, geom0, dchi, :membrane, nc, outputcsys = ocsys)
            # fld = elemfieldfromintegpoints(femm, geom0, dchi, :moment, nc)
        push!(scalars, ("n$nc", fld.values))
    end
    vtkwrite("pressurized_cylinder_free-n.vtu", fens, fes; scalars = scalars, vectors = [("u", dchi.values[:, 1:3])])
    scalars = []
    for nc in 1:2
        fld = fieldfromintegpoints(femm, geom0, dchi, :shear, nc, outputcsys = ocsys)
            # fld = elemfieldfromintegpoints(femm, geom0, dchi, :moment, nc)
        push!(scalars, ("q$nc", fld.values))
    end
    vtkwrite("pressurized_cylinder_free-q.vtu", fens, fes; scalars = scalars, vectors = [("u", dchi.values[:, 1:3])])

    # Visualization
    if visualize
        scattersysvec!(dchi, (L/8)/maximum(abs.(U)).*U)
        update_rotation_field!(Rfield0, dchi)
        plots = cat(plot_space_box([[0 0 -L/2]; [L/2 L/2 L/2]]),
            #plot_nodes(fens),
            plot_midsurface(fens, fes; x = geom0.values, facecolor = "rgb(12, 12, 123)"),
            plot_midsurface(fens, fes; x = geom0.values, u = dchi.values[:, 1:3], R = Rfield0.values);
            dims = 1)
        pl = render(plots)
    end

    return true
end

function test_convergence(formul = FEMMShellT3FFModule)
    @info "Pressurized Cylindrical shell, formulation=$(formul)"
    for n in [100, ]
        _execute_dsg_model(formul, n, false)
    end
    return true
end

function allrun()
    println("#####################################################")
    println("# test_convergence ")
    test_convergence()
    return true
end # function allrun

@info "All examples may be executed with "
println("using .$(@__MODULE__); $(@__MODULE__).allrun()")

end # module
nothing


text:
# This is the baseline distribution (i.e. a guassian process or iid uniform)
abstract type TimeseriesDistribution end

## Time series that are independent and identically distributed
struct IID{D} <: TimeseriesDistribution where {D}
    x::Array{Float64} # Sample locations
    distribution::D # Sampling distributions
end

# Number of points in the time series
N_pts(t::TimeseriesDistribution) = length(t.x)

# logpdf is just the summation over the individual values
Distributions.logpdf(iid::IID{D}, y) where {D} = sum([logpdf(iid.distribution, yi) for yi in y])

# Uniform distribution
function Base.rand(rng::AbstractRNG, iid::IID{Uniform{Float64}}, lb::Array{Float64} = -Inf*ones(N_pts(iid)), ub::Array{Float64} = Inf*ones(N_pts(iid)))
    samples = Array{Float64}(undef, length(iid.x))
    l, u = max.(lb, iid.distribution.a),  min.(ub, iid.distribution.b)
    for i=1:length(iid.x)
        samples[i] = l[i] == u[i] ? l[i] : rand(rng, Uniform(l[i], u[i]))
    end
    samples
end

# Gaussian Distribution
function Base.rand(rng::AbstractRNG, iid::IID{Normal{Float64}}, lb::Array{Float64} = -Inf*ones(N_pts(iid)), ub::Array{Float64} = Inf*ones(N_pts(iid)))
    samples = Array{Float64}(undef, length(iid.x))
    for i=1:length(iid.x)
        samples[i] = lb[i] == ub[i] ? lb[i] : rand(rng, Truncated(iid.distribution, lb[i], ub[i]))
    end
    samples
end

# Categorical
function Base.rand(rng::AbstractRNG, iid::IID{Categorical{Float64, Array{Float64,1}}}, feasible::Array{Array{Int64,1},1} = fill(collect(1:length(iid.distribution.p)), N_pts(iid)))
    samples = Array{Int64}(undef, length(iid.x))
    for i=1:length(iid.x)
        probs = zeros(length(iid.distribution.p))
        probs[feasible[i]] = iid.distribution.p[feasible[i]]
        d = Categorical(probs ./ sum(probs))
        samples[i] = rand(rng, d)
    end
    samples
end

# Bernoulli
function Base.rand(rng::AbstractRNG, iid::IID{Bernoulli{Float64}}, feasible::Array{Array{Int64,1},1} = fill([0,1], N_pts(iid)))
    samples = Array{Bool}(undef, length(iid.x))
    for i=1:length(iid.x)
        if length(feasible[i]) == 1
            samples[i] = Bool(feasible[i][1])
        else
            samples[i] = rand(rng, iid.distribution)
        end
    end
    samples
end

## Time series distributed according to a Gaussian Processs
squared_exp_kernel(;l=2, σ2 = 1) = (x,xp) -> σ2*exp(-(x-xp)^2/(2*l^2))

# Construct the mean vector
μ(X::Array{Float64}, m) = [m(x) for x in X]

# Construct the covariance matrix
K(X::Array{Float64}, X′::Array{Float64}, k) = [k(x,x′) for x in X, x′ in X′]

# Struct defining a Guassian Process
@with_kw struct GaussianProcess <: TimeseriesDistribution
    m::Function # Mean function (x_i) -> μ_i
    k::Function # Kernel function (x_i, x_j) -> k_ij
    x::Array{Float64} # Sample locations
    σ2::Float64 = 1e-6 # std deviation of noise on the samples
end

# Generate a random sample from the gaussian process
function Base.rand(rng::AbstractRNG, gp::GaussianProcess, lb::Array{Float64} = -Inf*ones(N_pts(gp)), ub::Array{Float64} = Inf*ones(N_pts(gp)))
    Xν, Xs, X, y = gp.x, gp.x, Float64[], Float64[]

    # Convert equality constraints to known points
    eq = lb .≈ ub
    l, u = copy(lb), copy(ub)
    X, y = Float64[X..., Xν[eq]...], Float64[y..., l[eq]...]
    l[eq] .= -Inf
    u[eq] .= Inf

    # Setup gram matrices
    N, Ns, Nν = length(X), length(Xs), length(Xν)
    Kxx = K(X, X, gp.k)
    Kxxν = K(X, Xν, gp.k)
    Kxxs = K(X, Xs, gp.k)
    Kxνxν = K(Xν, Xν, gp.k)
    Kxsxν = K(Xs, Xν, gp.k)
    Kxsxs = K(Xs, Xs, gp.k)
    Ixx = Matrix{Float64}(I, N, N)
    Ixsxs = Matrix{Float64}(I, Ns, Ns)
    Ixνxν = Matrix{Float64}(I, Nν, Nν)

    # Compute cholesky factors and important matrices
    L = cholesky(Kxx + gp.σ2*Ixx).L
    v1 = L \ Kxxν
    v2 = L \ Kxxs
    A1 = (L' \ v1)'
    A2 = (L' \ v2)'
    B1 = Kxνxν + gp.σ2*Ixνxν - v1' * v1
    B2 = Kxsxs + gp.σ2*Ixsxs - v2' * v2
    B3 = Kxsxν - v2' * v1

    L1 = cholesky(B1).L
    v3 = L1 \ B3'
    A = (L1' \ v3)'
    B = A2 - A * A1
    Σ = B2 - v3' * v3

    # Get mean vectors
    μo = μ(X, gp.m)
    μs = μ(Xs, gp.m)
    μν = μ(Xν, gp.m)

    # Sample from the posterior
    Q = cholesky(Σ).L
    Cm = mvrandn_μ(rng, μν + A1*(y - μo), l, u, B1, 1)
    Um = rand(rng, Normal(), (Ns, 1))

    dropdims(μs + B*(y .- μo) .+ (A*(-μν .+ Cm) + Q*Um), dims=2)
end

# Get the log probability of the sample point
function Distributions.logpdf(gp::GaussianProcess, y::Array{Float64})
    μ_vals = μ(gp.x, gp.m)
    Σ = K(gp.x, gp.x, gp.k) .+ gp.σ2*Matrix(I, N_pts(gp), N_pts(gp))
    logpdf(MvNormal(μ_vals, Σ), y)
end


text:
function brainfuck(file_name, memsize = 30000)

    # Read program and filter symbols
    symbols = ['>' '<' '+' '-' '.' ',' '[' ']']
    code = filter(x -> in(x, symbols), open(readall, file_name))

    # Memory of the program
    memory = zeros(Char, memsize)
    # Stack for loops
    stack = Array(Int, 0)
    ptr = 1                 # Memory pointer
    instr = 1               # Instruction pointer

    # Run the program
    while instr <= length(code)
        @match code[instr] begin
            '>' => ptr += 1
            '<' => ptr -= 1
            '+' => memory[ptr] += 1
            '-' => memory[ptr] -= 1
            '.' => print(memory[ptr])
            ',' => memory[ptr] = read(STDIN, Char)
            '[' => if memory[ptr] == zero(Char)
                       instr = findnext(code, ']', instr)
                   else
                       push!(stack, instr)
                   end
            ']' => instr = pop!(stack) - 1
        end
        instr += 1
    end
end


text:
using Jive
push!(stack, 10)
@__END__
push!(stack, 20)