text:
using Base.Meta

abstract SyscallProperty
immutable FDArgument <: SyscallProperty
  which::UInt8
end
immutable BufferArgument <: SyscallProperty
  whichData::UInt8
  whichLength::UInt8
end
immutable CstringArgument <: SyscallProperty
  which::UInt8
end
immutable SigmaskPtrArgument <: SyscallProperty
  which::UInt8
end
if !isdefined(:CustomTransform)
immutable CustomTransform{T}
  which::UInt8
  F::T
end
end
(::Type{CustomTransform}){T}(which::Integer, F::T) = CustomTransform{T}(UInt8(which), F)

immutable Constant
  name::Symbol
  value::Int
end

macro constants(array, stripprefix, expr)
    ret = Expr(:block)
    # Initialize the name lookup array
    push!(ret.args,:(const $array = Vector{Constant}()))
    for e in expr.args
        if !isexpr(e,:const)
            continue
        end
        eq = e.args[1]
        @assert isexpr(eq,:(=))
        name = string(eq.args[1])
        name = replace(name,stripprefix,"",1)
        push!(ret.args,e)
        push!(ret.args,:(push!($array, Constant($(quot(Symbol(name))), $(eq.args[1])))))
    end
    return esc(ret)
end

function bitfield(val, constants)
    join(map(x->String(x.name), filter(x->(x.value&val)!=0, constants)), "|")
end

# Some constants - others we'll pull right from the headers
@constants RWX_OK "" begin
    const R_OK = 4
    const W_OK = 2
    const X_OK = 1
end
const F_OK = 0

const syscalls = [
#  name , x86, x64, nargs
  (:exit, 1, 60, -1, Any[]),
  (:fork, 2, 57, -1, Any[]),
  (:read, 3, 0, 3, Any[]),
  (:write, 4, 1, 3, Any[FDArgument(1), BufferArgument(2, 3)]),
  (:open, 5, 2, 3, Any[]),
  (:close, 6, 3, 1, Any[FDArgument(1)]),
  (:waitpid, 7, -1, -1, Any[]),
  (:creat, 8, 85, -1, Any[]),
  (:link, 9, 86, -1, Any[]),
  (:unlink, 10, 87, -1, Any[]),
  (:execve, 11, 59, 3, Any[]),
  (:chdir, 12, 80, -1, Any[]),
  (:time, 13, 201, -1, Any[]),
  (:mknod, 14, 133, -1, Any[]),
  (:chmod, 15, 90, -1, Any[]),
  (:lchown, 16, 94, -1, Any[]),
  (:_break, 17, -1, -1, Any[]),
  (:oldstat, 18, -1, -1, Any[]),
  (:lseek, 19, 8, -1, Any[]),
  (:getpid, 20, 39, -1, Any[]),
  (:mount, 21, 165, -1, Any[]),
  (:umount, 22, -1, -1, Any[]),
  (:setuid, 23, 105, -1, Any[]),
  (:getuid, 24, 102, -1, Any[]),
  (:stime, 25, -1, -1, Any[]),
  (:ptrace, 26, 101, -1, Any[]),
  (:alarm, 27, 37, -1, Any[]),
  (:oldfstat, 28, -1, -1, Any[]),
  (:pause, 29, 34, -1, Any[]),
  (:utime, 30, 132, -1, Any[]),
  (:stty, 31, -1, -1, Any[]),
  (:gtty, 32, -1, -1, Any[]),
  (:access, 33, 21, 2, Any[
    CstringArgument(1),
    CustomTransform(2,arg->arg == F_OK ? "F_OK" : bitfield(arg, RWX_OK))
  ]),
  (:nice, 34, -1, -1, Any[]),
  (:ftime, 35, -1, -1, Any[]),
  (:sync, 36, 162, -1, Any[]),
  (:kill, 37, 62, -1, Any[]),
  (:rename, 38, 82, -1, Any[]),
  (:mkdir, 39, 83, -1, Any[]),
  (:rmdir, 40, 84, -1, Any[]),
  (:dup, 41, 32, -1, Any[]),
  (:pipe, 42, 22, -1, Any[]),
  (:times, 43, 100, -1, Any[]),
  (:prof, 44, -1, -1, Any[]),
  (:brk, 45, 12, 1, Any[]),
  (:setgid, 46, 106, -1, Any[]),
  (:getgid, 47, 104, -1, Any[]),
  (:signal, 48, -1, -1, Any[]),
  (:geteuid, 49, 107, 0, Any[]),
  (:getegid, 50, 108, 0, Any[]),
  (:acct, 51, 163, -1, Any[]),
  (:umount2, 52, 166, -1, Any[]),
  (:lock, 53, -1, -1, Any[]),
  (:ioctl, 54, 16, 3, Any[FDArgument(1)]),
  (:fcntl, 55, 72, 2, Any[]),
  (:mpx, 56, -1, -1, Any[]),
  (:setpgid, 57, 109, -1, Any[]),
  (:ulimit, 58, -1, -1, Any[]),
  (:oldolduname, 59, -1, -1, Any[]),
  (:umask, 60, 95, -1, Any[]),
  (:chroot, 61, 161, -1, Any[]),
  (:ustat, 62, 136, -1, Any[]),
  (:dup2, 63, 33, -1, Any[]),
  (:getppid, 64, 110, -1, Any[]),
  (:getpgrp, 65, 111, -1, Any[]),
  (:setsid, 66, 112, -1, Any[]),
  (:sigaction, 67, -1, -1, Any[]),
  (:sgetmask, 68, -1, -1, Any[]),
  (:ssetmask, 69, -1, -1, Any[]),
  (:setreuid, 70, 113, -1, Any[]),
  (:setregid, 71, 114, -1, Any[]),
  (:sigsuspend, 72, -1, -1, Any[]),
  (:sigpending, 73, -1, -1, Any[]),
  (:sethostname, 74, 170, -1, Any[]),
  (:setrlimit, 75, 160, -1, Any[]),
  (:getrlimit, -1, 97, 2, Any[]),
  (:getrusage, 77, 98, -1, Any[]),
  (:gettimeofday, 78, 96, -1, Any[]),
  (:settimeofday, 79, 164, -1, Any[]),
  (:getgroups, 80, 115, -1, Any[]),
  (:setgroups, 81, 116, -1, Any[]),
  (:select, 82, 23, -1, Any[]),
  (:symlink, 83, 88, -1, Any[]),
  (:oldlstat, 84, -1, -1, Any[]),
  (:readlink, 85, 89, -1, Any[]),
  (:uselib, 86, 134, -1, Any[]),
  (:swapon, 87, 167, -1, Any[]),
  (:reboot, 88, 169, -1, Any[]),
  (:readdir, 89, -1, -1, Any[]),
  (:mmap, 90, 9, 6, Any[]),
  (:munmap, 91, 11, 2, Any[]),
  (:truncate, 92, 76, -1, Any[]),
  (:ftruncate, 93, 77, -1, Any[]),
  (:fchmod, 94, 91, -1, Any[]),
  (:fchown, 95, 93, -1, Any[]),
  (:getpriority, 96, 140, -1, Any[]),
  (:setpriority, 97, 141, -1, Any[]),
  (:profil, 98, -1, -1, Any[]),
  (:statfs, 99, 137, 2, Any[]),
  (:fstatfs, 100, 138, -1, Any[]),
  (:ioperm, 101, 173, -1, Any[]),
  (:socketcall, 102, -1, -1, Any[]),
  (:syslog, 103, 103, -1, Any[]),
  (:setitimer, 104, 38, -1, Any[]),
  (:getitimer, 105, 36, -1, Any[]),
  (:stat, 106, 4, -1, Any[]),
  (:lstat, 107, 6, -1, Any[]),
  (:fstat, 108, 5, 2, Any[]),
  (:olduname, 109, -1, -1, Any[]),
  (:iopl, 110, 172, -1, Any[]),
  (:vhangup, 111, 153, -1, Any[]),
  (:idle, 112, -1, -1, Any[]),
  (:vm86old, 113, -1, -1, Any[]),
  (:wait4, 114, 61, -1, Any[]),
  (:swapoff, 115, 168, -1, Any[]),
  (:sysinfo, 116, 99, -1, Any[]),
  (:ipc, 117, -1, -1, Any[]),
  (:fsync, 118, 74, -1, Any[]),
  (:sigreturn, 119, -1, -1, Any[]),
  (:clone, 120, 56, -1, Any[]),
  (:setdomainname, 121, 171, -1, Any[]),
  (:uname, 122, 63, -1, Any[]),
  (:modify_ldt, 123, 154, -1, Any[]),
  (:adjtimex, 124, 159, -1, Any[]),
  (:mprotect, 125, 10, 3, Any[]),
  (:sigprocmask, 126, -1, -1, Any[]),
  (:create_module, 127, 174, -1, Any[]),
  (:init_module, 128, 175, -1, Any[]),
  (:delete_module, 129, 176, -1, Any[]),
  (:get_kernel_syms, 130, 177, -1, Any[]),
  (:quotactl, 131, 179, -1, Any[]),
  (:getpgid, 132, 121, -1, Any[]),
  (:fchdir, 133, 81, -1, Any[]),
  (:bdflush, 134, -1, -1, Any[]),
  (:sysfs, 135, 139, -1, Any[]),
  (:personality, 136, 135, -1, Any[]),
  (:afs_syscall, 137, 183, -1, Any[]),
  (:setfsuid, 138, 122, -1, Any[]),
  (:setfsgid, 139, 123, -1, Any[]),
  (:_llseek, 140, -1, -1, Any[]),
  (:getdents, 141, 78, -1, Any[]),
  (:_newselect, 142, -1, -1, Any[]),
  (:flock, 143, 73, -1, Any[]),
  (:msync, 144, 26, -1, Any[]),
  (:readv, 145, 19, -1, Any[]),
  (:writev, 146, 20, -1, Any[]),
  (:getsid, 147, 124, -1, Any[]),
  (:fdatasync, 148, 75, -1, Any[]),
  (:_sysctl, 149, 156, -1, Any[]),
  (:mlock, 150, 149, -1, Any[]),
  (:munlock, 151, 150, -1, Any[]),
  (:mlockall, 152, 151, -1, Any[]),
  (:munlockall, 153, 152, -1, Any[]),
  (:sched_setparam, 154, 142, -1, Any[]),
  (:sched_getparam, 155, 143, -1, Any[]),
  (:sched_setscheduler, 156, 144, -1, Any[]),
  (:sched_getscheduler, 157, 145, -1, Any[]),
  (:sched_yield, 158, 24, -1, Any[]),
  (:sched_get_priority_max, 159, 146, -1, Any[]),
  (:sched_get_priority_min, 160, 147, -1, Any[]),
  (:sched_rr_get_interval, 161, 148, -1, Any[]),
  (:nanosleep, 162, 35, -1, Any[]),
  (:mremap, 163, 25, -1, Any[]),
  (:setresuid, 164, 117, -1, Any[]),
  (:getresuid, 165, 118, -1, Any[]),
  (:vm86, 166, -1, -1, Any[]),
  (:query_module, 167, 178, -1, Any[]),
  (:poll, 168, 7, -1, Any[]),
  (:nfsservctl, 169, 180, -1, Any[]),
  (:setresgid, 170, 119, -1, Any[]),
  (:getresgid, 171, 120, -1, Any[]),
  (:prctl, 172, 157, 5, Any[]),
  (:rt_sigreturn, 173, 15, -1, Any[]),
  (:rt_sigaction, 174, 13, 4, Any[]),
  (:rt_sigprocmask, 175, 14, 4, Any[SigmaskPtrArgument(2),SigmaskPtrArgument(3)]),
  (:rt_sigpending, 176, 127, -1, Any[]),
  (:rt_sigtimedwait, 177, 128, -1, Any[]),
  (:rt_sigsuspend, 179, 130, -1, Any[]),
  (:pread64, 180, 17, -1, Any[]),
  (:pwrite64, 181, 18, -1, Any[]),
  (:chown, 182, 92, -1, Any[]),
  (:getcwd, 183, 79, -1, Any[]),
  (:capget, 184, 125, -1, Any[]),
  (:capset, 185, 126, -1, Any[]),
  (:sigaltstack, 186, 131, -1, Any[]),
  (:sendfile, 187, 40, -1, Any[]),
  (:getpmsg, 188, 181, -1, Any[]),
  (:putpmsg, 189, 182, -1, Any[]),
  (:vfork, 190, 58, -1, Any[]),
  (:ugetrlimit, 191, -1, -1, Any[]),
  (:mmap2, 192, -1, -1, Any[]),
  (:truncate64, 193, -1, -1, Any[]),
  (:ftruncate64, 194, -1, -1, Any[]),
  (:stat64, 195, -1, -1, Any[]),
  (:lstat64, 196, -1, -1, Any[]),
  (:fstat64, 197, -1, -1, Any[]),
  (:lchown32, 198, -1, -1, Any[]),
  (:getuid32, 199, -1, -1, Any[]),
  (:getgid32, 200, -1, -1, Any[]),
  (:geteuid32, 201, -1, -1, Any[]),
  (:getegid32, 202, -1, -1, Any[]),
  (:setreuid32, 203, -1, -1, Any[]),
  (:setregid32, 204, -1, -1, Any[]),
  (:getgroups32, 205, -1, -1, Any[]),
  (:setgroups32, 206, -1, -1, Any[]),
  (:fchown32, 207, -1, -1, Any[]),
  (:setresuid32, 208, -1, -1, Any[]),
  (:getresuid32, 209, -1, -1, Any[]),
  (:setresgid32, 210, -1, -1, Any[]),
  (:getresgid32, 211, -1, -1, Any[]),
  (:chown32, 212, -1, -1, Any[]),
  (:setuid32, 213, -1, -1, Any[]),
  (:setgid32, 214, -1, -1, Any[]),
  (:setfsuid32, 215, -1, -1, Any[]),
  (:setfsgid32, 216, -1, -1, Any[]),
  (:pivot_root, 217, 155, -1, Any[]),
  (:mincore, 218, 27, -1, Any[]),
  (:madvise, 219, 28, -1, Any[]),
  (:getdents64, 220, 217, -1, Any[]),
  (:fcntl64, 221, -1, -1, Any[]),
  (:gettid, 224, 186, 0, Any[]),
  (:readahead, 225, 187, -1, Any[]),
  (:setxattr, 226, 188, -1, Any[]),
  (:lsetxattr, 227, 189, -1, Any[]),
  (:fsetxattr, 228, 190, -1, Any[]),
  (:getxattr, 229, 191, -1, Any[]),
  (:lgetxattr, 230, 192, -1, Any[]),
  (:fgetxattr, 231, 193, -1, Any[]),
  (:listxattr, 232, 194, -1, Any[]),
  (:llistxattr, 233, 195, -1, Any[]),
  (:flistxattr, 234, 196, -1, Any[]),
  (:removexattr, 235, 197, -1, Any[]),
  (:lremovexattr, 236, 198, -1, Any[]),
  (:fremovexattr, 237, 199, -1, Any[]),
  (:tkill, 238, 200, -1, Any[]),
  (:sendfile64, 239, -1, -1, Any[]),
  (:futex, 240, 202, 6, Any[]),
  (:sched_setaffinity, 241, 203, -1, Any[]),
  (:sched_getaffinity, 242, 204, -1, Any[]),
  (:set_thread_area, 243, 205, -1, Any[]),
  (:get_thread_area, 244, 211, -1, Any[]),
  (:io_setup, 245, 206, -1, Any[]),
  (:io_destroy, 246, 207, -1, Any[]),
  (:io_getevents, 247, 208, -1, Any[]),
  (:io_submit, 248, 209, -1, Any[]),
  (:io_cancel, 249, 210, -1, Any[]),
  (:fadvise64, 250, 221, -1, Any[]),
  (:exit_group, 252, 231, -1, Any[]),
  (:lookup_dcookie, 253, 212, -1, Any[]),
  (:epoll_create, 254, 213, -1, Any[]),
  (:epoll_ctl, 255, 233, -1, Any[]),
  (:epoll_wait, 256, 232, -1, Any[]),
  (:remap_file_pages, 257, 216, -1, Any[]),
  (:set_tid_address, 258, 218, 1, Any[]),
  (:timer_create, 259, 222, -1, Any[]),
  (:timer_settime, 260, 223, -1, Any[]),
  (:timer_gettime, 261, 224, -1, Any[]),
  (:timer_getoverrun, 262, 225, -1, Any[]),
  (:timer_delete, 263, 226, -1, Any[]),
  (:clock_settime, 264, 227, -1, Any[]),
  (:clock_gettime, 265, 228, -1, Any[]),
  (:clock_getres, 266, 229, -1, Any[]),
  (:clock_nanosleep, 267, 230, -1, Any[]),
  (:statfs64, 268, -1, -1, Any[]),
  (:fstatfs64, 269, -1, -1, Any[]),
  (:tgkill, 270, 234, -1, Any[]),
  (:utimes, 271, 235, -1, Any[]),
  (:fadvise64_64, 272, -1, -1, Any[]),
  (:vserver, 273, 236, -1, Any[]),
  (:mbind, 274, 237, -1, Any[]),
  (:get_mempolicy, 275, 239, -1, Any[]),
  (:set_mempolicy, 276, 238, -1, Any[]),
  (:mq_open, 277, 240, -1, Any[]),
  (:mq_unlink, 278, 241, -1, Any[]),
  (:mq_timedsend, 279, 242, -1, Any[]),
  (:mq_timedreceive, 280, 243, -1, Any[]),
  (:mq_notify, 281, 244, -1, Any[]),
  (:mq_getsetattr, 282, 245, -1, Any[]),
  (:kexec_load, 283, 246, -1, Any[]),
  (:waitid, 284, 247, -1, Any[]),
  (:add_key, 286, 248, -1, Any[]),
  (:request_key, 287, 249, -1, Any[]),
  (:keyctl, 288, 250, -1, Any[]),
  (:ioprio_set, 289, 251, -1, Any[]),
  (:ioprio_get, 290, 252, -1, Any[]),
  (:inotify_init, 291, 253, -1, Any[]),
  (:inotify_add_watch, 292, 254, -1, Any[]),
  (:inotify_rm_watch, 293, 255, -1, Any[]),
  (:migrate_pages, 294, 256, -1, Any[]),
  (:openat, 295, 257, -1, Any[]),
  (:mkdirat, 296, 258, -1, Any[]),
  (:mknodat, 297, 259, -1, Any[]),
  (:fchownat, 298, 260, -1, Any[]),
  (:futimesat, 299, 261, -1, Any[]),
  (:fstatat64, 300, 262, -1, Any[]),
  (:unlinkat, 301, 263, -1, Any[]),
  (:renameat, 302, 264, -1, Any[]),
  (:linkat, 303, 265, -1, Any[]),
  (:symlinkat, 304, 266, -1, Any[]),
  (:readlinkat, 305, 267, -1, Any[]),
  (:fchmodat, 306, 268, -1, Any[]),
  (:faccessat, 307, 269, -1, Any[]),
  (:pselect6, 308, 270, -1, Any[]),
  (:ppoll, 309, 271, -1, Any[]),
  (:unshare, 310, 272, -1, Any[]),
  (:set_robust_list, 311, 273, 3, Any[]),
  (:get_robust_list, 312, 274, 3, Any[]),
  (:splice, 313, 275, -1, Any[]),
  (:sync_file_range, 314, 277, -1, Any[]),
  (:tee, 315, 276, -1, Any[]),
  (:vmsplice, 316, 278, -1, Any[]),
  (:move_pages, 317, 279, -1, Any[]),
  (:getcpu, 318, 309, -1, Any[]),
  (:epoll_pwait, 319, 281, -1, Any[]),
  (:utimensat, 320, 280, -1, Any[]),
  (:signalfd, 321, 282, -1, Any[]),
  (:timerfd_create, 322, 283, -1, Any[]),
  (:eventfd, 323, 284, -1, Any[]),
  (:fallocate, 324, 285, -1, Any[]),
  (:timerfd_settime, 325, 286, -1, Any[]),
  (:timerfd_gettime, 326, 287, -1, Any[]),
  (:signalfd4, 327, 289, -1, Any[]),
  (:eventfd2, 328, 290, -1, Any[]),
  (:epoll_create1, 329, 291, -1, Any[]),
  (:dup3, 330, 292, -1, Any[]),
  (:pipe2, 331, 293, -1, Any[]),
  (:inotify_init1, 332, 294, -1, Any[]),
  (:preadv, 333, 295, -1, Any[]),
  (:pwritev, 334, 296, -1, Any[]),
  (:rt_sigqueueinfo, 178, 129, -1, Any[]),
  (:rt_tgsigqueueinfo, 335, 297, -1, Any[]),
  (:perf_event_open, 336, 298, 5, Any[]),
  (:recvmmsg, 337, 299, -1, Any[]),
  (:fanotify_init, 338, 300, -1, Any[]),
  (:fanotify_mark, 339, 301, -1, Any[]),
  (:prlimit64, 340, 302, -1, Any[]),
  (:name_to_handle_at, 341, 303, -1, Any[]),
  (:open_by_handle_at, 342, 304, -1, Any[]),
  (:clock_adjtime, 343, 305, -1, Any[]),
  (:syncfs, 344, 306, -1, Any[]),
  (:sendmmsg, 345, 307, -1, Any[]),
  (:setns, 346, 308, -1, Any[]),
  (:process_vm_readv, 347, 310, -1, Any[]),
  (:process_vm_writev, 348, 311, -1, Any[]),
  (:kcmp, 349, 312, -1, Any[]),
  (:finit_module, 350, 313, -1, Any[]),
  (:sched_setattr, 351, 314, -1, Any[]),
  (:sched_getattr, 352, 315, -1, Any[]),
  (:renameat2, 353, 316, -1, Any[]),
  (:seccomp, 354, 317, -1, Any[]),
  (:getrandom, 355, 318, -1, Any[]),
  (:memfd_create, 356, 319, -1, Any[]),
  (:bpf, 357, 321, -1, Any[]),
  (:execveat, 358, 322, -1, Any[]),
  (:userfaultfd, 374, 323, -1, Any[]),
  (:membarrier, 375, 324, -1, Any[]),
  (:mlock2, 376, 325, -1, Any[]),
  (:copy_file_range, 377, 326, -1, Any[]),
  (:preadv2, 378, 327, -1, Any[]),
  (:pwritev2, 379, 328, -1, Any[]),
  (:restart_syscall, -1, 219, -1, Any[]),
  (:rrcall_init_preload, 442, 442, 0, Any[]),
  (:rrcall_init_buffers, 443, 443, 1, Any[]),
  (:rrcall_notify_syscall_hook_exit, 444, 444, -1, Any[]),
  (:rrcall_notify_control_msg, 445, 445, -1, Any[]),
  (:rrcall_reload_auxv, 446, 446, -1, Any[]),
  (:rrcall_mprotect_record, 447, 447, -1, Any[]),
  (:socket, 359, 41, -1, Any[]),
  (:connect, 362, 42, -1, Any[]),
  (:accept, -1, 43, -1, Any[]),
  (:sendto, 369, 44, -1, Any[]),
  (:recvfrom, 371, 45, -1, Any[]),
  (:sendmsg, 370, 46, -1, Any[]),
  (:recvmsg, 372, 47, -1, Any[]),
  (:shutdown, 373, 48, -1, Any[]),
  (:bind, 361, 49, -1, Any[]),
  (:listen, 363, 50, -1, Any[]),
  (:getsockname, 367, 51, -1, Any[]),
  (:getpeername, 368, 52, -1, Any[]),
  (:socketpair, 360, 53, -1, Any[]),
  (:setsockopt, 366, 54, -1, Any[]),
  (:getsockopt, 365, 55, -1, Any[]),
  (:accept4, 364, 288, -1, Any[]),
  (:shmget, -1, 29, -1, Any[]),
  (:shmat, -1, 30, -1, Any[]),
  (:shmctl, -1, 31, -1, Any[]),
  (:semget, -1, 64, -1, Any[]),
  (:semop, -1, 65, -1, Any[]),
  (:semctl, -1, 66, -1, Any[]),
  (:shmdt, -1, 67, -1, Any[]),
  (:msgget, -1, 68, -1, Any[]),
  (:msgsnd, -1, 69, -1, Any[]),
  (:msgrcv, -1, 70, -1, Any[]),
  (:msgctl, -1, 71, -1, Any[]),
  (:semtimedop, -1, 220, -1, Any[]),
  (:arch_prctl, -1, 158, 2, Any[]),
  (:tuxcall, -1, 184, -1, Any[]),
  (:security, -1, 185, -1, Any[]),
  (:epoll_ctl_old, -1, 214, -1, Any[]),
  (:epoll_wait_old, -1, 215, -1, Any[])
]


text:
@testset "Potree" begin
    workdir = dirname(dirname(pathof(FileManager)))
    # test_file = joinpath(BASE_FOLDER, "data", "file.txt")

    potreeLAS = joinpath(workdir,"test","Files/stairsLAS")
    potreeLAZ = joinpath(workdir,"test","Files/stairsLAZ")

    oneNodeLAS = joinpath(workdir,"test","Files/stairsLAS/data/r/r0.las")
    oneNodeLAZ = joinpath(workdir,"test","Files/stairsLAZ/data/r/r0.laz")

    totalNodes = 71 # aka number of files
    maxDepth = 3    # depth of the tree
    totalPoints = (3, 357003) # using that to check coordinates and rgbs ( 3 (xyz/rgb), 357003 (total points))
    boundingbox = (1.4770147800445557, -0.7153962850570679, -1.4153246879577637, 5.361339569091797, 3.1689285039901735, 2.4690001010894777)

    @testset "las2pointcloud" begin
        @test size(FileManager.las2pointcloud((FileManager.get_all_values(FileManager.potree2trie(potreeLAS)))...).coordinates) == totalPoints
        @test size(FileManager.las2pointcloud((FileManager.get_all_values(FileManager.potree2trie(potreeLAZ)))...).coordinates) == totalPoints

        @test size(FileManager.las2pointcloud((FileManager.get_all_values(FileManager.potree2trie(potreeLAS)))...).rgbs) == totalPoints
        @test size(FileManager.las2pointcloud((FileManager.get_all_values(FileManager.potree2trie(potreeLAZ)))...).rgbs) == totalPoints
    end

    @testset "las2larpoints" begin
        @test (FileManager.las2larpoints(oneNodeLAS)) == (FileManager.las2larpoints(oneNodeLAZ))
    end

    @testset "max_depth" begin
        @test FileManager.max_depth(FileManager.potree2trie(potreeLAS)) == maxDepth
        @test FileManager.max_depth(FileManager.potree2trie(potreeLAZ)) == maxDepth
    end

    @testset "get_all_values" begin

        # size gives a tuple (totalNodes, ) so use [1] to check the first element
        @test size(FileManager.get_all_values(FileManager.potree2trie(potreeLAS)))[1] == totalNodes
        @test size(FileManager.get_all_values(FileManager.potree2trie(potreeLAZ)))[1] == totalNodes
    end

    @testset "sub_trie" begin

    end

    @testset "get_files_in_potree_folder + get_files" begin

    # size gives a tuple (totalNodes, ) so use [1] to check the first element

        # LOD = 0, just one node (radix node)
        @test size(FileManager.get_files_in_potree_folder(potreeLAS, 0))[1] == 1
        @test size(FileManager.get_files_in_potree_folder(potreeLAZ, 0))[1] == 1

        # LOD = 1, radix + 7 child
        @test size(FileManager.get_files_in_potree_folder(potreeLAS, 1))[1] == 8
        @test size(FileManager.get_files_in_potree_folder(potreeLAZ, 1))[1] == 8

        # LOD = 2, radix + 7 child + 26 child of child
        @test size(FileManager.get_files_in_potree_folder(potreeLAS, 2))[1] == 36
        @test size(FileManager.get_files_in_potree_folder(potreeLAZ, 2))[1] == 36

        # LOD = 3, radix + 7 child + 26 child of child + 35 child = totalNodes (71)
        @test size(FileManager.get_files_in_potree_folder(potreeLAS, 3))[1] == totalNodes
        @test size(FileManager.get_files_in_potree_folder(potreeLAZ, 3))[1] == totalNodes
    end
end

ext: jl


text:
module Octokit
	using HttpCommon
	using HTTPClient
	import JSON

	immutable Endpoint
		url::URI
	end

	const default_endpoint = Endpoint(URI("https://api.github.com"))

	function api_uri(endpoint,path,query,userinfo="")
		uri = endpoint.url
		URI(uri.schema,uri.host,uri.port,joinpath(uri.path,path),query,"",userinfo,uri.specifies_authority)
	end

	immutable APIRequestError <: Exception
		message::String
	end

	immutable InvalidDataError <: Exception
		message::String
		errors::Array
	end

	function api_error(resp::Response)
		if resp.status == 400
			throw(APIRequestError(JSON.parse(resp.data)["message"]))
		elseif resp.status == 422
			p = JSON.parse(resp.data)
			throw(InvalidDataError(p["message"],p["errors"]))
		elseif resp.status == 404
			throw(APIRequestError("404: Not found"))
		end
		resp
	end

	# Authentication

	abstract Credentials

	immutable BasicAuth <: Credentials
		username::String
		password::String
	end

	immutable OAuthToken <: Credentials
		token::String
	end

	immutable OAuthSecret <: Credentials
		client_id::String
		client_secret::String
	end

	immutable Anonymous <: Credentials
	end

	do_query(path, parameters, auth::Credentials = Anonymous(), endpoint = default_endpoint) =
		api_error(_do_request(path,parameters,auth,endpoint))

	_do_query(path,parameters,auth::Anonymous,endpoint) = HTTPClient.get(api_uri(endpoint,path,""))
	_do_query(path,parameters,auth::BasicAuth,endpoint) = HTTPClient.get(api_uri(endpoint,path,"","$(auth.username):$(auth.password)"))
	_do_query(path,parameters,auth::OAuthToken,endpoint) = HTTPClient.get(api_uri(endpoint,path,""),headers={"Authorization"=>"token $(auth.token)"})
	function _do_query(path,parameters,auth::OAuthSecret,endpoint)
		params = {"client_secret" => auth.client_secret, "client_id" => auth.client_id}
		merge!(params,parameters)
		_do_query(path,params,Anonymous(),endpoint)
	end

	do_action(path, parameters, data, auth::Credentials = Anonymous(), endpoint = default_endpoint) =
		api_error(_do_action(path,parameters,data,auth,endpoint))

	_do_action(path,parameters,data,auth::Anonymous,endpoint) = HTTPClient.post(api_uri(endpoint,path,""),data)
	_do_action(path,parameters,data,auth::BasicAuth,endpoint) = HTTPClient.post(api_uri(endpoint,path,"","$(auth.username):$(auth.password)"),data)
	_do_action(path,parameters,data,auth::OAuthToken,endpoint) = HTTPClient.post(api_uri(endpoint,path,""),data,headers={"Authorization"=>"token $(auth.token)"})
	function _do_action(path,parameters,auth::OAuthSecret,endpoint)
		params = {"client_secret" => auth.client_secret, "client_id" => auth.client_id}
		merge!(params,parameters)
		_do_action(path,params,data,Anonymous(),endpoint)
	end

	function createToken(auth::BasicAuth,scopes=["public_repo"],note="Created using Octokit.jl";endpoint=default_endpoint)
		r = do_action("/authorizations",{},JSON.to_json({"scopes"=>scopes,"note"=>note}),auth,endpoint)
		d = JSON.parse(r.data)
		(d["id"],OAuthToken(d["token"]))
	end
end


text:
using Proportions
using Test

@testset "Proportions.jl" begin
    # Write your tests here.
    @test Proportions.get_proportion([1.0,1.0,1.0,1.0]) == [0.25,0.25,0.25,0.25]
    @test Proportions.get_proportion([1.0,1.0,1.0,2.5]) != [0.25,0.25,0.25,0.25]
    @test Proportions.get_proportion_round([1.33,1.33,1.23,1.1111],round_digits=2) ==[0.26, 0.27, 0.25, 0.22]
    @test Proportions.get_proportion_round([33,33,33.23,33.1111],round_digits=6) ==[0.249356, 0.249356, 0.251093, 0.250195]
    @test Proportions.get_proportion_round_add1251([33.009, 33.31223, 33.2113, 33.111122],round_digits=6) ==[0.24997, 0.25003, 0.25001, 0.24999]
    @test Proportions.get_proportion_2d([1.0 2.0 ; 4.0 5.0]) == [0.08333333333333333 0.16666666666666666; 0.3333333333333333 0.4166666666666667]
    @test Proportions.get_proportion_round_2d([1.1101 2.243 ; 4.9898 5.87],round_digits=5) == [0.07811 0.15781; 0.35108 0.413]
    @test Proportions.get_proportion_round_add1251_2d([1.1101 2.243 ; 4.9898 5.87 ; 34.333 6.78],round_digits=8) == [0.16559399 0.16574381; 0.16610708 0.16622349; 0.16998779 0.16634384]
end

max_stars_repo_name: hillelawaskar/Proportions

max_issues_repo_name: hillelawaskar/Proportions


text:
type TransformedChannel <: AbstractChannel
    original::AbstractChannel
    transform::Function
end

close(ch::TransformedChannel) = close(ch.original)
isopen(ch::TransformedChannel) = isopen(ch.original)
# put!(ch::TransformedChannel, v) = put!(ch.original, v)
# push!(ch::TransformedChannel, v) = push!(ch.original, v)
fetch(ch::TransformedChannel) = ch.transform(fetch(ch.original))
take!(ch::TransformedChannel) = ch.transform(take!(ch.original))

# TODO: what other methods should be implemented? what methods should be forbidden?

map(f::Function, ch::AbstractChannel) = TransformedChannel(ch, f)


text:
using ArcadeLearningEnvironment
using CartesianGeneticProgramming
using IICGP
using UnicodePlots
using ImageCore
using ImageTransformations
using Interpolations
using BenchmarkTools
using TiledIteration
using Images
using ImageMorphology
using LinearAlgebra
using Random

out(plt) = println(IOContext(stdout, :color=>true), plt)

function print_usage()
	out = read(`top -bn1 -p $(getpid())`, String)
	res = split(split(out,  "\n")[end-1])
	println("RES: ", res[6], "   %MEM: ", res[10], "   %CPU: ", res[9])
	parse(Float64, replace(res[10], "," => "."))
end

function fakeplay(n_steps::Int64)
	for t in 1:n_steps
		s = [rand(UInt8, 80, 105)]
		output = IICGP.process(enco, redu, cont, ccfg, s)

		#CartesianGeneticProgramming.process(enco, s)
		#features_flatten = rand(35)
	    #push!(features_flatten, 0:1.0/(10-1):1.0...)
		#CartesianGeneticProgramming.process(cont, features_flatten)
	end
end

function play(game::Game, n_steps::Int64, grayscale::Bool, downscale::Bool)
	IICGP.reset!(game)
	s = get_state_buffer(game, grayscale)
	o = get_observation_buffer(game, grayscale, downscale)
	for t in 1:n_steps
		get_state!(s, game, grayscale)
		get_observation!(o, s, game, grayscale, downscale)
		#s = getScreenRGB(game.ale)
		output = IICGP.process(enco, redu, cont, ccfg, o)
		act(game.ale, game.actions[rand(1:length(game.actions))])
		if game_over(game.ale)
			break
		end
	end
end

seed = 4
Random.seed!(seed)
n_iter = 25000
n_para = 4
n_steps = 10000
rom_name = "space_invaders"
#games = [Game(rom_name, 0) for _ in 1:n_para]
mem_usage = Vector{Float64}()
cfgpath = "/home/opaweynch/.julia/environments/v1.6/dev/IICGP/cfg/eccgp_atari_nsga2.yaml"
mcfg, ecfg, ccfg, redu, bootstrap = IICGP.dualcgp_config(cfgpath, rom_name)
enco = IPCGPInd(ecfg)
cont = CGPInd(ccfg)
grayscale, downscale = true, true

##

for e in 1:n_iter
	#=for i in 1:n_para
		fakeplay(n_steps)
	end=#
	@sync for i in 1:n_para
		Threads.@spawn begin
			fakeplay(n_steps)
			#play(games[i], n_steps, grayscale, downscale)
		end
	end
	mem = print_usage()
	push!(mem_usage, mem)
	out(lineplot(mem_usage, title = "%MEM"))
end

#=for game in games
	close!(game)
end=#


text:
export Representation, HRepresentation, VRepresentation, coefficienttype, fulldim
export RepIterator
export Rep

"""
    Representation{N, T<:Real}

Supertype for H-(or V-)representations of an `N`-dimensional` with coefficient type `T`.
"""
abstract type Representation{N, T <: Real} end
"""
    HRepresentation{N, T<:Real}

Supertype for H-representations of an `N`-dimensional` with coefficient type `T`.
"""
abstract type HRepresentation{N,T} <: Representation{N,T} end
"""
    VRepresentation{N, T<:Real}

Supertype for V-representations of an `N`-dimensional` with coefficient type `T`.
"""
abstract type VRepresentation{N,T} <: Representation{N,T} end

export Rep, HRep, VRep

const  Rep{N,T} = Union{ Representation{N,T}, Polyhedron{N,T}}
const HRep{N,T} = Union{HRepresentation{N,T}, Polyhedron{N,T}}
const VRep{N,T} = Union{VRepresentation{N,T}, Polyhedron{N,T}}

"""
    coefficienttype(rep::Rep)

Returns the type of the coefficients used in the representation of `rep`.
"""
MultivariatePolynomials.coefficienttype(rep::Union{Rep{N,T}, Type{<:Rep{N,T}}}) where {N,T} = T

"""
    fulldim(rep::Rep)

Returns the dimension of the space in which the representation is defined.
That is, a straight line in a 3D space has `fulldim` 3.
"""
fulldim(p) = fulldim(FullDim(p))
FullDim(rep::Union{Rep{N}, Type{<:Rep{N}}}) where N = FullDim{N}()

# Check that it is either empty or it has a point
vconsistencyerror() = error("Non-empty V-representation must contain at least one point. If it is a polyhedral cone, the origin should be added.")
function checkvconsistency(vrep::VRep)
    if !haspoints(vrep) && hasallrays(vrep)
        vconsistencyerror()
    end
end
checkvconsistency(p::Polyhedron) = vrepiscomputed(p) && checkvconsistency(vrep(p))

# This method solves the ambiguity with the following methods and the general method
# Base.convert{T}(::Type{T}, p::T) = p
Base.convert(::Type{T}, p::T) where {T<:HRepresentation} = p
Base.convert(::Type{T}, p::T) where {T<:VRepresentation} = p

Base.convert(RepT::Type{<:HRep}, p::HRepresentation)            = hconvert(RepT, p)
Base.convert(RepT::Type{<:HRepresentation}, p::HRep)            = hconvert(RepT, p)
# avoid ambiguity
Base.convert(RepT::Type{<:HRepresentation}, p::HRepresentation) = hconvert(RepT, p)

Base.copy(rep::HRepresentation) = typeof(rep)(hreps(rep)...)
Base.copy(rep::VRepresentation) = typeof(rep)(vreps(rep)...)

function Polyhedron{N, S}(p::Polyhedron{N, T}) where {N, S, T}
    RepT = similar_type(typeof(p), S)
    if !hrepiscomputed(p) && vrepiscomputed(p)
        vconvert(RepT, p)
    else
        hconvert(RepT, p)
    end
end

Base.convert(RepT::Type{<:VRep}, p::VRepresentation)            = vconvert(RepT, p)
Base.convert(RepT::Type{<:VRepresentation}, p::VRep)            = vconvert(RepT, p)
# avoid ambiguity
Base.convert(RepT::Type{<:VRepresentation}, p::VRepresentation) = vconvert(RepT, p)

# Used by SimpleVRepPolyhedraModel
Base.convert(::Type{VRep}, p::VRepresentation) = p

MultivariatePolynomials.changecoefficienttype(p::Rep{N,T}, ::Type{T}) where {N,T} = p
MultivariatePolynomials.changecoefficienttype(p::Rep, T::Type) = similar_type(typeof(p), T)(p)

VRepresentation{N, T}(v::VRepresentation) where {N, T} = similar_type(typeof(v), FullDim{N}(), T)(v)
HRepresentation{N, T}(h::HRepresentation) where {N, T} = similar_type(typeof(h), FullDim{N}(), T)(h)

VRep{N, T}(v::VRepresentation) where {N, T} = VRepresentation{N, T}(v)
VRep{N, T}(p::Polyhedron) where {N, T} = Polyhedron{N, T}(p)
HRep{N, T}(h::HRepresentation) where {N, T} = HRepresentation{N, T}(h)
HRep{N, T}(p::Polyhedron) where {N, T} = Polyhedron{N, T}(p)

# FIXME it does not get called. The calls always go throug vconvert and hconvert. Use changecoefficienttype instead
#function Base.convert{N, T, RepT<:Representation}(::Type{Representation{N, T}}, rep::RepT)
#  if fulldim(RepT) != N
#    error("Cannot convert representations of the same dimension")
#  end
#  Base.convert(changecoefficienttype(RepT, T), rep)
#end
#function Base.convert{N, T, RepT<:HRepresentation}(::Type{HRepresentation{N, T}}, rep::RepT)
#  if fulldim(RepT) != N
#    error("Cannot convert representations of the same dimension")
#  end
#  Base.convert(changecoefficienttype(RepT, T), rep)
#end
#function Base.convert{M, S, RepT<:VRepresentation}(::Type{VRepresentation{M, S}}, rep::RepT)
#  if fulldim(RepT) != M
#    error("Cannot convert representations of the same dimension")
#  end
#  Base.convert(changecoefficienttype(RepT, S), rep)
#end


text:
using Suppressor: @capture_out
using Test
using TestProgress
using TestProgress: DOT

# Needs to be outside of the `@testset`s to test `LoudTestSet` bneing applied at top scope
output = @capture_out begin
    @testset LoudTestSet "top-level" begin
        @testset "nested 1" begin
            @test true
            @test 2 == 2
        end
        @testset "nested 2" begin
            @test true
            @test 2 == 2
            @test 3 == 3
        end
    end  # testset
end

@testset "TestProgress.jl" begin
    @test DOT == '•' == '\u2022'

    # Should see passing test before any testset ends
    @test output[1] == DOT

    # Should still print the usual summary
    @test occursin("Test Summary", output)

    lines = split(output, '\n')
    # Should have the a DOT for every passing test in "nested 1"
    @test lines[1] == DOT^2

    # Should see the testset finish before anymore tests
    @test startswith(lines[2], "Finished ")

    # Should be the "nested 1" testset that finishes first
    @test occursin("nested 1", lines[2])

    # Should have the a DOT for every passing test in "nested 2"
    @test lines[3] == DOT^3
end


text:
"""
    add_obj_fun!(
        ata_model::RobustMaximinModel;
        psychometrics = false,
        items::Vector{Psychometrics.Item} = Psychometrics.Item[],
        items_file = "",
        kwargs...
    )

# Description

It adds the objective function as specified in the `settings_file`. It requires the [`start_ata`](#ATA.start_ata) build step.
Computes the IIFs at predefined ability points using the estimated item parameters in the item bank.
It computes also the standard deviations of the IIFs given R samples of the item parameters provided by a vector of `Psychometrics.Item`.
The vector of items can be passed either through the argument `items` (`Vector{Psychometrics.Item}`) or through the argument `items_file` (string file name).
In both cases, the items in the vector must have the same order of the items in the item bank and they must contain the R sampled item parameters in the field `parameters.chain`.

- **`ata_model::RobustMaximinModel`** : Required.
"""
function add_obj_fun!(
    ata_model::RobustMaximinModel;
    psychometrics = false,
    items::Vector{Psychometrics.Item} = Psychometrics.Item[],
    items_file = "",
    kwargs...,
)

    try
        if psychometrics
            compute_estimated_iif!(ata_model)
            robust_load_parameters_chain!(
                ata_model;
                items_file = items_file,
                items = items,
                kwargs...,
            )
        end
        success!(ata_model, "Objective function loaded.")
        success!(ata_model, "IIFs computed.")
        success!(ata_model, "Standard deviations computed.")

        # open("opt/Settings.jl", "a") do f
        #     write(f, "K = $K\n\n")
        # end

    catch e
        error!(ata_model, string(sprint(showerror, e)))

    end
    return nothing
end


text:
mse_action_loss(π, 𝒫, 𝒟; kwargs...) = Flux.mse(action(π, 𝒟[:s]), 𝒟[:a])

function mse_value_loss(π, 𝒫, 𝒟; kwargs...)
    eloss = -mean(entropy(π, 𝒟[:s]))
    mseloss = Flux.mse(value(π, 𝒟[:s]), 𝒟[:value])
    𝒫[:λe]*eloss + mseloss
end

function logpdf_bc_loss(π, 𝒫, 𝒟; info=Dict())
    eloss = -mean(entropy(π, 𝒟[:s]))
    lloss = -mean(logpdf(π, 𝒟[:s], 𝒟[:a]))
    ignore() do
        info[:entropy] = -eloss
        info[:logpdf] = lloss
    end
    𝒫[:λe]*eloss + lloss
end

function BC(;π,
             S,
             𝒟_demo,
             normalize_demo::Bool=true,
             loss=nothing,
             validation_fraction=0.3,
             window=100,
             λe::Float32=1f-3,
             opt::NamedTuple=(;),
             log::NamedTuple=(;),
             kwargs...)

    if isnothing(loss)
        loss = π isa ContinuousNetwork ? mse_action_loss : logpdf_bc_loss
    end
    normalize_demo && (𝒟_demo = normalize!(deepcopy(𝒟_demo), S, action_space(π)))
    𝒟_demo = 𝒟_demo |> device(π)

    # Split between train and validation sets
    shuffle!(𝒟_demo)
    𝒟_train, 𝒟_validate = split(𝒟_demo, [1-validation_fraction, validation_fraction])
    #TODO: We should include a validation loss, then early stopping should just analyze the history of the validation loss.

    𝒫 = (λe=λe,)
    BatchSolver(;agent=PolicyParams(π),
                 S=S,
                 𝒫=𝒫,
                 𝒟_train=𝒟_train,
                 a_opt=TrainingParams(;early_stopping=stop_on_validation_increase(π, 𝒫, 𝒟_validate, loss, window=window), loss=loss, opt...),
                 log=LoggerParams(;dir="log/bc", period=1, log...),
                 kwargs...)
end


text:
module test_bukdu_plugs_loggers

using Test
using Bukdu # Plug plug
using Logging: AbstractLogger
using HTTP

struct MyLogger <: AbstractLogger
    stream
end

function Plug.Loggers.print_message(logger::MyLogger, args...; kwargs...)
    io = logger.stream
    Base.printstyled(io, "MYLOG ", color=:yellow)
    Base.println(io, args...; kwargs...)
    Base.flush(io)
end

function Plug.Loggers.info_response(logger::MyLogger, req, route::NamedTuple{(:controller, :action)})
    io = logger.stream
    Base.printstyled(io, "MYLOG ", color=:yellow)
    Plug.Loggers.default_info_response(io, req, route)
    Base.flush(io)
end

plug(MyLogger, IOContext(Core.stdout, :color => Plug.Loggers.have_color()))

Bukdu.start(8191)
@test_throws HTTP.ExceptionRequest.StatusError HTTP.get("http://localhost:8191/")
Bukdu.stop()

access_log_path = normpath(@__DIR__, "access.log")
plug(MyLogger, open(access_log_path, "w"))

Bukdu.start(8191)
@test_throws HTTP.ExceptionRequest.StatusError HTTP.get("http://localhost:8191/")
Bukdu.stop()

@test read(access_log_path, String) == """
MYLOG Bukdu Listening on 127.0.0.1:8191
MYLOG INFO: GET     MissingController   not_found       404 /
MYLOG Bukdu has stopped.
"""
try Base.rm(access_log_path) catch end

end # module test_bukdu_plugs_loggers


text:
using BinaryProvider # requires BinaryProvider 0.3.0 or later

# 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, String["liberfa"], :liberfa),
]

# Download binaries from hosted location
bin_prefix = "https://github.com/JuliaAstro/ERFABuilder/releases/download/v1.4.0"

# Listing of files generated by BinaryBuilder:
download_info = Dict(
    Linux(:aarch64, :glibc) => ("$bin_prefix/liberfa.aarch64-linux-gnu.tar.gz", "ed2e309708bb40dda20439f9b6a7924c01e1b2b9875d2213b4d9b6669517f8b3"),
    Linux(:aarch64, :musl) => ("$bin_prefix/liberfa.aarch64-linux-musl.tar.gz", "72a4196e9a259b513fcdf62c98c8c74264b689263b5847200c796b2c7483fd65"),
    Linux(:armv7l, :glibc, :eabihf) => ("$bin_prefix/liberfa.arm-linux-gnueabihf.tar.gz", "d736a6a44ce531a61dbe844ea0d6279a429bc269ee786cd32d339c5f3d8bd3e9"),
    Linux(:armv7l, :musl, :eabihf) => ("$bin_prefix/liberfa.arm-linux-musleabihf.tar.gz", "be0422495e97a64b56d35ba1c3e44317b54725cf7824f39700dc4af50904a2fd"),
    Linux(:i686, :glibc) => ("$bin_prefix/liberfa.i686-linux-gnu.tar.gz", "c75d0a48142336924e30442085f1617e2d5c48048c9a5b6045334a535893749d"),
    Linux(:i686, :musl) => ("$bin_prefix/liberfa.i686-linux-musl.tar.gz", "86db97332f22a2f057dbfcc2ce6620df1dee7297c7aaafbb285061584d09a0d5"),
    Windows(:i686) => ("$bin_prefix/liberfa.i686-w64-mingw32.tar.gz", "acc29f41824dc0db9c81c96ba11da81259f97fd87ae37d72a3d61538fc7d4e55"),
    Linux(:powerpc64le, :glibc) => ("$bin_prefix/liberfa.powerpc64le-linux-gnu.tar.gz", "b56adcbcabc579e5733b91e11f158bf0e14ad4ca5fa7b1338545406b3f60d153"),
    MacOS(:x86_64) => ("$bin_prefix/liberfa.x86_64-apple-darwin14.tar.gz", "6d20ae186a6a934ee9a12bcde91d932aa2ea331387cfa6e79fd63b1e667143e0"),
    Linux(:x86_64, :glibc) => ("$bin_prefix/liberfa.x86_64-linux-gnu.tar.gz", "3cee94d8773ed7a6737de2606758b22f3bd17fead6d8c258b4c029f104b2227b"),
    Linux(:x86_64, :musl) => ("$bin_prefix/liberfa.x86_64-linux-musl.tar.gz", "b664f8c99e1fb8caf8c0de1197ce50135b0013bd006ef3c60e9c886c542c7e88"),
    FreeBSD(:x86_64) => ("$bin_prefix/liberfa.x86_64-unknown-freebsd11.1.tar.gz", "3ced46efdf0626e5f954e3689afbb63fc1a71eed2b0e243e202ed054847122f0"),
    Windows(:x86_64) => ("$bin_prefix/liberfa.x86_64-w64-mingw32.tar.gz", "de23159790b9df6aaad1faead33aaaafc118ca1910b4baf320120c8538b0d30d"),
)

# Install unsatisfied or updated dependencies:
unsatisfied = any(!satisfied(p; verbose=verbose) for p in products)
if haskey(download_info, platform_key())
    url, tarball_hash = download_info[platform_key()]
    if unsatisfied || !isinstalled(url, tarball_hash; prefix=prefix)
        # Download and install binaries
        install(url, tarball_hash; prefix=prefix, force=true, verbose=verbose)
    end
elseif unsatisfied
    # If we don't have a BinaryProvider-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 $(triplet(platform_key())) is not supported by this package!")
end

# Write out a deps.jl file that will contain mappings for our products
write_deps_file(joinpath(@__DIR__, "deps.jl"), products)


text:
# name = "KNITRO"
# KNITRO = "67920dd8-b58e-52a8-8622-53c4cffbe346"

using KNITRO

KNITRO_OPT = KNITRO.Optimizer()
MOI.set(KNITRO_OPT, MOI.Silent(), true)
MOI.set(KNITRO_OPT, MOI.TimeLimitSec(), 5)
# KNITRO_OPT = MOI.Bridges.Constraint.SOCtoNonConvexQuad{Float64}(KNITRO_OPT)

push!(solvers_complements, (opt = KNITRO_OPT, mode = BilevelJuMP.ComplementMode()))


text:
module TestGenerateJuliaPrograms

using Test

using Catlab, Catlab.Theories
using Catlab.Programs.GenerateJuliaPrograms

# Compilation
#############

# Note: Further tests of compilation are provided by the roundtripping
# integration tests in `TestParseJuliaPrograms`.

W, X, Y, Z = Ob(FreeCartesianCategory, :W, :X, :Y, :Z)
f, g, h = Hom(:f, X, Y), Hom(:g, Y, Z), Hom(:h, Z, W)

@test compile(f) isa Function
@test compile(compose(f,g)) isa Function
@test compile(otimes(f,h)) isa Function
@test compile(compose(f, mcopy(Y), otimes(g,g))) isa Function

# Evaluation
############

ℝ = Ob(FreeCartesianCategory, :ℝ)

plus, cos_hom, sin_hom = Hom(:+, ℝ⊗ℝ, ℝ), Hom(:cos, ℝ, ℝ), Hom(:sin, ℝ, ℝ)
generators = Dict{Symbol,Any}(:+ => +, :cos => cos, :sin => sin)
ev = (args...; kw...) -> evaluate(args...; generators=generators, kw...)

# Generators.
x = collect(range(-2,stop=2,length=50))
@test ev(sin_hom, π/2) == sin(π/2)
@test ev(cos_hom, x; broadcast=true) == cos.(x)

# Composition.
@test ev(compose(cos_hom, sin_hom), 1) == sin(cos(1))
@test ev(compose(cos_hom, sin_hom), x; broadcast=true) == sin.(cos.(x))
@test ev(id(ℝ), 1) == 1

# Symmetric monoidal product.
@test ev(otimes(cos_hom, sin_hom), 1, 2) == (cos(1), sin(2))
@test ev(otimes(cos_hom, sin_hom), x, x; broadcast=true) == (cos.(x), sin.(x))
@test ev(braid(ℝ,ℝ), 1, 2) == (2, 1)

# Copying and deleting.
@test ev(mcopy(ℝ), 1) == (1, 1)
@test ev(mcopy(ℝ⊗ℝ), 1, 2) == (1, 2, 1, 2)
@test ev(delete(ℝ), 1) == nothing
@test ev(delete(ℝ⊗ℝ), 1, 2) == nothing

f = compose(mcopy(ℝ), otimes(cos_hom, sin_hom), plus)
@test ev(f, 1) == cos(1) + sin(1)
@test ev(f, x; broadcast=true) == cos.(x) + sin.(x)

end


text:
"""
    nndescent(GraphT::Type{ApproximateKNNGraph}, data, n_neighbors, metric; kwargs...)

Find the approximate neighbors of each point in `data` by  iteratively
refining a KNN graph of type `GraphT`. Returns the final KNN graph.

# Keyword Arguments
- `max_iters = 10`: Limits the number of iterations to refine candidate
nearest neighbors. Higher values trade off speed for accuracy. Note that graph
construction may terminate early if little progress is being made.
- `sample_rate = 1`: The sample rate for calculating *local joins*
around each point. Lower values trade off accuracy for speed.
- `precision = 1e-3`: The threshold for early termination,
where precision is "roughly the fraction of true kNN allowed to be missed due to
early termination". Lower values take longer but return more accurate results.
"""
function nndescent(GraphT::Type{<:ApproximateKNNGraph},
                   data::AbstractVecOrMat,
                   n_neighbors::Integer,
                   metric::PreMetric;
                   max_iters = 10,
                   sample_rate = 1,
                   precision = 1e-3,
                  )

    validate_args(data, n_neighbors, metric, max_iters, sample_rate, precision)

    graph = GraphT(data, n_neighbors, metric)
    for i in 1:max_iters
        c = local_join!(graph; sample_rate=sample_rate)
        if c ≤ precision * n_neighbors * nv(graph)
            break
        end
    end
    return graph
end

"""
    nndescent(data, n_neighbors, metric; kwargs...)

Do nndescent using `HeapKNNGraph` as the KNN Graph type.
"""
nndescent(data, n_neighbors, metric; kwargs...) = nndescent(HeapKNNGraph, data, n_neighbors, metric; kwargs...)

"""
    local_join!(graph; kwargs...)

Perform a local join on each vertex `v`'s neighborhood `N[v]` in `graph`. Given vertex `v`
and its neighbors `N[v]`, compute the similarity `graph.metric(p, q)` for each pair `p, q ∈ N[v]`
and update `N[q]` and `N[p]`.

This mutates `graph` in-place and returns a nonnegative integer indicating how many neighbor
updates took place during the local join.
"""
function local_join! end

function local_join!(graph::HeapKNNGraph; sample_rate = 1)
    # find in and out neighbors - old neighbors have already participated in a previous local join
    data = graph.data
    metric = graph.metric
    old_neighbors, new_neighbors = get_neighbors!(graph, sample_rate)
    c = 0
    # compute local join
    for v in vertices(graph)
        for p in new_neighbors[v]
            for q in (q_ for q_ in new_neighbors[v] if p < q_)
                # both new
                dist = evaluate(metric, data[p], data[q])
                c += add_edge!(graph, edgetype(graph)(p, q, dist))
                if !(metric isa SemiMetric) # not symmetric
                    dist = evaluate(metric, data[q], data[p])
                end
                c += add_edge!(graph, edgetype(graph)(q, p, dist))

            end
            for q in (q_ for q_ in old_neighbors[v] if p != q_)
                # one new, one old
                dist = evaluate(metric, data[p], data[q])
                c += add_edge!(graph, edgetype(graph)(p, q, dist))
                if !(metric isa SemiMetric) # not symmetric
                    dist = evaluate(metric, data[q], data[p])
                end
                c += add_edge!(graph, edgetype(graph)(q, p, dist))
            end
        end
    end

    return c
end

function local_join!(graph::LockHeapKNNGraph; sample_rate = 1)
    data = graph.data
    metric = graph.metric
    old_neighbors, new_neighbors = get_neighbors!(graph, sample_rate)
    count = Threads.Atomic{Int}(0)
    # compute local join
    Threads.@threads for v in vertices(graph)
        for p in new_neighbors[v]
            for q in (q_ for q_ in new_neighbors[v] if p < q_)
                # both new
                dist = evaluate(metric, data[p], data[q])
                res = add_edge!(graph, edgetype(graph)(p, q, dist))
                Threads.atomic_add!(count, Int(res))
                if !(metric isa SemiMetric) # not symmetric
                    dist = evaluate(metric, data[q], data[p])
                end
                res = add_edge!(graph, edgetype(graph)(q, p, dist))
                Threads.atomic_add!(count, Int(res))
            end
            for q in (q_ for q_ in old_neighbors[v] if p != q_)
                # one new, one old
                dist = evaluate(metric, data[p], data[q])
                res = add_edge!(graph, edgetype(graph)(p, q, dist))
                Threads.atomic_add!(count, Int(res))
                if !(metric isa SemiMetric) # not symmetric
                    dist = evaluate(metric, data[q], data[p])
                end
                res = add_edge!(graph, edgetype(graph)(q, p, dist))
                Threads.atomic_add!(count, Int(res))
            end
        end
    end
    return count[]
end

"""
Get the neighbors of each point in a KNN graph `graph` as sets of integer ids.

For the NNDescent algorithm, these are separated into the old and new neighbors.
"""
function get_neighbors!(graph::ApproximateKNNGraph{V}, sample_rate=1) where V
    old_neighbors = [V[] for _ in 1:nv(graph)]
    new_neighbors = [V[] for _ in 1:nv(graph)]
    for ind in edge_indices(graph)
        @inbounds e = node_edge(graph, ind[1], ind[2])
        if flag(e) # isnew(e) => new edges haven't participated in local join
            if rand() ≤ sample_rate
                # mark sampled new forward neighbors as old
                @inbounds e = update_flag!(graph, ind[1], ind[2], false)
                push!(new_neighbors[src(e)], dst(e))
                push!(new_neighbors[dst(e)], src(e))
            end
        else # old neighbors
            # always include old forward
            push!(old_neighbors[src(e)], dst(e))
            # sample old reverse neighbors
            if rand() ≤ sample_rate
                push!(old_neighbors[dst(e)], src(e))
            end
        end
    end
    return (unique!).((sort!).(old_neighbors)), (unique!).((sort!).(new_neighbors))
end


text:
function getcelltype(nd,elemtype)

if nd==2
    if elemtype==0
        cell_t = 5;
    else
        cell_t = 9;
    end
elseif nd==3
    if elemtype==0
        cell_t = 10;
    else
        cell_t = 12;
    end
else
    error("Number of mesh spatial dimensions should be 2 or 3");
end

return cell_t

end

max_stars_repo_name: glwagner/Exasim

max_issues_repo_name: glwagner/Exasim

max_forks_repo_name: glwagner/Exasim


text:
# syntax: proto2
# COV_EXCL_START
using ProtoBuf
import ProtoBuf.meta
import ..hadoop

# service methods for ApplicationClientProtocolService
const _ApplicationClientProtocolService_methods = MethodDescriptor[
        MethodDescriptor("getNewApplication", 1, hadoop.yarn.GetNewApplicationRequestProto, hadoop.yarn.GetNewApplicationResponseProto),
        MethodDescriptor("getApplicationReport", 2, hadoop.yarn.GetApplicationReportRequestProto, hadoop.yarn.GetApplicationReportResponseProto),
        MethodDescriptor("submitApplication", 3, hadoop.yarn.SubmitApplicationRequestProto, hadoop.yarn.SubmitApplicationResponseProto),
        MethodDescriptor("failApplicationAttempt", 4, hadoop.yarn.FailApplicationAttemptRequestProto, hadoop.yarn.FailApplicationAttemptResponseProto),
        MethodDescriptor("forceKillApplication", 5, hadoop.yarn.KillApplicationRequestProto, hadoop.yarn.KillApplicationResponseProto),
        MethodDescriptor("getClusterMetrics", 6, hadoop.yarn.GetClusterMetricsRequestProto, hadoop.yarn.GetClusterMetricsResponseProto),
        MethodDescriptor("getApplications", 7, hadoop.yarn.GetApplicationsRequestProto, hadoop.yarn.GetApplicationsResponseProto),
        MethodDescriptor("getClusterNodes", 8, hadoop.yarn.GetClusterNodesRequestProto, hadoop.yarn.GetClusterNodesResponseProto),
        MethodDescriptor("getQueueInfo", 9, hadoop.yarn.GetQueueInfoRequestProto, hadoop.yarn.GetQueueInfoResponseProto),
        MethodDescriptor("getQueueUserAcls", 10, hadoop.yarn.GetQueueUserAclsInfoRequestProto, hadoop.yarn.GetQueueUserAclsInfoResponseProto),
        MethodDescriptor("getDelegationToken", 11, hadoop.common.GetDelegationTokenRequestProto, hadoop.common.GetDelegationTokenResponseProto),
        MethodDescriptor("renewDelegationToken", 12, hadoop.common.RenewDelegationTokenRequestProto, hadoop.common.RenewDelegationTokenResponseProto),
        MethodDescriptor("cancelDelegationToken", 13, hadoop.common.CancelDelegationTokenRequestProto, hadoop.common.CancelDelegationTokenResponseProto),
        MethodDescriptor("moveApplicationAcrossQueues", 14, hadoop.yarn.MoveApplicationAcrossQueuesRequestProto, hadoop.yarn.MoveApplicationAcrossQueuesResponseProto),
        MethodDescriptor("getApplicationAttemptReport", 15, hadoop.yarn.GetApplicationAttemptReportRequestProto, hadoop.yarn.GetApplicationAttemptReportResponseProto),
        MethodDescriptor("getApplicationAttempts", 16, hadoop.yarn.GetApplicationAttemptsRequestProto, hadoop.yarn.GetApplicationAttemptsResponseProto),
        MethodDescriptor("getContainerReport", 17, hadoop.yarn.GetContainerReportRequestProto, hadoop.yarn.GetContainerReportResponseProto),
        MethodDescriptor("getContainers", 18, hadoop.yarn.GetContainersRequestProto, hadoop.yarn.GetContainersResponseProto),
        MethodDescriptor("getNewReservation", 19, hadoop.yarn.GetNewReservationRequestProto, hadoop.yarn.GetNewReservationResponseProto),
        MethodDescriptor("submitReservation", 20, hadoop.yarn.ReservationSubmissionRequestProto, hadoop.yarn.ReservationSubmissionResponseProto),
        MethodDescriptor("updateReservation", 21, hadoop.yarn.ReservationUpdateRequestProto, hadoop.yarn.ReservationUpdateResponseProto),
        MethodDescriptor("deleteReservation", 22, hadoop.yarn.ReservationDeleteRequestProto, hadoop.yarn.ReservationDeleteResponseProto),
        MethodDescriptor("listReservations", 23, hadoop.yarn.ReservationListRequestProto, hadoop.yarn.ReservationListResponseProto),
        MethodDescriptor("getNodeToLabels", 24, hadoop.yarn.GetNodesToLabelsRequestProto, hadoop.yarn.GetNodesToLabelsResponseProto),
        MethodDescriptor("getLabelsToNodes", 25, hadoop.yarn.GetLabelsToNodesRequestProto, hadoop.yarn.GetLabelsToNodesResponseProto),
        MethodDescriptor("getClusterNodeLabels", 26, hadoop.yarn.GetClusterNodeLabelsRequestProto, hadoop.yarn.GetClusterNodeLabelsResponseProto),
        MethodDescriptor("updateApplicationPriority", 27, hadoop.yarn.UpdateApplicationPriorityRequestProto, hadoop.yarn.UpdateApplicationPriorityResponseProto),
        MethodDescriptor("signalToContainer", 28, hadoop.yarn.SignalContainerRequestProto, hadoop.yarn.SignalContainerResponseProto),
        MethodDescriptor("updateApplicationTimeouts", 29, hadoop.yarn.UpdateApplicationTimeoutsRequestProto, hadoop.yarn.UpdateApplicationTimeoutsResponseProto),
        MethodDescriptor("getResourceTypeInfo", 30, hadoop.yarn.GetAllResourceTypeInfoRequestProto, hadoop.yarn.GetAllResourceTypeInfoResponseProto)
    ] # const _ApplicationClientProtocolService_methods
const _ApplicationClientProtocolService_desc = ServiceDescriptor("hadoop.yarn.ApplicationClientProtocolService", 1, _ApplicationClientProtocolService_methods)

ApplicationClientProtocolService(impl::Module) = ProtoService(_ApplicationClientProtocolService_desc, impl)

mutable struct ApplicationClientProtocolServiceStub <: AbstractProtoServiceStub{false}
    impl::ProtoServiceStub
    ApplicationClientProtocolServiceStub(channel::ProtoRpcChannel) = new(ProtoServiceStub(_ApplicationClientProtocolService_desc, channel))
end # mutable struct ApplicationClientProtocolServiceStub

mutable struct ApplicationClientProtocolServiceBlockingStub <: AbstractProtoServiceStub{true}
    impl::ProtoServiceBlockingStub
    ApplicationClientProtocolServiceBlockingStub(channel::ProtoRpcChannel) = new(ProtoServiceBlockingStub(_ApplicationClientProtocolService_desc, channel))
end # mutable struct ApplicationClientProtocolServiceBlockingStub

getNewApplication(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetNewApplicationRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[1], controller, inp, done)
getNewApplication(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetNewApplicationRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[1], controller, inp)

getApplicationReport(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationReportRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[2], controller, inp, done)
getApplicationReport(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationReportRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[2], controller, inp)

submitApplication(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.SubmitApplicationRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[3], controller, inp, done)
submitApplication(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.SubmitApplicationRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[3], controller, inp)

failApplicationAttempt(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.FailApplicationAttemptRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[4], controller, inp, done)
failApplicationAttempt(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.FailApplicationAttemptRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[4], controller, inp)

forceKillApplication(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.KillApplicationRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[5], controller, inp, done)
forceKillApplication(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.KillApplicationRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[5], controller, inp)

getClusterMetrics(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetClusterMetricsRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[6], controller, inp, done)
getClusterMetrics(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetClusterMetricsRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[6], controller, inp)

getApplications(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationsRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[7], controller, inp, done)
getApplications(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationsRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[7], controller, inp)

getClusterNodes(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetClusterNodesRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[8], controller, inp, done)
getClusterNodes(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetClusterNodesRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[8], controller, inp)

getQueueInfo(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetQueueInfoRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[9], controller, inp, done)
getQueueInfo(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetQueueInfoRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[9], controller, inp)

getQueueUserAcls(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetQueueUserAclsInfoRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[10], controller, inp, done)
getQueueUserAcls(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetQueueUserAclsInfoRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[10], controller, inp)

getDelegationToken(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.common.GetDelegationTokenRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[11], controller, inp, done)
getDelegationToken(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.common.GetDelegationTokenRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[11], controller, inp)

renewDelegationToken(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.common.RenewDelegationTokenRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[12], controller, inp, done)
renewDelegationToken(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.common.RenewDelegationTokenRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[12], controller, inp)

cancelDelegationToken(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.common.CancelDelegationTokenRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[13], controller, inp, done)
cancelDelegationToken(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.common.CancelDelegationTokenRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[13], controller, inp)

moveApplicationAcrossQueues(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.MoveApplicationAcrossQueuesRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[14], controller, inp, done)
moveApplicationAcrossQueues(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.MoveApplicationAcrossQueuesRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[14], controller, inp)

getApplicationAttemptReport(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationAttemptReportRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[15], controller, inp, done)
getApplicationAttemptReport(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationAttemptReportRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[15], controller, inp)

getApplicationAttempts(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationAttemptsRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[16], controller, inp, done)
getApplicationAttempts(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetApplicationAttemptsRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[16], controller, inp)

getContainerReport(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetContainerReportRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[17], controller, inp, done)
getContainerReport(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetContainerReportRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[17], controller, inp)

getContainers(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetContainersRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[18], controller, inp, done)
getContainers(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetContainersRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[18], controller, inp)

getNewReservation(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetNewReservationRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[19], controller, inp, done)
getNewReservation(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetNewReservationRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[19], controller, inp)

submitReservation(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationSubmissionRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[20], controller, inp, done)
submitReservation(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationSubmissionRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[20], controller, inp)

updateReservation(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationUpdateRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[21], controller, inp, done)
updateReservation(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationUpdateRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[21], controller, inp)

deleteReservation(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationDeleteRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[22], controller, inp, done)
deleteReservation(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationDeleteRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[22], controller, inp)

listReservations(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationListRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[23], controller, inp, done)
listReservations(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.ReservationListRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[23], controller, inp)

getNodeToLabels(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetNodesToLabelsRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[24], controller, inp, done)
getNodeToLabels(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetNodesToLabelsRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[24], controller, inp)

getLabelsToNodes(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetLabelsToNodesRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[25], controller, inp, done)
getLabelsToNodes(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetLabelsToNodesRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[25], controller, inp)

getClusterNodeLabels(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetClusterNodeLabelsRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[26], controller, inp, done)
getClusterNodeLabels(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetClusterNodeLabelsRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[26], controller, inp)

updateApplicationPriority(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.UpdateApplicationPriorityRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[27], controller, inp, done)
updateApplicationPriority(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.UpdateApplicationPriorityRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[27], controller, inp)

signalToContainer(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.SignalContainerRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[28], controller, inp, done)
signalToContainer(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.SignalContainerRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[28], controller, inp)

updateApplicationTimeouts(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.UpdateApplicationTimeoutsRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[29], controller, inp, done)
updateApplicationTimeouts(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.UpdateApplicationTimeoutsRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[29], controller, inp)

getResourceTypeInfo(stub::ApplicationClientProtocolServiceStub, controller::ProtoRpcController, inp::hadoop.yarn.GetAllResourceTypeInfoRequestProto, done::Function) = call_method(stub.impl, _ApplicationClientProtocolService_methods[30], controller, inp, done)
getResourceTypeInfo(stub::ApplicationClientProtocolServiceBlockingStub, controller::ProtoRpcController, inp::hadoop.yarn.GetAllResourceTypeInfoRequestProto) = call_method(stub.impl, _ApplicationClientProtocolService_methods[30], controller, inp)

export ApplicationClientProtocolService, ApplicationClientProtocolServiceStub, ApplicationClientProtocolServiceBlockingStub, getNewApplication, getApplicationReport, submitApplication, failApplicationAttempt, forceKillApplication, getClusterMetrics, getApplications, getClusterNodes, getQueueInfo, getQueueUserAcls, getDelegationToken, renewDelegationToken, cancelDelegationToken, moveApplicationAcrossQueues, getApplicationAttemptReport, getApplicationAttempts, getContainerReport, getContainers, getNewReservation, submitReservation, updateReservation, deleteReservation, listReservations, getNodeToLabels, getLabelsToNodes, getClusterNodeLabels, updateApplicationPriority, signalToContainer, updateApplicationTimeouts, getResourceTypeInfo
# COV_EXCL_STOP


text:
export UsersList, UsersListResponse

@slackmethod(UsersList, "users.list",
    begin
        presence::Nullable{Int}
    end,

    begin
        members::Vector{User}
    end)


text:
module TestPrecompile2

using TestPrecompile
TestPrecompile.forgetful(2)

end # module


text:
@testset "Multiple Dispatch" begin

    @mockable foo(x::Int, y::Int) = 1
    @mockable foo(x::Int, y::Float64) = 2

    # Patch some methods
    apply(foo => (x::Int, y::Int) -> 3) do
        @test foo(1, 1) == 3
        @test foo(1, 2.0) == 2
    end

    # Patch all methods
    apply(foo => (x::Int, y::Int) -> 3,
          foo => (x::Int, y::Float64) -> 4) do
        @test foo(1, 1) == 3
        @test foo(1, 2.0) == 4
    end
end


text:
t = Template(; user=me)
pkg_dir = joinpath(t.dir, test_pkg)

@testset "TravisCI" begin
    @testset "Plugin creation" begin
        p = TravisCI()
        @test isempty(p.gitignore)
        @test p.src == joinpath(PkgTemplates.DEFAULTS_DIR, "travis.yml")
        @test p.dest == ".travis.yml"
        @test p.badges == [
            Badge(
                "Build Status",
                "https://travis-ci.com/{{USER}}/{{PKGNAME}}.jl.svg?branch=master",
                "https://travis-ci.com/{{USER}}/{{PKGNAME}}.jl",
            ),
        ]
        @test isempty(p.view)
        p = TravisCI(; config_file=nothing)
        @test p.src === nothing
        p = TravisCI(; config_file=test_file)
        @test p.src == test_file
        @test_throws ArgumentError TravisCI(; config_file=fake_path)
    end

    @testset "Badge generation" begin
        p = TravisCI()
        @test badges(p, me, test_pkg) == ["[![Build Status](https://travis-ci.com/$me/$test_pkg.jl.svg?branch=master)](https://travis-ci.com/$me/$test_pkg.jl)"]
    end

    @testset "File generation" begin
        # Without a coverage plugin in the template, there should be no post-test step.
        p = TravisCI()
        @test gen_plugin(p, t, test_pkg) == [".travis.yml"]
        @test isfile(joinpath(pkg_dir, ".travis.yml"))
        travis = read(joinpath(pkg_dir, ".travis.yml"), String)

        @test !occursin("after_success", travis)
        @test !occursin("Codecov.submit", travis)
        @test !occursin("Coveralls.submit", travis)
        @test !occursin("stage: Documentation", travis)
        rm(joinpath(pkg_dir, ".travis.yml"))

        # Generating the plugin with Codecov in the template should create a post-test step.
        t.plugins[Codecov] = Codecov()
        gen_plugin(p, t, test_pkg)
        delete!(t.plugins, Codecov)
        travis = read(joinpath(pkg_dir, ".travis.yml"), String)
        @test occursin("after_success", travis)
        @test occursin("Codecov.submit", travis)
        @test !occursin("Coveralls.submit", travis)
        @test !occursin("stage: Documentation", travis)
        rm(joinpath(pkg_dir, ".travis.yml"))

        # Coveralls should do the same.
        t.plugins[Coveralls] = Coveralls()
        gen_plugin(p, t, test_pkg)
        delete!(t.plugins, Coveralls)
        travis = read(joinpath(pkg_dir, ".travis.yml"), String)
        @test occursin("after_success", travis)
        @test occursin("Coveralls.submit", travis)
        @test !occursin("Codecov.submit", travis)
        @test !occursin("stage: Documentation", travis)
        rm(joinpath(pkg_dir, ".travis.yml"))

        # With a Documenter plugin, there should be a docs deployment step.
        t.plugins[GitHubPages] = GitHubPages()
        gen_plugin(p, t, test_pkg)
        delete!(t.plugins, GitHubPages)
        travis = read(joinpath(pkg_dir, ".travis.yml"), String)
        @test occursin("after_success", travis)
        @test occursin("stage: Documentation", travis)
        @test !occursin("Codecov.submit", travis)
        @test !occursin("Coveralls.submit", travis)
        rm(joinpath(pkg_dir, ".travis.yml"))

        p = TravisCI(; config_file=nothing)
        @test isempty(gen_plugin(p, t, test_pkg))
        @test !isfile(joinpath(pkg_dir, ".travis.yml"))
    end
end

rm(pkg_dir; recursive=true)


text:
# # [Sparse Identification with noisy data](@id noisy_sindy)
#
# Many real world data sources are corrupted with measurment noise, which can have
# a big impact on the recovery of the underlying equations of motion. This example show how we can
# use [`collocation`](@ref collocation) and [`batching`](@ref DataSampler) to perform SINDy in the presence of
# noise.

using DataDrivenDiffEq
using LinearAlgebra
using ModelingToolkit
using OrdinaryDiffEq
#md using Plots
#md gr()

function pendulum(u, p, t)
    x = u[2]
    y = -9.81sin(u[1]) - 0.3u[2]^3 -3.0*cos(u[1]) - 10.0*exp(-((t-5.0)/5.0)^2)
    return [x;y]
end

u0 = [0.99π; -1.0]
tspan = (0.0, 15.0)
prob = ODEProblem(pendulum, u0, tspan)
sol = solve(prob, Tsit5(), saveat = 0.01);

# We add random noise to our measurements.

X = sol[:,:] + 0.2 .* randn(size(sol));
ts = sol.t;

#md plot(ts, X', color = :red)
#md plot!(sol, color = :black)

# To estimate the system, we first create a [`DataDrivenProblem`](@ref) via feeding in the measurement data.
# Using a [Collocation](@ref) method, it automatically provides the derivative and smoothes the trajectory. Control signals can be passed
# in as a function `(u,p,t)->control` or an array of measurements.

prob = ContinuousDataDrivenProblem(X, ts, GaussianKernel() ,
    U = (u,p,t)->[exp(-((t-5.0)/5.0)^2)], p = ones(2))

#md plot(prob, size = (600,600))

# Now we infer the system structure. First we define a [`Basis`](@ref) which collects all possible candidate terms.
# Since we want to use SINDy, we call `solve` with an [`Optimizer`](@ref sparse_optimization), in this case [`STLSQ`](@ref) which iterates different sparsity thresholds
# and returns a pareto optimal solution of the underlying [`sparse_regression!`](@ref). Note that we include the control signal in the basis as an additional variable `c`.

@variables u[1:2] c[1:1]
@parameters w[1:2]
u = collect(u)
c = collect(c)
w = collect(w)

h = Num[sin.(w[1].*u[1]);cos.(w[2].*u[1]); polynomial_basis(u, 5); c]

basis = Basis(h, u, parameters = w, controls = c)

# To solve the problem, we also define a [`DataSampler`](@ref) which defines randomly shuffled minibatches of our data and selects the
# best fit.

sampler = DataSampler(Batcher(n = 5, shuffle = true, repeated = true))
λs = exp10.(-10:0.1:-1)
opt = STLSQ(λs)
res = solve(prob, basis, opt, progress = false, sampler = sampler, denoise = false, normalize = false, maxiter = 5000)
println(res) #hide

# !!! info
#     A more detailed description of the result can be printed via `print(res, Val{true})`, which also includes the discovered equations and parameter values.
#
# Where the resulting [`DataDrivenSolution`](@ref) stores information about the inferred model and the parameters:

system = result(res)
params = parameters(res)
println(system) #hide
println(params) #hide

# And a visual check of the result can be perfomed via plotting the result

#md plot(
#md     plot(prob), plot(res), layout = (1,2)
#md )

#md # ## [Copy-Pasteable Code](@id autoregulation_copy_paste)
#md #
#md # ```julia
#md # @__CODE__
#md # ```

## Test #src
for r_ in [res] #src
    @test all(aic(r_) .> 1e3) #src
    @test all(determination(r_) .>= 0.9) #src
end #src


text:
import HTTP, JSON2
using Test
using Dash

@testset "callid" begin
    id = callid"id1.prop1 => id2.prop2"
    @test id isa CallbackId
    @test length(id.state) == 0
    @test length(id.input) == 1
    @test length(id.output) == 1
    @test id.input[1] == (:id1, :prop1)
    @test id.output[1] == (:id2, :prop2)

    id = callid"{state1.prop1, state2.prop2} input1.prop1, input2.prop2 => output1.prop1, output2.prop2"
    @test id isa CallbackId
    @test length(id.state) == 2
    @test length(id.input) == 2
    @test length(id.output) == 2
    @test id.input[1] == (:input1, :prop1)
    @test id.input[2] == (:input2, :prop2)
    @test id.output[1] == (:output1, :prop1)
    @test id.output[2] == (:output2, :prop2)
    @test id.state[1] == (:state1, :prop1)
    @test id.state[2] == (:state2, :prop2)
end

@testset "callback!" begin
    app = dash()
    app.layout = html_div() do
            dcc_input(id = "my-id", value="initial value", type = "text"),
            html_div(id = "my-div")
        end

    callback!(app, callid"my-id.value => my-div.children") do value
        return value
    end
    @test length(app.callbacks) == 1
    @test haskey(app.callbacks, Symbol("my-div.children"))
    @test app.callbacks[Symbol("my-div.children")].func("test") == "test"

    handler = make_handler(app)
    request = HTTP.Request("GET", "/_dash-dependencies")
    resp = HTTP.handle(handler, request)
    deps = JSON2.read(String(resp.body))

    @test length(deps) == 1
    cb = deps[1]
    @test cb.output == "my-div.children"
    @test cb.inputs[1].id == "my-id"
    @test cb.inputs[1].property == "value"
    @test :clientside_function in keys(cb)
    @test isnothing(cb.clientside_function)

    app = dash()
    app.layout = html_div() do
            dcc_input(id = "my-id", value="initial value", type = "text"),
            html_div(id = "my-div"),
            html_div(id = "my-div2")
        end
    callback!(app, callid"{my-id.type} my-id.value => my-div.children, my-div2.children") do state, value
        return state, value
    end
    @test length(app.callbacks) == 1
    @test haskey(app.callbacks, Symbol("..my-div.children...my-div2.children.."))
    @test app.callbacks[Symbol("..my-div.children...my-div2.children..")].func("state", "value") == ("state", "value")

    app = dash()

    app.layout = html_div() do
            dcc_input(id = "my-id", value="initial value", type = "text"),
            html_div(id = "my-div"),
            html_div(id = "my-div2")
        end

    callback!(app, callid"my-id.value => my-div.children") do value
        return value
    end
    callback!(app, callid"my-id.value => my-div2.children") do value
        return "v_$(value)"
    end

    @test length(app.callbacks) == 2
    @test haskey(app.callbacks, Symbol("my-div.children"))
    @test haskey(app.callbacks, Symbol("my-div2.children"))
    @test app.callbacks[Symbol("my-div.children")].func("value") == "value"
    @test app.callbacks[Symbol("my-div2.children")].func("value") == "v_value"

    @test_throws ErrorException callback!(app, callid"my-id.value => my-div2.children") do value
        return "v_$(value)"
    end

    @test_throws ErrorException callback!(app, callid"{my-id.value} my-id.value => my-id.value") do value
        return "v_$(value)"
    end

    @test_throws ErrorException callback!(app, callid"my-div.children, my-id.value => my-id.value") do value
        return "v_$(value)"
    end
    @test_throws ErrorException callback!(app, callid"my-id.value => my-div.children, my-id.value") do value
        return "v_$(value)"
    end

    @test_throws ErrorException callback!(app, callid" => my-div2.title, my-id.value") do value
        return "v_$(value)"
    end

    @test_throws ErrorException callback!(app, callid"my-id.value => my-div2.title, my-div2.title") do value
        return "v_$(value)"
    end

    @test_throws ErrorException callback!(app, callid"my-id.value => my-div2.title") do
        return "v_"
    end

    app = dash()
    app.layout = html_div() do
            dcc_input(id = "my-id", value="initial value", type = "text"),
            html_div("test2", id = "my-div"),
            html_div(id = "my-div2") do
                html_h1("gggg", id = "my-h")
            end
        end
    callback!(app, callid"{my-id.type} my-id.value => my-div.children, my-h.children") do state, value
        return state, value
    end
    @test length(app.callbacks) == 1
end

@testset "clientside callbacks function" begin
    app = dash()
    app.layout = html_div() do
            dcc_input(id = "my-id", value="initial value", type = "text"),
            html_div(id = "my-div")
        end

    callback!(ClientsideFunction("namespace", "func_name"),app, callid"my-id.value => my-div.children")

    @test length(app.callbacks) == 1
    @test haskey(app.callbacks, Symbol("my-div.children"))
    @test app.callbacks[Symbol("my-div.children")].func isa ClientsideFunction
    @test app.callbacks[Symbol("my-div.children")].func.namespace == "namespace"
    @test app.callbacks[Symbol("my-div.children")].func.function_name == "func_name"

    @test_throws ErrorException callback!(app, callid"my-id.value => my-div.children") do value
        return "v_$(value)"
    end

    handler = make_handler(app)
    request = HTTP.Request("GET", "/_dash-dependencies")
    resp = HTTP.handle(handler, request)
    deps = JSON2.read(String(resp.body))

    @test length(deps) == 1
    cb = deps[1]
    @test cb.output == "my-div.children"
    @test cb.inputs[1].id == "my-id"
    @test cb.inputs[1].property == "value"
    @test :clientside_function in keys(cb)
    @test cb.clientside_function.namespace == "namespace"
    @test cb.clientside_function.function_name == "func_name"
end
@testset "clientside callbacks string" begin
    app = dash()
    app.layout = html_div() do
            dcc_input(id = "my-id", value="initial value", type = "text"),
            html_div(id = "my-div")
        end

    callback!(
        """
        function(input_value) {
            return (
                parseFloat(input_value_1, 10)
            );
        }
        """
        , app, callid"my-id.value => my-div.children"
        )

    @test length(app.callbacks) == 1
    @test haskey(app.callbacks, Symbol("my-div.children"))
    @test app.callbacks[Symbol("my-div.children")].func isa ClientsideFunction
    @test app.callbacks[Symbol("my-div.children")].func.namespace == "_dashprivate_my-div"
    @test app.callbacks[Symbol("my-div.children")].func.function_name == "children"
    @test length(app.inline_scripts) == 1
    @test occursin("clientside[\"_dashprivate_my-div\"]", app.inline_scripts[1])
    @test occursin("ns[\"children\"]", app.inline_scripts[1])

    handler = make_handler(app)
    request = HTTP.Request("GET", "/_dash-dependencies")
    resp = HTTP.handle(handler, request)
    deps = JSON2.read(String(resp.body))

    @test length(deps) == 1
    cb = deps[1]
    @test cb.output == "my-div.children"
    @test cb.inputs[1].id == "my-id"
    @test cb.inputs[1].property == "value"
    @test :clientside_function in keys(cb)
    @test cb.clientside_function.namespace == "_dashprivate_my-div"
    @test cb.clientside_function.function_name == "children"
    request = HTTP.Request("GET", "/")
    resp = HTTP.handle(handler, request)
    body = String(resp.body)
    @test occursin("clientside[\"_dashprivate_my-div\"]", body)
    @test occursin("ns[\"children\"]", body)
end


text:
# %% Fractal dimension of chaotic attractors
using DrWatson
@quickactivate "NonlinearDynamicsTextbook"
include(srcdir("style.jl"))
using DynamicalSystems, PyPlot, Statistics, DelimitedFiles

fig = figure()
ax_ts = fig.add_subplot(1,3,1)
ax_3d = fig.add_subplot(1,3,2; projection = "3d")
ax_fd = fig.add_subplot(1,3,3)

vostok = readdlm(projectdir("exercise_data", "17.csv"))
time = vostok[:, 1]
δT = vostok[:, 2]

# ax_ts.plot(time, δT; lw = 1.0, alpha = 0.5)

# Interpolate Vostok data
using Dierckx
# interpolation object:
spl = Spline1D(time, δT; k=3, bc="extrapolate")
# equi-spaced time vector:
t = range(minimum(time), maximum(time); length = 2000)

T = spl(t)

ax_ts.plot(t ./ 1000, T; lw = 1.0)
ax_ts.set_xlabel("time (kyr)")
ax_ts.set_ylabel("\$\\delta T\$ (K)")

ax_ts.set_xticks([0, 200, 400])
ax_ts.set_xticklabels([0, -200, -400])

# mi = selfmutualinfo(T, 1:1000)
# ax_fd.plot(1:1000, mi)
τ = 75 # inspect the above plot to see a good delay time

# plot attractor
R = embed(T, 3, τ)
ax_3d.plot(columns(R)...; lw = 1.0)
ax_3d.set_xticklabels([])
ax_3d.set_yticklabels([])
ax_3d.set_zticklabels([])
ax_3d.dist=8
ax_3d.text(5, 0, 7, "b"; bbox = bbox, zorder = 99, va = "top")

# estimate fractal dim
ds = 3:12
colors = matplotlib.cm.inferno(ds ./ (ds[end] + 2))
es = estimate_boxsizes(R; z = 0)

for (i, d) in enumerate(ds)
    A = embed(T, d, τ)
    Cs = boxed_correlationsum(A, es)
    j = findfirst(z -> z > 0, Cs)
    x, y = log.(es)[j:end], log.(Cs)[j:end]
    # x, y = log.(es), log.(Cs)
    # li, Δ = linear_region(x, y)
    c = colors[i, :]
    ax_fd.plot(x, y; color = c, lw = 1.5)
    # li = findall(z -> -4 ≤ z ≤ 0, x)
    _, Δ = linreg(x, y)
    @show (d, Δ)
    # ax_fd.plot(x[[1, end]], y[[1, end]],
    # zorder = 2, ms = 10, marker = "o", ls = "None", color = c, alpha = 0.75,
    # label = "d=$(d), Δ=$(round(Δ; digits=2))", )
end

# Show two regions
# ax_fd.axvspan(-3, -0.25; color = "C1", alpha = 0.1)
el1 = matplotlib.patches.Ellipse(
    (-1, -10), 3, 5; angle = -15, linewidth = 2, color = "C1",
    fill = false
)
ax_fd.add_patch(el1)
el2 = matplotlib.patches.Ellipse(
    (0.5, -5), 4, 6; angle = -20, linewidth = 2, color = "C2",
    fill = false
)
ax_fd.add_patch(el2)

ax_fd.set_xlabel("\$\\log(\\varepsilon)\$")
ax_fd.set_ylabel("\$\\log(C)\$";labelpad = -10)
ax_fd.set_yticks(0:-4:-12)
add_identifiers!(fig)
fig.tight_layout(;pad = 0.3)
fig.tight_layout(;pad = 0.33)
wsave(plotsdir("12", "vostok"), fig)

max_stars_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_issues_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_forks_repo_name: JuliaDynamics/NonlinearDynamicsTextbook


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "Clipper"
version = v"6.4.2"

# Collection of sources required to build Clipper
sources = [
    ArchiveSource("https://downloads.sourceforge.net/project/polyclipping/clipper_ver6.4.2.zip", "a14320d82194807c4480ce59c98aa71cd4175a5156645c4e2b3edd330b930627"),
    DirectorySource("./cwrapper")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/
cp cclipper.cpp ./cpp/cclipper.cpp
cd cpp
mkdir "${libdir}"
${CXX} -fPIC -std=c++11 -shared -o "${libdir}/libcclipper.${dlext}" clipper.cpp cclipper.cpp
cd ..
install_license License.txt
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms())
# The products that we will ensure are always built
products = [
    LibraryProduct("libcclipper", :libcclipper)
]

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

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
#-------------barnes_hut.jl----------------------------------------------------#
#
# Purpose: To implement the Barnes-Hut galaxy simulator in julia
#
#------------------------------------------------------------------------------#

# Type for particles later to be used with Verlet integration
type Particle
    p::Vector{Float64}
    prev_p::Vector{Float64}
    vel::Vector{Float64}
    acc::Vector{Float64}
    mass::Float64
    radius::Float64

    Particle(p::Vector{Float64}, prev_p::Vector{Float64}, vel::Vector{Float64},
             acc::Vector{Float64}, mass::Float64, radius::Float64) =
        new(p, prev_p, vel, acc, mass, radius)
end

# type for node, to be used as an octree
type Node
    p::Vector{Float64}
    box_length::Float64
    parent::Nullable{Node}
    children::Vector{Node}
    com::Particle
    p_vec::Vector{Particle}
    Node(p::Vector{Float64}, box_length::Float64, parent::Nullable{Node},
         children::Vector{Node}, com::Particle, p_vec::Vector{Particle}) =
        new(p, box_length, parent, children, com, p_vec)
end

#------------------------------------------------------------------------------#
# SUBROUTINES
#------------------------------------------------------------------------------@

# Function to create random distribution
function create_rand_dist(box_length::Float64, pnum::Int)
    # initialize p_vec
    p_vec = fill(Particle(zeros(3), zeros(3), zeros(3), zeros(3),1.0,1.0), 0)
    for i = 1:pnum
        push!(p_vec, Particle(rand(3)*box_length-(box_length * 0.5),
                              rand(3)*box_length-(box_length * 0.5),
                              rand(3)*box_length-(box_length * 0.5),
                              rand(3)*box_length-(box_length * 0.5),
                              1, 1))
    end
    return p_vec
end

# Function to initialize root node of octree
function make_octree(p_vec::Vector{Particle}, box_length::Float64)
    com = Particle(zeros(3), zeros(3), zeros(3), zeros(3),1.0,1.0)
    root = Node([0.0; 0.0; 0.0], box_length, Nullable{Node}(),
                Array(Node, 0), com, p_vec)
    return root
end

# Function to create children in a given node
function make_octchild(curr::Node)
    node_length = curr.box_length * 0.5
    quarter_box = curr.box_length * 0.25

    # Defining null com
    com = Particle(zeros(3), zeros(3), zeros(3), zeros(3),1.0,1.0)

    # iterating through possible location for new children nodes
    # wrtten by laurensbl
    for k = -1:2:1
        for j = -1:2:1
            for i = -1:2:1
                n = 2 * k + j + (i+1)/2 + 3;
                push!(curr.children, Node([curr.p[1] + k * quarter_box;
                                      curr.p[2] + j * quarter_box;
                                      curr.p[3] + i * quarter_box],
                                      curr.box_length*.5, Nullable{Node}(curr),
                                      Array(Node, 0), com,
                                      fill(com,0)))
            end
        end
    end
end

# Function to check if we are in a box
function in_box(curr::Node, p::Particle)
    half_box = curr.box_length * 0.5
    return p.p[1] >= curr.p[1] - half_box &&
           p.p[1] <  curr.p[1] + half_box &&
           p.p[2] >= curr.p[2] - half_box &&
           p.p[2] <  curr.p[2] + half_box &&
           p.p[3] >= curr.p[3] - half_box &&
           p.p[3] <  curr.p[3] + half_box

end

# Function to divide root node onto octree
function divide_octree(curr::Node, box_threshold::Int64)
    make_octchild(curr)
    for i = 1:8
        for p in curr.p_vec
            if (in_box(curr.children[i], p))
                push!(curr.children[i].p_vec, p)
                curr.children[i].p += p.p * p.mass
                curr.children[i].com.mass += p.mass
            end
        end
        curr.children[i].com.p /= curr.children[i].com.mass
        if (length(curr.children[i].p_vec) > box_threshold)
            divide_octree(curr.children[i], box_threshold)
        end
    end
end

# Function to output particle positions
# Note: Don't forget to opena nd close file surrounding this function
function particle_output(curr::Node, file::IOStream)
    if (length(curr.p_vec) == 1)
        writedlm(file,curr.p_vec[1].p')
    end

    for child in curr.children
        particle_output(child, file)
    end
end

# Function to find acceleration of single particle
function RKsearch(curr::Node, part::Particle)
    d = -part.p
    inverse_r = 1/sqrt(d[1]*d[1] + d[2]*d[2] + d[3]*d[3])

    if (inverse_r > 10.0)
        inverse_r = 10.0
    end
    if (inverse_r < -10.0)
        inverse_r = -10.0
    end

    part.acc += d * inverse_r * 10.0

end

# Verlet integration
function verlet(part::Particle, dt::Float64)
    temp = part.p
    part.p = 2 * part.p - part.prev_p + part.acc * dt * dt
    part.prev_p = temp
end

# Function to find acceleration of particles in Barnes-Hut tree
function force_integrate(root::Node, dt::Float64)

    # Going through all particles in p_vec to find a new acceleration
    for part in root.p_vec
        RKsearch(root, part)
    end

    # Going through all particles and updating position
    for part in root.p_vec
        verlet(part, dt)
    end

end

# Main function
function main()
    numsteps = 5
    p_output = open("pout_julia.dat", "w")

    vel = sqrt(10)
    dt = 0.01
    p_vec = fill(Particle([1.0; 0.0; 0.0],[cos(vel*dt); sin(vel*dt); 0.0],
                 [0.0; vel; 0.0],zeros(3),1E10,1.0), 1)
    println(p_vec[1].prev_p)

    root = make_octree(p_vec, 1000.0)
    divide_octree(root, 1)

    for i = 1:numsteps
        root = make_octree(p_vec, 1000.0)
        divide_octree(root, 1)
        if (i % 1 == 0 || (i-1) == 0)
            particle_output(root, p_output)
            write(p_output, "\n\n")
        end
        force_integrate(root, 0.01)
    end

    close(p_output)
end

@time main()

max_stars_repo_name: vchuravy/skillpill-julia

max_issues_repo_name: shiffman/simuleios

max_forks_repo_name: shiffman/simuleios


text:
function _initialization_attempt(mcmc::MCMC{S, M},
                                 max_lposterior::Float64) where {
                                 S <: DiseaseStateSequence,
                                 M <: ILM}
  events = generate(Events, mcmc)
  rparams = generate(RiskParameters, mcmc)
  lprior = logprior(rparams, mcmc.risk_priors)
  if M <: PhyloILM
    sm = generate(mcmc.substitution_model, mcmc.substitution_model_prior)
    lprior += logprior(sm, mcmc.substitution_model_prior)
  end
  llikelihood, tr, tx = loglikelihood(rparams,
                                      mcmc.risk_functions,
                                      events,
                                      mcmc.population,
                                      mcmc.starting_states,
                                      early_decision_value = max_lposterior - lprior)
  lposterior = llikelihood + lprior
  if lposterior > max_lposterior
    network = generate(TransmissionNetwork, tr, mcmc, tx)
    if M <: PhyloILM
      tree, obs_nodes = generate(Tree, events, mcmc.event_observations, network)
      leaf_data = Dict{Int64, RNASeq}()
      for k = eachindex(obs_nodes)
        if !isnothing(obs_nodes[k])
          leaf_data[obs_nodes[k]] = mcmc.event_observations.seq[k]
        end
      end
      lposterior += PhyloModels.loglikelihood(tree, sm, leaf_data)
    end
  end
  if lposterior > max_lposterior
    if M <: PhyloILM
      return MarkovChain{S, M}(events, network, rparams, sm, lposterior)
    elseif M <: TNILM
      return MarkovChain{S, M}(events, network, rparams, lposterior)
    end
  else
    return nothing
  end
end

function initialize(::Type{MarkovChain},
                    mcmc::MCMC{S, M},
                    progress_channel::RemoteChannel;
                    attempts::Int64=1000) where {
                    S <: DiseaseStateSequence,
                    M <: ILM}
  if attempts <= 0
    throw(ErrorException("Must have at least 1 initialization attempt"))
  end
  local markov_chain
  max_lposterior = -Inf
  for i in 1:attempts
    initialization = _initialization_attempt(mcmc, max_lposterior)
    if initialization !== nothing
      markov_chain = initialization
      max_lposterior = markov_chain.log_posterior[1]
    end
    put!(progress_channel, true)
  end
  if max_lposterior == -Inf
    @error "Failed to initialize Markov Chain"
    markov_chain = nothing
  end
  return markov_chain
end

function initialize(::Type{MarkovChain},
                    mcmc::MCMC{S, M};
                    attempts::Int64=1000) where {
                    S <: DiseaseStateSequence,
                    M <: ILM}
  if attempts <= 0
    throw(ErrorException("Must have at least 1 initialization attempt"))
  end
  max_lposterior = -Inf
  local markov_chain
  pmeter = Progress(attempts, "Initialization progress")
  for i in 1:attempts
    initialization = _initialization_attempt(mcmc, max_lposterior)
    if initialization !== nothing
      markov_chain = initialization
      max_lposterior = markov_chain.log_posterior[1]
    end
    next!(pmeter)
  end
  finish!(pmeter)
  if max_lposterior == -Inf
    @error "Failed to initialize Markov Chain"
    markov_chain = nothing
  end
  return markov_chain
end


text:
"""
    solub_co2(temp[, salinity=0.])

Calculate CO2 solubility in natural water.

# Parameters

* `temp`: Temperature in Kelvin.
* `salinity` (*optional*): Salinity in per mil mass fraction (g kg^-1 seawater).

# Returns

Bunsen solubility coefficient of COS [dimensionless].

# See also

`solub_cos` : Calculate COS solubility in pure water.

# References

[MR71] Murray, C. N. and Riley, J. P. (1971). The solubility of gases
    in distilled water and seawater--IV. Carbon dioxide. *Deep-Sea Res.*, 18,
    533--541. <https://doi.org/10.1016/0011-7471(71)90077-5>.

[W74] Weiss, R. F. (1974). Carbon dioxide in water and seawater: the solubility
    of a non-ideal gas. *Mar. Chem.*, 2, 203--215.
    <https://doi.org/10.1016/0304-4203(74)90015-2>.

# Examples

```jldoctest
julia> @printf "%g" solub_co2(298.15)
0.831005
```
"""
function solub_co2(temp, salinity=0.)
    t = temp * 1e-2  # a transferred scale
    kcp_co2 = exp(-58.0931 + 90.5069 / t + 22.2940 * log(t) +
                     salinity * (0.027766 - 0.025888 * t + 0.0050578 * t * t))
    # Note: kcp = c_aq / p_i [mol L^-1 atm^-1], where p_i is the partial
    # pressure. To convert it to the Bunsen solubility [dimensionless],
    # multiply kcp by the air molar concentration at the standard pressure
    # [mol m^-3]. There is no pressure dependence because it cancels out.
    air_conc = Constants.atm / (Constants.R * temp)
    return kcp_co2 * 1e3 / air_conc
end

"""
    solub_cos(temp)

Calculate COS solubility in pure water.

# Parameters

`temp`: Temperature in Kelvin.

# Returns

Bunsen solubility coefficient of COS [dimensionless].

# See also

`solub_co2` : Calculate CO2 solubility in natural water.

# References

[E89] Elliott, S., Lu, E., and Rowland, F. S. (1989). Rates and
    mechanisms for the hydrolysis of carbonyl sulfide in natural waters.
    *Environ. Sci. Tech*. 23(4), 458--461.
    <https://doi.org/10.1021/es00181a011>.

# Examples

```jldoctest
julia> @printf "%g" solub_cos(298.15)
0.487598
```
"""
function solub_cos(temp)
    return temp * exp(4050.32 / temp - 20.0007)
end