MDA broken pipe with fetchmail / dovecot

Question: I have set up a home mail server with dovecot to download and archive email from multiple webmail accounts via IMAP. The goal is to do this automatically every week with a cron job.
I'm not sure if I should use dovecot sync/backup or fetchmail, but the latter being popular I tried fetchmail first. However, it doesn't seem to work, I get this:
user@mail:~$ fetchmail
38081 messages for firstname.lastname@example.com at imap.fastmail.com (folder Archive).
fetchmail: Error writing to MDA: Broken pipe
reading message firstname.lastname@example.com@imap.fastmail.com:1 of 38081 (2100 header octets) (726 body octets) not flushed
reading message email@example.com@imap.fastmail.com:2 of 38081 (4404 header octets) (6082 body octets)fetchmail: error writing message text
fetchmail: MDA error while fetching from email@example.com@imap.fastmail.com
fetchmail: Query status=6 (IOERR)

~/.fetchmailrc looks like this:
poll imap.fastmail.com protocol IMAP
     user "email@example.com" is "user@localhost" here
     folder Archive
     ssl fetchall
     mda "/usr/lib/dovecot/deliver -d user@localhost -m .fastmail.Archive"

The .fastmail.Archive folder is at the root of ~/Maildir. I am using Maildir in my dovecot config.
in ~/.netrc I have the following:
machine imap.fastmail.com
login firstname.lastname@example.com
password <secret>

I also ran deliver manually using strace as root, and I am not getting any message delivered when I check my ~/Maildir afterwards. Here is the output, not sure what to make of it.
root@mail:/home/user/fastmail# strace /usr/lib/dovecot/deliver -d user@localhost < 'test.eml'
execve("/usr/lib/dovecot/deliver", ["/usr/lib/dovecot/deliver", "-d", "user@localhost"], 0x7ffcd6f61be0 /* 12 vars */) = 0
brk(NULL)                               = 0x5593bc6d8000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/tls/x86_64/x86_64/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/tls/x86_64/x86_64", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/tls/x86_64/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/tls/x86_64", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/tls/x86_64/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/tls/x86_64", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/tls/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/tls", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/x86_64/x86_64/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/x86_64/x86_64", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/x86_64/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/x86_64", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/x86_64/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
stat("/usr/lib/dovecot/x86_64", 0x7fffbb1506b0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/lib/dovecot/libdovecot-lda.so.0", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\3206\0\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=34968, ...}) = 0
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f99e4722000
mmap(NULL, 37136, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f99e4718000
mmap(0x7f99e471b000, 12288, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7f99e471b000
mmap(0x7f99e471e000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x6000) = 0x7f99e471e000
mmap(0x7f99e4720000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x7000) = 0x7f99e4720000
close(3)                                = 0
openat(AT_FDCWD, "/usr/lib/dovecot/libdovecot-storage.so.0", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0000\332\3\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=1436376, ...}) = 0
mmap(NULL, 1439128, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f99e45b8000
mprotect(0x7f99e45ee000, 1167360, PROT_NONE) = 0
mmap(0x7f99e45ee000, 856064, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x36000) = 0x7f99e45ee000
mmap(0x7f99e46bf000, 307200, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x107000) = 0x7f99e46bf000
mmap(0x7f99e470b000, 53248, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x152000) = 0x7f99e470b000
close(3)                                = 0
openat(AT_FDCWD, "/usr/lib/dovecot/libdovecot.so.0", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\300\337\3\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=1619272, ...}) = 0
mmap(NULL, 1632856, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f99e4429000
mmap(0x7f99e4460000, 909312, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x37000) = 0x7f99e4460000
mmap(0x7f99e453e000, 450560, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x115000) = 0x7f99e453e000
mmap(0x7f99e45ac000, 36864, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x182000) = 0x7f99e45ac000
mmap(0x7f99e45b5000, 10840, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f99e45b5000
close(3)                                = 0
openat(AT_FDCWD, "/usr/lib/dovecot/libc.so.6", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=35918, ...}) = 0
mmap(NULL, 35918, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f99e4420000
close(3)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260A\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1824496, ...}) = 0
mmap(NULL, 1837056, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f99e425f000
mprotect(0x7f99e4281000, 1658880, PROT_NONE) = 0
mmap(0x7f99e4281000, 1343488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22000) = 0x7f99e4281000
mmap(0x7f99e43c9000, 311296, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a000) = 0x7f99e43c9000
mmap(0x7f99e4416000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b6000) = 0x7f99e4416000
mmap(0x7f99e441c000, 14336, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f99e441c000
close(3)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libdl.so.2", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0000\21\0\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=14592, ...}) = 0
mmap(NULL, 16656, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f99e425a000
mmap(0x7f99e425b000, 4096, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1000) = 0x7f99e425b000
mmap(0x7f99e425c000, 4096, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x2000) = 0x7f99e425c000
mmap(0x7f99e425d000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x2000) = 0x7f99e425d000
close(3)                                = 0
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f99e4258000
arch_prctl(ARCH_SET_FS, 0x7f99e4259000) = 0
mprotect(0x7f99e4416000, 16384, PROT_READ) = 0
mprotect(0x7f99e425d000, 4096, PROT_READ) = 0
mprotect(0x7f99e45ac000, 32768, PROT_READ) = 0
mprotect(0x7f99e470b000, 28672, PROT_READ) = 0
mprotect(0x7f99e4720000, 4096, PROT_READ) = 0
mprotect(0x5593baf97000, 4096, PROT_READ) = 0
mprotect(0x7f99e474b000, 4096, PROT_READ) = 0
munmap(0x7f99e4420000, 35918)           = 0
getuid()                                = 0
geteuid()                               = 0
getrandom("\x1c\x75\x34\x6d", 4, 0)     = 4
brk(NULL)                               = 0x5593bc6d8000
brk(0x5593bc6f9000)                     = 0x5593bc6f9000
uname({sysname="Linux", nodename="mail", ...}) = 0
getpid()                                = 7234
openat(AT_FDCWD, "/dev/null", O_WRONLY) = 3
fcntl(3, F_GETFD)                       = 0
fcntl(3, F_SETFD, FD_CLOEXEC)           = 0
rt_sigaction(SIGPIPE, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7f99e4296840}, NULL, 8) = 0
rt_sigaction(SIGALRM, {sa_handler=0x7f99e4520210, sa_mask=[], sa_flags=SA_RESTORER|SA_SIGINFO, sa_restorer=0x7f99e4296840}, NULL, 8) = 0
geteuid()                               = 0
rt_sigaction(SIGINT, {sa_handler=0x7f99e4520c20, sa_mask=[], sa_flags=SA_RESTORER|SA_SIGINFO, sa_restorer=0x7f99e4296840}, NULL, 8) = 0
pipe([4, 5])                            = 0
fcntl(4, F_GETFL)                       = 0 (flags O_RDONLY)
fcntl(4, F_SETFL, O_RDONLY|O_NONBLOCK)  = 0
fcntl(5, F_GETFL)                       = 0x1 (flags O_WRONLY)
fcntl(5, F_SETFL, O_WRONLY|O_NONBLOCK)  = 0
fcntl(4, F_GETFD)                       = 0
fcntl(4, F_SETFD, FD_CLOEXEC)           = 0
fcntl(5, F_GETFD)                       = 0
fcntl(5, F_SETFD, FD_CLOEXEC)           = 0
epoll_create(128)                       = 6
fcntl(6, F_GETFD)                       = 0
fcntl(6, F_SETFD, FD_CLOEXEC)           = 0
epoll_ctl(6, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161333872, u64=94093009887344}}) = 0
rt_sigaction(SIGTERM, {sa_handler=0x7f99e4520c20, sa_mask=[], sa_flags=SA_RESTORER|SA_SIGINFO, sa_restorer=0x7f99e4296840}, NULL, 8) = 0
umask(077)                              = 022
socket(AF_UNIX, SOCK_STREAM, 0)         = 7
fcntl(7, F_GETFL)                       = 0x2 (flags O_RDWR)
fcntl(7, F_SETFL, O_RDWR|O_NONBLOCK)    = 0
connect(7, {sa_family=AF_UNIX, sun_path="/var/run/dovecot/config"}, 110) = 0
fcntl(7, F_GETFL)                       = 0x802 (flags O_RDWR|O_NONBLOCK)
fcntl(7, F_SETFL, O_RDWR)               = 0
write(7, "VERSION\tconfig\t2\t0\nREQ\tmodule=ld"..., 70) = 70
fstat(7, {st_mode=S_IFSOCK|0777, st_size=0, ...}) = 0
fcntl(7, F_GETFL)                       = 0x2 (flags O_RDWR)
alarm(10)                               = 0
read(7, "\nmail_privileged_group=mail\nname"..., 8192) = 810
alarm(0)                                = 10
close(7)                                = 0
stat("/etc/resolv.conf", {st_mode=S_IFREG|0644, st_size=174, ...}) = 0
openat(AT_FDCWD, "/etc/host.conf", O_RDONLY|O_CLOEXEC) = 7
fstat(7, {st_mode=S_IFREG|0644, st_size=9, ...}) = 0
read(7, "multi on\n", 4096)             = 9
read(7, "", 4096)                       = 0
close(7)                                = 0
openat(AT_FDCWD, "/etc/resolv.conf", O_RDONLY|O_CLOEXEC) = 7
fstat(7, {st_mode=S_IFREG|0644, st_size=174, ...}) = 0
read(7, "# Dynamic resolv.conf(5) file fo"..., 4096) = 174
read(7, "", 4096)                       = 0
close(7)                                = 0
uname({sysname="Linux", nodename="mail", ...}) = 0
socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 7
connect(7, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
close(7)                                = 0
socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 7
connect(7, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
close(7)                                = 0
openat(AT_FDCWD, "/etc/nsswitch.conf", O_RDONLY|O_CLOEXEC) = 7
fstat(7, {st_mode=S_IFREG|0644, st_size=526, ...}) = 0
read(7, "# /etc/nsswitch.conf\n#\n# Example"..., 4096) = 526
read(7, "", 4096)                       = 0
close(7)                                = 0
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 7
fstat(7, {st_mode=S_IFREG|0644, st_size=35918, ...}) = 0
mmap(NULL, 35918, PROT_READ, MAP_PRIVATE, 7, 0) = 0x7f99e4420000
close(7)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libnss_files.so.2", O_RDONLY|O_CLOEXEC) = 7
read(7, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0003\0\0\0\0\0\0"..., 832) = 832
fstat(7, {st_mode=S_IFREG|0644, st_size=55792, ...}) = 0
mmap(NULL, 83768, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 7, 0) = 0x7f99e4243000
mprotect(0x7f99e4246000, 40960, PROT_NONE) = 0
mmap(0x7f99e4246000, 28672, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 7, 0x3000) = 0x7f99e4246000
mmap(0x7f99e424d000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 7, 0xa000) = 0x7f99e424d000
mmap(0x7f99e4250000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 7, 0xc000) = 0x7f99e4250000
mmap(0x7f99e4252000, 22328, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f99e4252000
close(7)                                = 0
mprotect(0x7f99e4250000, 4096, PROT_READ) = 0
munmap(0x7f99e4420000, 35918)           = 0
openat(AT_FDCWD, "/etc/hosts", O_RDONLY|O_CLOEXEC) = 7
lseek(7, 0, SEEK_CUR)                   = 0
fstat(7, {st_mode=S_IFREG|0644, st_size=210, ...}) = 0
read(7, "127.0.0.1\tlocalhost\n192.168.1.24"..., 4096) = 210
lseek(7, 0, SEEK_CUR)                   = 210
read(7, "", 4096)                       = 0
close(7)                                = 0
access("/etc/ssl/certs", X_OK)          = 0
socket(AF_UNIX, SOCK_STREAM, 0)         = 7
fcntl(7, F_GETFL)                       = 0x2 (flags O_RDWR)
fcntl(7, F_SETFL, O_RDWR|O_NONBLOCK)    = 0
connect(7, {sa_family=AF_UNIX, sun_path="/var/run/dovecot/stats-writer"}, 110) = 0
fstat(7, {st_mode=S_IFSOCK|0777, st_size=0, ...}) = 0
fcntl(7, F_GETFL)                       = 0x802 (flags O_RDWR|O_NONBLOCK)
epoll_ctl(6, EPOLL_CTL_ADD, 7, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161385712, u64=94093009939184}}) = 0
write(7, "VERSION\tstats-client\t3\t0\n", 25) = 25
epoll_ctl(6, EPOLL_CTL_DEL, 4, 0x7fffbb150b0c) = 0
epoll_create(128)                       = 8
fcntl(8, F_GETFD)                       = 0
fcntl(8, F_SETFD, FD_CLOEXEC)           = 0
epoll_ctl(8, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161395728, u64=94093009949200}}) = 0
epoll_ctl(8, EPOLL_CTL_ADD, 7, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161395856, u64=94093009949328}}) = 0
epoll_ctl(6, EPOLL_CTL_DEL, 7, 0x7fffbb150b1c) = 0
epoll_wait(8, [{EPOLLIN, {u32=3161395856, u64=94093009949328}}], 2, -1) = 1
read(7, "VERSION\tstats-server\t3\t0\nFILTER\t"..., 8192) = 33
epoll_ctl(8, EPOLL_CTL_DEL, 4, 0x7fffbb150b2c) = 0
epoll_ctl(6, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161333872, u64=94093009887344}}) = 0
epoll_ctl(6, EPOLL_CTL_ADD, 7, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161385712, u64=94093009939184}}) = 0
epoll_ctl(8, EPOLL_CTL_DEL, 7, 0x7fffbb150b1c) = 0
epoll_ctl(6, EPOLL_CTL_DEL, 4, 0x7fffbb150b2c) = 0
epoll_ctl(8, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161395728, u64=94093009949200}}) = 0
epoll_ctl(8, EPOLL_CTL_DEL, 4, 0x7fffbb150aec) = 0
epoll_ctl(6, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161333872, u64=94093009887344}}) = 0
close(8)                                = 0
socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0) = 8
connect(8, {sa_family=AF_UNIX, sun_path="/dev/log"}, 110) = 0
socket(AF_UNIX, SOCK_STREAM, 0)         = 9
fcntl(9, F_GETFL)                       = 0x2 (flags O_RDWR)
fcntl(9, F_SETFL, O_RDWR|O_NONBLOCK)    = 0
connect(9, {sa_family=AF_UNIX, sun_path="/var/run/dovecot/auth-userdb"}, 110) = 0
epoll_ctl(6, EPOLL_CTL_DEL, 4, 0x7fffbb150d5c) = 0
epoll_create(128)                       = 10
fcntl(10, F_GETFD)                      = 0
fcntl(10, F_SETFD, FD_CLOEXEC)          = 0
epoll_ctl(10, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161405440, u64=94093009958912}}) = 0
fstat(9, {st_mode=S_IFSOCK|0777, st_size=0, ...}) = 0
fcntl(9, F_GETFL)                       = 0x802 (flags O_RDWR|O_NONBLOCK)
lseek(9, 0, SEEK_CUR)                   = -1 ESPIPE (Illegal seek)
getsockname(9, {sa_family=AF_UNIX}, [28->2]) = 0
epoll_ctl(10, EPOLL_CTL_ADD, 9, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161406112, u64=94093009959584}}) = 0
setsockopt(9, SOL_TCP, TCP_CORK, [1], 4) = -1 EOPNOTSUPP (Operation not supported)
write(9, "VERSION\t1\t0\nUSER\t1\tuser@loca"..., 50) = 50
epoll_wait(10, [{EPOLLIN, {u32=3161406112, u64=94093009959584}}], 2, 155000) = 1
read(9, "VERSION\t1\t1\nSPID\t7235\n", 8192) = 22
epoll_wait(10, [{EPOLLIN, {u32=3161406112, u64=94093009959584}}], 2, 154984) = 1
read(9, "NOTFOUND\t1\n", 8170)          = 11
epoll_ctl(10, EPOLL_CTL_DEL, 4, 0x7fffbb150c7c) = 0
epoll_ctl(6, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161333872, u64=94093009887344}}) = 0
epoll_ctl(6, EPOLL_CTL_DEL, 4, 0x7fffbb150c7c) = 0
epoll_ctl(10, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161405440, u64=94093009958912}}) = 0
epoll_ctl(10, EPOLL_CTL_DEL, 4, 0x7fffbb150d8c) = 0
epoll_ctl(6, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161333872, u64=94093009887344}}) = 0
epoll_ctl(6, EPOLL_CTL_DEL, 4, 0x7fffbb150d8c) = 0
epoll_ctl(10, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161405440, u64=94093009958912}}) = 0
epoll_ctl(10, EPOLL_CTL_DEL, 9, 0x7fffbb150dbc) = 0
epoll_ctl(10, EPOLL_CTL_DEL, 4, 0x7fffbb150d4c) = 0
epoll_ctl(6, EPOLL_CTL_ADD, 4, {EPOLLIN|EPOLLPRI|EPOLLERR|EPOLLHUP, {u32=3161333872, u64=94093009887344}}) = 0
close(10)                               = 0
close(9)                                = 0
epoll_ctl(6, EPOLL_CTL_DEL, 7, 0x7fffbb15105c) = 0
close(7)                                = 0
epoll_ctl(6, EPOLL_CTL_DEL, 4, 0x7fffbb15105c) = 0
close(4)                                = 0
close(5)                                = 0
close(6)                                = 0
close(3)                                = 0
exit_group(67)                          = ?
+++ exited with 67 +++

output of doveconf -n:
root@mail:/etc/dovecot# dovecot -n
# 22.214.171.124 (f79e8e7e4): /etc/dovecot/dovecot.conf
# Pigeonhole version 0.5.4 ()
# OS: Linux 4.19.0-17-amd64 x86_64 Debian 10.10
# Hostname: mail
mail_location = maildir:~/Maildir
mail_privileged_group = mail
namespace inbox {
  inbox = yes
  location =
  mailbox Archive {
    special_use = \Archive
  }
  mailbox Drafts {
    special_use = \Drafts
  }
  mailbox Junk {
    special_use = \Junk
  }
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    special_use = \Trash
  }
  prefix =
}
passdb {
  driver = pam
}
protocols = " imap"
ssl = required
ssl_cert = </etc/letsencrypt/live/domain.com/fullchain.pem
ssl_client_ca_dir = /etc/ssl/certs
ssl_dh = # hidden, use -P to show it
ssl_key = # hidden, use -P to show it
userdb {
  driver = passwd
}

permissions of /var/run/dovecot/stat
root@mail:/etc/dovecot# ls -l /var/run/dovecot/*stat*
srw------- 1 root root    0 Aug  9 13:37 /var/run/dovecot/old-stats
prw------- 1 root root    0 Aug  9 13:37 /var/run/dovecot/old-stats-mail
prw------- 1 root root    0 Aug  9 13:37 /var/run/dovecot/old-stats-user
srw------- 1 root root    0 Aug  9 13:37 /var/run/dovecot/stats-reader
srw-rw---- 1 root dovecot 0 Aug  9 13:37 /var/run/dovecot/stats-writer

Any ideas what could be wrong, and would it be better to use dovecot sync/backup for this?
Comment: Trying to decode the strace(1) (cumbersome) I'd say it is trying to tell you tha user@localhost cannot be found. If so, it does not know either about 'user', localhost, or 'user@localhost'.
Comment: Please try piping a message to `deliver` separately, I suspect that will show you an error message you are not seeing when called via fetchmail. e.g. Is `deliver` called as the user owning the Maildir? (also, repeated `fetchall` sounds odd, if you can you really want to use the features Dovecot includes)
Comment: @anx my original idea was to use dsync (https://wiki2.dovecot.org/Migration/Dsync) but when I read more about it (https://wiki.dovecot.org/Tools/Doveadm/Sync) it seems like it doesn't really fit my usage scenario - I want to download email and remove copies from the server. I don't want to keep my local IMAP folders in sync with the folders on the remote IMAP server, I want to make sure I keep all my local copies even if they have been deleted from the remote server. So it would seem fetchmail is what I want? I piped a message into deliver and I do not get any error, but it doesn't work.
Comment: Did you use the `-e` flag to *print* errors, instead of sending a "bounce" notification? I believe either way, you should have something in your logs.
Comment: @anx I don't have /var/log/dovecot.log, I guess all logging is done to /var/log/syslog etc. Should I double check in dovecot config somewhere if all logging is enabled? I will use the -e flag and report back.
Comment: @anx adding -e makes no difference, I do not get any error output on the command line.
Answer: It turns out that the line
     mda "/usr/lib/dovecot/deliver -d user@localhost -m .fastmail.Archive"

Doesn't work. When I removed @localhost, and fixed the folder name, it works:
     mda "/usr/lib/dovecot/deliver -d user -m fastmail.Archive"

What I still don't understand is why I was not getting any kind of error output, the command just acts like it worked, and I can't see anything in the dovecot logs either. At least not without turning on debug logging options. The above seek error in the output of strace is confusing, I don't understand what the relationship is between that and the removal of the @localhost fixing the problem.
Comment: Isn't fetchmail capable of delivering mail directly to the dovecot LMTP socket? You will usually get much more useful (error) feedback when you use the full protocol instead of a simple pipe to an lda binary.


Is it possible for a view to have two outputs

Question: The reason I need this because I create a view to search through document and need two outputs. One being the document and the other being the files are part of the document group the file is associated with.
*Is this possible with one exposed filter
Thanks for any help with this
Comment: You mean 2 sections on one page? Or 2 separate pages generated from one view?
Comment: two section on one page
Answer: You can use an attached View. An attached View is a View display that is attached to another View display, a compounded View.
In this question is explained its purpose:
What is the purpose of Views "Attachment", "Content pane" & "Context"?

The Attachment option is to create yet another view that you can attach before and/or after any of the displays on your current view.
Answer: You can use Views Field View; allows you to embed a view as a field in a view.
It can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
Answer:
You can use attached view. Attached view have view display before or after to page or master. So u can easily attached another views on same page


Enhancing/manipulating react children props

Question: I was hoping to abstract away the binding of event listeners on children components. Or allow a component to alter props of children.
I'm wanting to express the components in JSX like
<DocumentScreen name="Type">
  <DocumentInput value="L" name="(=learner)" icon="lerners.svg" />
  <DocumentInput value="P" name="(=probationary)" icon="probationary.svg" />
  <DocumentInput value="Full" icon="full.svg" />
</DocumentScreen>

Which is an enhanced radio or checkbox grouping.
Now I want to enhance the inputs to automagically notify the parent component of changes to store state.
I was hoping this would be possible
{React.Children.toArray(this.props.children).map((Child => (<Child onClick={() => console.log("yea!")} />)))}
Or more simply
{this.props.children.map((Child => (<Child onClick={() => console.log("yea!")} />)))}
But I get a typescript error
JSX element type 'Child' does not have any construct or call signatures
Using
"react": "^16.8.6",
"typescript": "^3.5.2"

Is this possible or is there another way to achieve this?
Comment: I used children as array, but I put the components in "[" and "]"...
Answer: You can use cloneElement
https://reactjs.org/docs/react-api.html#cloneelement
render() {
        return (

          {React.Children.map(this.props.children, child => {
            return React.cloneElement(child, {
                onClick : () => console.log("yea!")
            })
         })}

       )
}

Comment: Thank you that pointed in me in the right direction. I was missing `onClick` as a prop in the child component. Once I added `onClick: (value: string) => void` and cast child to any it worked.


Integração Ruby Bematech (ou similares)

Question: Alguém já fez alguma integração Ruby com uma impressora Bematech ou outra do tipo ? Quais gems ou meios de conseguir imprimir numa impressora fiscal ?
Answer: Não existe uma gem específica para impressoras Bematech, infelizmente.
Sabes que no caso do Windows as impressoras instalam drivers e com eles vêm uma implementação de interface provida pelo sistema operacional, certo? Se não, pois eu explico: os drivers de dispositivos externos nada mais são que implementações de interface de como fazer as coisas.
No caso da impressora, você deve acessar a .dll (se for Windows) através do Ruby - usando require - e utilizar do método de impressão da mesma.
Pra te ajudar, você pode baixar os drivers/as dlls neste link.
Uma documentação mais completa e específica você encontra no endereço acima.
Answer: No site da Bematech es existe toda a documentação das DLL's e como fazer as chamadas de suas funções, inclusive com exemplos.
Outra alternativa é utilizar o ACBrMonitor.
Comment: Valeu pelo link do forum, não conhecia. Marquei a do @guilherme pois falou da integração direto.

Integração Ruby Bematech (ou similares)


Executar N threads e saber quando todas terminaram de executar

Question: Tenho o seguinte problema, preciso rodar o mesmo método N vezes num for e saber quando todas as threads já terminaram de rodar ela.
Precisava de algo tipo assim:
foreach (MeuObjeto obj in lstObj)
{
    new Thread(delegate() { MetodoX(obj ); }).Start();
}
metodoY(); // só rodar depois que todas as thread  acima já tiverem terminado.

Answer: É possível fazer isso usando Parallels (i.e. PLINQ) ou Tasks. Eu recomendo que use Tasks, pois provavelmente o PLINQ em algum momento se tornará obsoleto em favor do anterior.
Veja como fazer:

usando o método ForAll do PLINQ... é a que fica mais simples de todas:
lstObj.AsParallel().ForAll(MetodoX);
metodoY();

usando Task.WhenAll: chamada simples, método alterado
var manyTasks = lstObj.Select(MetodoX); // a chamada fica símples
Task.WhenAll(manyTasks).Wait();
metodoY();

Sendo que o MetodoX teria de ser mudado também para usar async e await:
private async Task MetodoX(MeuObjeto obj)
{
    await Task.Yield(); // primeira linha do método deve ser um Yield

usando Task.WhenAll e Task.Run: chamada menos simples, método original
var manyTasks = lstObj.Select(x => Task.Run(() => MetodoX(x)));
Task.WhenAll(manyTasks).Wait();
metodoY();

Se você ainda assim não quiser usar nenhuma dessas alternativas, não quiser usar LINQ, nem PLINQ, nem Tasks, e quiser manipular Threads na mão, então pode fazer assim:
var threads = new List<Thread>();
foreach (string obj in lstObj)
    threads.Add(new Thread(delegate() { MetodoX(obj); }));

foreach (var thread in threads)
    thread.Start();

foreach (var thread in threads)
    thread.Join();

Answer: É possível usar Tasks conforme a recomendação do Miguel Anelo e fazer de forma simplificada sem se preocupar com o mecanismo:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Program {
    public static void Main() {
        var lstObj = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
        Parallel.ForEach(lstObj, obj => MetodoX(obj));
        Console.WriteLine("Fim"); //aqui poderia ser o MetodoY()
    }
    public static void MetodoX(int obj) {
        Console.WriteLine($"ThreadID: {Thread.CurrentThread.ManagedThreadId, 3}, Valor: {obj}");
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
De uma maneira geral não é recomendado usar Threads brutas até que exista um bom motivo para usar.


Error message when deleting folders/files on Maintenance mode

Question: I turn the site in maintenance mode for update Drupal Core from 7.30 to 7.32. I follow the step on Drupal docmentation to delete all folders and files, beside "site" folder(on step 5). However, I got the error message and warning about missing files. I dont think that how maintenace mode should be. What am i missing?
PS:
1. the site does show in maintenance mode before I delete all the folders and files(beside site folder)
2. Site back to normal after copying v7.32 folders and files(beside site folder)
Comment: Yes. To prevent changes from happening in the meantime. Imagine someone adds new content, or fills multistep form. What happen if you delete PHP file right before it is needed? You can end up with inconsistent data in database. You don't want that. Maintenance mode is the best simple way to prevent it. Even in two-machine upgrade scenario I turn on maintenance mode on machine that's going to get upgrades - and this machine is not visible to anyone but me, my boss and our admins.
Comment: What I would recommend though, is that you look at git. If you do the update through git, the update will take milliseconds, and no one will ever even notice the site was missing.
Comment: What exactly you did, step by step? And what you expected? If you delete files, and before you will upload new ones, you will have missing files. That's pretty obvious, isn't it?
Comment: @Mołot I followed all the steps in Update Drupal Core Documentation(https://www.drupal.org/node/1494290). The only issue I have is step 5. I got an error message instead of maintenance mode until I copy all the new files back. I thought the whole process would be in maintenance mode.
Comment: "I got an error message instead of maintenance mode until I copy all the new files back." - that's expected - you deleted Drupal, and there was not enough of it left to handle even maintenance mode. That's why in pro environments things like that are made differently, with second (virtual) server and so on.
Comment: @Mołot Do you know what is the purpose to put site in maintenance mode while update the Drupal Core?
Comment: @Mołot Thank you Mołot. I never thought about that. It would be nice if the maintenance mode still on while deleting these files.
Comment: @CocoSkin It would be nice, but where would the page be generated when you have deleted all the files?
Comment: To be fair though, it wouldn't hurt for the instructions to mention that this will happen.
Comment: @Letharion At first, I thought the maintenance mode will not load any data but the maintenance message. Which I'm wrong and should be very simple. In the future before deleting files, I should replace the index.php with simple html table & messages.
Comment: That still doesn't make any sense. "will not load any data but the maintenance message". What code would load that message? Where would the message be stored? _all_ the basic logic is deleted. But yes, sticking a new file in place is a useful workaround.
Comment: @Letharion ty for the recommendation. I will take a look at git.
Comment: if git isn't an option, something else simple you can do is to create a static index.php which holds a 'maintenance mode' layout and message - copy it over first so that any calls to the server go through it, then delete everything except /sites and index.php
Answer: Rather than the two step deleting the folders and then uploading the new ones, I would recommend just copying over the old ones with new ones. You'll probably have to tell your FTP program to overwrite but when I upgrade in this fashion, I select all the files and directories except for sites folder and push them to the server.
When possible, I use the Drush tool via a terminal window as it is a much quicker and easier solution.
Comment: not sure about this. There must be a reason why the Update Drupal Core Documentation says to delete all these files. It's possible the new and old Drupal has different amount of files?
Comment: Yes, I'm not sure about that either except perhaps for thoroughness. Most FTP client programs I've used will prompt you to overwrite a file or directory if it already exists so maybe the folks at Drupal.org were concerned about confusing the issue. If you delete a folder and then upload the new one, there is less chance of confusion in that regard.
Comment: There's (at least two risks). One is that if the update gets "half done", you have no way to tell, and might not even know. Instead you end up with odd and hard to reproduce bugs because you run some sort of 7.31 and half chimera. The other is that the update might require the removal of some file, so again, you end up with parts of the previous version, that may cause problems in the new version. In most cases it will all work just fine though, but the official guide has to be careful.


Questions on topological manifolds

Question:
Does the dimension of a manifold depend on the topology? That is, can I endow a set with a topology $T$ and get an $n$-dimensional manifold, and endow the exact same set with another toplogy $T'$ and get an $m$-dimensional manifold, with $n\neq m$?
Can a curve like this:

$\hskip1.3in$
be given the topology of a 1-manifold? Or a curve like this cannot be a manifold with any topology?
Comment: It seems hopeless to characterize what you can do with a bare _set_. $\mathbf R$ and $\mathbf R^2$ have the same cardinality, for example.
Comment: @kein Exapnding on Dylan comment: For each $n$ you can give a topology to $\mathbb R$ so that $\mathbb R$ is an $n$-manifold.
Comment: OK so you are saying that those questions are impossible to prove or disprove?
Comment: Yep, that is correct. If S is a bijection between R and R^n, you can give R the topology induced by S (the open sets of R are the images of S which are open on R^n in the usual sense), and with that S is an homeomorphism. Thanks for helping me clarify this topic.
Answer: (1) Yes, the dimension of the manifold depends on the topology.  A $3$-manifold has neighborhoods which are homeomorphic to $\mathbb{R}^3$, a $2$-manifold has open neighborhoods homeomorphic to $\mathbb{R}^2$, and so forth.
As Dylan Moreland points out in the comments, $\mathbb{R}$ and $\mathbb{R}^2$ both have the same cardinality.  We may regard them as in bijection, therefore as two representations of the same uncountable set.  When we endow them with two different topologies, we have two manifolds of different dimension.
For another example, consider $\mathbb{Z}$ and $\mathbb{Q}$.  Again, they are in bijection, but while $\mathbb{Z}$ (with its discrete topology) is a $0$-dimensional manifold, $\mathbb{Q}$ with the topology inherited from its inclusion in $\mathbb{R}$ is not a manifold at all.
(2) As a set, certainly; the curve can be put in bijection with $\mathbb{R}^2$ and given the same topology.  If you are really asking whether the curve is a $1$-dimensional manifold, then the answer is "no."  To be a manifold, about every point on the curve there must be an open neighborhood homeomorphic to $\mathbb{R}$.  Observe that no connected neighborhood of its point of self-intersection is homeomorphic to $\mathbb{R}$ since removing any point of $\mathbb{R}$ results in two open components, but removing the point of self-intersection from a small connected neighborhood of the point of self-intersection results in four open components.

Here are some more general comments.  You're conflating two levels of abstraction here: the basic machinery of point-set topology and the foundations of manifold theory.  Manifold theory is more concrete than point-set topology, in the sense that all of manifold theory deals with very specific types of topological spaces.  To admit the possibility of having the structure of a topological manifold, the topology of a set must already be Hausdorff, paracompact, and second-countable. This rules out entire classes of topological spaces, and even rules out many metric spaces.
Meanwhile, most of the topological spaces we encounter frequently are built from uncountable sets.  It may be an understatement when I say that there are many, many topologies you can put on an uncountable set.  Only a tiny, tiny fraction of them could have the faintest hope of ever possibly sitting under a manifold structure.  So it seems strange to try to think about a manifold structure in terms of the topology of the underlying set; they're in different layers of abstraction.
Maybe a computing analogy would help. Working with a topology on a set is like designing a processor.  Working with a manifold is like programming software.  To program software, you need a working processor, but once your processor works, you generally forget about the processor design, unless it becomes relevant, and just deal with the programming language.

Edited in response to comments by Henry T. Horton and Mariano Suarez-Alvarez.
Comment: $\mathbb{Q}$ can be made into a $0$-dimensional manifold by equipping it with the discrete topology (since it is a countable set). You're probably thinking of it with the subspace topology inherited from $\mathbb{R}$, however. There is also the trivial example that $\varnothing$ can be a manifold of any dimension, since it satisfies the necessary conditions vacuously.
Comment: Ey thanks for the elaborated answer!
Comment: Just for precision's sake: it is not true that «removing the point of self-intersection from a small neighborhood of the point of self-intersection results in four open components», because you can start with a neighborhood of the point which is itself already not connected! (the components need not be open, either)
Comment: R^2 in fact is homeomorphic to R, with the topology of R^2 where, if S is a bijection from R^2 to R, the open subsets of R^2 are the images of S which are open in R (in the usual sense). With those topologies, S is an homeomorphism.

Questions on topological manifolds


Authenticate Postfix through Dovecot with slightly different settings

Question: I'm setting up a server with Dovecot (2.2.2) and Postfix (3.1.0). Dovecot authenticates against LDAP and Postfix uses Dovecots SASL. That already works fine. But I would like to have slightly different LDAP settings for Dovecot and Postfix. Current setup:
passdb {
  driver = ldap
  args = /etc/dovecot/dovecot-ldap.conf.ext
}
userdb {
  driver = ldap
  args = /etc/dovecot/dovecot-ldap.conf.ext
}

Excerpt from dovecot-ldap.conf.ext:
user_filter = (& \
    (objectClass=gosaMailAccount) \
    (allowedServices=*I*) \
    (uid=%u) \
)

I wanted to have sparate LDAP filters (allowedServices=*I* for Dovecot and allowedServices=*S* for Postfix), to be able to disable SMTP and IMAP independently. Does anybody know a way to separate those settings?
Answer: I got an answer on the Dovecot list. I used the %s (service variable) like this:
user_filter = (& \
    (objectClass=gosaMailAccount) \
    (allowedServices=*%L1s*) \
    (uid=%u) \
)

%L1s uses the first letter of the %s variable, which returns imap and smtp for the respective services.


how to shrink a textbox in pygame when you delete text?

Question: When the user enters or deletes text I want the rectangle to shrink and grow depending on how much text is entered. This process works just fine except for one small error. When you delete text an empty rectangle forms in place of the letter that was deleted. How do I fix this?
from pygame import *

init()
screen = display.set_mode((800, 600))

name_font = font.Font(None, 32)
name_text = ''

class Rectangle:

    def __init__(self, x, y):
        self.active = False
        self.x = x
        self.y = y
        self.text_surface = name_font.render(name_text, True, (255, 255, 255))
        self.rect_width = max(140, 10 + self.text_surface.get_width())
        self.input_rect = Rect(x, y, self.rect_width, 32)
        self.input_rect.w = self.text_surface.get_width() + 10
        self.click_value = 10

    def naming(self, events):
        global rect_1
        global name_text

        for e in events:
            if e.type == MOUSEBUTTONDOWN:
                if self.input_rect.x + self.click_value >= mx >= self.input_rect.x - 10 and self.input_rect.y + 26 >= my >= self.input_rect.y - 10:
                    self.active = True
                else:
                    self.active = False

            if e.type == KEYDOWN:
                if self.active:
                    if e.key == K_BACKSPACE:
                        name_text = name_text[:-1]
                        screen.fill((0, 0, 0))
                    else:
                        name_text += e.unicode
                        self.click_value += 7

                    self.text_surface = name_font.render(name_text, True, (255, 255, 255))

    def draw(self, screen):
        draw.rect(screen, (0, 0, 0), self.input_rect, 0)
        draw.rect(screen, (255, 255, 255), self.input_rect, 2)
        self.input_rect.w = self.text_surface.get_width() + 10
        screen.blit(self.text_surface, (self.input_rect.x + 5, self.input_rect.y + 5))

rect_1 = Rectangle(200, 200)

while True:
    mx, my = mouse.get_pos()
    events = event.get()
    for e in events:
        if e.type == QUIT:
            quit()

    rect_1.naming(events)
    rect_1.draw(screen)
    display.update()
    time.delay(1)

Answer: You have to compute the width of the input rectangle before you draw it:
class Rectangle:
    # [...]

    def draw(self, screen):
        self.input_rect.w = self.text_surface.get_width() + 10
        draw.rect(screen, (0, 0, 0), self.input_rect, 0)
        draw.rect(screen, (255, 255, 255), self.input_rect, 2)
        screen.blit(self.text_surface, (self.input_rect.x + 5, self.input_rect.y + 5))

However, the wrong order doesn't matter if you were to clear the screen every frame. The bug would hardly be noticeable as it would only be visible for a single frame. Clear the screen in every frame and not in case of K_BACKSPACE:
while True:
    mx, my = mouse.get_pos()
    events = event.get()
    for e in events:
        if e.type == QUIT:
            quit()

    rect_1.naming(events)

    screen.fill((0, 0, 0)) # <---
    rect_1.draw(screen)
    display.update()
    time.delay(1)


Configuring gzip with nginx

Question: I am using nginx for the first time and have some confusions regarding configurations. I have a nginx as load balancer and backends as nginx as well. With my understanding I have configured mod_security module on the load balancer as its the entry point. I have also added required response headers on the load balancer. Now I have to enable the gzip for nginx. Confusion is where it should be configured? Load balancer or the backend nginx servers?
Answer: You can configure gzip globally in /etc/nginx/nginx.conf or just for one site in e.g. /etc/nginx/sites-available/your-site.
The configuration could like this:
gzip on;

gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

Comment: My confusion is if it is a good practice to do it on the load balancer? or do it on the backend nginx servers?
Comment: To the backend nginx servers. While testing or debuging you don't have to pass through the balancer to gzip.
Answer: It depends.
For dynamic gzipping (e.g. HTML output of your site/app)
If your load balancer is a powerful machine, then you may want to do gzip on the load balancer, in order to reduce CPU usage elsewhere.
If you have some modsecurity rules that require inspecting the response body, and gzipping is done in the nodes, then that would mean that modsecurity needs to ungzip backend response/inspect/re-gzip (and thus cause processing overhead) or those rules would simply not work. That's another case when you want to gzip in load balancer.
In all other cases, I assume gzipping on the nodes would be better.
For static files
.. it's best to rely on static gzip (pre-compress your assets). However, since you have many backends, it means pre-compressing assets on each.
If your backends are different websites/apps (that means, you're not doing actual load balancing), it's not an issue.
If your backends are actual nodes of the same app, then you can do max gzip on each node, and "proxy cache" results on the load balancer.

Configuring gzip with nginx


Number field question

Question: Show that $\sqrt3$ $\notin$ $\Bbb Q[\sqrt[4]2]$
The problem wishes us to use the trace function of a number field, and hints to write $\sqrt 3$ as $a+bx+bx^2+cx^3$.
Why can we write it like this, and where do we go from there?
Answer: Note that the matrix of the multiplication $m_\alpha:\mathbb{Q}(\sqrt[4]{2})\to \mathbb{Q}(\sqrt[4]{2})$ map with respect to a generic element $\alpha=a+b\sqrt[4]{2}+c\sqrt[4]{2^2}+d\sqrt[4]{2^3}$ is (in the canonical basis)
$$\begin{pmatrix}a & 2d & 2b & 2b \\ b & a & 2d & 2c \\ c & b & a & 2d \\ d & c & b & a \end{pmatrix}$$
so, the trace of the matrix is $4a$. Now, note that if $\sqrt{3}\in\mathbb{Q}(\sqrt[4]{2})$ then
$$\text{Tr}_{\mathbb{Q}(\sqrt[4]{2})/\mathbb{Q}}(\sqrt{3})=\text{Tr}_{\mathbb{Q}(\sqrt{3})/\mathbb{Q}}\left(\text{Tr}_{\mathbb{Q}(\sqrt[4]{2})/\mathbb{Q}(\sqrt{3})}(\sqrt{3})\right)=\text{Tr}_{\mathbb{Q}(\sqrt{3})/\mathbb{Q}}(2\sqrt{3})=0$$
(this is just using the transitivity of the field trace--a similar result can be arrived at calculating the minimal polynomial of $\sqrt{3}$). So, $a=0$. Thus, by dividing both sides by $\sqrt[4]{2}$ we get
$$\sqrt[4]{\frac{9}{2}}=b+c\sqrt[4]{2^2}+d\sqrt[4]{2^3}$$
Taking the minimal polynomial of the left hand side shows that $\text{Tr}_{\mathbb{Q}(\sqrt[4]{2})/\mathbb{Q}})\left(\sqrt[4]{\frac{9}{2}}\right)=0$. But, the trace of the right hand side is $b$. Continuing this process you find that $a=b=c=d=0$, which is clearly impossible.
EDIT: Just for funsies, here is another number theoretic way to approach this problem. This is actually what initially occurred to me--not the trace trick. I hope you find it enlightening.
$\text{ }$
$\text{ }$
Derivation of the ring of integers of $\mathbb{Q}(\sqrt[4]{2})$--skip if you're willing to believe it's $\mathbb{Z}[\sqrt[4]{2}]$.

Let $K=\mathbb{Q}(\sqrt[4]{2})$. It's obvious that $\mathbb{Z}[\sqrt[4]{2}]\subseteq\mathcal{O}_K$, and so to show that $\mathcal{O}_K=\mathbb{Z}[\sqrt[4]{2}]$ it suffices to show that $\mathbb{Z}[\sqrt[4]{2}]$ is integrally closed, or equivalently, that its locally integrally closed.
But, since $\mathbb{Z}[\sqrt[4]{2}]$ is a simple integral extension of $\mathbb{Z}$, with generating having minimal polynomial $f(x)=x^4-2$, it suffices to check that its integrally closed only at maximal ideals containing $f'(\sqrt[4]{2})=4 \sqrt[4]{2^3}$. In particular, we see that if $f'(\sqrt[4]{2})\in M$, then $8=\sqrt[4]{2}f'(\sqrt[4]{2})\in M$, so that $M$ lies over $2$. But, since $x^4-2\equiv x^4 \mod 2$, the only max ideal of $\mathbb{Z}[\sqrt[4]{2}]$ lying over $2$ is $M=(2,\sqrt[4]{2})$. But, since this max ideal is already principal $M=(\sqrt[4]{2})$ it's trivial that the only maximal ideal, and thus the only prime ideal (since $\mathbb{Z}[\sqrt[4]{2}]$ is dimension $1$, and thus so is $\mathbb{Z}[\sqrt[4]{2}]_M$) of $\mathbb{Z}[\sqrt[4]{2}]_M$ is principal. Thus, $\mathbb{Z}[\sqrt[4]{2}]_M$ is a PID, and so, in particular, integrally closed. It follows from previous discussion that $\mathbb{Z}[\sqrt[4]{2}]$ is integrally closed, and thus $\mathcal{O}_K=\mathbb{Z}[\sqrt[4]{2}]$.

$\text{ }$
$\text{ }$
Now, note that we can use the Dedekind-Kummer theorem to factor $3\mathcal{O}_K$. Namely, since $(x^2+x+2)(x^2+2x+2)$ is the factorization into irreducibles of $x^4-2$ in $\mathbb{F}_3[x]$ we see that $(3,\sqrt[4]{2^2}+\sqrt[4]{2}+2)(3,\sqrt[4]{2^2}+2\sqrt[4]{2}+2)$ is the factorization of $3\mathcal{O}_K$ into primes. In particular, $3$ doesn't ramify in $K$ (this could have also been determined by finding $d_K$, but I thought it would be nice to have the actual factorization).
But, since $3$ ramifies in $\mathbb{Q}(\sqrt{3})$ we must have that $\mathbb{Q}(\sqrt{3})\not\subseteq\mathbb{Q}(\sqrt[4]{2})$ as desired.
The above is all kind of misleading. It makes it seem like the technique involving traces is much more natural than the above, but this is only because some more sophisticated machinery went into it--and that I fully fleshed it out. The idea is simpler, and is the one I would imagine would immediately occur to most people. Namely, it's simple--$3$ ramifies in $\mathbb{Q}(\sqrt{3})$ but not in $\mathbb{Q}(\sqrt[4]{2})$, so we can't possibly have $\sqrt{3}\in\mathbb{Q}(\sqrt[4]{2})$.
Comment: +1.  I think you mean, $b + c\sqrt[4]{2^2} + d\sqrt[4]{2^3}$, yes?
Comment: @Goos I did, thank you :)
Comment: I do not understand your first explanation very well, I do not know why your trace is 0 in the first series of equalities, nor do I have any clue where your second equality came from (the one with b,c,d).
Comment: @JohnnyApple The first equality just uses the fact that the trace is transitive. The second equality comes from using the fact that necessarily $a=0$, and so $\sqrt{3}=b\sqrt[4]{2}+c\sqrt[4]{2^2}+d\sqrt[4]{2^3}$, and then dividing both sides by $\sqrt[4]{2}$.
Answer: But more simply, if $\sqrt3$ is an element of $Q[\sqrt[4]2]$, then $Q[\sqrt2,\sqrt3]$ is a subfield of $Q[\sqrt[4]2]$. However, since both are order 4, they must be isometric. But the first is a splitting field and the second is not.

Number field question


iframe - weird src - data:image/png - how it gets parsed

Question: i saw this:

and this will be rendered in html as real url,
how does this weird thing work?
Answer: It's a data URI - https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
They "allow content creators to embed small files inline in documents". (quote from MDN)
Answer: It is a data URI, which is a resource, typically an image, embedded in the URI as opposed to one loaded from an external URL.
iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAFElEQVQYV2P8DwQMBADjqCKiggAAmZsj5vuXmnUAAAAASUVORK5CYII   is  sResourceData for this iframe.
what is sResourceData:  A text-representation of the data of the resource, where content is represented as URL-allowed characters. Unsafe characters must be percent-encoded.
If src is set to base64 it tells that the data specified by the sResourceData parameter is encoded as base64; otherwise, the data is assumed to be percent-encoded.
for more info read this:http://msdn.microsoft.com/en-us/library/cc848897(v=vs.85).aspx


How to properly stub an element when unit testing a LitElement component?

Question: I'm trying to unit test LitElement components. When trying to isolate components, I got perplexed how to actually stub elements. That is, I cannot find a solution how to replace a proper element with a hollowed one.
The polymer project on the topic of unit testing mentions this I failed to find the definition of the replace() function to see the implementation details. Actually, what is described by the polymer project in the "Create Stub Elements" heading is what I'm looking for.
Element definition file
export class AppElement extends LitElement {
    render() {
        return html`

                <menu-element></menu-element>
                <social-media-element></social-media-element>
                <contacts-element></contacts-element>
                <tap-list-element name="Fridge List" display="fridge"></tap-list-element>
                <tap-list-element route="tap" name="Tap List" display="tap" ></tap-list-element>
                <home-element></home-element>
                <about-us-element></about-us-element>
                <not-found-element></not-found-element>

       `;
   }
}

Element testing file
describe("Test Case for the AppElement Component", function() {
beforeEach(() => {
    app = new AppElement();
    document.body.appendChild(app);
    shadow = app.shadowRoot;
    app.updateComplete.then(() => {
        const tapListStub = new TapListElementStub();
        const tapListNodes = shadow.querySelectorAll('tap-list-element');
        console.log(app);
        const tapListLength = tapListNodes.length;
        const tapListNode = tapListLength === 1 ? tapListNodes[0] : null;
        tapListNode.replaceWith(tapListStub);
    });
});

it("should have the node for tap-list replaced with a stub", function(done) {
    app.updateComplete.then(() => {
        const newTap: TapListElement = shadow.querySelector('tap-list-element');
        console.log(shadow);
        assert.strictEqual('Tap List Stub', newTap.name);
        done();
    })
});

Here is the code for the original TapListElement
@customElement('tap-list-element')
export class TapListElement extends LitElement {
    private _menu: Menu;
    private _tapList: Section;
    private _bottleList: Section;

    @property()
    name: string = 'Tap List';

    @property({type: String, attribute: true})
    display: string;

    constructor() {
        super();
        super.connectedCallback();
    }
}

And here is the stub
@customElement('tap-list-element')
export class TapListElementStub extends LitElement {

    @property()
    name: string = 'Tap List Stub';

    @property({type: String, attribute: true})
    display: string;

    constructor() {
        super();
        super.connectedCallback();
    }
}

Apologies for any indentation typos.
When I tried the code above, I get the error that the web component with that name "tap-list-element" had already been registered. I tried removing the @customElement decorator in the TapListElementStub but then I get the error that an Illegal Constructor had been called.
Has anyone tried stubbing litElement components?
I'm coming from an Angular background. There the TestBed helper library sets up the module and you can substitute any component as long as the attributes remain the same and the name of the component in the decorator is the same.
Answer: The first error is likely caused by <tap-list-element> being defined twice in the two versions. This is not avoidable since as of now custom elements are not un-definable (and thus re-definable with a different class). Removing the registration call as you tried doesn't solve the problem because the component would still be created using the original class.
The simplest solution would be to use a different tag name (even the Polymer docs you cited do this). If you really need the tag names to be the same then what I can suggest is to only replace some properties/methods of the original class. OpenWC and Modern Web testing guides have some parts (1, 2) dedicated to this.
Comment: thank you. The resources you references are the perfect starting point. I'm thinking that somehow implementing the import-maps would solve my issue.


How to determine the block device booted from in a shell script?

Question: I'm crafting up a shell script (to be called by cron) that runs smartctl on the booted disk on a weekly basis. Is there a fairly universal way to determine what the boot block device is (IE - /dev/sda, /dev/hdb, etc)? The expected install would be standard, I think I could get away with using grep " / " on /etc/fstab, I'm just wondering if there's a more graceful way.
This script will specifically be deployed on Fedora and possibly Ubuntu boxes.
Comment: Are you really looking for the boot device, or are you looking for the root device?  If you are looking for / in fstab, and your boot device is different from your root device then you may not get the results you want.
Comment: That is a valid point. For my specific needs, it will always be the same device.
Comment: What boot-loader are you using on these machines?
Comment: Grub currently, but the best solution should be future-proofed against alternatives.
Answer: df -P / | tail -n 1 | awk '/.*/ { print $1 }'
Will return the root FS block device. Not necessarily the boot device though.
Better question might be why you're not scanning SMART on all the disks in the server?
Comment: In my specific case, this is a script that will be deployed to hundreds of single-disk kiosk machines with either a SATA or PATA disk (so 99% of them would be /dev/sda or /dev/hda, I just want to make sure I don't miss the 1% that somehow ended up being /dev/sdb or something). Your solution almost works. Unfortunately, what I need is the boot device (That returns /dev/sda3, I just need /dev/sda).
Answer: for /boot:
readlink -f /dev/block/$(mountpoint -d /boot)
for rootfs:
readlink -f /dev/block/$(mountpoint -d /)
Explanation:
1) mountpoint -d
 - gives major:minor numbers of device mounted at
2) /dev/block folder
- contains symlinks os all block devices by device numbers pointing back to regular device file in /dev
3) readlink -f
- reconstruct device name from sym link
Works on all modern Linuxes
Comment: This needs an explanation.
Answer: cat /proc/mounts |grep /boot |awk '{print $1}'

Will return something like /dev/sda1 if your /boot is not on the root device.Combine this with the answer from Chris S.
Answer: You've probably long since moved on from this task, but I was trying to do something similar and figured I'd look into the missing piece of your puzzle, namely to get the drive designation (e.g. /dev/sda) instead of the partition designation (e.g. /dev/sda1).
I started off with Chris S's excellent answer (which also solved the task I was seeking to accomplish), and then just used good old fashioned bash string manipulation to trim the number off the end (leaving you with the drive vs the partition):
# first, save the output (e.g. /dev/sda1) to a variable
rootpart=$(df -P / | tail -n 1 | awk '/.*/ { print $1 }')

# now you can trim the number off:
echo ${rootpart//[[:digit:]]/}

# if ${rootpart} was "/dev/sda1", output would be "/dev/sda"


Can p4api.net connect to a (local) p4 personal server?

Question: Can p4api.net connect to a (local) p4 personal server?
I started a personal server with
p4 -u itsame -d c:\perforce\local -c itsameClient clone -m 1 -v -p p4server:somePort -f //repo/path/...

It works - it can use it in p4v or from the command like - there's even the .p4root in c:\perforce\local.
However, from the latest p4api.net, it just keeps trying to use TCP to connect. Is there no way to say this is to the file system - or perhaps does the personal server expose itself to localhost:port somehow?
Comment: What `P4PORT` value are you using in your P4API.NET application?
Comment: I just point it to the .p4root file on the file system.I assume that's wrong, but I couldn't find or see anything about a local tcp endpoint being instantiated.
Comment: Run `p4 set` at the command line in your local server to see what the `P4PORT` syntax is for connecting to a personal server and launching a p4d each time you run a command (`rsh:p4d...` or something like that).  If you just set it to your P4ROOT folder, what's probably happening is that it's trying to do a DNS lookup on the string `.p4root` or whatever you gave it.
Comment: You may also be able to just use the `.p4config` file that was set up as part of the `p4 clone` (rather than hardcoding P4PORT) if you set `cwd` correctly in your P4API application and don't override any of the other connection settings.
Answer: The client application's P4PORT needs to be set correctly in order to connect to a server.  For a remote server you simply specify the hostname:port.  For a personal server, there's a special P4PORT syntax that specifies how the local server executable is to be invoked to service client requests.  You can see it by running p4 set P4PORT within your personal server directory:
C:\Perforce\test>p4 set P4PORT
P4PORT=rsh:p4d.exe -i -r "c:\Perforce\test\.p4root" (config 'c:\Perforce\test\p4config.txt')

Note that when you initialize a personal server, it automatically sets up P4CONFIG in that directory, which is why that P4PORT is automagically set for you already.  Your P4API.NET application should be able to use that same config (removing the need to manually copy over the P4PORT string) as long as:

it has the correct cwd set (i.e. the directory the personal server lives in)
the P4PORT is not overridden with an incorrect value


on click doesn't seem to fire

Question: having what I imagine is probably a simple problem. Although I've set alerts in my on click "toggle" function, they never appear. I presume the trouble is somehow with adding the event handlers, but I really don't know. Any thoughts would be greatly appreciated! Many thanks.
index.html:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Men With Arms</title>

MEN WITH ARMS

LLOYD

DAD

MARTHA

                        © mothers favorite pictures 2012

                            moc.smrahtiwnem@mom

scripts.js:
function toggle(e) {
    alert('click!');
    alert(get_source_element(e).tagName);
    if (get_source_element(e).tagName=='a') {
        document.getElementById(get_source_element(e).innerHTML.toLowercase()).style.display='block';
        document.getElementById('front').style.display='none';
        return false;
    }
    else {
        alert('hide!');
        var frames = document.getElementById('content').getElementsByTagName('iframe');
        for (i = 0; i < frames.length; i++) {
            frames[i].style.display='none';
        }
        document.getElementById('front').style.display='block';
    }
}
// return event source
function get_source_element(e) {
    var targ;
    if (!e) e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    return targ;
}
function load() {
    document.getElementById('yall').addEventListener('onclick', toggle, false);
    document.getElementById('content').addEventListener('onclick', toggle, false);
    var as = document.getElementById('menu').getElementsByTagName('a');
    for (i = 0; i < as.length; i++) {
        as[i].addEventListener('onclick', toggle, false);
    }
}
document.addEventListener('DOMContentLoaded', load, false);

Answer: You may try this
document.addEventListener('DOMContentLoaded', load, false);

or
window.onload=load; // onload will work in all browsers so use this

The load function
function load()
{
    var yall=document.getElementById('yall');
    addEvent(yall, 'click', toggle, false);
    var content=document.getElementById('content');
    addEvent(content, 'click', toggle, false);
    var as = document.getElementById('menu').getElementsByTagName('a');
    for (i = 0; i < as.length; i++) {
        (function(n){
            addEvent(as[n], 'click', toggle, false);
        })(i)
    }
}

The addEvent function to work with both addEventListener and attachEvent
function addEvent(el, event, func, bubble)
{
    if(el.addEventListener) el.addEventListener(event, func, bubble)
    el.attachEvent('on'+event, function(){ func.call(el) }, bubble);
}

Also notice the e that is the event object in your toggle function
function toggle(e)
{
    e=e||window.event; // if you need event object, that's e
    alert(e.type+' occured on'+this.innerHTML);
}

An Example.
Answer: When calling addEventListener, you should drop the on prefix. So just click.
Additionally, to allow support for browsers that use attachEvent, try this:
var elem = document.getElementById('yall');
(elem.attachEvent || elem.addEventListener)('click',toggle,false);

on click doesn't seem to fire


Use avahi in schroot (chroot) environment

Question: I'm working on debian wheezy and use avahi to communicate with test hardware. For a renewal of the test suite I had to change to a chroot environment (jessie). Is there any possibility to find an 'avahi on chroot' solution, so that I can communicate with the test hardware as before?
Answer: Found a way to solve this issue:

In your host machine (wheezy in my case) do:
sudo vi /etc/schroot/default/fstab
and add the line
/var/run/avahi-daemon  /var/run/avahi-daemon       none    rw,bind     0   0
In the chroot environment (jessie in my case) do:
sudo apt-get install libnss-mdns
and
sudo vi /etc/nsswitch.conf
there make sure the line for the hosts looks like this:
hosts:  files mdns4_minimal [NOTFOUND=return] dns mdns4
Comment: Instead of editing the default profile, it might be a better idea to create your own profile and edit it there. `cp -R /etc/schroot/default /etc/schroot/myprofile` and then set `profile=myprofile` in your `schroot.conf`.


Is it possible to send a message to a user's friend using the Bots for Messenger API?

Question: I am looking at using the new Facebook Messenger API to send a message to a user's friend.
For example:
Alice's messenger session:

Alice: Send this result to Bob
Bot: Did you mean Bob Smith?
Alice: Yes
Bot: OK, sent.

On Bob's messenger:

Bot: Alice wanted to let you know that x

Obviously Facebook has to have some spam control in place.
Is this scenario possible without Bob having to connect with the Messenger bot first?
Comment: I hope not … sounds like ti would generate a lot of spam.
Comment: Very much doubt it. The user ID's you use to send a message to a user, or get their name/profile picture, are contextual to your facebook page. For example, if one user chat to both Page A and Page B - the user ID those pages receive for that user are both different.
Answer: recently they introduce the Share Button. This button can be included on a generic template. The problem is that the message will be sent by the user who clicks on Share and not by the bot.
Here the reference: https://developers.facebook.com/docs/messenger-platform/send-api-reference/share-button
Answer: The only way how to send post to an "unknown" user is try "customer matching" (one time $99 fee).
From documentation:

When messages are sent to phone numbers, we will only send the message
  if we have a certain level of confidence of expected delivery. If you
  find that during testing you cannot message your own phone number,
  re-verify it under Facebook user settings and wait 24 hours. At that
  point, you should be able to successfully send a message to your own
  phone.


Orchestration question: Should I change which woodwinds get which lines?

Question: I have orchestrated the exposition of Eine Kleine Nachtmusik and gotten several comments. Here I will concentrate on a single comment that I got, that the oboes are too high in bar 11. I got no suggestions as to how to fix the issue though, which I thought was just wrong, given that I had a detailed analysis of my orchestration mistakes. But I thought of a few solutions to the issue. Here is the edition of Mozart's score that I used for my orchestration:
Mozart's Werke Edition
I would use the Mozart manuscript, since it is written neatly and easily readable. But most of the Mozart manuscript isn't there, just a few pages of each movement. So the manuscript is out of the question as far as reference material goes.
And here is what the woodwinds look like in bars 10-15 of my orchestration:

The green note is just defaults from Musescore, I didn't make that note green, in case you were wondering.
Just in case you are wondering, here is my instrumentation:

2 Flutes
2 Oboes
2 Clarinets
2 Bassoons
2 Horns(I originally thought of having a third horn but was told that it wasn't very Mozartesque to do that, so I retracted the third horn)
2 Bb Trumpets(I was told that I should change this to C trumpets, but Bb is the default for the Classical Orchestra template)
Tympani
1st Violins
2nd Violins
Violas
Cellos
Double basses

Here are my proposed solutions for the woodwind issue at bar 11:
Option 1: Switch oboes and clarinets
Here, I would move the oboe part to the clarinets and likewise, I would move the clarinet part to the oboes. This would, if I'm correct on this, give a mellower sound than having the oboes up in that range. Just to make sure that I don't overwrite anything in the process of doing this in Musescore, I had the horns be silent here. Here is what it looks like after the switch:

Option 2: Oboes double clarinets, Flutes take over oboe part
Here, I would simply have the oboes doubling the clarinets. The flutes would be playing what in the previous version, I had the oboes play. Here is what it looks like after that change:

Myself, I think I prefer the oboe and clarinet switch over the doubling. I already have enough doublings between the woodwinds and the strings. I don't need more between 2 different woodwind parts. Plus, I think that upper reinforcement of the flutes is necessary. Having the flutes take over the oboe part would get rid of this upper reinforcement.
Here is what I have so far of my orchestration, so that you can listen to it. Note, that this is before any error corrections occurred.
https://musescore.com/user/50070/scores/5626150
Should I go with option 1 or option 2? Or is there something else that I missed? Note: I'm not thinking of just taking the oboe out entirely. That would be, I think, the worst option.
Answer: Here's an idea which you might consider, which none of your examples show: use the oboes, but don't give the first oboe the top line. Here is an extract (b.36-39) of the first movement of Mozart's Symphony 41, K551. The staves are flute, oboes, bassoons. No other instrument doubles the flute or 1st oboe at that point.

To translate that to your arrangement: how about giving the flute the theme as you've done, and give one oboe the next line down (the line you give the 2nd oboe in your first example). A flute playing that high can well be heard, without the need for an oboe to double it at the unison.
Answer: The problem seems to be of your own making, since you decided to move the top lines of Mozart's version up an octave. In your first version, you then have the oboes screaming away on their top notes (optimistically marked "p" with a slur) with the "tenor" and "bass" parts a long way apart, and a long way below the tune. The result will just sound weedy (because of the big gaps between the parts) and out of tune (because pairs of woodwinds playing in unison always are out of tune with each other, in real life!)
If you want to double up woodwind lines, do it on different instruments, e.g. make Ob 1 and Cl 1 play in unison (or in octaves) and Ob 2 and Cl 2 play a different line in unison.
If you want the top part an octave higher than Mozart wrote it, the only realistic solution is two flutes as in your "option 2."
Mozart wrote "textbook" four part harmony here, for four instruments (strings) of the same family with homogeneous timbres. Woodwinds are anything but homogeneous, and to avoid the out-of-tune-unison issues classical woodwind scoring is often in 8 parts, not 4. Of course classical woodwind scoring also includes a lot of solo passages - don't make everybody play all the time.
If you want to arrange this passage for wind, do something like this (which is only in 6 parts, not 8!), and don't be scared to add notes that Mozart didn't write:
Of course you could get a lot more adventurous than the above. Starting the tune to the bassoons an octave lower than Mozart's version and letting it progress upwards from instrument to instrument  might be fun, for example:


How do I create a View Modifier that returns a view as well as an action?

Question: I have created a View modifier alongside a sheet manager to deal with and create popup views throughout my project. It works perfectly with a simply popup and a close button to dismiss the view. Now what I am trying to is add more functionality to this sheet manager and modifier so that I can create/use heftier custom popups. By that I mean being able to use buttons and their actions on these popups.
view modifier code
    func popup(with sheetManager: SheetManager, action: @escaping () -> Void) -> some View {
        self.modifier(PopupViewModifier(sheetManager: sheetManager){ })
    }

function/view being called
struct PopupViewModifier: ViewModifier {
    @ObservedObject var sheetManager: SheetManager
    var popupAction: () -> (Void)

    func body(content: Content) -> some View {
        content
            .disabled(sheetManager.action.isPresented ? true : false )
            .blur(radius: sheetManager.action.isPresented ? 05 : 0)
            .overlay(alignment: .center) {
                if case let .present(config) = sheetManager.action {
                    switch config.type {
                    case .popupAlert:
                        PopupView(config: config) {
                            withAnimation {
                                sheetManager.dismiss()
                            }
                        }
                    case .soundProfileList:
                        SoundProfilePopupView(config: config) {
                            withAnimation {
                                sheetManager.dismiss()
                            }
                        } tappedProfile: {
                            popupAction()
                        }
                    }
                }
            }
            .ignoresSafeArea()
    }
}

And how its called in the main view where I am trying to get the action callback
@EnvironmentObject var sheetManager: SheetManager

var body: some View {
    buttonToCallPopup( didPress: {
        sheetManager.present(with: Config.innit)
    }) {
        Text("Open up popup")
      }
    .popup(with: sheetManager) {
      print("button from popup has been pressed")
    }
}

SheetManager code
enum SheetType {
    case popupAlert
    case soundProfileList
}
final class SheetManager: ObservableObject {
    typealias Config = Action.Info
    @Published private(set) var action: Action = .na

    enum Action {
        struct Info {
            let systemName: String
            let title: String
            let content: String
            let type: SheetType
        }

        case na
        case present(info: Info)
        case dismiss
    }

    func present(with config: Config) {
        guard !action.isPresented else { return }
        self.action = .present(info: config)
    }

    func dismiss() {
        self.action = .dismiss
    }
}

extension SheetManager.Action {
    var isPresented: Bool {
        guard case .present(_) = self else {return false}
        return true
    }
}

I have tried creating a typealias of Void and View so that popup can return that, and I have also tried making popup return just a closure so that I could call
.popup(with: sheetManager) { // action I want taken on the button of the popup view
}

but I have met only build errors and no action. It took awhile to reduce the errors but there is still no action. the action I want to be done from the .popup is what I want propagated up from tappedProfile which is being called in the view modifier.
Comment: "I have met only build errors"—okay, so edit your question to include the code that produces build errors, and also include the errors. And please be sure to copy and paste accurately. I can see a couple of typos in the code you already posted that I do not think are the errors you need help with.
Answer:  func popup(with sheetManager: SheetManager, action: @escaping () -> Void) -> some View {
        self.modifier(PopupViewModifier(sheetManager: sheetManager){  action() })
    }

action() was never being used, and just needed to be called in the function


Fitting a histogram with python

Question: I have a histogram
H=hist(my_data,bins=my_bin,histtype='step',color='r')

I can see that the shape is almost gaussian but I would like to fit this histogram with a gaussian function and print the value of the mean and sigma I get. Can you help me?
Comment: "fit this histogram with a gaussian function"?  Usually we just compute the mean and standard deviation of the histogram directly.  What do you mean by "fit this histogram with a gaussian function"?
Comment: There are equations for the mean and standard deviation of any set of data points regardless of their distribution.  And any curve (such as a straight line y = mx + b) can be fit to any set of data.  You will need to read up on basic statistical functions (mean, median, mode, variance, ...) and least-squares approximation.  Understand curve fitting for basic (linear and quadratic) functions first before trying it out on more complex curves.
Comment: Curve fitting is not actually required, if you've got the data. Just find the mean and the standard deviation, and plug them into the formula for the normal (aka Gaussian) distribution (http://en.wikipedia.org/wiki/Normal_distribution).
Comment: The mean of a histogram is `sum( value*frequency for value,frequency in h )/sum( frequency for _,frequency in h )`.  The standard deviation is equally simple -- but a bit long for a comment.  Can you please **update** the question to explain in more detail what you're trying to do?
Comment: how can you compute the mean and standard deviation "directly". What if the histogram is not really a gaussian and I want to fit it, let's say, with a log-normal distribution?
Comment: @ThomasK: BTW, finding the mean and standard deviation is actually curve fitting for a Gaussian distribution (and is the optimal fitting mechanism in certain senses).
Answer: Here you have an example working on py2.6 and py3.2:
from scipy.stats import norm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# read data from a text file. One number per line
arch = "test/Log(2)_ACRatio.txt"
datos = []
for item in open(arch,'r'):
    item = item.strip()
    if item != '':
        try:
            datos.append(float(item))
        except ValueError:
            pass

# best fit of data
(mu, sigma) = norm.fit(datos)

# the histogram of the data
n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)

# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=2)

#plot
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma))
plt.grid(True)

plt.show()

Comment: Because of deprecation issues, "scipy.stats.norm.pdf" is preferable instead of "mlab.normpdf"
Comment: I want to do this to my dataset, without scaling, thus getting my data's sigma.. Not some scaled sigma!
Comment: @user2820579 What do you mean with the "fitting of the height" ? This post perfectly answers the question on the OP. If it doesn't fit your particular problem, make a new question, but do not downvote a valid answer.
Comment: "AttributeError: module 'matplotlib.mlab' has no attribute 'norm'": Use `from scipy.stats import norm` and `norm.pdf()` instead
Comment: Sorry, I misunderstood the `(mu, sigma) = norm.fit(datos)`.
Comment: Is this a Guassian fit?
Comment: @JamesWarner, Yes, use data parameters to draw the line for a normal distribution
Comment: For the Histogram plot, I would label the Y axis as density or frequency rather than probability to avoid the wrath of Statisticians. https://math.stackexchange.com/a/105456
Comment: @MossaNova you can read how the norming is done in the docs (https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html). Bascially you just need to multiply the normpdf-values by `sum of all your bin-heights` * `bin-width`
Answer: Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail.  An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).
from pylab import *
from numpy import loadtxt
from scipy.optimize import leastsq

fitfunc  = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
errfunc  = lambda p, x, y: (y - fitfunc(p, x))

filename = "gaussdata.csv"
data     = loadtxt(filename,skiprows=1,delimiter=',')
xdata    = data[:,0]
ydata    = data[:,1]

init  = [1.0, 0.5, 0.5, 0.5]

out   = leastsq( errfunc, init, args=(xdata, ydata))
c = out[0]

print "A exp[-0.5((x-mu)/sigma)^2] + k "
print "Parent Coefficients:"
print "1.000, 0.200, 0.300, 0.625"
print "Fit Coefficients:"
print c[0],c[1],abs(c[2]),c[3]

plot(xdata, fitfunc(c, xdata))
plot(xdata, ydata)

title(r'$A = %.3f\  \mu = %.3f\  \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));

show()

Output:
A exp[-0.5((x-mu)/sigma)^2] + k
Parent Coefficients:
1.000, 0.200, 0.300, 0.625
Fit Coefficients:
0.961231625289 0.197254597618 0.293989275502 0.65370344131

Comment: I am wondering why i get very different fits when using your function and the one joaquin proposes? see my related question for details.... https://stackoverflow.com/questions/44630658/difference-scipy-stats-norm-mlab-normpdf-and-fitting-gaussian
Answer: Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.
The NormalDist object can be built from a set of data with the NormalDist.from_samples method and provides access to its mean (NormalDist.mean) and standard deviation (NormalDist.stdev):
from statistics import NormalDist

# data = [0.7237248252340628, 0.6402731706462489, -1.0616113628912391, -1.7796451823371144, -0.1475852030122049, 0.5617952240065559, -0.6371760932160501, -0.7257277223562687, 1.699633029946764, 0.2155375969350495, -0.33371076371293323, 0.1905125348631894, -0.8175477853425216, -1.7549449090704003, -0.512427115804309, 0.9720486316086447, 0.6248742504909869, 0.7450655841312533, -0.1451632129830228, -1.0252663611514108]
norm = NormalDist.from_samples(data)
# NormalDist(mu=-0.12836704320073597, sigma=0.9240861018557649)
norm.mean
# -0.12836704320073597
norm.stdev
# 0.9240861018557649

Answer: Here is another solution using only matplotlib.pyplot and numpy packages.
It works only for Gaussian fitting. It is based on maximum likelihood estimation and have already been mentioned in this topic.
Here is the corresponding code :
# Python version : 2.7.9
from __future__ import division
import numpy as np
from matplotlib import pyplot as plt

# For the explanation, I simulate the data :
N=1000
data = np.random.randn(N)
# But in reality, you would read data from file, for example with :
#data = np.loadtxt("data.txt")

# Empirical average and variance are computed
avg = np.mean(data)
var = np.var(data)
# From that, we know the shape of the fitted Gaussian.
pdf_x = np.linspace(np.min(data),np.max(data),100)
pdf_y = 1.0/np.sqrt(2*np.pi*var)*np.exp(-0.5*(pdf_x-avg)**2/var)

# Then we plot :
plt.figure()
plt.hist(data,30,normed=True)
plt.plot(pdf_x,pdf_y,'k--')
plt.legend(("Fit","Data"),"best")
plt.show()

and here is the output.
Answer: I was a bit puzzled that norm.fit apparently only worked with the expanded list of sampled values.  I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples.  Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...
# histogram is [(val,count)]
from math import sqrt

def normfit(hist):
    n,s,ss = univar(hist)
    mu = s/n
    var = ss/n-mu*mu
    return (mu, sqrt(var))

def univar(hist):
    n = 0
    s = 0
    ss = 0
    for v,c in hist:
        n += c
        s += c*v
        ss += c*v*v
    return n, s, ss

I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead.  Feel free to point to the correct way to do it and downvote me :-)
Comment: Thanks! Yeah, it would be nice to see something like this, which I wrote up at [ENH: Accept run-length encoded data as input to functions like scipy.stats.describe() · Issue #15679 · scipy/scipy](https://github.com/scipy/scipy/issues/15679)

Fitting a histogram with python


Obtain pod labels of kubernetes deployment

Question: I'm trying to write code in Go to fetch the labels of the pods created in a deployment. For example:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

I know if I use ObjectMeta, I would be able to fetch the metadata of the deployment, but I would not be able to fetch the spec. Is there a way to get the data from the spec level of the resource?
Comment: Add your code in the question
Answer: Using kubernetes client-go and this example I was able to get the labels for each container
package main

import (
    "context"
    "flag"
    "fmt"
    "log"
    "path/filepath"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/homedir"
)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()

    // use the current context in kubeconfig
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        log.Fatalf(err.Error())
    }

    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatalf(err.Error())
    }

  // get pods
    pods, err := clientset.CoreV1().Pods("your-namespace").List(context.TODO(), metav1.ListOptions{})
    if err != nil {
        log.Fatalf(err.Error())
    }

  // get labels
  for _, pod := range pods.Items {
    labels := pod.GetObjectMeta().GetLabels()
    fmt.Printf("%+v", labels)
  }
}


Powershell Regex Match Beginning and End String Doesn't Match?

Question: I am attempting to match the following string, it always
begins with Removing:
and ends with --- For User:
I tried using the following regex:
\bRemoving: \w+\ --- For User: \b

Removing: Random_Group_Here --- For User: - Should Match This
I'm trying to assign this regex to a powershell variable that I can use for a -replace string.
$regex = "\[\bRemoving: \w+\ --- For User: \b\]"

Comment: If you get rid of the `\b` on either end it works.
Comment: Oh wow you're right, thanks!
Answer: The last \b word boundary only matches if there is a word char (i.e. mostly a letter, digit, _) after the space at the end of the pattern. Since there is no such a char, the last word boundary prevents from matching.
Either remove the last \b, or - if you want to only match that space when not followed with a word char - with (?!\w) negative lookahead that will check just that.
You may also replace literal spaces with \s* (0+ whitespaces) / \s+ (1+ whitespaces)  patterns to match any kind and any amount of whitespace between specific chars.
Here is a variation:
\bRemoving:\s*\w+\s*---\s*For\s+User:\s*

See the regex demo.
Comment: @LotPings Regex101 does not support .NET regex. To have a similar .NET experience, I'd recommend Ultrapico Expresso. See a [screenshot](http://imgur.com/a/0rLnn). I posted a link to an online regex tester (RegexStorm.net) that supports .NET regex syntax, it is a *proof* that the regex will work in Powershell that uses .NET regex, too.
Comment: IMO [RegEx101](https://regex101.com/r/vM3BS1/1) has better explanations.


Automap package: Negative values and variogram fitting

Question: I started using the automap package for automated variogram modelling two days ago and played around with it (doing it manually was tedious and doesn't come with too many advantages...although I find it strange that automap seems really to love the Matérn function for modelling the variogram). What came to my mind was the presence of negative values in the dataset while those were not shown on the map that is produced by this package.
Here is a figure I just glued together: Nr. 1 is the output after using autoFitVariogram and autoKrige. It appears to have no negative values. As I didn't like the graphical output, I performed ordinary kriging with gstat that uses the variogram from autoFitVariogram (from automap) (Nr. 2) and it clearly shows areas of negative precipitation. I exported the map produced from autoKrige to QGIS and double checked and there were also lots of negative values (Nr. 3; blackened areas).

So my questions:
1.) The kriging prediction map produced by autoKrige apparently produces a map that follows a scheme such as "if var.pred < 0 then 0". I can see this is usefull for producing such a map, but how does this make sense with the actual data? I want to use my dataset for further analyses and negative rainfall values appear a bit...non-realistic. Would it be mathematically sound to just apply this "if var.pred < 0 then 0" scheme also to the data if this would make it physically plausible?
2.) You may determine variogram parameters additionally with Generalized Least Squares (GLS) as an own argument in the automap package. However, I want to use a REML fit from gstat (fit.variogram.reml). I tried substituting variogram$var_model with my REML estimates (which also produced my modified variogram), but when performing kriging with autoKrige the original variogram model is used again. Is there a way to fit the model by other means than those provided by the package? (there is an argument 'data_variogram' in the autoKrige manual, but this seems to do something else).
Thanks!
Comment: I am quite sure automap does not restrict predictions to above zero. This is probably a by product of the variogram you are using. In addition, you cannot use fit.variogram.reml right now.
Answer:
I don't think this is the case; you seem to conclude this from looking at a graph, but please verify the numbers produced. Graph 1 does not appear to me that it does not contain negative values.
autoKrige uses fit.variogram, and cannot use fit.variogram.reml; that is how it's coded, but feel free to modify it.
Comment: 1. Graph 1 and 3 are from the identical output (Nr. 1 from `autoKrige` output, Nr. 3 the same map exported as an ascii file and imported in a GIS where I colored negative values in black, whereas graph 2 (not based on `autoKrige` but on `autofitVariogram`, so the same data) exposes areas with negative values. If graph 1 also contains negative values, the color scheme or the signature is really misleading then. I tried substituting all negative values for graph 2 with 0 (`ifelse(prediction_spdf$var1.pred<0,0,prediction_spdf$var1.pred)`) and it looked identical to graph 1.
Comment: 2. Such a pitty. Unfortunately I'm not capable of writing my own packages (yet), but Paul may take this as a possible future implementation :-)


Definir dimensão em px com base em dimensão em %

Question: Estou com problemas ao desenvolver um script de resize
function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.style.width + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();

O script não apresenta nenhum erro, porém, o height do elemento não é definido, o que está causando o erro e, como corrigir ?
Comment: Primeiro você atribui "25%" ao `width`, depois define que `heigth` será `width + "px"`, que resulta em `25%px`. Não parece fazer sentido. Quais são os valores exibidos no console?
Answer: Seu código:
function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.style.width + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();

Na terceira linha, você atribui o valor 25% ao atributo width. Na quinta linha, você atribui ao atributo height o valor de width concatenado com a string px. Considerando que o atributo terá o valor 25%, dada a linha 3, o valor de height será 25%px, que não faz sentido algum e o navegador provavelmente descarta.
Agora, se a sua intenção é obter o valor em pixels que o width possui após ser atribuído 25%, então você deve usar a propriedade offsetWidth do elemento. Ficaria algo como:
function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.offsetWidth + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();

Veja o exemplo:

function resizeImagePreview(){
    var imageHolder = document.getElementById("image-holder");
    imageHolder.style.width = "25%";
    console.log(imageHolder.style.width);
    imageHolder.style.height = imageHolder.offsetWidth + "px";
    console.log(imageHolder.style.height);
}resizeImagePreview();
#image-holder {
  background: blue;
}

Comment: Boa, eu tinha esquecido do `offsetWidth`. Provavelmente sua resposta tem performance melhor que a minha.
Comment: Sim, depende do que ele quer. É que as "peculiaridades" do box model + as peculiaridades dessas propriedades podem confundir.
Comment: perfeito, eu também havia esquecido de offsetWidth
Comment: Uma coisa de que me dei conta só agora: o `offsetWidth` vai incluir padding e bordas na conta, então atenção. Tem também o `clientWidth`, que só inclui o padding e não inclui bordas. Se essa div estiver com `box-sizing: content-box` (o padrão), nenhuma dessas propriedades bate com a largura, se houver bordas e/ou padding.
Comment: @bfavaretto Mas `padding` e `border` não são modificadores das dimensões? Digo, faz sentido ser considerado no `width` visto que o elemento tem sua largura aumentada com o `padding` e `border`, diferente do `margin` que não modifica as dimensões.
Answer: Se entendi bem o que você quer, é necessário ler a largura calculada pelo browser e definir a altura com base nela. Algo assim:
var estilos = getComputedStyle(imageHolder);

// estilos.width já é uma string com 'px' no final.
// se quiser como número, usar parseInt(estilos.width, 10)
imageHolder.style.height = estilos.width;


Javascript só funciona após dois cliques

Question: Estou usando um menu lateral num site e queria que ele retraísse com um clique no botão... acontece que isso só está acontecendo após dois cliques!!
function resp() {

   var clique = document.getElementById("btn-menu");

   var menuLateral = document.getElementById("menu-lateral");

   clique.onclick = function (e) {

        e.preventDefault();

        menuLateral.classList.toggle('toggleMenu');

  };

}

Estou usando um link para chamar a função script:

menu-lateral é o id da div do menu lateral
toggleMenu é  a classe que é adicionada a div do menu lateral

Esse código eu peguei como base de outra pessoa, porém ela não usava como function() e não tinha um onClick na tag ... porém assim o meu não funciona... alguém sabe o que pode ser?? é chato ter que clicar duas vezes pro menu retrair (isso só acontece no primeiro toque depois de atualizado a página)
Comment: Por favor, marque uma das respostas com ✓. Não precisa ser a minha, mas é muito importante marcar uma resposta que lhe ajudou ou então informar o que não ajudou. Obg!
Answer: Acontece que da forma que você está fazendo, você está chamando a função resp e depois atribuindo uma nova ação ao botão btn-menu
Você não precisa adicionar o evento onclick novamente.

function resp() {
   var menuLateral = document.getElementById("menu-lateral");
   menuLateral.classList.toggle('toggleMenu');

   return false;
}

Answer: Você não precisa da função resp() e nem mesmo do onClick no elemento. Apenas o evento onclick = function já captura o click e resolve o problema. Da forma que está fazendo, está chamando duas funções após o primeiro click.
Usando .onclick

var clique = document.getElementById("btn-menu");
var menuLateral = document.getElementById("menu-lateral");
clique.onclick = function (e) {
     e.preventDefault();
     menuLateral.classList.toggle('toggleMenu');
};
.toggleMenu{
   background: red;
}
Menu

   itens do menu

Usando onclick

function resp() {
   var menuLateral = document.getElementById("menu-lateral");
   menuLateral.classList.toggle('toggleMenu');
}
.toggleMenu{
   background: red;
}
Menu

   itens do menu

Alternativamente, você pode chamar a função direto no href:

function resp() {
   var menuLateral = document.getElementById("menu-lateral");
   menuLateral.classList.toggle('toggleMenu');
}
.toggleMenu{
   background: red;
}
Menu

   itens do menu


Daily queries log file

Question: Has MySQL a daily log rotation system? like Apache that creates daily log files?
I'm having a very hard time to find any good info about this.
Win Server 2008 R2
MySQL 5.1.11
I'm logging all (general) queries and the log file size gets large very quickly. would be nice to divide it on a daily basis.
Answer: On Windows, the simplest way to rotate a query log is:

Rename the log file, e.g. rename mysql-query.log mysql-query-old.log
Flush the logs by issuing FLUSH LOGS from a MySQL CLI or mysqladmin flush-logs from Windows. This will cause MySQL to close the file you just renamed and create a new file with the original name.

Note that Step 1 could easily be scripted to append the date, then Step 3 to zip the file, etc.
See http://dev.mysql.com/doc/refman/5.1/en/log-file-maintenance.html
Comment: I've automated this before with Windows Script Host/JavaScript, and more recently used PowerShell/C# to automate similar tasks. Both have worked flawlessly in production.
Comment: I'm doing it that way today, I thought there may be a built-in feature that I don't know about. However, Thank you.
Comment: I've searched for such a thing before (and in answering this) and came up empty. Since the process described is officially recommended for all 5.x, this is probably as close to built-in as we will see.

Daily queries log file