No TCP connections to hosts behind VPN server (SYN, SYN-ACK, but no ACK), UDP, ICMP works

Question: I'm probably doing something incredibly stupid, but I just can't seem to figure out what. Here's what I'm trying to accomplish: I want remote users to be able to log into our network, so I set up a Windows 2008 Server as a VPN Server inside as a VM in XenCenter. Let's call him Benjamin. He's also doubling as a file server.
So far, what works:

Remote VPN Login with Mac, Windows and iOS Clients
Access to the file shares on Benjamin
Ping to all hosts on the local network and on the internet, even with big packets (>1000 bytes)

What doesn't:
I can't establish any TCP connection (SSH, HTTP, …) to hosts on the local network besides Benjamin itself. In Wireshark, I can see the SYN and SYN-ACKs on both the client and the computer I'm trying to reach, but there's never an ACK. (Funnily, in the Wireshark Logs I prepared there are some DUP ACKs for some reason - and they are exactly the wrong way around than how it should be. I have no idea why.)
There was a problem before with even pinging anything besides Benjamin, but I solved that by disabling IP checksum offloading on Benjamin (somehow it didn't work and then packets would be thrown away).
I tried setting really small MTUs on my client, setting the gateway to Benjamin on the computer in the internal network any lots of other stuff, but nothing helped.
I suspect it's some kind of routing issue, but those ACKs are nowhere to be found. Any ideas? Where should I investigate further? Thanks in advance!
Update:
Weird thing I just discovered: When I try to ssh from the internal network into the VPN client, the client gets the SYN (I see it in Wireshark), but again, he never responds. I get the feeling that it has to be some configuration issue on the clients, but on all of them? And what could it be? There's no Firewall, and according to Wireshark, the packet looks valid (checksum and all). Does anyone know why it wouldn't respond to neither a SYN nor a SYN-ACK, when there's no firewall which could throw away those packets?
Update 2:
To add to the confusion, I've just confirmed that using netcat and UDP, everything works correctly, in both directions (nc listening on internal network host and on the VPN client). Maybe TCP just doesn't like me anymore?
Here's some more information:
Local net:   172.17.0.0/16
Router:     172.17.0.1 (Port Forwarding TCP 1701, UDP 500 and 4500)
XenServer:  172.17.0.10
Benjamin:   172.17.1.1
VPN DHCP range: 172.17.7.1..240
Wireshark log on the client (172.17.7.2 when in the VPN):
No.     Time        Source                Destination           Protocol Length Info
      1 0.000000    172.17.4.4            172.17.7.2            TCP      68     ssh > 61653 [SYN, ACK] Seq=0 Ack=0 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641695654 TSecr=440887504 SACK_PERM=1

Frame 1: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61653 (61653), Seq: 0, Ack: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      2 5.337197    172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887658 TSecr=0 SACK_PERM=1

Frame 2: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      3 5.479947    172.17.4.4            172.17.7.2            TCP      68     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641701208 TSecr=440887658 SACK_PERM=1

Frame 3: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      4 6.256638    172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887667 TSecr=0 SACK_PERM=1

Frame 4: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      5 6.449901    172.17.4.4            172.17.7.2            TCP      56     [TCP Dup ACK 3#1] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641702152 TSecr=440887667

Frame 5: 56 bytes on wire (448 bits), 56 bytes captured (448 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      6 6.609908    172.17.4.4            172.17.7.2            TCP      68     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641702305 TSecr=440887667 SACK_PERM=1

Frame 6: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      7 7.258316    172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887677 TSecr=0 SACK_PERM=1

Frame 7: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      8 7.450032    172.17.4.4            172.17.7.2            TCP      56     [TCP Dup ACK 6#1] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641703139 TSecr=440887677

Frame 8: 56 bytes on wire (448 bits), 56 bytes captured (448 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      9 8.259938    172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887687 TSecr=0 SACK_PERM=1

Frame 9: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     10 8.490122    172.17.4.4            172.17.7.2            TCP      56     [TCP Dup ACK 6#2] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641704143 TSecr=440887687

Frame 10: 56 bytes on wire (448 bits), 56 bytes captured (448 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     11 9.249943    172.17.4.4            172.17.7.2            TCP      68     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641704904 TSecr=440887687 SACK_PERM=1

Frame 11: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     12 9.261766    172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887697 TSecr=0 SACK_PERM=1

Frame 12: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     13 9.430047    172.17.4.4            172.17.7.2            TCP      56     [TCP Dup ACK 11#1] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641705119 TSecr=440887697

Frame 13: 56 bytes on wire (448 bits), 56 bytes captured (448 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     14 10.263852   172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887707 TSecr=0 SACK_PERM=1

Frame 14: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     15 10.439839   172.17.4.4            172.17.7.2            TCP      56     [TCP Dup ACK 11#2] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641706132 TSecr=440887707

Frame 15: 56 bytes on wire (448 bits), 56 bytes captured (448 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     16 12.267344   172.17.7.2            172.17.4.4            TCP      68     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887727 TSecr=0 SACK_PERM=1

Frame 16: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     17 12.469629   172.17.4.4            172.17.7.2            TCP      56     [TCP Dup ACK 11#3] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641708126 TSecr=440887727

Frame 17: 56 bytes on wire (448 bits), 56 bytes captured (448 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     18 16.719912   172.17.4.4            172.17.7.2            TCP      68     ssh > 61653 [SYN, ACK] Seq=0 Ack=0 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641712353 TSecr=440887504 SACK_PERM=1

Frame 18: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61653 (61653), Seq: 0, Ack: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     19 21.679611   172.17.4.4            172.17.7.2            TCP      68     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641717388 TSecr=440887727 SACK_PERM=1

Frame 19: 68 bytes on wire (544 bits), 68 bytes captured (544 bits)
Point-to-Point Protocol
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0
Wireshark log in the computer in the local network (172.17.4.4):
No.     Time        Source                Destination           Protocol Length Info
      1 0.000000    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887658 TSecr=0 SACK_PERM=1

Frame 1: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      2 0.000102    172.17.4.4            172.17.7.2            TCP      78     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641701208 TSecr=440887658 SACK_PERM=1

Frame 2: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      3 0.950403    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887667 TSecr=0 SACK_PERM=1

Frame 3: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      4 0.950567    172.17.4.4            172.17.7.2            TCP      66     [TCP Dup ACK 2#1] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641702152 TSecr=440887667

Frame 4: 66 bytes on wire (528 bits), 66 bytes captured (528 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      5 1.104130    172.17.4.4            172.17.7.2            TCP      78     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641702305 TSecr=440887667 SACK_PERM=1

Frame 5: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      6 1.940779    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887677 TSecr=0 SACK_PERM=1

Frame 6: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      7 1.940962    172.17.4.4            172.17.7.2            TCP      66     [TCP Dup ACK 5#1] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641703139 TSecr=440887677

Frame 7: 66 bytes on wire (528 bits), 66 bytes captured (528 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      8 2.950009    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887687 TSecr=0 SACK_PERM=1

Frame 8: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
      9 2.950198    172.17.4.4            172.17.7.2            TCP      66     [TCP Dup ACK 5#2] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641704143 TSecr=440887687

Frame 9: 66 bytes on wire (528 bits), 66 bytes captured (528 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     10 3.714242    172.17.4.4            172.17.7.2            TCP      78     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641704904 TSecr=440887687 SACK_PERM=1

Frame 10: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     11 3.929627    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887697 TSecr=0 SACK_PERM=1

Frame 11: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     12 3.929819    172.17.4.4            172.17.7.2            TCP      66     [TCP Dup ACK 10#1] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641705119 TSecr=440887697

Frame 12: 66 bytes on wire (528 bits), 66 bytes captured (528 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     13 4.949931    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887707 TSecr=0 SACK_PERM=1

Frame 13: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     14 4.950122    172.17.4.4            172.17.7.2            TCP      66     [TCP Dup ACK 10#2] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641706132 TSecr=440887707

Frame 14: 66 bytes on wire (528 bits), 66 bytes captured (528 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     15 6.950093    172.17.7.2            172.17.4.4            TCP      78     61655 > ssh [SYN] Seq=0 Win=65535 Len=0 MSS=1240 WS=8 TSval=440887727 TSecr=0 SACK_PERM=1

Frame 15: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec), Dst: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff)
Internet Protocol Version 4, Src: 172.17.7.2 (172.17.7.2), Dst: 172.17.4.4 (172.17.4.4)
Transmission Control Protocol, Src Port: 61655 (61655), Dst Port: ssh (22), Seq: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     16 6.950281    172.17.4.4            172.17.7.2            TCP      66     [TCP Dup ACK 10#3] ssh > 61655 [ACK] Seq=1 Ack=1 Win=262140 Len=0 TSval=1641708126 TSecr=440887727

Frame 16: 66 bytes on wire (528 bits), 66 bytes captured (528 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 1, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     17 7.955752    172.17.4.4            172.17.7.2            TCP      78     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641709126 TSecr=440887727 SACK_PERM=1

Frame 17: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     18 11.196585   172.17.4.4            172.17.7.2            TCP      78     ssh > 61653 [SYN, ACK] Seq=0 Ack=0 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641712353 TSecr=440887504 SACK_PERM=1

Frame 18: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61653 (61653), Seq: 0, Ack: 0, Len: 0

No.     Time        Source                Destination           Protocol Length Info
     19 16.252632   172.17.4.4            172.17.7.2            TCP      78     ssh > 61655 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1060 WS=4 TSval=1641717388 TSecr=440887727 SACK_PERM=1

Frame 19: 78 bytes on wire (624 bits), 78 bytes captured (624 bits)
Ethernet II, Src: Apple_4e:5b:ff (c8:2a:14:4e:5b:ff), Dst: c6:4f:51:a3:48:ec (c6:4f:51:a3:48:ec)
Internet Protocol Version 4, Src: 172.17.4.4 (172.17.4.4), Dst: 172.17.7.2 (172.17.7.2)
Transmission Control Protocol, Src Port: ssh (22), Dst Port: 61655 (61655), Seq: 0, Ack: 1, Len: 0
Potentially related server fault questions, but didn't help me so far:
PPTP-Gateway routes icmp but no http
SNAT through Racoon IPSec VPN
Linux fails to interpret ACK, keeps resending SYN+ACK
Answer: I would start by taking a look at your masking.  If the general hosts are in 172.17.0.0/16 and your VPN subnet is in 172.17.7.0/24 then it's entirely possible for there to be some uncertain connectivity situations.
A general host in 172.17.0.0/16 when sending a packet to a VPN host in 172.17.7.0/24 will attempt to ARP for the VPN host's address (rather than sending it to a gateway).
The VPN host, in turn, tries to send a frame to a host in the general subnet.  It's going to send via its gateway.  If this gateway is a member of both the /24 and the /16 then you've got a similar problem - either it's an illegal configuration or the packet is actually being bridged rather than routed.
It's possible you have proxy-arp configured - that would cause a routing device to answer ARP requests in the larger subnet for a host it has a route to, but this isn't clear from your posted materials.
It's also possible that you have bridging set up somewhere in the mix.  This could yield some strange situations as a standard ARP would work in one direction but in the other some sort of gateway would be called upon to forward a nominally routed frame back out the receiving interface - which, again, might work in some circumstances but isn't good (nb - this could be a source of duplicate ACK's).
Can you put your VPN hosts in a non-overlapping subnet?  Say give it a 172.18.x.x address and then configure routing between the gateway for this new subnet and the default gateway for 172.17.0.0/16?  At a minimum this would make the whole thing simpler to troubleshoot and it very well might fix things.
Comment: I've updated my original post to correct an error - it's not actually a 172.17.7.0/24 subnet but rather the same /16 mask, it's just that the Windows Server assigns VPN clients IP from 172.17.7.1 to .240. As you mentioned ARP: I see on my internal host that in his routing table, he has an entry like this: `172.17.7.7         c6:4f:51:a3:48:ec  UHLWIi          0        2     en0   1196`. I guess that MAC address belongs somehow to the Windows Server, but how can I verify that? `ipconfig /all` gives me nothing. I'll try your suggestion with the different subnet now. Thanks!
Comment: Okay, so the VPN clients now get IPs from the 172.18.x.x range. When I added a static route on the router for 172.18.0.0/16 -> 172.17.1.1 pings started to work again, but it didn't change anything for TCP. Any additional info I could provide that might help? Any clue why those DUP ACKs seem to be coming from the internal host?


Parsing JSON/YAML as Network.HTTP.Base.Request

Question: I'm trying to parse a YAML chunk and create a Request instance from it.
So basically I have the following (implementations of FromJSON URI, FromJSON RequestMethod and FromJSON Header are omitted for brevity):
...
instance FromJSON (Request r) where
  parseJSON (Object v) = Request <$>
    v .: "uri" <*>
    v .: "method" <*>
    v .: "headers" <*>
    v .: "body"

Trying to compile (using GHC) this code produces:
    No instance for (FromJSON r)
      arising from a use of `.:'
    In the second argument of `(<*>)', namely `v .: "body"'
    In the expression:
      Request <$> v .: "uri" <*> v .: "method" <*> v .: "headers"
      <*> v .: "body"
    In an equation for `parseJSON':
        parseJSON (Object v)
          = Request <$> v .: "uri" <*> v .: "method" <*> v .: "headers"
            <*> v .: "body"

I feel it's a newbie question (and that's who I am), but apparently GHC cannot infer the type for the request body (which appears to be polymorphic) and I'm lacking the skills for handling this. Although I managed to "pacify" the compiler by replacing the instance declaration with:
instance FromJSON (Request Text) where
...

and adding {-# LANGUAGE FlexibleInstances #-} option, but I'm somehow sure it's wrong.
So, how do I properly parse this (and similar cases)?
Thank you!
Comment: That's probably fine. It just needs to be able to infer from the context what the `a` type needs to be. You can do this either by adding a type annotation where you're using it, or by restricting the type to something like `tj :: Maybe (Request Text)`.
Comment: Have you tried adding a `FromJSON` constraint to your instance? E.g. `instance FromJSON r => FromJSON (Request r)`
Comment: It worked! This makes sense, and the code got compiled. I tried testing it:

    tj :: Maybe (Request a)
    tj = decode "{uri: 'http://example.com/', method: GET, headers: [], body: 'hello'}"

...but got error:

    No instance for (FromJSON a)
      arising from a use of `decode'
    In the expression:
      decode
        "{uri: 'http://example.com/', method: GET, headers: [], body: 'hello'}"
    In an equation for `tj':
        tj
          = decode
              "{uri: 'http://example.com/', method: GET, headers: [], body: 'hello'}"

I wonder if I'm on the right track?
Comment: Updated the testing function declaration to:

`tj :: FromJSON a => Maybe (Request a)`

Now it compiles, but outputs:

    Ambiguous type variable `a0' in the constraint:
      (FromJSON a0) arising from a use of `tj'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression: tj
    In an equation for `it': it = tj

When I try to call "tj". I'm afraid, this is a wrong way to go.
Answer: Thanks to @hammar, the answer boils down to the 2 following points:
1) To be able to join the computation, "r" (which refers to the request body) in the instance declaration has to be restricted to "FromJSON" class.
instance FromJSON r => FromJSON (Request r) where
  parseJSON (Object v) = Request <$>
    v .: "uri" <*>
    v .: "method" <*>
    v .: "headers" <*>
    v .: "body"

2) and, when the parser is used, it must be explicitly notified of the body type it is to handle:
testJSON :: Maybe (Request Text)
testJSON = decode "{uri: 'http://example.com/', method: GET, headers: [], body: 'hello'}"

I'm not sure how obvious that was, but GHC could've inferred the class restriction on its own, I guess. Not yet, perhaps.


Currency Converter on python broken

Question: I am assigned to make a currency converter and I am not sure why it isn't working.
This is the program:
print(
    "Welcome to Currency Converter"
)

USD = input(
    "What amount of USD would you like to convert to another currency? Write only the number and click enter "
)

Currency = input(
    "Which currency would you like to convert USD from? (Options: The Canadian Dollar(CAD), The Swiss Franc(CHF), The Japanese Yen(JPY), or The British Pound(GBP) PLEASE ENTER 3 LETTER CURRENCY CODE IN UPPERCASE"
)

if Currency == "CAD":
    print(USD * 1.252910,
        " Canadian Dollars")

if Currency == "CHF":
    print(USD * 0.94122, " Swiss Franc")

if Currency == "JPY":
    print(USD * 109.29, " Japanese Yen")

if Currency == "GBP":
    print(USD * 0.71832,
        "British Pounds")

This question has been resolved I had not defined "USD" as an int before the input
Comment: Please elaborate on what isn't working, where you think the broken logic is, and what you've tried.
Comment: Your input USD is a string, not a number. You have to convert it into an integer with `int()`, before you can perform mathematical calculations with this variable. And chances are that you will benefit from reading [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)
Comment: `USD = int(input(...))`
Comment: Please don't post pictures of code or error messages on SO, post the text directly here in your question. And as we said: Your input in Python 3 is a string, you have to tell [Python to treat it as a number.](https://www.tutorialspoint.com/python3/python_numbers.htm)
Comment: Thank you for helping me with the type error. My program now works but I have a follow up question. Should I have this program be a def and if so how do I go about that. I thought I begin by having it be as follows
def CurrencyConverter
(put all the code here)
CurrencyConverter()

Will this prevent the prompt from closing instantly after running the code.
Answer: I took the liberty to remake your program with some "improvements".

Textwrap.dedent to format text nicely
Dictionary to hold the currency values
Functions to make sure you get valid input

Here:
from textwrap import dedent

curr_dict = {'CAD':1.252910,
             'CHF':0.94122,
             'JPY':0.71832,
             'GBP':109.29}

def float_input(text):
    while True:
        try:
            return float(input(text))
        except ValueError:
            print('Not a number! Insert correct value.')

def conversion_func(text):
    while True:
        currency = input(text)
        if currency in curr_dict:
            return curr_dict.get(currency)
        else:
            print('Not a valid currency. Try again.')

def main():
    '''
    Asks for amount to convert (USD) and desired currency
    Prints the result
    '''
    amount = float_input(dedent('''\
        Welcome to Joseph Pilotte's Currency Converter
        What amount of USD would you like to convert to another currency?
        Write only the number and click enter\n'''))

    conversion = conversion_func(dedent('''\n\
        Which currency would you like to convert USD from?
        (Options: The Canadian Dollar(CAD), The Swiss Franc(CHF),
                  The Japanese Yen(JPY) or The British Pound(GBP)
        PLEASE ENTER 3 LETTER CURRENCY CODE IN UPPERCASE'''))

    print(amount*conversion)

main()

Currency Converter on python broken


Problema com array no Java

Question: Estou tentando criar uma agenda de contatos em java, estou usando algumas classes que foram pedidas no exercício.
a classe principal:
    import java.util.Scanner;

    public class Lista15Q03 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int max = 3;

        Endereco end[] = new Endereco[max];

        Telefones tel[] = new Telefones[max];

        Emails email[] = new Emails[max];

        Contatos con[] = new Contatos[max];
        Contatos c = new Contatos();
        c.setEndereco(end);

        int op;
        int indice = 0;

        do {

            System.out.println("1 - adicionar");
            System.out.println("2 - listar");
            System.out.println("3 - mostrar");
            System.out.println("4 - alterar");
            System.out.println("5 - apagar");
            System.out.println("6 - sair");
            System.out.print("escolha: ");
            op = scan.nextInt();

            switch(op){
                case 1:
                    if(indice < max){

                        c = new Contatos();

                        System.out.println("nome: ");
                        String nome = scan.next();
                        c.setNome(nome);

                        System.out.print("nome da rua: ");
                        String rua = scan.next();
                        end[indice].setRua(rua);

                        System.out.print("número: ");
                        String num = scan.next();
                        end[indice].setNumero(num);

                        System.out.print("bairro: ");
                        String bairro = scan.next();
                        end[indice].setRua(bairro);

                        con[indice] = c;
                        indice++;
                    }else{
                        System.out.println("");
                        System.out.println("lista de contatos cheia");
                        System.out.println("");
                    }
                    break;
                case 2:
                    break;
                case 6:
                    break;
                default:
                    System.out.println("opção inválida");
            }

        } while (op != 6);

    }

}

a classe de contatos:
public class Contatos {
    private String nome;
    private Endereco[] endereco;
    private Emails[] email;
    private Telefones[] telefones;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Endereco[] getEndereco(){
        return endereco;
    }

    public void setEndereco(Endereco[] endereco){
        this.endereco = endereco;
    }

    public Emails[] getEmail() {
        return email;
    }

    public void setEmail(Emails[] email) {
        this.email = email;
    }

    public Telefones[] getTelefones() {
        return telefones;
    }

    public void setTelefones(Telefones[] telefones) {
        this.telefones = telefones;
    }

}

erro executando no terminal:

Exception in thread "main" java.lang.NullPointerException
          at Lista15Q03.main(Lista15Q03.java:46)

erro executando no netbeans:
Exception in thread "main" java.lang.NullPointerException
    at lista15q03.Lista15Q03.main(Lista15Q03.java:41)
/home/henrique/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 5 segundos)

Comment: Onde é a linha 46?
Comment: Esse indice do vetor  não foi inicializado, vc apenas inicializou ele como array, mas não individualmente
Comment: Você criou um vetor de endereços mas o vetor não possui nenhum objeto do tipo endereço. Logo você está acessando um vetor vazio. Por isso ocorre o nullpointer.
Comment: Posta o stack trace completo.
Comment: Poderia detalhar mais o projeto e aonde ocorre o problema?
Comment: a linha 46 é essa: end[indice].setRua(rua);
Comment: Os dois erros ocorrem em linhas diferentes, um diz linha 41 e outro 43
Comment: Tenho que criar uma agenda com funcionalidades crud, então criei 4 classes, Email, Telefones, Endereco e Contatos. Eu referencio a outras classes na classe contatos como array. Na classe principal do programa, eu instancio a classe Contatos e também jogo ela dentro do array.
Comment: Isso é por que no netbeans tem a linha do package e no sublime não. Então o erro é realmente a partir desse trecho: end[indice].setRua(rua);
Comment: então no caso eu tenho que instanciar Endereco e jogar o objeto dentro c.setEndereco(); ?
Answer: Faltou vc instanciar os objetos nas posições dos arrays end[], tel[], email.
Nas chamadas

Endereco end[] = new Endereco[max];

Telefones tel[] = new Telefones[max];

Emails email[] = new Emails[max];

Apenas foram instanciados os array de cada um desses objetos com operador new.
Para cada array vc precisa um for que percorre todo o array instanciando os objetos
Como no exemplo abaixo
  for (int i = 0; i < max; i++) {
            end[i] = new Endereco();
        }

No entanto, noto que os objetos Endereco, Emails, e Telefones já são atributos da classe Contatos. Deste modo, uma maneira mais correta seria removê-los da classe main e adicionar um método para a inicialização destes objetos em suas próprias classes. Como no exemplo abaixo.
public class Contatos {

    int max;
    private String nome;
    private Endereco[] endereco;
    private Emails[] email;
    private Telefones[] telefones;

    public Contatos(int max) {
        this.max = max;
        initEnderecos();
   }

    public String getNome() {
        return nome;
   }

    public void setNome(String nome) {
        this.nome = nome;
   }

    public Endereco[] getEndereco() {
       return endereco;
   }

    public void setEndereco(Endereco[] endereco) {
        this.endereco = endereco;
  }

    public Emails[] getEmail() {
        return email;
  }

    public void setEmail(Emails[] email) {
       this.email = email;
  }

    public Telefones[] getTelefones() {
       return telefones;
  }

   public void setTelefones(Telefones[] telefones) {
      this.telefones = telefones;
  }

   private void initEnderecos() {
        for (int i = 0; i < max; i++) {
            this.endereco[i] = new Endereco();
        }
   }
}

Neste exemplo eu movi o atributo max, que é o tamanho máximo da lista de contatos para a classe Contato e inicializo apenas o array de Endereco. Os outros vc pode fazer de forma análoga.
Note que, esta é apenas uma das melhorias que vc pode fazer neste código
Comment: vou tentar implementar isso, já já posto resultado, mas desde já agradeço.
Comment: Obrigado pela resposta. Irei deu certo com a resposta do parceiro ali em cima, vou tentar implementar essas dicas depois. vlw.
Comment: Beleza, a resposta que publiquei foi apenas para a resolução deste problema. Identifiquei alguns outros problemas no código, no entanto resolvi apenas o problema relacionado a dúvida.
Answer: Olá, o problema que está acontecendo é que foi apenas declaro o valor para array como new Endereco, contudo cada item dela fica null até ser inicializada, então terá que fazer essa inicialização antes de aderir valores as variáveis desse objeto.
 switch(op){
             case 1:
                 if(indice < max){

                     end[indice] = new Endereco();
                     c = new Contato();

                     System.out.println("nome: ");
                     String nome = scan.next();
                     c.setNome(nome);

                     System.out.print("nome da rua: ");
                     String rua = scan.next();
                     end[indice].setRua(rua);

                     System.out.print("número: ");
                     String num = scan.next();
                     end[indice].setNumero(num);

                     System.out.print("bairro: ");
                     String bairro = scan.next();
                     end[indice].setBairro(bairro);

                     c.setEndereco(end);
                     con[indice] = c;
                     indice++;
                 }

Uma outra coisa que percebi analisando seu codigo é que seta um endereço no objeto c, contudo dps inicializa-o novamente, perdendo o que foi setado que no caso não tinha nada, o mais correto a se fazer é apenas colocar esse valor depois de inserir todos os itens do endereço, e tbm estava colocando o valor do bairro na rua.
Comment: kk Valeu, nem tinha reparado nessa parte do valor do bairro na rua. Resolução muito simples, muito obrigado fera. :) acho que lembro de você de uma outra dúvida anterior de Java tbm kk vlw \o/
Comment: kkkkkk, Normalmente os erros que dão são bem simples, o ruim é encontrar.
Answer: Se puder usar List, faça que vai ser mais feliz, se não puder, tera que criar um objeto para cada Array que você criou, pois cada posição do Array está esperando um objeto  e você está passando uma String. então no seu caso ficaria assim.
obs: vou fazer apenas com um dos Array e vocÊ replica.
Endereco []end = new Endereco[max]; // cada posição tem que ser um objeto
Endereco endereco = new Endereco();

System.out.print("nome da rua: ");
String rua = scan.next();
endereco.setRua(rua);
end[indice] = endereco;

end[indice].getRua(); //para mostrar o valor depois.

Problema com array no Java


How to use the node title in the "Override title" field of contextual filter

Question: Situation:

A view has a contextual filter on a field named type.

The view sorts by date and has the pager set to display 1 item (I want only the newest node).

I want to show type + the node title as the view title.

So, what I want to put in the Override title field is
{{ arguments.field_type_value }} {{ title }}

But {{ title }} doesn't work. It outputs nothing. This isn't a surprise because (a) {{ title }} isn't in the Replacement Patterns list and (b) I assume the view expects to display multiple nodes, so there isn't just one {{ title }} to display.
Is there a straightforward way to do what I want to do using a view as I'm doing? There are reasons why I want to use a view.
Answer: Simply add title as a field and checkmark hide from display, now {{ title }} should work despite not being listed as replacement pattern.
Also make sure your view's title is set to none

Alternatively, you could also solve it by not overriding it in the contextual filter settings and instead overwrite it directly in the view's title.
Add title and type as fields, hide them if you want/need to.

But, if you're using teaser

The above two solutions won't work, so you can solve it programmatically:
/**
 * Implements hook_views_post_render()
 */
function mymodule_views_post_render($view) {
  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $node = $view->result[0]->_entity;
    $new_title = $node->type->entity->label() . ' ' . $node->getTitle();
    $view->setTitle($new_title);
  }
}

Comment: Thanks, @No Sssweat. I'm using Show: Content, so I updated my question to reflect that. Your coded solution worked perfectly for me. I also tested your first two solutions with Show: Fields and they work in that case as well. I've never used views_post_render before. And I had no idea Twig syntax can be used in a title field, so I learned something new there as well!


Grey background in navigation bar with searchController added to navigationItem during push

Question: I have a table view in navigation controller so that I can push the detail view controller on the stack. It works fine, until I add a search controller to the navigation item, like so:
searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.delegate = self
searchController.searchBar.tintColor = Colors.mlLabel
navigationItem.searchController = searchController
definesPresentationContext = true

It results in temporary grey background, see below:

When debugging the view hierarchy, it looks like UIViewControllerWrapperView's _UIParallaxDimmingView(selected below) is causing this, as both navigation bar and status bar are transparent.

How can I fix this?
Note: Setting the animated property in pushViewController() to false works, but I'd like to keep the animation.
Update: This seems to be issue only on iOS 13. Probably from some recent version even, as I didn't have this issue earlier.
Update 2: I've noticed the same issue on multiple places in my app now, and it's not just in combination with SearchController. Basically the _UIParallaxDimmingView sticks its nose out.
Comment: Can you please share how are u implementing search contrıkker=
Comment: @EmreÖnder please check updated question, nothing fancy. Just `UISearchController(searchResultsController: nil)`
Comment: Where do you add the search controller is it in viewDidLaod method or somewhere else?
Comment: @m1sh0 yes, `viewDidLoad()`
Comment: do you need to use transparent navigation bar? you can configure as opaque?
Comment: @gadu I've set `navigationBar.isTranslucent = false`, but it has no effect in this case. So I've just tried adding `navigationBar.backgroundColor = .white`, which does the job, but the status bar is still transparent.
Comment: in the view debugger you can actually tap on the navigation bar and see if the `isTranslucent` worked. if it still shows up as translucent something isn't working... you can try: `UINavigationBar.appearance().translucent = false` some where early in your app like `appDidFinishLaunching` otherwise try setting `navigationBar.isTranslucent` before its added to view hierarchy, sometimes with apple elements it doesn't let you adjust after its been pushed/presented you have to do it before
Comment: It says `Translucent Off`, I guess it just didn't have the background color which I've set now. Problem is with the status bar.
Comment: Looks like it's problem only since iOS 13.
Comment: @AdamBardon How you are showing "Subscribers" text? As viewcontroller's title?
Comment: @ShebinKoshy yes, in vieWillAppear()
Comment: Tested in Xcode 11, not facing this issue. What i have done is created a view controller with tableView and push another view controller on tableView's didSelectRowAt delegate. The second view controller's viewDidLoad has the provided code.
Comment: I've been working on this app since may, and I don't recall having this issue before. I'm almost sure it's some new, under the hood change.
Comment: I'm sorry if my question look silly, but does this happen also on an acutal device or just in the Simulator? Anyways, as a workaround, I would create an empty VC with the hight of search bar, white BG, and make it the first element of stack.
Comment: Yep, it does happen also on an actual device.
Comment: Did you tried `searchController.hidesNavigationBarDuringPresentation = true` ?
Comment: @KomalGoyani yes, doesn't seem to be related.
Answer: Update
Here's the code I use to go from a large title to a small title. These are properties for the large title viewcontroller, or more specific its navigation controller:
navigationController.navigationBar.prefersLargeTitles = true
navigationController.topViewController?.extendedLayoutIncludesOpaqueBars = true

Perhaps the second line above might help you?
As for pushing any view controllers, I see I've overridden the push-function from the navigation controller (as I use the navigation controller for each tab in my tabbar):
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
    if viewControllers.count >= 1 {
        viewController.hidesBottomBarWhenPushed = true
        viewController.navigationItem.largeTitleDisplayMode = .never
    }
    super.pushViewController(viewController, animated: animated)
}

Previous answer
I saw this a couple of times before in my life and it always had to do something with the background color of the view controller itself. If it's transparent you see this stuff when animating.
But since it's a search controller, it might be the navigation bar. Anyway, since the issue is only since iOS13, I believe the issue can be resolved using this:
searchController.searchBar.backgroundColor = UIColor.clear (or whatever color)

This new property (UISearchBar.searchTextField.backgroundColor) has been added since iOS13, so maybe this will solve it for you? :)
Comment:  thanks. I also have the same setup, large to small in one of my apps without issues. I'll check the code and post something later today!
Comment: I've tried what you suggested but no effect. And I always set the background color of a view controller. As it turns out, I've wrongly assumed it's connected directly to SearchController. Looks like this happens when the current VC has large title and the one which is being pushed on the stack has not.
Comment: Ah ok, so you solved it yourself in the end? :) I suggest you post your own answer and accept it for devs in the future that come across this same issue.
Comment: I haven't :/ The current setup I have is what I need, e.g. turning the title from large to small is not something I'd like to compromise on. I'm almost sure I've started to having this issue with some recent XCode version update, definitely not at the beginning(like first XCode 11 beta...)
Comment: I've awarded your answer with the bounty which was about to end so that the reputation is not wasted :) Enjoy!
Comment: @AdamBardon I just updated my answer with some code I use to push from a large title to a small title. Perhaps you'll find something in there that helps you :)
Answer: I've finally found a solution. One of the problems was that I've set a background color for the navbar like so:
UINavigationBar.appearance().backgroundColor = .white

So removing the above line and adding the below line to the view controller being pushed fixed it.
extendedLayoutIncludesOpaqueBars = true

Comment: Ah nice! That second line was also in the code of my updated answer ;) Good to hear you can finally continue :)
Comment: You're my hero!


Finding generalized eigenvectors from a Jordan form

Question: I am trying to understand the relation between Jordan form, characteristic polynomial and minimal characteristic polynomial.
From: Problem5

Consider a matrix A, assume that A has characteristic polynomial
$$(s − \lambda _1)^5 (s − \lambda_2)^3$$
that it has four linearly independent eigenvectors and
has minimal polynomial $$(s − \lambda_1)^2(s − \lambda_2)^3.$$
Write down the Jordan form J of this matrix.

The answer available here says:

[...]
• The eigenvalue $\lambda_2$ will have only 1 block of 3 × 3, that contains only 1 eigenvector of A and two generalized eigenvectors.
• The eigenvalue $\lambda_1$ will have a block of 2 × 2, that contains only 1 eigenvector of A and one generalized eigenvector. [...]

How do I know how many eigenvectors are in each Jordan block? How many of  those are L.I.? How many of those are generalized? Is there a fast way to obtain the eigenvectors from a Jordan form matrix? Or should I just use the definition of eigenvector?
Also if you could suggest any online material on Jordan form properties and relation to eigenvectors that would be great.
Answer: First I will answer your questions and then explain how to write J.
Each n$\times$n Jordan block represents one eigenvector and n − 1 generalized eigenvectors. All the eigenvectors and generalized eigenvectors are linearly independent. You cannot determine the eigenvectors from J unless J = A; you also need the matrix M from the similarity transformation J = M$^{-1}$AM.  Hence, yes, you can use the definition of an eigenvector applied to matrix A.  One online source on Jordan normal form properties and their relation to eigenvectors is the Wikipedia article "Generalized eigenvector," which also justifies my answers.
Here is how to write J.  The degree of the characteristic polynomial gives the size of J, 8$\times$8 in this case.  With the characteristic polynomial in the form you have it, the exponent of each monomial gives the number of times the corresponding eigenvalue appears along the diagonal of J; in this case, λ$_1$ appears five times and λ$_2,$ three times.  The number of linearly independent eigenvalues gives the number of Jordan blocks, four in this case.  With the minimal polynomial in the form you have it, the exponent of each monomial gives the size of the largest Jordan block for the corresponding eigenvalue.  In this case, λ$_2$ has a 3$\times$3 Jordan block, which takes care of all three λ$_2$'s along the diagonal of J.  The largest Jordan block for λ$_1$ is 2$\times$2, and we need three Jordan blocks for λ$_1.$  The only way to arrange that is to have two 2$\times$2 and one 1$\times$1 Jordan blocks. Thus, we can write J as shown in your answer document.


How can I prevent Drupal from saving the user's initial email address? (init in the users_field_data table)?

Question: I am trying to reduce the amount of PII (personally identifiable information) that my site collects.
When a user registers an account, by default, that email address is saved twice in the users_field_data table-- once to the mail column, and again to the init column.  This may be useful for some sites, but as far as I know core never uses the init value for anything, and so I would like to prevent any value being saved to init.
Answer: Looking into this, the initial email is only collected automatically if the user registers using the registration form; decoupled registrations do not have init set.
I know the general recommendation is not to patch core, but in this case it's a single line:
diff --git a/core/modules/user/src/RegisterForm.php b/core/modules/user/src/RegisterForm.php
index 0a4da2dcf1..cf2fdd159b 100644
--- a/core/modules/user/src/RegisterForm.php
+++ b/core/modules/user/src/RegisterForm.php
@@ -81,7 +81,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
     $form_state->cleanValues();

     $form_state->setValue('pass', $pass);
-    $form_state->setValue('init', $form_state->getValue('mail'));
+    // $form_state->setValue('init', $form_state->getValue('mail'));

     parent::submitForm($form, $form_state);
   }


Blazor Webassembly Bunit test changing blazorCulture?

Question: I am trying to test the blazorCulture change using Bunit Test but I am unable to get and set the blazorCulture.
Below code works in the actual blazor Wasm application but not working within a Bunit
var js = Services.GetRequiredService<IJSRuntime>();
            var result = await js.InvokeAsync<string>("blazorCulture.get");

            if (result != null)
            {
                CultureInfo.CurrentCulture = new CultureInfo(result);
            }
            else
            {
                CultureInfo.CurrentCulture = new CultureInfo("de-De");
                await js.InvokeVoidAsync("blazorCulture.set", "de-De");
            }

What is the way to change the Rendered Components culture and language using Bunit test?
Answer: You are invoking JavaScript, which bUnit does not run, it runs entirely in C#. However, bUnit does come with a fake JSInterop implementation, that you can use to verify that you have made the correct calls to your blazorCulture.get and blazorCulture.set methods.
In your test, you can write something like this:
// arrange
var ctx = new TestContext();
ctx.JSInterop.Setup<string>("blazorCulture.get").SetResult("da-DK");
ctx.JSInterop.SetupVoid("blazorCulture.set").SetVoidResult();

// act
...

// assert
var invocations = ctx.JSInterop.Invocations["blazorCulture.set"];
var argument = invocations[0].Arguments[0]; // assumes only one invocation with one argument
Assert.Equal("de-De", argument);

Learn more here: https://bunit.dev/docs/test-doubles/emulating-ijsruntime.html


Domain of a composite function $g(h(x))$

Question: Say we have $g(x)=x-5$ and $h(x)=x^2+4x+6$. Say we have to find the composite function $g(h(x))$ and then find the domain of that function. I know that $g(h(x))=x^2+4x+1$. Now, if I had to consider the function $x^2+4x+1$ on its own and not as a composite of two other function then I can easily say that its domain is $(-\infty, \infty)$. However, I'm not sure of the domain of the composite function $g(h(x))$ would be the same since $h(x)$ has range $[2, \infty)$ and the values of $h(x)$ are the inputs of the composite function.
Answer: The domain is indeed $\Bbb R$. You can still put any value of $x\in(-\infty,\infty)$ into $g(h(x))$. The fact that $h$ has range $[2,\infty)$ will simply only affect the range of $g\circ h$. The range of $h$ does not affect the domain of $g\circ h$ in this case because $g$ has domain $\Bbb R$.
If $g$ were a function with domain $[3,\infty)$ for example, then the domain of $g\circ h$ would need to change, because $h(x)\in [2,\infty)$ if $x\in(-\infty,\infty)$. For instance, if $x=-2$ then $h(x)=2$, and then $g(h(x))=g(2)$ is undefined.
In general, if $f:X\subseteq \Bbb R\to Y\subseteq \Bbb R$ and $g:U\subseteq \Bbb R\to\Bbb R$, then we can compose $g\circ f$ if $Y\subseteq U$.
Comment: It wouldn't have to be equal, but certainly the domain of $g \circ h$ would need to be changed so that the range of $h$ is contained in the domain of $g$.
Comment: So in the scenario you mentioned the domain of $g \circ h$ would need to be changed to a subset of the domain of $h$ s.t. the range of h is equal to the domain of $g$?
Answer: You can find the domain of any composite function using the following formula
$$
D_{f\circ g} = \left\{\begin{aligned}
&x\in D_g\\
&g(x)\in D_f
\end{aligned}
\right.
$$
In your example
$
g(x)=x+5,D_g=\mathbb R
$
and
$
h(x)=x^2+4x+6,D_h=\mathbb R
$
then the domain of the composite function will be
$$
D_{g\circ h} = \left\{\begin{aligned}
&x\in D_h\\
&h(x)\in D_g
\end{aligned}
\right.
=
\left\{\begin{aligned}
&x\in \mathbb R\\
&x^2+4x+6\in \mathbb R
\end{aligned}
\right.
=
\mathbb R
$$
so
$
(g\circ h)(x)=g(h(x))=x^2+4x+1
$


SQL Server - Execute first where clause and if valid don't execute second

Question: I have the SQL Server Select statement:
SELECT *
FROM Table
WHERE(ClientPlants = 621 AND Carriers = 226)
 OR (Carriers = 226 AND ClientPlants IS NULL)
 ORDER BY ClientPlants

Now problem is when the first is valid, it still executes the second clause after the 'or'.  How do I make it so the second clause is only executed if the first clause fails?
As in, if there are no results found for where clause 1 (ClientPlants = 621 AND Carriers = 226), go to 2 (Carriers = 226 AND ClientPlants IS NULL).  If there is a result for clause 1, return query and stop.
I tried to look into CASE statement but couldn't see how to add it to my code.
Thanks in advance!
Comment: Add some sample table data and the expected result. As formatted text, not images.
Comment: Not sure I get your query. Why not WHERE ClientPlants = 621 OR Carriers = 226?
Comment: Syntax error expected.
Comment: I guess the first question is what are you trying to achieve? from the query i see you want to get records where ClientPlants = 621 and also Carriers = 226 and also when Carriers = 226. The logic seems to ignore the ClientPlants filter
Comment: The answers below will do what you ask but more than likely a refined where clause will accomplished what you want. Posting sample data and desired results would help us help you. Or maybe an explanation.
Answer: You could use CASE WHEN:
SELECT *
FROM Table
WHERE (CASE WHEN ClientPlants = 621 AND Carriers IN (226) THEN 1
            WHEN Carriers IN (226) THEN 1
            ELSE 0
       END) = 1
ORDER BY ClientPlantsK;

Answer: Do you mean something like this:
IF EXISTS (SELECT * FROM Table WHERE ClientPlants = 621 AND Carriers = 226)
    SELECT * FROM Table WHERE ClientPlants = 621 AND Carriers = 226 ORDER BY ClientPlantsK
ELSE
    SELECT * FROM Table WHERE Carriers = 226 ORDER BY ClientPlantsK
;

Update:
Given that you are only wanting to return 1 row, I think something like this would work for a single T-SQL query in a stored procedure:
CREATE PROCEDURE ProcedureName
    @ClientPlants int
    , @Carriers int
AS

SELECT
    Carriers
    , ClientPlants
    -- Add the rest of the columns
FROM
    (
        SELECT
            Carriers
            , ClientPlants
            -- Add the rest of the columns
            , ROW_NUMBER() OVER (ORDER BY CASE WHEN ClientPlants = @ClientPlants THEN 0 ELSE 1 END) R
        FROM Table
        WHERE Carriers = @Carriers
    ) Q
WHERE R = 1

Usage:
EXEC ProcedureName 621, 226

I've recommended you name your columns rather than using SELECT * to avoid having column R in the output.
Comment: Also, it's important to note that my answer is not just a single SQL query, but is technically procedural code.
Comment: That's it.  Didn't know you could put an if-else in there with SQL. Thanks so much Chris!
Comment: You're welcome! - Please mark the answer as correct if it's working.
Comment: @Scottie. Pay attention to Chris comment above. While this may actually work there are probably many other ways to achieve what you are after that are way more efficient and elegant. SQL is not geared to operate procedurally and coding as such should be done as a last result.
Comment: Thanks DaniDev.  Then how would I do via straight SQL?  If I have to, I can put this into a stored proc for executing...
Comment: @Scottie, if I understand your requirement, you need to alter your `WHERE` clause based on the existence of certain types of records within the table, (i.e. your `ClientPlants = 621 AND Carriers = 226` records - if any exist, you want only these, but if there aren't any, you want all records where `Carriers = 226`). It seems an unusual requirement, but if that's what it is, I don't see a way to do it in one T-SQL query. However, what I've posted does work, and will work fine in a stored procedure.
Comment: Thanks Chris.  Yes that is what I'm looking for.  If a record has a specific carrier (226) with a specific plant (621), use that one (clause 1).  Note, there will only be one record per plant/carrier pair.  If it doesn't exist, then return the generic case for a specific plant (621) and the carrier is null (clause 2)
Comment: @Scottie, given your last comment, I've updated my answer, as I think you might be able to do this in one T-SQL statement.
Comment: I tried your answer but it doesn't work if I change the ClientPlant to be something other than 621 in the table (i.e. 620).  I need it fall to the second clause of ClientPlant = 621 and Carrier IS NULL or not return anything if there is not a row with the carrier null in it.
Comment: I've updated my answer - you could pass your values in via a stored procedure.
Answer: Do you mean like this?
SELECT a.*
       CASE WHEN ClientPlants = 621 AND Carriers = 226 THEN column
            WHEN ClientPlans <> 621 AND Carriers = 226 THEN column
         ELSE NULL
        END Column

 FROM table A


como adicionar Midia na Biblioteca do Wordpress programaticamente?

Question: Considere a situação em que centenas de arquivos .jpg já estejam disponíveis no diretório wp-content/uploads/2014/09 como padrão e precisamos que eles apareçam na Biblioteca de Mídia (http://meu-site.com.br/wp-admin/upload.php) do site WordPress.
Existe algum script SQL que possa simplesmente atualizar o database ou devo usar um script PHP ?
Qual a melhor abordagem ?
Answer: A função a seguir foi desenvolvida para importação de fotos de outro site, porem pode ser adaptada a sua necessidade.
Você poderia fazer algo desta forma:
function _import_photo( $postid, $photo_name ) {
    $post = get_post( $postid );
    if( empty( $post ) )
        return false;

    if( !class_exists( 'WP_Http' ) )
      include_once( ABSPATH . WPINC. '/class-http.php' );

    $photo = new WP_Http();
    $photo = $photo->request( 'http://example.com/photos/directory/' . $photo_name . '.jpg' );
    if( $photo['response']['code'] != 200 )
        return false;

    $attachment = wp_upload_bits( $user_login . '.jpg', null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );
    if( !empty( $attachment['error'] ) )
        return false;

    $filetype = wp_check_filetype( basename( $attachment['file'] ), null );

    $postinfo = array(
        'post_mime_type'    => $filetype['type'],
        'post_title'        => $post->post_title . ' employee photograph',
        'post_content'      => '',
        'post_status'       => 'inherit',
    );
    $filename = $attachment['file'];
    $attach_id = wp_insert_attachment( $postinfo, $filename, $postid );

    if( !function_exists( 'wp_generate_attachment_data' ) )
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id,  $attach_data );
    return $attach_id;
}


Prove $ 3^{n}> n^{2}$ for $n=2$ by induction

Question: I understand base case at $n=1$, and $n=2$. Then I do understand the inductive hypothesis of assuming $n=k$. The part that confuses me is when showing $n=k+1$. On other tutorials that are online, they multiply by 3 to both sides instead of plugging in $k+1$ for n and proving from there.
I started the proof for $n=k+1$ like this:
Proving the statement holds for $n=k+1$:
$ 3^{k} > k^{2}$ = $ 3^{k+1} > (k+1)^{2}$
=> $ 3^{k}*3 > k^{2}+2k+1$ I am confused right here.
Or compare the left side of the inequality with the right side  $ 3^{k}*3 > k^{2}$
Where  $3^{k}*3 > k^{2}$, $ 3^{k} $ is less than $ k^{2}$ by inductive hypothesis
Then I am not sure where to go from there.
Comment: Use equals signs only for equality.  You write $3^k>k^2\color{red}{=}3^{k+1}>(k+1)^2$.  You mean to write "*We wish to prove that $3^k>k^2$ implies that $3^{k+1}>(k+1)^2$*"
Comment: Suggested reading: [How to write a clear induction proof](https://math.stackexchange.com/questions/1253956/proof-writing-how-to-write-a-clear-induction-proof).
Comment: You have $3^{k+1}=3\cdot 3^k>3k^2$. The rest should be easy.
Comment: Read the linked question on how to write a proper proof by induction.  You should be trying to line everything up in one line if possible, or if not then at least in one line of implications.  You should be able in this problem be able to write $3^{k+1}\geq \dots \geq \dots \geq \dots \geq (k+1)^2$ where the inbetween steps follow from simple algebraic manipulations, the fact that $k$ is at least as large as your base case, and the induction hypothesis.
Comment: Jmoravitz sir is $>$ not $\geq $
Comment: @Theoneandonly then modify my line to say $\geq \dots \geq \dots \geq \dots >\dots \geq \dots (k+1)^2$.  All that is required is a single strict inequality in the chain and the rest be non-strict.  The point is that some of those in the chain can be strict equalities if one chooses.  That will fall naturally from using the induction hypothesis anyways for this problem
Answer: $$ 3^{n+1} = 3^n \cdot 3 > 3 n^2 = n^2 + n^2 + n^2 > n^2 + 2n + 1 = (n+1)^2 QED$$
Comment: It wasn't me, but for low effort questions like this a popular strategy for teaching is explicitly *not* to give them a full answer and holding their hands but rather to give them the tools they need to complete it themselves, asking leading questions, showing them other related but distinct examples, etc...  I could see someone thinking your answer here was too complete.
Comment: @JMoravitz Now the answer that has just been posted that is too complete.
Comment: why the downvote ?
Comment: Why did you multiply the $n^{2}$ by 3 though?
Comment: induction hypothesis: $n^2 > 3^n$ and so  $3 3^{n} > 3 n^2 $
Comment: do you mean $n^{2} < 3^{n}$
Comment: @user1829 Recall that $3^{a+b}=3^a\times 3^b$... in particular $3^{k+1}=3^k\times 3^1$ or simplified $3^k\times 3$.  Now... recall that if $a>b$ and $c>0$ then $a\times c > b\times c$... so $3^k\times 3 > k^2 \times 3$
Comment: yes which is $3^n > n^2$
Comment: I still dont understand the downvote tho.
Comment: Obviously it was a hint and proof of this is the OP asking some questions about it. He still needs to figure out things and write it out nicely. Do you really think this is too complete?
Answer: First of all.... don't write $3^{k+1} > (k+1)^2$.  That's what you have to prove.... you don't know it yet.
DO not start with what you need to prove and work backwards.
Startt with what you know and work foreward.
What you know is $3^k > k^2$.
So $3*3^k > 3*k^2$
So $3^{k+1} > 3*k^2$.
Now what you need to prove is (scribble this on note paper to the side) $3k^2 \ge (k+1)^2= k^2 + 2k + 1$.
So $3^{k+1} > k^2 + k^2 + k^2$
Now what we need to prove (still scribbling on note paper to the side) is that $k^2 + k^2 \ge 2k + 1$.
We know that $k \ge 2$ so $k*k \ge 2*k$ so
So $3^{k+1} > k^2 + k^2 + k^2 \ge k^2 + 2k + k^2$.
Now we need to prove (scribble scribble) that $k^2 \ge 1$.
We know that $k \ge 1$ so $k*k \ge 1*k = k \ge 2 > 1$ so
So $3^{k+1} > 3k^2= k^2+k^2 + k^2 \ge k^2 + 2k + k^2 > k^2 + 2k + 1  =(k+1)^2$.
....
Now we are done.


Japanese String in Java

Question: I'm a newbie in Java so please bear with me if this is a very easy problem. I have a JUnit Test where I have a hardcoded Japanese word assigned directly to a string variable. Now right after that string is assigned, it turns to "??" meaning that the encoding is incorrect somewhere.
public class TestTest extends TestCase {
  public void testLocal(){
    Locale.setDefault(Locale.JAPAN);//same problem with or without this line
    String test = "会社";
    //after this line, by watching at the debugger, the variable "test" contains "??"
    assertEquals("会社", test);
  }
}

Because this is a testcase, I believe it completely isolates the problem from other UI environments. Please help me in this. Been 2 days with no solution. Thank you in advance.
Comment: Perhaps your debugger is not compliant?
Also, you cannot assume that the assigned string is Unicode by looking at your code sample.  So, like John Skeet suggested, \u**** representation might be better.
Answer: If you've got the same exact string twice, it shouldn't really matter what encoding is being used... but I would suggest using the \uxxxx escape format to make it clear which Unicode characters are actually being used. That way it's basically encoding-independent.
If you really want to use string literals with Japanese in your code, check that all your build tools (etc) agree on the file encoding you're using. This will vary between IDE, Ant etc. (It's the -encoding flag for javac, for example.)
Answer: Try this
    ...
    assertEquals("会社", new String(test.getBytes(),"utf8"));
    ...

Answer: A little update on my earlier comment:  I was able to reproduce your results, with the question marks.  I did exactly as you did except I changed my shell default LANG settings.
The reason you are (might) be getting questions marks is because your environment locale does not match your intended locale.  Try doing this first in your shell(Bash):
export LANG="ja_JP.UTF-8"

or on Windows:
set LANG=ja_JP.UTF-8

If that doesn't work, you can try from your command prompt: chsh 65001 then run your java program. Sorry to throw out all these suggestions..hope it works!
Comment: Thank you for your answer.I tried to set the LANG (I am in Windows so I hope it is the same), but I have the same problem.
Answer: If your debug output is depending on System.out, it is possible that the output is being converted to the default encoding of your platform.
I always run with -Dfile.encoding=UTF8 when wanting to support international character sets (which is nearly always!)
i.e.  run as:
java -Dfile.encoding=UTF8 MyApp
(NOTE: If you are not running from a CLI, there may be other ways you set these properties)

Japanese String in Java


c++ value_type not work for std::tr1:tuple in a std::map

Question: The following code snippet work with Visual Studio 2008 but not with Visual Studio 2010.
template <typename TKey>
struct MyStruct
{
    typedef std::map<TKey, int>  Keys;

    MyStruct()
    {
    }

    void set(TKey& key)
    {
#if 1
        // This works with VS 2008 but not with 2010
        keys_.insert(typename Keys::value_type(key, 1));
#else
        // This works with VS 2008 and VS 2010
        keys_.insert(std::pair<TKey, int>(key, 1));
#endif
    };

private:
    Keys keys_;
};

Usage
typedef std::tr1::tuple<int, int> MyValueType;
MyStruct<MyValueType> a;
MyValueType x;
a.set(x);

I get following error:

1>C:\Program Files\Microsoft Visual Studio 10.0\VC\include\tuple(127):
  error C2440: 'initializing' : cannot convert from 'const MyValueType'
  to 'int' 1>          No user-defined-conversion operator available
  that can perform this conversion, or the operator cannot be called 1>
  C:\Program Files\Microsoft Visual Studio 10.0\VC\include\xxtuple0(9) :
  see reference to function template instantiation
  'std::tr1::_Cons_node<_Car,_Cdr>::_Cons_node<_Ty,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&,std::tr1::_Nil&>(_Farg0
  &&,_Farg1,_Farg2,_Farg3,_Farg4,_Farg5,_Farg6,_Farg7,_Farg8,_Farg9)'
  being compiled 1>          with 1>          [ 1>
  _Car=int, 1>              _Cdr=std::tr1::_Cons_node::_Type>,
  1>              _Ty=MyValueType, 1>              _Farg0=MyValueType,
  1>              _Farg1=std::tr1::_Nil &, 1>
  _Farg2=std::tr1::_Nil &, 1>              _Farg3=std::tr1::_Nil &, 1>              _Farg4=std::tr1::_Nil &, 1>              _Farg5=std::tr1::_Nil &, 1>              _Farg6=std::tr1::_Nil &, 1>              _Farg7=std::tr1::_Nil &, 1>              _Farg8=std::tr1::_Nil &, 1>              _Farg9=std::tr1::_Nil & 1>          ] 1>          C:\Program Files\Microsoft Visual Studio
  10.0\VC\include\utility(145) : see reference to function template instantiation 'std::tr1::tuple<_Arg0,_Arg1>::tuple>(_Farg0 &&)' being compiled 1>
  with 1>          [ 1>              _Arg0=int, 1>
  _Arg1=int, 1>              _Farg0=const std::tr1::tuple 1>          ] 1>          C:\Program Files\Microsoft Visual Studio
  10.0\VC\include\utility(142) : while compiling class template member function 'std::_Pair_base<_Ty1,_Ty2>::_Pair_base(const
  std::tr1::tuple<_Arg0,_Arg1> &&,int &&)' 1>          with 1>
  [ 1>              _Ty1=const MyValueType, 1>              _Ty2=int, 1>
  _Arg0=int, 1>              _Arg1=int 1>          ] 1>          C:\Program Files\Microsoft Visual Studio 10.0\VC\include\utility(174)
  : see reference to class template instantiation
  'std::_Pair_base<_Ty1,_Ty2>' being compiled 1>          with 1>
  [ 1>              _Ty1=const MyValueType, 1>              _Ty2=int 1>
  ] 1>
  D:\Projekte\demo\Demo.cpp(40)
  : see reference to class template instantiation 'std::pair<_Ty1,_Ty2>'
  being compiled 1>          with 1>          [ 1>
  _Ty1=const MyValueType, 1>              _Ty2=int 1>          ] 1>          D:\Projekte\demo\Demo.cpp(39)
  : while compiling class template member function 'void
  MyStruct::set(TKey &)' 1>          with 1>          [ 1>
  TKey=MyValueType 1>          ] 1>
  D:\Projekte\demo\Demo.cpp(92)
  : see reference to class template instantiation 'MyStruct' being
  compiled 1>          with 1>          [ 1>
  TKey=MyValueType 1>          ] 1>C:\Program Files\Microsoft Visual
  Studio 10.0\VC\include\tuple(127): error C2439:
  'std::tr1::_Cons_node<_Car,_Cdr>::_Value' : member could not be
  initialized 1>          with 1>          [ 1>              _Car=int,
  1>
  _Cdr=std::tr1::_Cons_node::_Type>
  1>          ] 1>          C:\Program Files\Microsoft Visual Studio
  10.0\VC\include\tuple(170) : see declaration of 'std::tr1::_Cons_node<_Car,_Cdr>::_Value' 1>          with 1>
  [ 1>              _Car=int, 1>
  _Cdr=std::tr1::_Cons_node::_Type>
  1>          ]
  ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

If a replace typedef std::tr1::tuple MyValueType with typedef int MyValueType it works.
Thank you in advance.
Comment: Seems to be a compiler bug, it [compiles on gcc](http://liveworkspace.org/code/a21f9394d98fef376487a2e9ce1fc868). You are missing `typename` before `Keys::value_type` (since `value_type` depends on `TKey`); but adding that doesn't fix the error either.
Comment: The problem lies with `value_type` being `pair` and it seems MSVC's implementation of `pair` doesn't correctly move from `const` qualified members.
Comment: Usually, I use `keys_.insert(std::make_pair(key, 1));` for such inserts. This should always work.
Comment: Oh, yes I forgot the typename. I extracted MyStruct from I third-party library that I used in my project. There has the typename. So I fix the sample above.
Answer: I think this is an error that related to bad implementation of move semantic in MSVC 2010 since you can successfully compile this code:
typename Keys::value_type v( key, 1 );
keys_.insert(v);

Comment: Thank you for the quick responses.
Is there a other way to compile the code without changing MyStruct.
Because I extracted MyStruct from a third-party library (Poco) that I used in my project.


How to programatically update a field for a revision?

Question: What is wrong with this approach for updating a field value in a specific revision:
public function myTest() {

  $test = 'mytest33';

  $node_revision = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision(10364);

  $node_revision->set('field_my_field', $test);
  $node_revision->save();

  return [
    '#markup' => 'Test page.',
  ];
}

When I load this simple test page and look at revision 10364 for the node, field_my_field doesn't update.
Answer: I needed to use the setSyncing method, like so:
public function myTest() {

  $test = 'mytest33';

  $node_revision = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision(10364);

  // See https://www.drupal.org/project/drupal/issues/2859042#comment-13083066
  $node_revision->original = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision(10364);

  // See https://www.drupal.org/project/drupal/issues/3335119
  $node_revision->setSyncing(TRUE);

  $node_revision->set('field_my_field', $test);
  $node_revision->save();

  return [
    '#markup' => 'Test page.',
  ];
}


Leverage Angular controllers with JSP loop

Question: I am pretty new to Angular.
Let's say I am using c:forEach to print a server-side generated content using JSP, like a list of fields.
Now I need to create a button where those fields will be added dinamically with javascript by the user (following the same template as the fields already printed from the server).
I am thinking of using angular to keep track of model changes instead of using plain jQuery, but I am having problems to use it with JSP.
My goal is to avoid angular to create the initial loop and to make it deal only with dynamic content manipulation after the HTML was generated by the application.
Is there a way to print a list of items using regular server-side language and then add angular just for the dinamic manipulation?
The example below would be the final HTML:

Server generated Content

Server generated Content2

<button>Add new list element</button>

By the way, am I using angular in the correct way?
EDIT:
I don't want to generate again the same content using JSON format, I want to leverage angular and the regular HTML markup. Does that make sense?
Answer: I believe that you can do something like this:
<input type="hidden" ng-model="myModel" value="[{k1: 'v1', k2: 'v2'}]"/>

where value is set on server side and it is in JSON format. Then:
<input type='button' ng-click='addElement()' value='Add new Element'/>

And define addElement() method in your angular controller, something like:
function MyController($scope) {
   $scope.addElement = function(){
      $scope.myModel.push({k3: 'v3'});
   }
}

Comment: Thing is I don't want to generate again the same content using JSON format, I want to leverage angular and the regular HTML markup.
Answer: The "angular way" of doing things does not account with server-side code generation, you should use REST or templates instead. Angular JS remove the burden of page loading or HTML manipulation from the server side and brings it to the front-end.
It is possible though to use server-side HTML generation and Angular JS using controllers and manipulating only a given portion of your page. If you are wondering about SEO keep in mind that Angular JS is not that friendly, other techniques should be used to deal with that case.
AngularJS is pretty useful for the internals of an application where SEO is irrelevant. In other hand, the public pages like the index should be simple and SEO friendly if your business require so.
Short answer: Angular does not work the way you supposed.


Using Javascript FileReader with huge files

Question: I have a problem using the Javascript FileRead trying to read huge files.
For example, I have a text file of 200mb and everytime I read this file the code stops working.
Its possible to read the text file, but for example ONLY the first 10 lines or stop reading after 10mb?
This is my code:
var file = form.getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();

reader.onload = (function(theFile) {
                return function(e) {
                    data = e.target.result;
                    form.displayedData=data;
                };
            })(file);

reader.readAsText(file);

The e.target.result always has the whole data of the file.
What can I do here?
Thx
Answer: This will only read the first 10 mb:
var file = form.getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();

reader.onload = function(e) {
    var data = e.target.result;
    form.displayedData = data;
};

reader.readAsText(file.slice(0, 10 * 1024 * 1024));

Comment: Yes this read first 10mb but file is still in memory, i think the original question was about reading huge files and not loading whole file into memory. Am I not right?
Comment: @Yetti no it only loads 10mb into memory.
Comment: @Fatih `Blob.slice` (same as `File.slice`) _shouldn't_ load the entire file into memory, it's basically true file streaming if you only read by slices (that said though, the actual underlying behavior is browser and system specific, e.g. it's possible that a 200MB file will be loaded into memory on a 64GB RAM system, but not a 20GB file). Related: https://stackoverflow.com/questions/24833487/what-is-html5-file-slice-method-actually-doing and https://chromium.googlesource.com/chromium/src/+/master/storage/browser/blob/README.md
Comment: Yes @Yetti my problem is same. if we try open 4GB file, file.slice will try load entire file.
Comment: Thanks @JohnWeisz I'll try.


Django queryset interpolation for a previous / next instance function

Question: Writing a dry function that returns either previous or next instances of a given instance.
This function return previous instances:
def previous(instance):
    try:
        return Picture.objects.filter(id__lt=instance.id).first()
    except Picture.DoesNotExist:
        return instance

I want to create an abstracted function which returns either the previous or the next instance using an additional gt_or_lt argument. The problem lies in interpolating that argument into the filter(id__gt_or_lt).
def seek_instance(gt_or_lt, instance):
    try:
        return Picture.objects.filter(id__gt_or_lt=instance.id).first()
    except Picture.DoesNotExist:
        return instance

I've tried:
return Picture.objects.filter(id__gt_or_lt = instance.id).first()
seek_instance("gt", instance)

return Picture.objects.filter(id__f"{gt_or_lt}" = instance.id).first()
seek_instance("gt", instance)

return Picture.objects.filter(f"{gt_or_lt}" = instance.id).first()

return Picture.objects.filter(gt_or_lt = instance.id).first()
seek("id__gt", instance)

All fail with their respective errors.
Answer: Use a dictionary with kwargs expansion.
return Picture.objects.filter(**{f"id__{gt_or_lt}": instance.id})

Answer: You can use dictionary expansion, like @DanielRoseman suggests. But that will still not per se render the previous, or next item. If for example the model has an ordering option [Django-doc], then it is possible that the order is different than on the id. Furthermore, for the previous one, you will need to reverse the ordering.
Furthermore depending on the situation, you might want to prevent that seek_instance can be given a different lookup, like 'in' for example.
We can thus use an if … elif … else here to branch on the item we wish to retrieve, and raise a ValueError in case you use some other lookup:
def seek_instance(lt_or_gt, instance):
    try:
        if lt_or_gt == 'lt':
            return Picture.objects.filter(pk__lt=instance.pk).order_by('-pk').first()
        elif lt_or_gt == 'gt':
            return Picture.objects.filter(pk__gt=instance.pk).order_by('pk').first()
        else:
            raise ValueError("Should be 'lt' or 'gt'")
    except Picture.DoesNotExist:
        return instance
Comment: @PersonPr7: sorry, that was something for another answer. The `Q` is not necessary here :)
Comment: Interesting. I see that you've imported Q but I don't see where it's used in the function. I'm probably missing something very obvious as I'm only vaguely familiar with Q.


real analysis - interior points of a set

Question: I need help constructing an if-and-only-if proof for the following:
Let $E \subseteq \mathbb{R}$. Define $E^o$ to be the interior points of $E$. Then $E^o$ is compact if and only if $E^o = ∅$.
I have experience proving that $E$ is open if $E^o = E$, and that $E$ is closed if $\bar E = E$, but I've never seen a proof that's presented like this.
Answer: Compact sets are closed. If the open set $E^{0}$ is compact then it is open and closed. Since $\mathbb R$ is connected the only sets that are both open and closed are the empty set and $\mathbb R$. Conclusion?
Proof without using connectedness: any open set in $\mathbb R$ is of the form $\cup_n (a_n,b_n)$ where the intervals are disjoint. If we write $E^{0}$ in this form and if we know that it is compact then $E^{0}=\cup_{n=1}^{N} (a_n,b_n)$ for some $N$. But then $E^{0}$ is the union of $(a_n,b_n),2\leq n \leq N$ and the intervals $(a_1+\frac 1 k, b_1-\frac 1 k)$ , so we get an open  cover which has no finite subcover.
Third proof: if $E^{0}$ is compact and nonempty then it has smallest element, say $x$. Since the set is open there exists $r>0$ such that $(x-r,x+r) \subset E^{0}$. But then $x-\frac r 2 \in E^{0}$ and this element is smaller than $x$, which is  contradiction.
Comment: In my class, we haven't learned about connected spaces yet. Do you know how to prove this without using the fact that $\mathbb{R}$ is connected? Thank you for answering.
Comment: @YeetYah See if my second proof is accessible.
Comment: I am new to real analysis. I'm sorry, but some of your notation is a little confusing for me to follow. So, any open set is a union of what exactly?  Why is $E^o$ the union of $(a_n, b_n), 2 \leq n \leq N$?
Comment: @YeetYah Any open set can be written as the union of sequence of disjoint open intervals.  For each point in the open set there is a largest open interval around that point which is contained in the open set. You can verify that the collection of all these maximal intervals has the properties we need.
Comment: This is making much more sense now, thanks. Is there a proof we can write using sequences? Perhaps a proof of contradiction?
Comment: @YeetYah OK, I have added  a third proof.
Comment: @YeetYah. A non-empty open $S\subset \Bbb R$ is equal to $\cup \Bbb J$ where $\Bbb J$ is a pairwise-disjoint family of non-empty convex open sets. (Note that open half-lines, and $\Bbb R$ itself, are convex open sets, as are bounded open intervals.).... For each $I\in \Bbb J$ let $f(I)\in I\cap \Bbb Q.$ Then$ f:\Bbb J\to \Bbb Q$ is injective (because $\Bbb J$ is a pairwise -disjoint family) and $\Bbb Q$ is countable, so $\Bbb J$ is countable. (Countable means "finite or countably infinite".)
Comment: Thank you so much!


using scales as a tool to identify lick

Question: I am learning how to play Children of the Sea by Black Sabbath. A tab that I found on the internet seems pretty accurate and straightforward, though I found the video of this guy playing and I found pretty cool the lick that he added to it (between 1:10 and 1:12).
As he provided no tab, I am trying to figure out what sequence of notes the lick is composed of.
The strategy that I developed so far is:

Find the key that the song is played: based on the chords it appears to me that it is played in the key of Em (potentially D#m, considering the D# standard tuning?)
Play around with the notes of the Em (or it corresponding major scale, which is G - considering that the song is played in the key of Em (not D#m))

I did play around with the notes of the key of G and I did not get quite there. How is my strategy to identify the notes of that lick? Should I also consider the pentatonic scale? It appears that he is potentially using two different shapes of the pentatonic scale
Please note that this is not a general question as for the best approach to transcribe music. Rather it is about a specific tool (scale) to aid in transcribing it
Comment: Does this answer your question? [How to transcribe music by ear?](https://music.stackexchange.com/questions/46/how-to-transcribe-music-by-ear)
Comment: It sounds like you're thinking about how to "reverse engineer" a lick, to get inside the guy's head and find the music theory behind the choices he made. That could be a useful exercise, especially for informing your own improvisation, but for practical purposes, it might be easier just to listen and look. You can slow down youtube playback, and you can see which frets he hits clearly. There's a fair bit of bending going on too.
Comment: @AndyBonner yes that was kind of my idea, to use scales as a tool to aid 'reverse engineering'. The first thing that I tried indeed was looking at the frets he played. They were not super clear though, I may need to look closer
Comment: There is very clear video of him playing the lick. Why not look at where he puts his fingers?
Comment: @Yorik see my answer above
Answer: The fact of a song being 'in a key' doesn't necessarily pin down the notes and chords in that song.  The key and its basic scale is a framework - but ONLY a framework.  Other notes and chords will occur.
I suggest you just listen carefully and work it out note by note.   If you recognise a familiar scale pattern, good!
Software than slows down, loops a portion etc. of a track will help.  I like this one.  There are others.  Even plain old Windows Media Player allows slowdown.
Transcribe!
Answer: I played guitar for about 20 years now. When I was learning, I would go through scales, I learnt just about every scale you can imagine, and learnt how to make them fit with pretty much anything playing through my speakers, it's fun being able to just pick up my guitar and improvise along to my favourite tunes. You can work out from there which notes the song is using more easily. If you can hear the note and learn to know how each note sounds on the guitar you can quickly find each note 1 by 1 and piece them together. My favourite learning software back when I was learning was guitar pro. You can hear if the tab is accurate and go through each section and play along to get your rhythm spot on as well as just the notation. Also if you're workign out chords, do it note by note so you can hear the chord being built, that way you won't have an off note by playing just a chord that fits the scale.
Answer: I'll attempt an answer that addresses the spirit of the question. You're not simply seeking the most pragmatic way to transcribe, but hoping to understand the music theory and idioms that cause musicians to make the improvisatory choices they do. Even if the end goal is transcription, this is not an unreasonable desire; I can transcribe a simple Mozart phrase more easily if I have the most rudimentary understanding of cadences and know that a IV is probably followed by a V and a I, and I don't have to painstakingly hear every single note in a chord.
Unfortunately, the best way to "reverse engineer" is simply to "forward engineer." The suggestion to "just learn all the scales, then play around with them and see what feels good" doesn't give you the analytical detail you're looking for, but it's a good place to start. Ultimately though, you'll probably benefit by identifying the chord changes (and overall tonality) that the improviser is soloing over. A solo doesn't have to constrain itself to these chords, but if it departs from them, it usually does so by conscious choice.
As mentioned, "find the key of the song" is the first step, but definitely not enough. "Long Distance Runaround" by Yes is overall in E major, but the riff that the instrumental intro is constructed around is in G natural minor (maybe. Plus some funky whole-tone stuff.). You'll also want to identify the actual chords going on at the moment of the lick in question.
Next, while one improv tool is to simply play your way up or down a scale, and while one might choose from multiple such scales (e.g. if the underlying chord is A minor, you might play an A minor, pentatonic, dorian, or blues scale), it can get boring and you might aspire to break into something more interesting. You could of course arpeggiate across chords ("Giant Steps," anyone?), or by mixing up your up-vs-down directions and the size of your leaps, before long you're just constructing a melody.
Since we're reverse-engineering here, listen for notes that "stick out" from the underlying chord. For instance, in the intro to "Heart of the Sunrise" (can you tell I like Yes?), they do simply run up and down an A pentatonic minor scale, but they fill in a few "gaps" chromatically, adding a C# and D#. Any non-chordal tones, bends, blue notes, etc. that "clash" with the underlying chord can point to what structural element they came from or are going to.
And finally, a smart solo-er will keep in mind where they're headed. You don't want to just run out of time and be left hanging at a point that doesn't mean anything. You want to aim for a final chord (maybe there's even a modulation involved!). You might want to wind up in a certain register—do you want to "go out on a high note," with a Dizzy-Gillespie squeal? Did you build up from a low register, but need to get back there to resume the rest of the song?
In the Black Sabbath lick in question, the lick is only a few notes long, and we can hear that it descends. The first thing I notice off the bat is that it covers an octave (seems to start on an A and end on the A an octave below), and to move in a mostly scalar fashion (i.e., it mostly goes down one step at a time, but not entirely, there are some intervallic skips). At that point, I hear the main notes as A G E D C A, which is pentatonic. There are some other squiggles, squeals, and bends going on, but now I have a starting point.
Comment: that's a very thorough and didactic answer, thanks very much. Still need some time (and more music theory under my belt) to understand 100% of what you wrote, will digest everything over time. Thanks again

using scales as a tool to identify lick